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.HiddenSequences;
58 import jalview.datamodel.PDBEntry;
59 import jalview.datamodel.SeqCigar;
60 import jalview.datamodel.Sequence;
61 import jalview.datamodel.SequenceGroup;
62 import jalview.datamodel.SequenceI;
63 import jalview.gui.ColourMenuHelper.ColourChangeListener;
64 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
65 import jalview.hmmer.HMMAlign;
66 import jalview.hmmer.HMMBuild;
67 import jalview.hmmer.HMMERParamStore;
68 import jalview.hmmer.HMMERPreset;
69 import jalview.hmmer.HMMSearch;
70 import jalview.hmmer.HmmerCommand;
71 import jalview.io.AlignmentProperties;
72 import jalview.io.AnnotationFile;
73 import jalview.io.BioJsHTMLOutput;
74 import jalview.io.DataSourceType;
75 import jalview.io.FileFormat;
76 import jalview.io.FileFormatI;
77 import jalview.io.FileFormats;
78 import jalview.io.FileLoader;
79 import jalview.io.FileParse;
80 import jalview.io.FormatAdapter;
81 import jalview.io.HtmlSvgOutput;
82 import jalview.io.IdentifyFile;
83 import jalview.io.JPredFile;
84 import jalview.io.JalviewFileChooser;
85 import jalview.io.JalviewFileView;
86 import jalview.io.JnetAnnotationMaker;
87 import jalview.io.NewickFile;
88 import jalview.io.ScoreMatrixFile;
89 import jalview.io.TCoffeeScoreFile;
90 import jalview.io.vcf.VCFLoader;
91 import jalview.jbgui.GAlignFrame;
92 import jalview.schemes.ColourSchemeI;
93 import jalview.schemes.ColourSchemes;
94 import jalview.schemes.ResidueColourScheme;
95 import jalview.schemes.TCoffeeColourScheme;
96 import jalview.util.MessageManager;
97 import jalview.viewmodel.AlignmentViewport;
98 import jalview.viewmodel.ViewportRanges;
99 import jalview.ws.DBRefFetcher;
100 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
101 import jalview.ws.jws1.Discoverer;
102 import jalview.ws.jws2.Jws2Discoverer;
103 import jalview.ws.jws2.jabaws2.Jws2Instance;
104 import jalview.ws.params.ArgumentI;
105 import jalview.ws.params.ParamDatastoreI;
106 import jalview.ws.params.WsParamSetI;
107 import jalview.ws.seqfetcher.DbSourceProxy;
109 import java.awt.BorderLayout;
110 import java.awt.Component;
111 import java.awt.Rectangle;
112 import java.awt.Toolkit;
113 import java.awt.datatransfer.Clipboard;
114 import java.awt.datatransfer.DataFlavor;
115 import java.awt.datatransfer.StringSelection;
116 import java.awt.datatransfer.Transferable;
117 import java.awt.dnd.DnDConstants;
118 import java.awt.dnd.DropTargetDragEvent;
119 import java.awt.dnd.DropTargetDropEvent;
120 import java.awt.dnd.DropTargetEvent;
121 import java.awt.dnd.DropTargetListener;
122 import java.awt.event.ActionEvent;
123 import java.awt.event.ActionListener;
124 import java.awt.event.FocusAdapter;
125 import java.awt.event.FocusEvent;
126 import java.awt.event.ItemEvent;
127 import java.awt.event.ItemListener;
128 import java.awt.event.KeyAdapter;
129 import java.awt.event.KeyEvent;
130 import java.awt.event.MouseEvent;
131 import java.awt.print.PageFormat;
132 import java.awt.print.PrinterJob;
133 import java.beans.PropertyChangeEvent;
135 import java.io.FileWriter;
136 import java.io.IOException;
137 import java.io.PrintWriter;
139 import java.util.ArrayList;
140 import java.util.Arrays;
141 import java.util.Deque;
142 import java.util.HashSet;
143 import java.util.List;
144 import java.util.Set;
145 import java.util.Vector;
147 import javax.swing.JCheckBoxMenuItem;
148 import javax.swing.JEditorPane;
149 import javax.swing.JFileChooser;
150 import javax.swing.JInternalFrame;
151 import javax.swing.JLayeredPane;
152 import javax.swing.JMenu;
153 import javax.swing.JMenuItem;
154 import javax.swing.JOptionPane;
155 import javax.swing.JScrollPane;
156 import javax.swing.SwingUtilities;
162 * @version $Revision$
164 public class AlignFrame extends GAlignFrame implements DropTargetListener,
165 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
167 public static final int DEFAULT_WIDTH = 700;
169 public static final int DEFAULT_HEIGHT = 500;
172 * The currently displayed panel (selected tabbed view if more than one)
174 public AlignmentPanel alignPanel;
176 AlignViewport viewport;
178 public AlignViewControllerI avc;
180 List<AlignmentPanel> alignPanels = new ArrayList<>();
183 * Last format used to load or save alignments in this window
185 FileFormatI currentFileFormat = null;
188 * Current filename for this alignment
190 String fileName = null;
194 * Creates a new AlignFrame object with specific width and height.
200 public AlignFrame(AlignmentI al, int width, int height)
202 this(al, null, width, height);
206 * Creates a new AlignFrame object with specific width, height and
212 * @param sequenceSetId
214 public AlignFrame(AlignmentI al, int width, int height,
215 String sequenceSetId)
217 this(al, null, width, height, sequenceSetId);
221 * Creates a new AlignFrame object with specific width, height and
227 * @param sequenceSetId
230 public AlignFrame(AlignmentI al, int width, int height,
231 String sequenceSetId, String viewId)
233 this(al, null, width, height, sequenceSetId, viewId);
237 * new alignment window with hidden columns
241 * @param hiddenColumns
242 * ColumnSelection or null
244 * Width of alignment frame
248 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
251 this(al, hiddenColumns, width, height, null);
255 * Create alignment frame for al with hiddenColumns, a specific width and
256 * height, and specific sequenceId
259 * @param hiddenColumns
262 * @param sequenceSetId
265 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
266 int height, String sequenceSetId)
268 this(al, hiddenColumns, width, height, sequenceSetId, null);
272 * Create alignment frame for al with hiddenColumns, a specific width and
273 * height, and specific sequenceId
276 * @param hiddenColumns
279 * @param sequenceSetId
284 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
285 int height, String sequenceSetId, String viewId)
287 setSize(width, height);
289 if (al.getDataset() == null)
294 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
296 alignPanel = new AlignmentPanel(this, viewport);
298 addAlignmentPanel(alignPanel, true);
302 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
303 HiddenColumns hiddenColumns, int width, int height)
305 setSize(width, height);
307 if (al.getDataset() == null)
312 viewport = new AlignViewport(al, hiddenColumns);
314 if (hiddenSeqs != null && hiddenSeqs.length > 0)
316 viewport.hideSequence(hiddenSeqs);
318 alignPanel = new AlignmentPanel(this, viewport);
319 addAlignmentPanel(alignPanel, true);
324 * Make a new AlignFrame from existing alignmentPanels
331 public AlignFrame(AlignmentPanel ap)
335 addAlignmentPanel(ap, false);
340 * initalise the alignframe from the underlying viewport data and the
345 if (!Jalview.isHeadlessMode())
347 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
350 avc = new jalview.controller.AlignViewController(this, viewport,
352 if (viewport.getAlignmentConservationAnnotation() == null)
354 // BLOSUM62Colour.setEnabled(false);
355 conservationMenuItem.setEnabled(false);
356 modifyConservation.setEnabled(false);
357 // PIDColour.setEnabled(false);
358 // abovePIDThreshold.setEnabled(false);
359 // modifyPID.setEnabled(false);
362 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
365 if (sortby.equals("Id"))
367 sortIDMenuItem_actionPerformed(null);
369 else if (sortby.equals("Pairwise Identity"))
371 sortPairwiseMenuItem_actionPerformed(null);
375 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
377 setMenusFromViewport(viewport);
378 buildSortByAnnotationScoresMenu();
379 calculateTree.addActionListener(new ActionListener()
383 public void actionPerformed(ActionEvent e)
390 if (Desktop.desktop != null)
392 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
393 addServiceListeners();
397 if (viewport.getWrapAlignment())
399 wrapMenuItem_actionPerformed(null);
402 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
404 this.overviewMenuItem_actionPerformed(null);
409 final List<AlignmentPanel> selviews = new ArrayList<>();
410 final List<AlignmentPanel> origview = new ArrayList<>();
411 final String menuLabel = MessageManager
412 .getString("label.copy_format_from");
413 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
414 new ViewSetProvider()
418 public AlignmentPanel[] getAllAlignmentPanels()
421 origview.add(alignPanel);
422 // make an array of all alignment panels except for this one
423 List<AlignmentPanel> aps = new ArrayList<>(
424 Arrays.asList(Desktop.getAlignmentPanels(null)));
425 aps.remove(AlignFrame.this.alignPanel);
426 return aps.toArray(new AlignmentPanel[aps.size()]);
428 }, selviews, new ItemListener()
432 public void itemStateChanged(ItemEvent e)
434 if (origview.size() > 0)
436 final AlignmentPanel ap = origview.get(0);
439 * Copy the ViewStyle of the selected panel to 'this one'.
440 * Don't change value of 'scaleProteinAsCdna' unless copying
443 ViewStyleI vs = selviews.get(0).getAlignViewport()
445 boolean fromSplitFrame = selviews.get(0)
446 .getAlignViewport().getCodingComplement() != null;
449 vs.setScaleProteinAsCdna(ap.getAlignViewport()
450 .getViewStyle().isScaleProteinAsCdna());
452 ap.getAlignViewport().setViewStyle(vs);
455 * Also rescale ViewStyle of SplitFrame complement if there is
456 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
457 * the whole ViewStyle (allow cDNA protein to have different
460 AlignViewportI complement = ap.getAlignViewport()
461 .getCodingComplement();
462 if (complement != null && vs.isScaleProteinAsCdna())
464 AlignFrame af = Desktop.getAlignFrameFor(complement);
465 ((SplitFrame) af.getSplitViewContainer())
467 af.setMenusForViewport();
471 ap.setSelected(true);
472 ap.alignFrame.setMenusForViewport();
477 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
478 .indexOf("devel") > -1
479 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
480 .indexOf("test") > -1)
482 formatMenu.add(vsel);
484 addFocusListener(new FocusAdapter()
487 public void focusGained(FocusEvent e)
489 Jalview.setCurrentAlignFrame(AlignFrame.this);
496 * Change the filename and format for the alignment, and enable the 'reload'
497 * button functionality.
504 public void setFileName(String file, FileFormatI format)
507 setFileFormat(format);
508 reload.setEnabled(true);
512 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
515 void addKeyListener()
517 addKeyListener(new KeyAdapter()
520 public void keyPressed(KeyEvent evt)
522 if (viewport.cursorMode
523 && ((evt.getKeyCode() >= KeyEvent.VK_0
524 && evt.getKeyCode() <= KeyEvent.VK_9)
525 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
526 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
527 && Character.isDigit(evt.getKeyChar()))
529 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
532 switch (evt.getKeyCode())
535 case 27: // escape key
536 deselectAllSequenceMenuItem_actionPerformed(null);
540 case KeyEvent.VK_DOWN:
541 if (evt.isAltDown() || !viewport.cursorMode)
543 moveSelectedSequences(false);
545 if (viewport.cursorMode)
547 alignPanel.getSeqPanel().moveCursor(0, 1);
552 if (evt.isAltDown() || !viewport.cursorMode)
554 moveSelectedSequences(true);
556 if (viewport.cursorMode)
558 alignPanel.getSeqPanel().moveCursor(0, -1);
563 case KeyEvent.VK_LEFT:
564 if (evt.isAltDown() || !viewport.cursorMode)
566 slideSequences(false,
567 alignPanel.getSeqPanel().getKeyboardNo1());
571 alignPanel.getSeqPanel().moveCursor(-1, 0);
576 case KeyEvent.VK_RIGHT:
577 if (evt.isAltDown() || !viewport.cursorMode)
579 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
583 alignPanel.getSeqPanel().moveCursor(1, 0);
587 case KeyEvent.VK_SPACE:
588 if (viewport.cursorMode)
590 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
591 || evt.isShiftDown() || evt.isAltDown());
595 // case KeyEvent.VK_A:
596 // if (viewport.cursorMode)
598 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
599 // //System.out.println("A");
603 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
604 * System.out.println("closing bracket"); } break;
606 case KeyEvent.VK_DELETE:
607 case KeyEvent.VK_BACK_SPACE:
608 if (!viewport.cursorMode)
610 cut_actionPerformed(null);
614 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
615 || evt.isShiftDown() || evt.isAltDown());
621 if (viewport.cursorMode)
623 alignPanel.getSeqPanel().setCursorRow();
627 if (viewport.cursorMode && !evt.isControlDown())
629 alignPanel.getSeqPanel().setCursorColumn();
633 if (viewport.cursorMode)
635 alignPanel.getSeqPanel().setCursorPosition();
639 case KeyEvent.VK_ENTER:
640 case KeyEvent.VK_COMMA:
641 if (viewport.cursorMode)
643 alignPanel.getSeqPanel().setCursorRowAndColumn();
648 if (viewport.cursorMode)
650 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
654 if (viewport.cursorMode)
656 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
661 viewport.cursorMode = !viewport.cursorMode;
662 statusBar.setText(MessageManager
663 .formatMessage("label.keyboard_editing_mode", new String[]
664 { (viewport.cursorMode ? "on" : "off") }));
665 if (viewport.cursorMode)
667 ViewportRanges ranges = viewport.getRanges();
668 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
670 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
673 alignPanel.getSeqPanel().seqCanvas.repaint();
679 Help.showHelpWindow();
680 } catch (Exception ex)
682 ex.printStackTrace();
687 boolean toggleSeqs = !evt.isControlDown();
688 boolean toggleCols = !evt.isShiftDown();
689 toggleHiddenRegions(toggleSeqs, toggleCols);
694 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
695 boolean modifyExisting = true; // always modify, don't clear
696 // evt.isShiftDown();
697 boolean invertHighlighted = evt.isAltDown();
698 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
702 case KeyEvent.VK_PAGE_UP:
703 viewport.getRanges().pageUp();
705 case KeyEvent.VK_PAGE_DOWN:
706 viewport.getRanges().pageDown();
712 public void keyReleased(KeyEvent evt)
714 switch (evt.getKeyCode())
716 case KeyEvent.VK_LEFT:
717 if (evt.isAltDown() || !viewport.cursorMode)
719 viewport.firePropertyChange("alignment", null,
720 viewport.getAlignment().getSequences());
724 case KeyEvent.VK_RIGHT:
725 if (evt.isAltDown() || !viewport.cursorMode)
727 viewport.firePropertyChange("alignment", null,
728 viewport.getAlignment().getSequences());
736 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
738 ap.alignFrame = this;
739 avc = new jalview.controller.AlignViewController(this, viewport,
744 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
746 int aSize = alignPanels.size();
748 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
750 if (aSize == 1 && ap.av.viewName == null)
752 this.getContentPane().add(ap, BorderLayout.CENTER);
758 setInitialTabVisible();
761 expandViews.setEnabled(true);
762 gatherViews.setEnabled(true);
763 tabbedPane.addTab(ap.av.viewName, ap);
765 ap.setVisible(false);
770 if (ap.av.isPadGaps())
772 ap.av.getAlignment().padGaps();
774 ap.av.updateConservation(ap);
775 ap.av.updateConsensus(ap);
776 ap.av.updateStrucConsensus(ap);
777 ap.av.initInformationWorker(ap);
781 public void setInitialTabVisible()
783 expandViews.setEnabled(true);
784 gatherViews.setEnabled(true);
785 tabbedPane.setVisible(true);
786 AlignmentPanel first = alignPanels.get(0);
787 tabbedPane.addTab(first.av.viewName, first);
788 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
791 public AlignViewport getViewport()
796 /* Set up intrinsic listeners for dynamically generated GUI bits. */
797 private void addServiceListeners()
799 final java.beans.PropertyChangeListener thisListener;
800 Desktop.instance.addJalviewPropertyChangeListener("services",
801 thisListener = new java.beans.PropertyChangeListener()
804 public void propertyChange(PropertyChangeEvent evt)
806 // // System.out.println("Discoverer property change.");
807 // if (evt.getPropertyName().equals("services"))
809 SwingUtilities.invokeLater(new Runnable()
816 "Rebuild WS Menu for service change");
817 BuildWebServiceMenu();
824 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
827 public void internalFrameClosed(
828 javax.swing.event.InternalFrameEvent evt)
830 // System.out.println("deregistering discoverer listener");
831 Desktop.instance.removeJalviewPropertyChangeListener("services",
833 closeMenuItem_actionPerformed(true);
836 // Finally, build the menu once to get current service state
837 new Thread(new Runnable()
842 BuildWebServiceMenu();
848 * Configure menu items that vary according to whether the alignment is
849 * nucleotide or protein
851 public void setGUINucleotide()
853 AlignmentI al = getViewport().getAlignment();
854 boolean nucleotide = al.isNucleotide();
856 loadVcf.setVisible(nucleotide);
857 showTranslation.setVisible(nucleotide);
858 showReverse.setVisible(nucleotide);
859 showReverseComplement.setVisible(nucleotide);
860 conservationMenuItem.setEnabled(!nucleotide);
862 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
863 showGroupConservation.setEnabled(!nucleotide);
865 showComplementMenuItem
866 .setText(nucleotide ? MessageManager.getString("label.protein")
867 : MessageManager.getString("label.nucleotide"));
871 * set up menus for the current viewport. This may be called after any
872 * operation that affects the data in the current view (selection changed,
873 * etc) to update the menus to reflect the new state.
876 public void setMenusForViewport()
878 setMenusFromViewport(viewport);
882 * Need to call this method when tabs are selected for multiple views, or when
883 * loading from Jalview2XML.java
888 void setMenusFromViewport(AlignViewport av)
890 padGapsMenuitem.setSelected(av.isPadGaps());
891 colourTextMenuItem.setSelected(av.isShowColourText());
892 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
893 modifyPID.setEnabled(abovePIDThreshold.isSelected());
894 conservationMenuItem.setSelected(av.getConservationSelected());
895 modifyConservation.setEnabled(conservationMenuItem.isSelected());
896 seqLimits.setSelected(av.getShowJVSuffix());
897 idRightAlign.setSelected(av.isRightAlignIds());
898 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
899 renderGapsMenuItem.setSelected(av.isRenderGaps());
900 wrapMenuItem.setSelected(av.getWrapAlignment());
901 scaleAbove.setVisible(av.getWrapAlignment());
902 scaleLeft.setVisible(av.getWrapAlignment());
903 scaleRight.setVisible(av.getWrapAlignment());
904 annotationPanelMenuItem.setState(av.isShowAnnotation());
906 * Show/hide annotations only enabled if annotation panel is shown
908 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
909 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
910 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
911 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
912 viewBoxesMenuItem.setSelected(av.getShowBoxes());
913 viewTextMenuItem.setSelected(av.getShowText());
914 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
915 showGroupConsensus.setSelected(av.isShowGroupConsensus());
916 showGroupConservation.setSelected(av.isShowGroupConservation());
917 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
918 showSequenceLogo.setSelected(av.isShowSequenceLogo());
919 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
920 showInformationHistogram.setSelected(av.isShowInformationHistogram());
921 showHMMSequenceLogo.setSelected(av.isShowHMMSequenceLogo());
922 normaliseHMMSequenceLogo.setSelected(av.isNormaliseHMMSequenceLogo());
924 ColourMenuHelper.setColourSelected(colourMenu,
925 av.getGlobalColourScheme());
927 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
928 hiddenMarkers.setState(av.getShowHiddenMarkers());
929 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
930 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
931 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
932 autoCalculate.setSelected(av.autoCalculateConsensus);
933 sortByTree.setSelected(av.sortByTree);
934 listenToViewSelections.setSelected(av.followSelection);
936 showProducts.setEnabled(canShowProducts());
937 setGroovyEnabled(Desktop.getGroovyConsole() != null);
943 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
947 public void setGroovyEnabled(boolean b)
949 runGroovy.setEnabled(b);
952 private IProgressIndicator progressBar;
957 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
960 public void setProgressBar(String message, long id)
962 progressBar.setProgressBar(message, id);
966 public void registerHandler(final long id,
967 final IProgressIndicatorHandler handler)
969 progressBar.registerHandler(id, handler);
974 * @return true if any progress bars are still active
977 public boolean operationInProgress()
979 return progressBar.operationInProgress();
983 public void setStatus(String text)
985 statusBar.setText(text);
989 * Added so Castor Mapping file can obtain Jalview Version
991 public String getVersion()
993 return jalview.bin.Cache.getProperty("VERSION");
996 public FeatureRenderer getFeatureRenderer()
998 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1002 public void fetchSequence_actionPerformed(ActionEvent e)
1004 new jalview.gui.SequenceFetcher(this);
1008 public void addFromFile_actionPerformed(ActionEvent e)
1010 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1014 public void hmmBuild_actionPerformed(boolean withDefaults)
1016 if (!alignmentIsSufficient(1))
1022 * get default parameters, and optionally show a dialog
1023 * to allow them to be modified
1025 ParamDatastoreI store = HMMERParamStore.forBuild(viewport);
1026 List<ArgumentI> args = store.getServiceParameters();
1030 WsParamSetI set = new HMMERPreset();
1031 WsJobParameters params = new WsJobParameters(store, set, args);
1032 if (params.showRunDialog())
1034 args = params.getJobParams();
1038 return; // user cancelled
1041 new Thread(new HMMBuild(this, args)).start();
1045 public void hmmAlign_actionPerformed(boolean withDefaults)
1047 if (!(checkForHMM() && alignmentIsSufficient(2)))
1053 * get default parameters, and optionally show a dialog
1054 * to allow them to be modified
1056 ParamDatastoreI store = HMMERParamStore.forAlign(viewport);
1057 List<ArgumentI> args = store.getServiceParameters();
1061 WsParamSetI set = new HMMERPreset();
1062 WsJobParameters params = new WsJobParameters(store, set, args);
1063 if (params.showRunDialog())
1065 args = params.getJobParams();
1069 return; // user cancelled
1072 new Thread(new HMMAlign(this, args)).start();
1076 public void hmmSearch_actionPerformed(boolean withDefaults)
1084 * get default parameters, and (if requested) show
1085 * dialog to allow modification
1087 ParamDatastoreI store = HMMERParamStore.forSearch(viewport);
1088 List<ArgumentI> args = store.getServiceParameters();
1092 WsParamSetI set = new HMMERPreset();
1093 WsJobParameters params = new WsJobParameters(store, set, args);
1094 if (params.showRunDialog())
1096 args = params.getJobParams();
1100 return; // user cancelled
1103 new Thread(new HMMSearch(this, args)).start();
1104 alignPanel.repaint();
1108 * Checks if the alignment has at least one hidden Markov model, if not shows
1109 * a dialog advising to run hmmbuild or load an HMM profile
1113 private boolean checkForHMM()
1115 if (viewport.getAlignment().getHmmSequences().isEmpty())
1117 JOptionPane.showMessageDialog(this,
1118 MessageManager.getString("warn.no_hmm"));
1125 * Checks if the alignment contains the required number of sequences.
1130 public boolean alignmentIsSufficient(int required)
1132 if (getViewport().getAlignment().getSequences().size() < required)
1134 JOptionPane.showMessageDialog(this,
1135 MessageManager.getString("label.not_enough_sequences"));
1142 * Opens a file browser and adds the selected file, if in Fasta, Stockholm or
1143 * Pfam format, to the list held under preference key "HMMSEARCH_DBS" (as a
1144 * comma-separated list)
1147 public void addDatabase_actionPerformed() throws IOException
1149 if (Cache.getProperty(Preferences.HMMSEARCH_DBS) == null)
1151 Cache.setProperty(Preferences.HMMSEARCH_DBS, "");
1154 String path = openFileChooser(false);
1155 if (path != null && new File(path).exists())
1157 IdentifyFile identifier = new IdentifyFile();
1158 FileFormatI format = identifier.identify(path, DataSourceType.FILE);
1159 if (format == FileFormat.Fasta || format == FileFormat.Stockholm
1160 || format == FileFormat.Pfam)
1162 String currentDbPaths = Cache
1163 .getProperty(Preferences.HMMSEARCH_DBS);
1164 currentDbPaths += Preferences.COMMA + path;
1165 Cache.setProperty(Preferences.HMMSEARCH_DBS, currentDbPaths);
1169 JOptionPane.showMessageDialog(this,
1170 MessageManager.getString("warn.invalid_format"));
1176 * Opens a file chooser, optionally restricted to selecting folders
1177 * (directories) only. Answers the path to the selected file or folder, or
1178 * null if none is chosen.
1183 protected String openFileChooser(boolean forFolder)
1185 // TODO duplicates GPreferences method - relocate to JalviewFileChooser?
1186 String choice = null;
1187 JFileChooser chooser = new JFileChooser();
1190 chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1192 chooser.setDialogTitle(
1193 MessageManager.getString("label.open_local_file"));
1194 chooser.setToolTipText(MessageManager.getString("action.open"));
1196 int value = chooser.showOpenDialog(this);
1198 if (value == JFileChooser.APPROVE_OPTION)
1200 choice = chooser.getSelectedFile().getPath();
1206 public void reload_actionPerformed(ActionEvent e)
1208 if (fileName != null)
1210 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1211 // originating file's format
1212 // TODO: work out how to recover feature settings for correct view(s) when
1213 // file is reloaded.
1214 if (FileFormat.Jalview.equals(currentFileFormat))
1216 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1217 for (int i = 0; i < frames.length; i++)
1219 if (frames[i] instanceof AlignFrame && frames[i] != this
1220 && ((AlignFrame) frames[i]).fileName != null
1221 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1225 frames[i].setSelected(true);
1226 Desktop.instance.closeAssociatedWindows();
1227 } catch (java.beans.PropertyVetoException ex)
1233 Desktop.instance.closeAssociatedWindows();
1235 FileLoader loader = new FileLoader();
1236 DataSourceType protocol = fileName.startsWith("http:")
1237 ? DataSourceType.URL
1238 : DataSourceType.FILE;
1239 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1243 Rectangle bounds = this.getBounds();
1245 FileLoader loader = new FileLoader();
1246 DataSourceType protocol = fileName.startsWith("http:")
1247 ? DataSourceType.URL
1248 : DataSourceType.FILE;
1249 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1250 protocol, currentFileFormat);
1252 newframe.setBounds(bounds);
1253 if (featureSettings != null && featureSettings.isShowing())
1255 final Rectangle fspos = featureSettings.frame.getBounds();
1256 // TODO: need a 'show feature settings' function that takes bounds -
1257 // need to refactor Desktop.addFrame
1258 newframe.featureSettings_actionPerformed(null);
1259 final FeatureSettings nfs = newframe.featureSettings;
1260 SwingUtilities.invokeLater(new Runnable()
1265 nfs.frame.setBounds(fspos);
1268 this.featureSettings.close();
1269 this.featureSettings = null;
1271 this.closeMenuItem_actionPerformed(true);
1277 public void addFromText_actionPerformed(ActionEvent e)
1280 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1284 public void addFromURL_actionPerformed(ActionEvent e)
1286 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1290 public void save_actionPerformed(ActionEvent e)
1292 if (fileName == null || (currentFileFormat == null)
1293 || fileName.startsWith("http"))
1295 saveAs_actionPerformed(null);
1299 saveAlignment(fileName, currentFileFormat);
1310 public void saveAs_actionPerformed(ActionEvent e)
1312 String format = currentFileFormat == null ? null
1313 : currentFileFormat.getName();
1314 JalviewFileChooser chooser = JalviewFileChooser
1315 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1317 chooser.setFileView(new JalviewFileView());
1318 chooser.setDialogTitle(
1319 MessageManager.getString("label.save_alignment_to_file"));
1320 chooser.setToolTipText(MessageManager.getString("action.save"));
1322 int value = chooser.showSaveDialog(this);
1324 if (value == JalviewFileChooser.APPROVE_OPTION)
1326 currentFileFormat = chooser.getSelectedFormat();
1327 while (currentFileFormat == null)
1329 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1330 MessageManager.getString(
1331 "label.select_file_format_before_saving"),
1332 MessageManager.getString("label.file_format_not_specified"),
1333 JvOptionPane.WARNING_MESSAGE);
1334 currentFileFormat = chooser.getSelectedFormat();
1335 value = chooser.showSaveDialog(this);
1336 if (value != JalviewFileChooser.APPROVE_OPTION)
1342 fileName = chooser.getSelectedFile().getPath();
1344 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1346 Cache.setProperty("LAST_DIRECTORY", fileName);
1347 saveAlignment(fileName, currentFileFormat);
1351 public boolean saveAlignment(String file, FileFormatI format)
1353 boolean success = true;
1355 if (FileFormat.Jalview.equals(format))
1357 String shortName = title;
1359 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1361 shortName = shortName.substring(
1362 shortName.lastIndexOf(java.io.File.separatorChar) + 1);
1365 success = new Jalview2XML().saveAlignment(this, file, shortName);
1367 statusBar.setText(MessageManager.formatMessage(
1368 "label.successfully_saved_to_file_in_format", new Object[]
1369 { fileName, format }));
1374 AlignmentExportData exportData = getAlignmentForExport(format,
1376 if (exportData.getSettings().isCancelled())
1380 FormatAdapter f = new FormatAdapter(alignPanel,
1381 exportData.getSettings());
1382 String output = f.formatSequences(format, exportData.getAlignment(), // class
1386 // occur in the distant future
1387 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1388 f.getCacheSuffixDefault(format),
1389 viewport.getAlignment().getHiddenColumns());
1399 PrintWriter out = new PrintWriter(new FileWriter(file));
1403 this.setTitle(file);
1404 statusBar.setText(MessageManager.formatMessage(
1405 "label.successfully_saved_to_file_in_format", new Object[]
1406 { fileName, format.getName() }));
1407 } catch (Exception ex)
1410 ex.printStackTrace();
1417 JvOptionPane.showInternalMessageDialog(this, MessageManager
1418 .formatMessage("label.couldnt_save_file", new Object[]
1420 MessageManager.getString("label.error_saving_file"),
1421 JvOptionPane.WARNING_MESSAGE);
1427 private void warningMessage(String warning, String title)
1429 if (new jalview.util.Platform().isHeadless())
1431 System.err.println("Warning: " + title + "\nWarning: " + warning);
1436 JvOptionPane.showInternalMessageDialog(this, warning, title,
1437 JvOptionPane.WARNING_MESSAGE);
1449 protected void outputText_actionPerformed(ActionEvent e)
1451 FileFormatI fileFormat = FileFormats.getInstance()
1452 .forName(e.getActionCommand());
1453 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1455 if (exportData.getSettings().isCancelled())
1459 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1460 cap.setForInput(null);
1463 FileFormatI format = fileFormat;
1464 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1465 .formatSequences(format, exportData.getAlignment(),
1466 exportData.getOmitHidden(),
1467 exportData.getStartEndPostions(),
1468 viewport.getAlignment().getHiddenColumns()));
1469 Desktop.addInternalFrame(cap, MessageManager
1470 .formatMessage("label.alignment_output_command", new Object[]
1471 { e.getActionCommand() }), 600, 500);
1472 } catch (OutOfMemoryError oom)
1474 new OOMWarning("Outputting alignment as " + e.getActionCommand(),
1481 public static AlignmentExportData getAlignmentForExport(
1482 FileFormatI format, AlignViewportI viewport,
1483 AlignExportSettingI exportSettings)
1485 AlignmentI alignmentToExport = null;
1486 AlignExportSettingI settings = exportSettings;
1487 String[] omitHidden = null;
1489 HiddenSequences hiddenSeqs = viewport.getAlignment()
1490 .getHiddenSequences();
1492 alignmentToExport = viewport.getAlignment();
1494 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1495 if (settings == null)
1497 settings = new AlignExportSettings(hasHiddenSeqs,
1498 viewport.hasHiddenColumns(), format);
1500 // settings.isExportAnnotations();
1502 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1504 omitHidden = viewport.getViewAsString(false,
1505 settings.isExportHiddenSequences());
1508 int[] alignmentStartEnd = new int[2];
1509 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1511 alignmentToExport = hiddenSeqs.getFullAlignment();
1515 alignmentToExport = viewport.getAlignment();
1517 alignmentStartEnd = viewport.getAlignment().getHiddenColumns()
1518 .getVisibleStartAndEndIndex(alignmentToExport.getWidth());
1519 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1520 omitHidden, alignmentStartEnd, settings);
1531 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1533 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1534 htmlSVG.exportHTML(null);
1538 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1540 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1541 bjs.exportHTML(null);
1544 public void createImageMap(File file, String image)
1546 alignPanel.makePNGImageMap(file, image);
1556 public void createPNG(File f)
1558 alignPanel.makePNG(f);
1568 public void createEPS(File f)
1570 alignPanel.makeEPS(f);
1574 public void createPDF(File f)
1576 alignPanel.makePDF(f);
1580 public void createSVG(File f)
1582 alignPanel.makeSVG(f);
1586 public void pageSetup_actionPerformed(ActionEvent e)
1588 PrinterJob printJob = PrinterJob.getPrinterJob();
1589 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1599 public void printMenuItem_actionPerformed(ActionEvent e)
1601 // Putting in a thread avoids Swing painting problems
1602 PrintThread thread = new PrintThread(alignPanel);
1607 public void exportFeatures_actionPerformed(ActionEvent e)
1609 new AnnotationExporter(alignPanel).exportFeatures();
1613 public void exportAnnotations_actionPerformed(ActionEvent e)
1615 new AnnotationExporter(alignPanel).exportAnnotations();
1619 public void associatedData_actionPerformed(ActionEvent e)
1620 throws IOException, InterruptedException
1622 // Pick the tree file
1623 JalviewFileChooser chooser = new JalviewFileChooser(
1624 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1625 chooser.setFileView(new JalviewFileView());
1626 chooser.setDialogTitle(
1627 MessageManager.getString("label.load_jalview_annotations"));
1628 chooser.setToolTipText(
1629 MessageManager.getString("label.load_jalview_annotations"));
1631 int value = chooser.showOpenDialog(null);
1633 if (value == JalviewFileChooser.APPROVE_OPTION)
1635 String choice = chooser.getSelectedFile().getPath();
1636 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1637 loadJalviewDataFile(choice, null, null, null);
1643 * Close the current view or all views in the alignment frame. If the frame
1644 * only contains one view then the alignment will be removed from memory.
1646 * @param closeAllTabs
1649 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1651 if (alignPanels != null && alignPanels.size() < 2)
1653 closeAllTabs = true;
1658 if (alignPanels != null)
1662 if (this.isClosed())
1664 // really close all the windows - otherwise wait till
1665 // setClosed(true) is called
1666 for (int i = 0; i < alignPanels.size(); i++)
1668 AlignmentPanel ap = alignPanels.get(i);
1675 closeView(alignPanel);
1682 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1683 * be called recursively, with the frame now in 'closed' state
1685 this.setClosed(true);
1687 } catch (Exception ex)
1689 ex.printStackTrace();
1694 * Close the specified panel and close up tabs appropriately.
1696 * @param panelToClose
1698 public void closeView(AlignmentPanel panelToClose)
1700 int index = tabbedPane.getSelectedIndex();
1701 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1702 alignPanels.remove(panelToClose);
1703 panelToClose.closePanel();
1704 panelToClose = null;
1706 tabbedPane.removeTabAt(closedindex);
1707 tabbedPane.validate();
1709 if (index > closedindex || index == tabbedPane.getTabCount())
1711 // modify currently selected tab index if necessary.
1715 this.tabSelectionChanged(index);
1721 void updateEditMenuBar()
1724 if (viewport.getHistoryList().size() > 0)
1726 undoMenuItem.setEnabled(true);
1727 CommandI command = viewport.getHistoryList().peek();
1728 undoMenuItem.setText(MessageManager
1729 .formatMessage("label.undo_command", new Object[]
1730 { command.getDescription() }));
1734 undoMenuItem.setEnabled(false);
1735 undoMenuItem.setText(MessageManager.getString("action.undo"));
1738 if (viewport.getRedoList().size() > 0)
1740 redoMenuItem.setEnabled(true);
1742 CommandI command = viewport.getRedoList().peek();
1743 redoMenuItem.setText(MessageManager
1744 .formatMessage("label.redo_command", new Object[]
1745 { command.getDescription() }));
1749 redoMenuItem.setEnabled(false);
1750 redoMenuItem.setText(MessageManager.getString("action.redo"));
1755 public void addHistoryItem(CommandI command)
1757 if (command.getSize() > 0)
1759 viewport.addToHistoryList(command);
1760 viewport.clearRedoList();
1761 updateEditMenuBar();
1762 viewport.updateHiddenColumns();
1763 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1764 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1765 // viewport.getColumnSelection()
1766 // .getHiddenColumns().size() > 0);
1772 * @return alignment objects for all views
1774 AlignmentI[] getViewAlignments()
1776 if (alignPanels != null)
1778 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1780 for (AlignmentPanel ap : alignPanels)
1782 als[i++] = ap.av.getAlignment();
1786 if (viewport != null)
1788 return new AlignmentI[] { viewport.getAlignment() };
1800 protected void undoMenuItem_actionPerformed(ActionEvent e)
1802 if (viewport.getHistoryList().isEmpty())
1806 CommandI command = viewport.getHistoryList().pop();
1807 viewport.addToRedoList(command);
1808 command.undoCommand(getViewAlignments());
1810 AlignmentViewport originalSource = getOriginatingSource(command);
1811 updateEditMenuBar();
1813 if (originalSource != null)
1815 if (originalSource != viewport)
1818 "Implementation worry: mismatch of viewport origin for undo");
1820 originalSource.updateHiddenColumns();
1821 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1823 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1824 // viewport.getColumnSelection()
1825 // .getHiddenColumns().size() > 0);
1826 originalSource.firePropertyChange("alignment", null,
1827 originalSource.getAlignment().getSequences());
1838 protected void redoMenuItem_actionPerformed(ActionEvent e)
1840 if (viewport.getRedoList().size() < 1)
1845 CommandI command = viewport.getRedoList().pop();
1846 viewport.addToHistoryList(command);
1847 command.doCommand(getViewAlignments());
1849 AlignmentViewport originalSource = getOriginatingSource(command);
1850 updateEditMenuBar();
1852 if (originalSource != null)
1855 if (originalSource != viewport)
1858 "Implementation worry: mismatch of viewport origin for redo");
1860 originalSource.updateHiddenColumns();
1861 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1863 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1864 // viewport.getColumnSelection()
1865 // .getHiddenColumns().size() > 0);
1866 originalSource.firePropertyChange("alignment", null,
1867 originalSource.getAlignment().getSequences());
1871 AlignmentViewport getOriginatingSource(CommandI command)
1873 AlignmentViewport originalSource = null;
1874 // For sequence removal and addition, we need to fire
1875 // the property change event FROM the viewport where the
1876 // original alignment was altered
1877 AlignmentI al = null;
1878 if (command instanceof EditCommand)
1880 EditCommand editCommand = (EditCommand) command;
1881 al = editCommand.getAlignment();
1882 List<Component> comps = PaintRefresher.components
1883 .get(viewport.getSequenceSetId());
1885 for (Component comp : comps)
1887 if (comp instanceof AlignmentPanel)
1889 if (al == ((AlignmentPanel) comp).av.getAlignment())
1891 originalSource = ((AlignmentPanel) comp).av;
1898 if (originalSource == null)
1900 // The original view is closed, we must validate
1901 // the current view against the closed view first
1904 PaintRefresher.validateSequences(al, viewport.getAlignment());
1907 originalSource = viewport;
1910 return originalSource;
1919 public void moveSelectedSequences(boolean up)
1921 SequenceGroup sg = viewport.getSelectionGroup();
1927 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1928 viewport.getHiddenRepSequences(), up);
1929 alignPanel.paintAlignment(true, false);
1932 synchronized void slideSequences(boolean right, int size)
1934 List<SequenceI> sg = new ArrayList<>();
1935 if (viewport.cursorMode)
1937 sg.add(viewport.getAlignment()
1938 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1940 else if (viewport.getSelectionGroup() != null
1941 && viewport.getSelectionGroup().getSize() != viewport
1942 .getAlignment().getHeight())
1944 sg = viewport.getSelectionGroup()
1945 .getSequences(viewport.getHiddenRepSequences());
1953 List<SequenceI> invertGroup = new ArrayList<>();
1955 for (SequenceI seq : viewport.getAlignment().getSequences())
1957 if (!sg.contains(seq))
1959 invertGroup.add(seq);
1963 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1965 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1966 for (int i = 0; i < invertGroup.size(); i++)
1968 seqs2[i] = invertGroup.get(i);
1971 SlideSequencesCommand ssc;
1974 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1975 viewport.getGapCharacter());
1979 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1980 viewport.getGapCharacter());
1983 int groupAdjustment = 0;
1984 if (ssc.getGapsInsertedBegin() && right)
1986 if (viewport.cursorMode)
1988 alignPanel.getSeqPanel().moveCursor(size, 0);
1992 groupAdjustment = size;
1995 else if (!ssc.getGapsInsertedBegin() && !right)
1997 if (viewport.cursorMode)
1999 alignPanel.getSeqPanel().moveCursor(-size, 0);
2003 groupAdjustment = -size;
2007 if (groupAdjustment != 0)
2009 viewport.getSelectionGroup().setStartRes(
2010 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
2011 viewport.getSelectionGroup().setEndRes(
2012 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
2016 * just extend the last slide command if compatible; but not if in
2017 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
2019 boolean appendHistoryItem = false;
2020 Deque<CommandI> historyList = viewport.getHistoryList();
2021 boolean inSplitFrame = getSplitViewContainer() != null;
2022 if (!inSplitFrame && historyList != null && historyList.size() > 0
2023 && historyList.peek() instanceof SlideSequencesCommand)
2025 appendHistoryItem = ssc.appendSlideCommand(
2026 (SlideSequencesCommand) historyList.peek());
2029 if (!appendHistoryItem)
2031 addHistoryItem(ssc);
2044 protected void copy_actionPerformed(ActionEvent e)
2046 if (viewport.getSelectionGroup() == null)
2050 // TODO: preserve the ordering of displayed alignment annotation in any
2051 // internal paste (particularly sequence associated annotation)
2052 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2053 String[] omitHidden = null;
2055 if (viewport.hasHiddenColumns())
2057 omitHidden = viewport.getViewAsString(true);
2060 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2061 seqs, omitHidden, null);
2063 StringSelection ss = new StringSelection(output);
2067 jalview.gui.Desktop.internalCopy = true;
2068 // Its really worth setting the clipboard contents
2069 // to empty before setting the large StringSelection!!
2070 Toolkit.getDefaultToolkit().getSystemClipboard()
2071 .setContents(new StringSelection(""), null);
2073 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2075 } catch (OutOfMemoryError er)
2077 new OOMWarning("copying region", er);
2081 HiddenColumns hiddenColumns = null;
2082 if (viewport.hasHiddenColumns())
2084 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2085 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2087 // create new HiddenColumns object with copy of hidden regions
2088 // between startRes and endRes, offset by startRes
2089 hiddenColumns = new HiddenColumns(
2090 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2091 hiddenCutoff, hiddenOffset);
2094 Desktop.jalviewClipboard = new Object[] { seqs,
2095 viewport.getAlignment().getDataset(), hiddenColumns };
2096 statusBar.setText(MessageManager.formatMessage(
2097 "label.copied_sequences_to_clipboard", new Object[]
2098 { Integer.valueOf(seqs.length).toString() }));
2106 * @throws InterruptedException
2107 * @throws IOException
2110 protected void pasteNew_actionPerformed(ActionEvent e)
2111 throws IOException, InterruptedException
2121 * @throws InterruptedException
2122 * @throws IOException
2125 protected void pasteThis_actionPerformed(ActionEvent e)
2126 throws IOException, InterruptedException
2132 * Paste contents of Jalview clipboard
2134 * @param newAlignment
2135 * true to paste to a new alignment, otherwise add to this.
2136 * @throws InterruptedException
2137 * @throws IOException
2139 void paste(boolean newAlignment) throws IOException, InterruptedException
2141 boolean externalPaste = true;
2144 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2145 Transferable contents = c.getContents(this);
2147 if (contents == null)
2156 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2157 if (str.length() < 1)
2162 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2164 } catch (OutOfMemoryError er)
2166 new OOMWarning("Out of memory pasting sequences!!", er);
2170 SequenceI[] sequences;
2171 boolean annotationAdded = false;
2172 AlignmentI alignment = null;
2174 if (Desktop.jalviewClipboard != null)
2176 // The clipboard was filled from within Jalview, we must use the
2178 // And dataset from the copied alignment
2179 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2180 // be doubly sure that we create *new* sequence objects.
2181 sequences = new SequenceI[newseq.length];
2182 for (int i = 0; i < newseq.length; i++)
2184 sequences[i] = new Sequence(newseq[i]);
2186 alignment = new Alignment(sequences);
2187 externalPaste = false;
2191 // parse the clipboard as an alignment.
2192 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2194 sequences = alignment.getSequencesArray();
2198 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2204 if (Desktop.jalviewClipboard != null)
2206 // dataset is inherited
2207 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2211 // new dataset is constructed
2212 alignment.setDataset(null);
2214 alwidth = alignment.getWidth() + 1;
2218 AlignmentI pastedal = alignment; // preserve pasted alignment object
2219 // Add pasted sequences and dataset into existing alignment.
2220 alignment = viewport.getAlignment();
2221 alwidth = alignment.getWidth() + 1;
2222 // decide if we need to import sequences from an existing dataset
2223 boolean importDs = Desktop.jalviewClipboard != null
2224 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2225 // importDs==true instructs us to copy over new dataset sequences from
2226 // an existing alignment
2227 Vector newDs = (importDs) ? new Vector() : null; // used to create
2228 // minimum dataset set
2230 for (int i = 0; i < sequences.length; i++)
2234 newDs.addElement(null);
2236 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2238 if (importDs && ds != null)
2240 if (!newDs.contains(ds))
2242 newDs.setElementAt(ds, i);
2243 ds = new Sequence(ds);
2244 // update with new dataset sequence
2245 sequences[i].setDatasetSequence(ds);
2249 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2254 // copy and derive new dataset sequence
2255 sequences[i] = sequences[i].deriveSequence();
2256 alignment.getDataset()
2257 .addSequence(sequences[i].getDatasetSequence());
2258 // TODO: avoid creation of duplicate dataset sequences with a
2259 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2261 alignment.addSequence(sequences[i]); // merges dataset
2265 newDs.clear(); // tidy up
2267 if (alignment.getAlignmentAnnotation() != null)
2269 for (AlignmentAnnotation alan : alignment
2270 .getAlignmentAnnotation())
2272 if (alan.graphGroup > fgroup)
2274 fgroup = alan.graphGroup;
2278 if (pastedal.getAlignmentAnnotation() != null)
2280 // Add any annotation attached to alignment.
2281 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2282 for (int i = 0; i < alann.length; i++)
2284 annotationAdded = true;
2285 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2287 AlignmentAnnotation newann = new AlignmentAnnotation(
2289 if (newann.graphGroup > -1)
2291 if (newGraphGroups.size() <= newann.graphGroup
2292 || newGraphGroups.get(newann.graphGroup) == null)
2294 for (int q = newGraphGroups
2295 .size(); q <= newann.graphGroup; q++)
2297 newGraphGroups.add(q, null);
2299 newGraphGroups.set(newann.graphGroup,
2300 new Integer(++fgroup));
2302 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2306 newann.padAnnotation(alwidth);
2307 alignment.addAnnotation(newann);
2317 addHistoryItem(new EditCommand(
2318 MessageManager.getString("label.add_sequences"),
2319 Action.PASTE, sequences, 0, alignment.getWidth(),
2322 // Add any annotations attached to sequences
2323 for (int i = 0; i < sequences.length; i++)
2325 if (sequences[i].getAnnotation() != null)
2327 AlignmentAnnotation newann;
2328 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2330 annotationAdded = true;
2331 newann = sequences[i].getAnnotation()[a];
2332 newann.adjustForAlignment();
2333 newann.padAnnotation(alwidth);
2334 if (newann.graphGroup > -1)
2336 if (newann.graphGroup > -1)
2338 if (newGraphGroups.size() <= newann.graphGroup
2339 || newGraphGroups.get(newann.graphGroup) == null)
2341 for (int q = newGraphGroups
2342 .size(); q <= newann.graphGroup; q++)
2344 newGraphGroups.add(q, null);
2346 newGraphGroups.set(newann.graphGroup,
2347 new Integer(++fgroup));
2349 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2353 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2357 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2365 // propagate alignment changed.
2366 viewport.getRanges().setEndSeq(alignment.getHeight());
2367 if (annotationAdded)
2369 // Duplicate sequence annotation in all views.
2370 AlignmentI[] alview = this.getViewAlignments();
2371 for (int i = 0; i < sequences.length; i++)
2373 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2378 for (int avnum = 0; avnum < alview.length; avnum++)
2380 if (alview[avnum] != alignment)
2382 // duplicate in a view other than the one with input focus
2383 int avwidth = alview[avnum].getWidth() + 1;
2384 // this relies on sann being preserved after we
2385 // modify the sequence's annotation array for each duplication
2386 for (int a = 0; a < sann.length; a++)
2388 AlignmentAnnotation newann = new AlignmentAnnotation(
2390 sequences[i].addAlignmentAnnotation(newann);
2391 newann.padAnnotation(avwidth);
2392 alview[avnum].addAnnotation(newann); // annotation was
2393 // duplicated earlier
2394 // TODO JAL-1145 graphGroups are not updated for sequence
2395 // annotation added to several views. This may cause
2397 alview[avnum].setAnnotationIndex(newann, a);
2402 buildSortByAnnotationScoresMenu();
2404 viewport.firePropertyChange("alignment", null,
2405 alignment.getSequences());
2406 if (alignPanels != null)
2408 for (AlignmentPanel ap : alignPanels)
2410 ap.validateAnnotationDimensions(false);
2415 alignPanel.validateAnnotationDimensions(false);
2421 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2423 String newtitle = new String("Copied sequences");
2425 if (Desktop.jalviewClipboard != null
2426 && Desktop.jalviewClipboard[2] != null)
2428 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2429 af.viewport.setHiddenColumns(hc);
2432 // >>>This is a fix for the moment, until a better solution is
2434 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2435 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2436 .getFeatureRenderer());
2438 // TODO: maintain provenance of an alignment, rather than just make the
2439 // title a concatenation of operations.
2442 if (title.startsWith("Copied sequences"))
2448 newtitle = newtitle.concat("- from " + title);
2453 newtitle = new String("Pasted sequences");
2456 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2461 } catch (Exception ex)
2463 ex.printStackTrace();
2464 System.out.println("Exception whilst pasting: " + ex);
2465 // could be anything being pasted in here
2470 protected void expand_newalign(ActionEvent e)
2474 AlignmentI alignment = AlignmentUtils
2475 .expandContext(getViewport().getAlignment(), -1);
2476 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2478 String newtitle = new String("Flanking alignment");
2480 if (Desktop.jalviewClipboard != null
2481 && Desktop.jalviewClipboard[2] != null)
2483 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2484 af.viewport.setHiddenColumns(hc);
2487 // >>>This is a fix for the moment, until a better solution is
2489 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2490 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2491 .getFeatureRenderer());
2493 // TODO: maintain provenance of an alignment, rather than just make the
2494 // title a concatenation of operations.
2496 if (title.startsWith("Copied sequences"))
2502 newtitle = newtitle.concat("- from " + title);
2506 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2508 } catch (Exception ex)
2510 ex.printStackTrace();
2511 System.out.println("Exception whilst pasting: " + ex);
2512 // could be anything being pasted in here
2513 } catch (OutOfMemoryError oom)
2515 new OOMWarning("Viewing flanking region of alignment", oom);
2526 protected void cut_actionPerformed(ActionEvent e)
2528 copy_actionPerformed(null);
2529 delete_actionPerformed(null);
2539 protected void delete_actionPerformed(ActionEvent evt)
2542 SequenceGroup sg = viewport.getSelectionGroup();
2549 * If the cut affects all sequences, warn, remove highlighted columns
2551 if (sg.getSize() == viewport.getAlignment().getHeight())
2553 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2554 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2555 if (isEntireAlignWidth)
2557 int confirm = JvOptionPane.showConfirmDialog(this,
2558 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2559 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2560 JvOptionPane.OK_CANCEL_OPTION);
2562 if (confirm == JvOptionPane.CANCEL_OPTION
2563 || confirm == JvOptionPane.CLOSED_OPTION)
2568 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2569 sg.getEndRes() + 1);
2571 SequenceI[] cut = sg.getSequences()
2572 .toArray(new SequenceI[sg.getSize()]);
2574 addHistoryItem(new EditCommand(
2575 MessageManager.getString("label.cut_sequences"), Action.CUT,
2576 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2577 viewport.getAlignment()));
2579 viewport.setSelectionGroup(null);
2580 viewport.sendSelection();
2581 viewport.getAlignment().deleteGroup(sg);
2583 viewport.firePropertyChange("alignment", null,
2584 viewport.getAlignment().getSequences());
2585 if (viewport.getAlignment().getHeight() < 1)
2589 this.setClosed(true);
2590 } catch (Exception ex)
2603 protected void deleteGroups_actionPerformed(ActionEvent e)
2605 if (avc.deleteGroups())
2607 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2608 alignPanel.updateAnnotation();
2609 alignPanel.paintAlignment(true, true);
2620 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2622 SequenceGroup sg = new SequenceGroup();
2624 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2626 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2629 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2630 viewport.setSelectionGroup(sg);
2631 viewport.sendSelection();
2632 // JAL-2034 - should delegate to
2633 // alignPanel to decide if overview needs
2635 alignPanel.paintAlignment(false, false);
2636 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2646 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2648 if (viewport.cursorMode)
2650 alignPanel.getSeqPanel().keyboardNo1 = null;
2651 alignPanel.getSeqPanel().keyboardNo2 = null;
2653 viewport.setSelectionGroup(null);
2654 viewport.getColumnSelection().clear();
2655 viewport.setSelectionGroup(null);
2656 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2657 // JAL-2034 - should delegate to
2658 // alignPanel to decide if overview needs
2660 alignPanel.paintAlignment(false, false);
2661 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2662 viewport.sendSelection();
2672 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2674 SequenceGroup sg = viewport.getSelectionGroup();
2678 selectAllSequenceMenuItem_actionPerformed(null);
2683 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2685 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2687 // JAL-2034 - should delegate to
2688 // alignPanel to decide if overview needs
2691 alignPanel.paintAlignment(true, false);
2692 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2693 viewport.sendSelection();
2697 public void invertColSel_actionPerformed(ActionEvent e)
2699 viewport.invertColumnSelection();
2700 alignPanel.paintAlignment(true, false);
2701 viewport.sendSelection();
2711 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2713 trimAlignment(true);
2723 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2725 trimAlignment(false);
2728 void trimAlignment(boolean trimLeft)
2730 ColumnSelection colSel = viewport.getColumnSelection();
2733 if (!colSel.isEmpty())
2737 column = colSel.getMin();
2741 column = colSel.getMax();
2745 if (viewport.getSelectionGroup() != null)
2747 seqs = viewport.getSelectionGroup()
2748 .getSequencesAsArray(viewport.getHiddenRepSequences());
2752 seqs = viewport.getAlignment().getSequencesArray();
2755 TrimRegionCommand trimRegion;
2758 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2759 column, viewport.getAlignment());
2760 viewport.getRanges().setStartRes(0);
2764 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2765 column, viewport.getAlignment());
2768 statusBar.setText(MessageManager
2769 .formatMessage("label.removed_columns", new String[]
2770 { Integer.valueOf(trimRegion.getSize()).toString() }));
2772 addHistoryItem(trimRegion);
2774 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2776 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2777 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2779 viewport.getAlignment().deleteGroup(sg);
2783 viewport.firePropertyChange("alignment", null,
2784 viewport.getAlignment().getSequences());
2795 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2797 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2800 if (viewport.getSelectionGroup() != null)
2802 seqs = viewport.getSelectionGroup()
2803 .getSequencesAsArray(viewport.getHiddenRepSequences());
2804 start = viewport.getSelectionGroup().getStartRes();
2805 end = viewport.getSelectionGroup().getEndRes();
2809 seqs = viewport.getAlignment().getSequencesArray();
2812 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2813 "Remove Gapped Columns", seqs, start, end,
2814 viewport.getAlignment());
2816 addHistoryItem(removeGapCols);
2818 statusBar.setText(MessageManager
2819 .formatMessage("label.removed_empty_columns", new Object[]
2820 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2822 // This is to maintain viewport position on first residue
2823 // of first sequence
2824 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2825 ViewportRanges ranges = viewport.getRanges();
2826 int startRes = seq.findPosition(ranges.getStartRes());
2827 // ShiftList shifts;
2828 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2829 // edit.alColumnChanges=shifts.getInverse();
2830 // if (viewport.hasHiddenColumns)
2831 // viewport.getColumnSelection().compensateForEdits(shifts);
2832 ranges.setStartRes(seq.findIndex(startRes) - 1);
2833 viewport.firePropertyChange("alignment", null,
2834 viewport.getAlignment().getSequences());
2845 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2847 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2850 if (viewport.getSelectionGroup() != null)
2852 seqs = viewport.getSelectionGroup()
2853 .getSequencesAsArray(viewport.getHiddenRepSequences());
2854 start = viewport.getSelectionGroup().getStartRes();
2855 end = viewport.getSelectionGroup().getEndRes();
2859 seqs = viewport.getAlignment().getSequencesArray();
2862 // This is to maintain viewport position on first residue
2863 // of first sequence
2864 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2865 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2867 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2868 viewport.getAlignment()));
2870 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2872 viewport.firePropertyChange("alignment", null,
2873 viewport.getAlignment().getSequences());
2884 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2886 viewport.setPadGaps(padGapsMenuitem.isSelected());
2887 viewport.firePropertyChange("alignment", null,
2888 viewport.getAlignment().getSequences());
2898 public void findMenuItem_actionPerformed(ActionEvent e)
2904 * Create a new view of the current alignment.
2907 public void newView_actionPerformed(ActionEvent e)
2909 newView(null, true);
2913 * Creates and shows a new view of the current alignment.
2916 * title of newly created view; if null, one will be generated
2917 * @param copyAnnotation
2918 * if true then duplicate all annnotation, groups and settings
2919 * @return new alignment panel, already displayed.
2921 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2924 * Create a new AlignmentPanel (with its own, new Viewport)
2926 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel);
2927 if (!copyAnnotation)
2930 * remove all groups and annotation except for the automatic stuff
2932 newap.av.getAlignment().deleteAllGroups();
2933 newap.av.getAlignment().deleteAllAnnotations(false);
2936 newap.av.setGatherViewsHere(false);
2938 if (viewport.viewName == null)
2940 viewport.viewName = MessageManager
2941 .getString("label.view_name_original");
2945 * Views share the same edits undo and redo stacks
2947 newap.av.setHistoryList(viewport.getHistoryList());
2948 newap.av.setRedoList(viewport.getRedoList());
2951 * Views share the same mappings; need to deregister any new mappings
2952 * created by copyAlignPanel, and register the new reference to the shared
2955 newap.av.replaceMappings(viewport.getAlignment());
2958 * start up cDNA consensus (if applicable) now mappings are in place
2960 if (newap.av.initComplementConsensus())
2962 newap.refresh(true); // adjust layout of annotations
2965 newap.av.viewName = getNewViewName(viewTitle);
2967 addAlignmentPanel(newap, true);
2968 newap.alignmentChanged();
2970 if (alignPanels.size() == 2)
2972 viewport.setGatherViewsHere(true);
2974 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2979 * Make a new name for the view, ensuring it is unique within the current
2980 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2981 * these now use viewId. Unique view names are still desirable for usability.)
2986 protected String getNewViewName(String viewTitle)
2988 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2989 boolean addFirstIndex = false;
2990 if (viewTitle == null || viewTitle.trim().length() == 0)
2992 viewTitle = MessageManager.getString("action.view");
2993 addFirstIndex = true;
2997 index = 1;// we count from 1 if given a specific name
2999 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
3001 List<Component> comps = PaintRefresher.components
3002 .get(viewport.getSequenceSetId());
3004 List<String> existingNames = getExistingViewNames(comps);
3006 while (existingNames.contains(newViewName))
3008 newViewName = viewTitle + " " + (++index);
3014 * Returns a list of distinct view names found in the given list of
3015 * components. View names are held on the viewport of an AlignmentPanel.
3020 protected List<String> getExistingViewNames(List<Component> comps)
3022 List<String> existingNames = new ArrayList<>();
3023 for (Component comp : comps)
3025 if (comp instanceof AlignmentPanel)
3027 AlignmentPanel ap = (AlignmentPanel) comp;
3028 if (!existingNames.contains(ap.av.viewName))
3030 existingNames.add(ap.av.viewName);
3034 return existingNames;
3038 * Explode tabbed views into separate windows.
3041 public void expandViews_actionPerformed(ActionEvent e)
3043 Desktop.explodeViews(this);
3047 * Gather views in separate windows back into a tabbed presentation.
3050 public void gatherViews_actionPerformed(ActionEvent e)
3052 Desktop.instance.gatherViews(this);
3062 public void font_actionPerformed(ActionEvent e)
3064 new FontChooser(alignPanel);
3074 protected void seqLimit_actionPerformed(ActionEvent e)
3076 viewport.setShowJVSuffix(seqLimits.isSelected());
3078 alignPanel.getIdPanel().getIdCanvas()
3079 .setPreferredSize(alignPanel.calculateIdWidth());
3080 alignPanel.paintAlignment(true, false);
3084 public void idRightAlign_actionPerformed(ActionEvent e)
3086 viewport.setRightAlignIds(idRightAlign.isSelected());
3087 alignPanel.paintAlignment(false, false);
3091 public void centreColumnLabels_actionPerformed(ActionEvent e)
3093 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3094 alignPanel.paintAlignment(false, false);
3100 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3103 protected void followHighlight_actionPerformed()
3106 * Set the 'follow' flag on the Viewport (and scroll to position if now
3109 final boolean state = this.followHighlightMenuItem.getState();
3110 viewport.setFollowHighlight(state);
3113 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
3124 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3126 viewport.setColourText(colourTextMenuItem.isSelected());
3127 alignPanel.paintAlignment(false, false);
3137 public void wrapMenuItem_actionPerformed(ActionEvent e)
3139 scaleAbove.setVisible(wrapMenuItem.isSelected());
3140 scaleLeft.setVisible(wrapMenuItem.isSelected());
3141 scaleRight.setVisible(wrapMenuItem.isSelected());
3142 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3143 alignPanel.updateLayout();
3147 public void showAllSeqs_actionPerformed(ActionEvent e)
3149 viewport.showAllHiddenSeqs();
3153 public void showAllColumns_actionPerformed(ActionEvent e)
3155 viewport.showAllHiddenColumns();
3156 alignPanel.paintAlignment(true, true);
3157 viewport.sendSelection();
3161 public void hideSelSequences_actionPerformed(ActionEvent e)
3163 viewport.hideAllSelectedSeqs();
3167 * called by key handler and the hide all/show all menu items
3172 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3175 boolean hide = false;
3176 SequenceGroup sg = viewport.getSelectionGroup();
3177 if (!toggleSeqs && !toggleCols)
3179 // Hide everything by the current selection - this is a hack - we do the
3180 // invert and then hide
3181 // first check that there will be visible columns after the invert.
3182 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3183 && sg.getStartRes() <= sg.getEndRes()))
3185 // now invert the sequence set, if required - empty selection implies
3186 // that no hiding is required.
3189 invertSequenceMenuItem_actionPerformed(null);
3190 sg = viewport.getSelectionGroup();
3194 viewport.expandColSelection(sg, true);
3195 // finally invert the column selection and get the new sequence
3197 invertColSel_actionPerformed(null);
3204 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3206 hideSelSequences_actionPerformed(null);
3209 else if (!(toggleCols && viewport.hasSelectedColumns()))
3211 showAllSeqs_actionPerformed(null);
3217 if (viewport.hasSelectedColumns())
3219 hideSelColumns_actionPerformed(null);
3222 viewport.setSelectionGroup(sg);
3227 showAllColumns_actionPerformed(null);
3236 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3237 * event.ActionEvent)
3240 public void hideAllButSelection_actionPerformed(ActionEvent e)
3242 toggleHiddenRegions(false, false);
3243 viewport.sendSelection();
3250 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3254 public void hideAllSelection_actionPerformed(ActionEvent e)
3256 SequenceGroup sg = viewport.getSelectionGroup();
3257 viewport.expandColSelection(sg, false);
3258 viewport.hideAllSelectedSeqs();
3259 viewport.hideSelectedColumns();
3260 alignPanel.paintAlignment(true, true);
3261 viewport.sendSelection();
3268 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3272 public void showAllhidden_actionPerformed(ActionEvent e)
3274 viewport.showAllHiddenColumns();
3275 viewport.showAllHiddenSeqs();
3276 alignPanel.paintAlignment(true, true);
3277 viewport.sendSelection();
3281 public void hideSelColumns_actionPerformed(ActionEvent e)
3283 viewport.hideSelectedColumns();
3284 alignPanel.paintAlignment(true, true);
3285 viewport.sendSelection();
3289 public void hiddenMarkers_actionPerformed(ActionEvent e)
3291 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3302 protected void scaleAbove_actionPerformed(ActionEvent e)
3304 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3305 // TODO: do we actually need to update overview for scale above change ?
3306 alignPanel.paintAlignment(true, false);
3316 protected void scaleLeft_actionPerformed(ActionEvent e)
3318 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3319 alignPanel.paintAlignment(true, false);
3329 protected void scaleRight_actionPerformed(ActionEvent e)
3331 viewport.setScaleRightWrapped(scaleRight.isSelected());
3332 alignPanel.paintAlignment(true, false);
3342 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3344 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3345 alignPanel.paintAlignment(false, false);
3355 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3357 viewport.setShowText(viewTextMenuItem.isSelected());
3358 alignPanel.paintAlignment(false, false);
3368 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3370 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3371 alignPanel.paintAlignment(false, false);
3374 public FeatureSettings featureSettings;
3377 public FeatureSettingsControllerI getFeatureSettingsUI()
3379 return featureSettings;
3383 public void featureSettings_actionPerformed(ActionEvent e)
3385 if (featureSettings != null)
3387 featureSettings.close();
3388 featureSettings = null;
3390 if (!showSeqFeatures.isSelected())
3392 // make sure features are actually displayed
3393 showSeqFeatures.setSelected(true);
3394 showSeqFeatures_actionPerformed(null);
3396 featureSettings = new FeatureSettings(this);
3400 * Set or clear 'Show Sequence Features'
3406 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3408 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3409 alignPanel.paintAlignment(true, true);
3413 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3414 * the annotations panel as a whole.
3416 * The options to show/hide all annotations should be enabled when the panel
3417 * is shown, and disabled when the panel is hidden.
3422 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3424 final boolean setVisible = annotationPanelMenuItem.isSelected();
3425 viewport.setShowAnnotation(setVisible);
3426 this.showAllSeqAnnotations.setEnabled(setVisible);
3427 this.hideAllSeqAnnotations.setEnabled(setVisible);
3428 this.showAllAlAnnotations.setEnabled(setVisible);
3429 this.hideAllAlAnnotations.setEnabled(setVisible);
3430 alignPanel.updateLayout();
3434 public void alignmentProperties()
3436 JEditorPane editPane = new JEditorPane("text/html", "");
3437 editPane.setEditable(false);
3438 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3441 MessageManager.formatMessage("label.html_content", new Object[]
3442 { contents.toString() }));
3443 JInternalFrame frame = new JInternalFrame();
3444 frame.getContentPane().add(new JScrollPane(editPane));
3446 Desktop.addInternalFrame(frame, MessageManager
3447 .formatMessage("label.alignment_properties", new Object[]
3448 { getTitle() }), 500, 400);
3458 public void overviewMenuItem_actionPerformed(ActionEvent e)
3460 if (alignPanel.overviewPanel != null)
3465 JInternalFrame frame = new JInternalFrame();
3466 final OverviewPanel overview = new OverviewPanel(alignPanel);
3467 frame.setContentPane(overview);
3468 Desktop.addInternalFrame(frame, MessageManager
3469 .formatMessage("label.overview_params", new Object[]
3470 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3473 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3474 frame.addInternalFrameListener(
3475 new javax.swing.event.InternalFrameAdapter()
3478 public void internalFrameClosed(
3479 javax.swing.event.InternalFrameEvent evt)
3482 alignPanel.setOverviewPanel(null);
3485 if (getKeyListeners().length > 0)
3487 frame.addKeyListener(getKeyListeners()[0]);
3490 alignPanel.setOverviewPanel(overview);
3494 public void textColour_actionPerformed()
3496 new TextColourChooser().chooseColour(alignPanel, null);
3500 * public void covariationColour_actionPerformed() {
3502 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3506 public void annotationColour_actionPerformed()
3508 new AnnotationColourChooser(viewport, alignPanel);
3512 public void annotationColumn_actionPerformed(ActionEvent e)
3514 new AnnotationColumnChooser(viewport, alignPanel);
3518 * Action on the user checking or unchecking the option to apply the selected
3519 * colour scheme to all groups. If unchecked, groups may have their own
3520 * independent colour schemes.
3525 public void applyToAllGroups_actionPerformed(boolean selected)
3527 viewport.setColourAppliesToAllGroups(selected);
3531 * Action on user selecting a colour from the colour menu
3534 * the name (not the menu item label!) of the colour scheme
3537 public void changeColour_actionPerformed(String name)
3540 * 'User Defined' opens a panel to configure or load a
3541 * user-defined colour scheme
3543 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3545 new UserDefinedColours(alignPanel);
3550 * otherwise set the chosen colour scheme (or null for 'None')
3552 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3553 viewport.getAlignment(), viewport.getHiddenRepSequences());
3558 * Actions on setting or changing the alignment colour scheme
3563 public void changeColour(ColourSchemeI cs)
3565 // TODO: pull up to controller method
3566 ColourMenuHelper.setColourSelected(colourMenu, cs);
3568 viewport.setGlobalColourScheme(cs);
3570 alignPanel.paintAlignment(true, true);
3574 * Show the PID threshold slider panel
3577 protected void modifyPID_actionPerformed()
3579 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3580 alignPanel.getViewName());
3581 SliderPanel.showPIDSlider();
3585 * Show the Conservation slider panel
3588 protected void modifyConservation_actionPerformed()
3590 SliderPanel.setConservationSlider(alignPanel,
3591 viewport.getResidueShading(), alignPanel.getViewName());
3592 SliderPanel.showConservationSlider();
3596 * Action on selecting or deselecting (Colour) By Conservation
3599 public void conservationMenuItem_actionPerformed(boolean selected)
3601 modifyConservation.setEnabled(selected);
3602 viewport.setConservationSelected(selected);
3603 viewport.getResidueShading().setConservationApplied(selected);
3605 changeColour(viewport.getGlobalColourScheme());
3608 modifyConservation_actionPerformed();
3612 SliderPanel.hideConservationSlider();
3617 * Action on selecting or deselecting (Colour) Above PID Threshold
3620 public void abovePIDThreshold_actionPerformed(boolean selected)
3622 modifyPID.setEnabled(selected);
3623 viewport.setAbovePIDThreshold(selected);
3626 viewport.getResidueShading().setThreshold(0,
3627 viewport.isIgnoreGapsConsensus());
3630 changeColour(viewport.getGlobalColourScheme());
3633 modifyPID_actionPerformed();
3637 SliderPanel.hidePIDSlider();
3648 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3650 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3651 AlignmentSorter.sortByPID(viewport.getAlignment(),
3652 viewport.getAlignment().getSequenceAt(0));
3653 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3654 viewport.getAlignment()));
3655 alignPanel.paintAlignment(true, false);
3665 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3667 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3668 AlignmentSorter.sortByID(viewport.getAlignment());
3670 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3671 alignPanel.paintAlignment(true, false);
3681 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3683 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3684 AlignmentSorter.sortByLength(viewport.getAlignment());
3685 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3686 viewport.getAlignment()));
3687 alignPanel.paintAlignment(true, false);
3697 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3699 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3700 AlignmentSorter.sortByGroup(viewport.getAlignment());
3701 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3702 viewport.getAlignment()));
3704 alignPanel.paintAlignment(true, false);
3714 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3716 new RedundancyPanel(alignPanel, this);
3726 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3728 if ((viewport.getSelectionGroup() == null)
3729 || (viewport.getSelectionGroup().getSize() < 2))
3731 JvOptionPane.showInternalMessageDialog(this,
3732 MessageManager.getString(
3733 "label.you_must_select_least_two_sequences"),
3734 MessageManager.getString("label.invalid_selection"),
3735 JvOptionPane.WARNING_MESSAGE);
3739 JInternalFrame frame = new JInternalFrame();
3740 frame.setContentPane(new PairwiseAlignPanel(viewport));
3741 Desktop.addInternalFrame(frame,
3742 MessageManager.getString("action.pairwise_alignment"), 600,
3748 public void autoCalculate_actionPerformed(ActionEvent e)
3750 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3751 if (viewport.autoCalculateConsensus)
3753 viewport.firePropertyChange("alignment", null,
3754 viewport.getAlignment().getSequences());
3759 public void sortByTreeOption_actionPerformed(ActionEvent e)
3761 viewport.sortByTree = sortByTree.isSelected();
3765 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3767 viewport.followSelection = listenToViewSelections.isSelected();
3771 * Constructs a tree panel and adds it to the desktop
3774 * tree type (NJ or AV)
3776 * name of score model used to compute the tree
3778 * parameters for the distance or similarity calculation
3780 void newTreePanel(String type, String modelName,
3781 SimilarityParamsI options)
3783 String frameTitle = "";
3786 boolean onSelection = false;
3787 if (viewport.getSelectionGroup() != null
3788 && viewport.getSelectionGroup().getSize() > 0)
3790 SequenceGroup sg = viewport.getSelectionGroup();
3792 /* Decide if the selection is a column region */
3793 for (SequenceI _s : sg.getSequences())
3795 if (_s.getLength() < sg.getEndRes())
3797 JvOptionPane.showMessageDialog(Desktop.desktop,
3798 MessageManager.getString(
3799 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3800 MessageManager.getString(
3801 "label.sequences_selection_not_aligned"),
3802 JvOptionPane.WARNING_MESSAGE);
3811 if (viewport.getAlignment().getHeight() < 2)
3817 tp = new TreePanel(alignPanel, type, modelName, options);
3818 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3820 frameTitle += " from ";
3822 if (viewport.viewName != null)
3824 frameTitle += viewport.viewName + " of ";
3827 frameTitle += this.title;
3829 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3840 public void addSortByOrderMenuItem(String title,
3841 final AlignmentOrder order)
3843 final JMenuItem item = new JMenuItem(MessageManager
3844 .formatMessage("action.by_title_param", new Object[]
3847 item.addActionListener(new java.awt.event.ActionListener()
3850 public void actionPerformed(ActionEvent e)
3852 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3854 // TODO: JBPNote - have to map order entries to curent SequenceI
3856 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3858 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3859 viewport.getAlignment()));
3861 alignPanel.paintAlignment(true, false);
3867 * Add a new sort by annotation score menu item
3870 * the menu to add the option to
3872 * the label used to retrieve scores for each sequence on the
3875 public void addSortByAnnotScoreMenuItem(JMenu sort,
3876 final String scoreLabel)
3878 final JMenuItem item = new JMenuItem(scoreLabel);
3880 item.addActionListener(new java.awt.event.ActionListener()
3883 public void actionPerformed(ActionEvent e)
3885 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3886 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3887 viewport.getAlignment());// ,viewport.getSelectionGroup());
3888 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3889 viewport.getAlignment()));
3890 alignPanel.paintAlignment(true, false);
3896 * last hash for alignment's annotation array - used to minimise cost of
3899 protected int _annotationScoreVectorHash;
3902 * search the alignment and rebuild the sort by annotation score submenu the
3903 * last alignment annotation vector hash is stored to minimize cost of
3904 * rebuilding in subsequence calls.
3908 public void buildSortByAnnotationScoresMenu()
3910 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3915 if (viewport.getAlignment().getAlignmentAnnotation()
3916 .hashCode() == _annotationScoreVectorHash)
3921 sortByAnnotScore.removeAll();
3922 Set<String> scoreSorts = new HashSet<>();
3923 for (SequenceI sqa : viewport.getAlignment().getSequences())
3925 AlignmentAnnotation[] anns = sqa.getAnnotation();
3926 for (int i = 0; anns != null && i < anns.length; i++)
3928 AlignmentAnnotation aa = anns[i];
3929 if (aa != null && aa.hasScore() && aa.sequenceRef != null)
3931 scoreSorts.add(aa.label);
3935 for (String label : scoreSorts)
3937 addSortByAnnotScoreMenuItem(sortByAnnotScore, label);
3939 sortByAnnotScore.setVisible(!scoreSorts.isEmpty());
3941 _annotationScoreVectorHash = viewport.getAlignment()
3942 .getAlignmentAnnotation().hashCode();
3946 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3947 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3948 * call. Listeners are added to remove the menu item when the treePanel is
3949 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3953 public void buildTreeSortMenu()
3955 sortByTreeMenu.removeAll();
3957 List<Component> comps = PaintRefresher.components
3958 .get(viewport.getSequenceSetId());
3959 List<TreePanel> treePanels = new ArrayList<>();
3960 for (Component comp : comps)
3962 if (comp instanceof TreePanel)
3964 treePanels.add((TreePanel) comp);
3968 if (treePanels.size() < 1)
3970 sortByTreeMenu.setVisible(false);
3974 sortByTreeMenu.setVisible(true);
3976 for (final TreePanel tp : treePanels)
3978 final JMenuItem item = new JMenuItem(tp.getTitle());
3979 item.addActionListener(new java.awt.event.ActionListener()
3982 public void actionPerformed(ActionEvent e)
3984 tp.sortByTree_actionPerformed();
3985 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3990 sortByTreeMenu.add(item);
3994 public boolean sortBy(AlignmentOrder alorder, String undoname)
3996 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3997 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3998 if (undoname != null)
4000 addHistoryItem(new OrderCommand(undoname, oldOrder,
4001 viewport.getAlignment()));
4003 alignPanel.paintAlignment(true, false);
4008 * Work out whether the whole set of sequences or just the selected set will
4009 * be submitted for multiple alignment.
4012 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4014 // Now, check we have enough sequences
4015 AlignmentView msa = null;
4017 if ((viewport.getSelectionGroup() != null)
4018 && (viewport.getSelectionGroup().getSize() > 1))
4020 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4021 // some common interface!
4023 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4024 * SequenceI[sz = seqs.getSize(false)];
4026 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4027 * seqs.getSequenceAt(i); }
4029 msa = viewport.getAlignmentView(true);
4031 else if (viewport.getSelectionGroup() != null
4032 && viewport.getSelectionGroup().getSize() == 1)
4034 int option = JvOptionPane.showConfirmDialog(this,
4035 MessageManager.getString("warn.oneseq_msainput_selection"),
4036 MessageManager.getString("label.invalid_selection"),
4037 JvOptionPane.OK_CANCEL_OPTION);
4038 if (option == JvOptionPane.OK_OPTION)
4040 msa = viewport.getAlignmentView(false);
4045 msa = viewport.getAlignmentView(false);
4051 * Decides what is submitted to a secondary structure prediction service: the
4052 * first sequence in the alignment, or in the current selection, or, if the
4053 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4054 * region or the whole alignment. (where the first sequence in the set is the
4055 * one that the prediction will be for).
4057 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4059 AlignmentView seqs = null;
4061 if ((viewport.getSelectionGroup() != null)
4062 && (viewport.getSelectionGroup().getSize() > 0))
4064 seqs = viewport.getAlignmentView(true);
4068 seqs = viewport.getAlignmentView(false);
4070 // limit sequences - JBPNote in future - could spawn multiple prediction
4072 // TODO: viewport.getAlignment().isAligned is a global state - the local
4073 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4074 if (!viewport.getAlignment().isAligned(false))
4076 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4077 // TODO: if seqs.getSequences().length>1 then should really have warned
4091 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4093 // Pick the tree file
4094 JalviewFileChooser chooser = new JalviewFileChooser(
4095 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4096 chooser.setFileView(new JalviewFileView());
4097 chooser.setDialogTitle(
4098 MessageManager.getString("label.select_newick_like_tree_file"));
4099 chooser.setToolTipText(
4100 MessageManager.getString("label.load_tree_file"));
4102 int value = chooser.showOpenDialog(null);
4104 if (value == JalviewFileChooser.APPROVE_OPTION)
4106 String filePath = chooser.getSelectedFile().getPath();
4107 Cache.setProperty("LAST_DIRECTORY", filePath);
4108 NewickFile fin = null;
4111 fin = new NewickFile(filePath, DataSourceType.FILE);
4112 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4113 } catch (Exception ex)
4115 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4116 MessageManager.getString("label.problem_reading_tree_file"),
4117 JvOptionPane.WARNING_MESSAGE);
4118 ex.printStackTrace();
4120 if (fin != null && fin.hasWarningMessage())
4122 JvOptionPane.showMessageDialog(Desktop.desktop,
4123 fin.getWarningMessage(),
4125 .getString("label.possible_problem_with_tree_file"),
4126 JvOptionPane.WARNING_MESSAGE);
4131 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4133 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4136 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4137 int h, int x, int y)
4139 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4143 * Add a treeviewer for the tree extracted from a Newick file object to the
4144 * current alignment view
4151 * Associated alignment input data (or null)
4160 * @return TreePanel handle
4162 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4163 AlignmentView input, int w, int h, int x, int y)
4165 TreePanel tp = null;
4171 if (nf.getTree() != null)
4173 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4179 tp.setLocation(x, y);
4182 Desktop.addInternalFrame(tp, treeTitle, w, h);
4184 } catch (Exception ex)
4186 ex.printStackTrace();
4192 private boolean buildingMenu = false;
4195 * Generates menu items and listener event actions for web service clients
4198 public void BuildWebServiceMenu()
4200 while (buildingMenu)
4204 System.err.println("Waiting for building menu to finish.");
4206 } catch (Exception e)
4210 final AlignFrame me = this;
4211 buildingMenu = true;
4212 new Thread(new Runnable()
4217 final List<JMenuItem> legacyItems = new ArrayList<>();
4220 // System.err.println("Building ws menu again "
4221 // + Thread.currentThread());
4222 // TODO: add support for context dependent disabling of services based
4224 // alignment and current selection
4225 // TODO: add additional serviceHandle parameter to specify abstract
4227 // class independently of AbstractName
4228 // TODO: add in rediscovery GUI function to restart discoverer
4229 // TODO: group services by location as well as function and/or
4231 // object broker mechanism.
4232 final Vector<JMenu> wsmenu = new Vector<>();
4233 final IProgressIndicator af = me;
4236 * do not i18n these strings - they are hard-coded in class
4237 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4238 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4240 final JMenu msawsmenu = new JMenu("Alignment");
4241 final JMenu secstrmenu = new JMenu(
4242 "Secondary Structure Prediction");
4243 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4244 final JMenu analymenu = new JMenu("Analysis");
4245 final JMenu dismenu = new JMenu("Protein Disorder");
4246 // JAL-940 - only show secondary structure prediction services from
4247 // the legacy server
4248 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4250 Discoverer.services != null && (Discoverer.services.size() > 0))
4252 // TODO: refactor to allow list of AbstractName/Handler bindings to
4254 // stored or retrieved from elsewhere
4255 // No MSAWS used any more:
4256 // Vector msaws = null; // (Vector)
4257 // Discoverer.services.get("MsaWS");
4258 Vector secstrpr = (Vector) Discoverer.services
4260 if (secstrpr != null)
4262 // Add any secondary structure prediction services
4263 for (int i = 0, j = secstrpr.size(); i < j; i++)
4265 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4267 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4268 .getServiceClient(sh);
4269 int p = secstrmenu.getItemCount();
4270 impl.attachWSMenuEntry(secstrmenu, me);
4271 int q = secstrmenu.getItemCount();
4272 for (int litm = p; litm < q; litm++)
4274 legacyItems.add(secstrmenu.getItem(litm));
4280 // Add all submenus in the order they should appear on the web
4282 wsmenu.add(msawsmenu);
4283 wsmenu.add(secstrmenu);
4284 wsmenu.add(dismenu);
4285 wsmenu.add(analymenu);
4286 // No search services yet
4287 // wsmenu.add(seqsrchmenu);
4289 javax.swing.SwingUtilities.invokeLater(new Runnable()
4296 webService.removeAll();
4297 // first, add discovered services onto the webservices menu
4298 if (wsmenu.size() > 0)
4300 for (int i = 0, j = wsmenu.size(); i < j; i++)
4302 webService.add(wsmenu.get(i));
4307 webService.add(me.webServiceNoServices);
4309 // TODO: move into separate menu builder class.
4310 boolean new_sspred = false;
4311 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4313 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4314 if (jws2servs != null)
4316 if (jws2servs.hasServices())
4318 jws2servs.attachWSMenuEntry(webService, me);
4319 for (Jws2Instance sv : jws2servs.getServices())
4321 if (sv.getName().toLowerCase().contains("jpred"))
4323 for (JMenuItem jmi : legacyItems)
4325 jmi.setVisible(false);
4331 if (jws2servs.isRunning())
4333 JMenuItem tm = new JMenuItem(
4334 "Still discovering JABA Services");
4335 tm.setEnabled(false);
4340 build_urlServiceMenu(me.webService);
4342 // TODO Mateusz - follow pattern for adding web service
4343 // JMenuItems for slivka-based services
4345 build_fetchdbmenu(webService);
4346 for (JMenu item : wsmenu)
4348 if (item.getItemCount() == 0)
4350 item.setEnabled(false);
4354 item.setEnabled(true);
4357 } catch (Exception e)
4360 "Exception during web service menu building process.",
4365 } catch (Exception e)
4368 buildingMenu = false;
4375 * construct any groupURL type service menu entries.
4379 private void build_urlServiceMenu(JMenu webService)
4381 // TODO: remove this code when 2.7 is released
4382 // DEBUG - alignmentView
4384 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4385 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4387 * @Override public void actionPerformed(ActionEvent e) {
4388 * jalview.datamodel.AlignmentView
4389 * .testSelectionViews(af.viewport.getAlignment(),
4390 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4392 * }); webService.add(testAlView);
4394 // TODO: refactor to RestClient discoverer and merge menu entries for
4395 // rest-style services with other types of analysis/calculation service
4396 // SHmmr test client - still being implemented.
4397 // DEBUG - alignmentView
4399 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4402 client.attachWSMenuEntry(
4403 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4409 * Searches the alignment sequences for xRefs and builds the Show
4410 * Cross-References menu (formerly called Show Products), with database
4411 * sources for which cross-references are found (protein sources for a
4412 * nucleotide alignment and vice versa)
4414 * @return true if Show Cross-references menu should be enabled
4416 public boolean canShowProducts()
4418 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4419 AlignmentI dataset = viewport.getAlignment().getDataset();
4421 showProducts.removeAll();
4422 final boolean dna = viewport.getAlignment().isNucleotide();
4424 if (seqs == null || seqs.length == 0)
4426 // nothing to see here.
4430 boolean showp = false;
4433 List<String> ptypes = new CrossRef(seqs, dataset)
4434 .findXrefSourcesForSequences(dna);
4436 for (final String source : ptypes)
4439 final AlignFrame af = this;
4440 JMenuItem xtype = new JMenuItem(source);
4441 xtype.addActionListener(new ActionListener()
4444 public void actionPerformed(ActionEvent e)
4446 showProductsFor(af.viewport.getSequenceSelection(), dna,
4450 showProducts.add(xtype);
4452 showProducts.setVisible(showp);
4453 showProducts.setEnabled(showp);
4454 } catch (Exception e)
4457 "canShowProducts threw an exception - please report to help@jalview.org",
4465 * Finds and displays cross-references for the selected sequences (protein
4466 * products for nucleotide sequences, dna coding sequences for peptides).
4469 * the sequences to show cross-references for
4471 * true if from a nucleotide alignment (so showing proteins)
4473 * the database to show cross-references for
4475 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4476 final String source)
4478 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4483 * Construct and display a new frame containing the translation of this
4484 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4487 public void showTranslation_actionPerformed(ActionEvent e)
4489 AlignmentI al = null;
4492 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4494 al = dna.translateCdna();
4495 } catch (Exception ex)
4497 jalview.bin.Cache.log.error(
4498 "Exception during translation. Please report this !", ex);
4499 final String msg = MessageManager.getString(
4500 "label.error_when_translating_sequences_submit_bug_report");
4501 final String errorTitle = MessageManager
4502 .getString("label.implementation_error")
4503 + MessageManager.getString("label.translation_failed");
4504 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4505 JvOptionPane.ERROR_MESSAGE);
4508 if (al == null || al.getHeight() == 0)
4510 final String msg = MessageManager.getString(
4511 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4512 final String errorTitle = MessageManager
4513 .getString("label.translation_failed");
4514 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4515 JvOptionPane.WARNING_MESSAGE);
4519 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4520 af.setFileFormat(this.currentFileFormat);
4521 final String newTitle = MessageManager
4522 .formatMessage("label.translation_of_params", new Object[]
4523 { this.getTitle() });
4524 af.setTitle(newTitle);
4525 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4527 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4528 viewport.openSplitFrame(af, new Alignment(seqs));
4532 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4539 * Set the file format
4543 public void setFileFormat(FileFormatI format)
4545 this.currentFileFormat = format;
4549 * Try to load a features file onto the alignment.
4552 * contents or path to retrieve file
4554 * access mode of file (see jalview.io.AlignFile)
4555 * @return true if features file was parsed correctly.
4557 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4559 return avc.parseFeaturesFile(file, sourceType,
4560 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4565 public void refreshFeatureUI(boolean enableIfNecessary)
4567 // note - currently this is only still here rather than in the controller
4568 // because of the featureSettings hard reference that is yet to be
4570 if (enableIfNecessary)
4572 viewport.setShowSequenceFeatures(true);
4573 showSeqFeatures.setSelected(true);
4579 public void dragEnter(DropTargetDragEvent evt)
4584 public void dragExit(DropTargetEvent evt)
4589 public void dragOver(DropTargetDragEvent evt)
4594 public void dropActionChanged(DropTargetDragEvent evt)
4599 public void drop(DropTargetDropEvent evt)
4601 // JAL-1552 - acceptDrop required before getTransferable call for
4602 // Java's Transferable for native dnd
4603 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4604 Transferable t = evt.getTransferable();
4605 final AlignFrame thisaf = this;
4606 final List<String> files = new ArrayList<>();
4607 List<DataSourceType> protocols = new ArrayList<>();
4611 Desktop.transferFromDropTarget(files, protocols, evt, t);
4612 } catch (Exception e)
4614 e.printStackTrace();
4618 new Thread(new Runnable()
4625 // check to see if any of these files have names matching sequences
4628 SequenceIdMatcher idm = new SequenceIdMatcher(
4629 viewport.getAlignment().getSequencesArray());
4631 * Object[] { String,SequenceI}
4633 ArrayList<Object[]> filesmatched = new ArrayList<>();
4634 ArrayList<String> filesnotmatched = new ArrayList<>();
4635 for (int i = 0; i < files.size(); i++)
4637 String file = files.get(i).toString();
4639 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4640 if (protocol == DataSourceType.FILE)
4642 File fl = new File(file);
4643 pdbfn = fl.getName();
4645 else if (protocol == DataSourceType.URL)
4647 URL url = new URL(file);
4648 pdbfn = url.getFile();
4650 if (pdbfn.length() > 0)
4652 // attempt to find a match in the alignment
4653 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4654 int l = 0, c = pdbfn.indexOf(".");
4655 while (mtch == null && c != -1)
4660 } while ((c = pdbfn.indexOf(".", l)) > l);
4663 pdbfn = pdbfn.substring(0, l);
4665 mtch = idm.findAllIdMatches(pdbfn);
4669 FileFormatI type = null;
4672 type = new IdentifyFile().identify(file, protocol);
4673 } catch (Exception ex)
4677 if (type != null && type.isStructureFile())
4679 filesmatched.add(new Object[] { file, protocol, mtch });
4683 // File wasn't named like one of the sequences or wasn't a PDB
4685 filesnotmatched.add(file);
4689 if (filesmatched.size() > 0)
4691 boolean autoAssociate = Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4694 String msg = MessageManager.formatMessage(
4695 "label.automatically_associate_structure_files_with_sequences_same_name",
4697 { Integer.valueOf(filesmatched.size())
4699 String ttl = MessageManager.getString(
4700 "label.automatically_associate_structure_files_by_name");
4701 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4702 ttl, JvOptionPane.YES_NO_OPTION);
4703 autoAssociate = choice == JvOptionPane.YES_OPTION;
4707 for (Object[] fm : filesmatched)
4709 // try and associate
4710 // TODO: may want to set a standard ID naming formalism for
4711 // associating PDB files which have no IDs.
4712 for (SequenceI toassoc : (SequenceI[]) fm[2])
4714 PDBEntry pe = new AssociatePdbFileWithSeq()
4715 .associatePdbWithSeq((String) fm[0],
4716 (DataSourceType) fm[1], toassoc, false,
4720 System.err.println("Associated file : "
4721 + ((String) fm[0]) + " with "
4722 + toassoc.getDisplayId(true));
4726 // TODO: do we need to update overview ? only if features are
4728 alignPanel.paintAlignment(true, false);
4734 * add declined structures as sequences
4736 for (Object[] o : filesmatched)
4738 filesnotmatched.add((String) o[0]);
4742 if (filesnotmatched.size() > 0)
4744 if (assocfiles > 0 && (Cache.getDefault(
4745 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4746 || JvOptionPane.showConfirmDialog(thisaf,
4747 "<html>" + MessageManager.formatMessage(
4748 "label.ignore_unmatched_dropped_files_info",
4751 filesnotmatched.size())
4754 MessageManager.getString(
4755 "label.ignore_unmatched_dropped_files"),
4756 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4760 for (String fn : filesnotmatched)
4762 loadJalviewDataFile(fn, null, null, null);
4766 } catch (Exception ex)
4768 ex.printStackTrace();
4776 * Attempt to load a "dropped" file or URL string, by testing in turn for
4778 * <li>an Annotation file</li>
4779 * <li>a JNet file</li>
4780 * <li>a features file</li>
4781 * <li>else try to interpret as an alignment file</li>
4785 * either a filename or a URL string.
4786 * @throws InterruptedException
4787 * @throws IOException
4789 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4790 FileFormatI format, SequenceI assocSeq)
4794 if (sourceType == null)
4796 sourceType = FormatAdapter.checkProtocol(file);
4798 // if the file isn't identified, or not positively identified as some
4799 // other filetype (PFAM is default unidentified alignment file type) then
4800 // try to parse as annotation.
4801 boolean isAnnotation = (format == null
4802 || FileFormat.Pfam.equals(format))
4803 ? new AnnotationFile().annotateAlignmentView(viewport,
4809 // first see if its a T-COFFEE score file
4810 TCoffeeScoreFile tcf = null;
4813 tcf = new TCoffeeScoreFile(file, sourceType);
4816 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4820 new TCoffeeColourScheme(viewport.getAlignment()));
4821 isAnnotation = true;
4822 statusBar.setText(MessageManager.getString(
4823 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4827 // some problem - if no warning its probable that the ID matching
4828 // process didn't work
4829 JvOptionPane.showMessageDialog(Desktop.desktop,
4830 tcf.getWarningMessage() == null
4831 ? MessageManager.getString(
4832 "label.check_file_matches_sequence_ids_alignment")
4833 : tcf.getWarningMessage(),
4834 MessageManager.getString(
4835 "label.problem_reading_tcoffee_score_file"),
4836 JvOptionPane.WARNING_MESSAGE);
4843 } catch (Exception x)
4846 "Exception when processing data source as T-COFFEE score file",
4852 // try to see if its a JNet 'concise' style annotation file *before*
4854 // try to parse it as a features file
4857 format = new IdentifyFile().identify(file, sourceType);
4859 if (FileFormat.ScoreMatrix == format)
4861 ScoreMatrixFile sm = new ScoreMatrixFile(
4862 new FileParse(file, sourceType));
4864 // todo: i18n this message
4865 statusBar.setText(MessageManager.formatMessage(
4866 "label.successfully_loaded_matrix",
4867 sm.getMatrixName()));
4869 else if (FileFormat.Jnet.equals(format))
4871 JPredFile predictions = new JPredFile(file, sourceType);
4872 new JnetAnnotationMaker();
4873 JnetAnnotationMaker.add_annotation(predictions,
4874 viewport.getAlignment(), 0, false);
4875 viewport.getAlignment().setupJPredAlignment();
4876 isAnnotation = true;
4878 // else if (IdentifyFile.FeaturesFile.equals(format))
4879 else if (FileFormat.Features.equals(format))
4881 if (parseFeaturesFile(file, sourceType))
4883 alignPanel.paintAlignment(true, true);
4888 new FileLoader().LoadFile(viewport, file, sourceType, format);
4894 alignPanel.adjustAnnotationHeight();
4895 viewport.updateSequenceIdColours();
4896 buildSortByAnnotationScoresMenu();
4897 alignPanel.paintAlignment(true, true);
4899 } catch (Exception ex)
4901 ex.printStackTrace();
4902 } catch (OutOfMemoryError oom)
4907 } catch (Exception x)
4912 + (sourceType != null
4913 ? (sourceType == DataSourceType.PASTE
4915 : "using " + sourceType + " from "
4919 ? "(parsing as '" + format + "' file)"
4921 oom, Desktop.desktop);
4926 * Method invoked by the ChangeListener on the tabbed pane, in other words
4927 * when a different tabbed pane is selected by the user or programmatically.
4930 public void tabSelectionChanged(int index)
4934 alignPanel = alignPanels.get(index);
4935 viewport = alignPanel.av;
4936 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4937 setMenusFromViewport(viewport);
4941 * 'focus' any colour slider that is open to the selected viewport
4943 if (viewport.getConservationSelected())
4945 SliderPanel.setConservationSlider(alignPanel,
4946 viewport.getResidueShading(), alignPanel.getViewName());
4950 SliderPanel.hideConservationSlider();
4952 if (viewport.getAbovePIDThreshold())
4954 SliderPanel.setPIDSliderSource(alignPanel,
4955 viewport.getResidueShading(), alignPanel.getViewName());
4959 SliderPanel.hidePIDSlider();
4963 * If there is a frame linked to this one in a SplitPane, switch it to the
4964 * same view tab index. No infinite recursion of calls should happen, since
4965 * tabSelectionChanged() should not get invoked on setting the selected
4966 * index to an unchanged value. Guard against setting an invalid index
4967 * before the new view peer tab has been created.
4969 final AlignViewportI peer = viewport.getCodingComplement();
4972 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4973 .getAlignPanel().alignFrame;
4974 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4976 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4982 * On right mouse click on view tab, prompt for and set new view name.
4985 public void tabbedPane_mousePressed(MouseEvent e)
4987 if (e.isPopupTrigger())
4989 String msg = MessageManager.getString("label.enter_view_name");
4990 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4991 JvOptionPane.QUESTION_MESSAGE);
4995 viewport.viewName = reply;
4996 // TODO warn if reply is in getExistingViewNames()?
4997 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5002 public AlignViewport getCurrentView()
5008 * Open the dialog for regex description parsing.
5011 protected void extractScores_actionPerformed(ActionEvent e)
5013 ParseProperties pp = new jalview.analysis.ParseProperties(
5014 viewport.getAlignment());
5015 // TODO: verify regex and introduce GUI dialog for version 2.5
5016 // if (pp.getScoresFromDescription("col", "score column ",
5017 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5019 if (pp.getScoresFromDescription("description column",
5020 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5022 buildSortByAnnotationScoresMenu();
5030 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5034 protected void showDbRefs_actionPerformed(ActionEvent e)
5036 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5042 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5046 protected void showNpFeats_actionPerformed(ActionEvent e)
5048 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5052 * find the viewport amongst the tabs in this alignment frame and close that
5057 public boolean closeView(AlignViewportI av)
5061 this.closeMenuItem_actionPerformed(false);
5064 Component[] comp = tabbedPane.getComponents();
5065 for (int i = 0; comp != null && i < comp.length; i++)
5067 if (comp[i] instanceof AlignmentPanel)
5069 if (((AlignmentPanel) comp[i]).av == av)
5072 closeView((AlignmentPanel) comp[i]);
5080 protected void build_fetchdbmenu(JMenu webService)
5082 // Temporary hack - DBRef Fetcher always top level ws entry.
5083 // TODO We probably want to store a sequence database checklist in
5084 // preferences and have checkboxes.. rather than individual sources selected
5086 final JMenu rfetch = new JMenu(
5087 MessageManager.getString("action.fetch_db_references"));
5088 rfetch.setToolTipText(MessageManager.getString(
5089 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5090 webService.add(rfetch);
5092 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5093 MessageManager.getString("option.trim_retrieved_seqs"));
5094 trimrs.setToolTipText(
5095 MessageManager.getString("label.trim_retrieved_sequences"));
5097 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5098 trimrs.addActionListener(new ActionListener()
5101 public void actionPerformed(ActionEvent e)
5103 trimrs.setSelected(trimrs.isSelected());
5104 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5105 Boolean.valueOf(trimrs.isSelected()).toString());
5109 JMenuItem fetchr = new JMenuItem(
5110 MessageManager.getString("label.standard_databases"));
5111 fetchr.setToolTipText(
5112 MessageManager.getString("label.fetch_embl_uniprot"));
5113 fetchr.addActionListener(new ActionListener()
5117 public void actionPerformed(ActionEvent e)
5119 new Thread(new Runnable()
5124 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5125 .getAlignment().isNucleotide();
5126 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5127 alignPanel.av.getSequenceSelection(),
5128 alignPanel.alignFrame, null,
5129 alignPanel.alignFrame.featureSettings, isNucleotide);
5130 dbRefFetcher.addListener(new FetchFinishedListenerI()
5133 public void finished()
5135 AlignFrame.this.setMenusForViewport();
5138 dbRefFetcher.fetchDBRefs(false);
5146 final AlignFrame me = this;
5147 new Thread(new Runnable()
5152 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5153 .getSequenceFetcherSingleton(me);
5154 javax.swing.SwingUtilities.invokeLater(new Runnable()
5159 String[] dbclasses = sf.getOrderedSupportedSources();
5160 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5161 // jalview.util.QuickSort.sort(otherdb, otherdb);
5162 List<DbSourceProxy> otherdb;
5163 JMenu dfetch = new JMenu();
5164 JMenu ifetch = new JMenu();
5165 JMenuItem fetchr = null;
5166 int comp = 0, icomp = 0, mcomp = 15;
5167 String mname = null;
5169 for (String dbclass : dbclasses)
5171 otherdb = sf.getSourceProxy(dbclass);
5172 // add a single entry for this class, or submenu allowing 'fetch
5174 if (otherdb == null || otherdb.size() < 1)
5178 // List<DbSourceProxy> dbs=otherdb;
5179 // otherdb=new ArrayList<DbSourceProxy>();
5180 // for (DbSourceProxy db:dbs)
5182 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5186 mname = "From " + dbclass;
5188 if (otherdb.size() == 1)
5190 final DbSourceProxy[] dassource = otherdb
5191 .toArray(new DbSourceProxy[0]);
5192 DbSourceProxy src = otherdb.get(0);
5193 fetchr = new JMenuItem(src.getDbSource());
5194 fetchr.addActionListener(new ActionListener()
5198 public void actionPerformed(ActionEvent e)
5200 new Thread(new Runnable()
5206 boolean isNucleotide = alignPanel.alignFrame
5207 .getViewport().getAlignment()
5209 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5210 alignPanel.av.getSequenceSelection(),
5211 alignPanel.alignFrame, dassource,
5212 alignPanel.alignFrame.featureSettings,
5215 .addListener(new FetchFinishedListenerI()
5218 public void finished()
5220 AlignFrame.this.setMenusForViewport();
5223 dbRefFetcher.fetchDBRefs(false);
5229 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5230 MessageManager.formatMessage(
5231 "label.fetch_retrieve_from", new Object[]
5232 { src.getDbName() })));
5238 final DbSourceProxy[] dassource = otherdb
5239 .toArray(new DbSourceProxy[0]);
5241 DbSourceProxy src = otherdb.get(0);
5242 fetchr = new JMenuItem(MessageManager
5243 .formatMessage("label.fetch_all_param", new Object[]
5244 { src.getDbSource() }));
5245 fetchr.addActionListener(new ActionListener()
5248 public void actionPerformed(ActionEvent e)
5250 new Thread(new Runnable()
5256 boolean isNucleotide = alignPanel.alignFrame
5257 .getViewport().getAlignment()
5259 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5260 alignPanel.av.getSequenceSelection(),
5261 alignPanel.alignFrame, dassource,
5262 alignPanel.alignFrame.featureSettings,
5265 .addListener(new FetchFinishedListenerI()
5268 public void finished()
5270 AlignFrame.this.setMenusForViewport();
5273 dbRefFetcher.fetchDBRefs(false);
5279 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5280 MessageManager.formatMessage(
5281 "label.fetch_retrieve_from_all_sources",
5283 { Integer.valueOf(otherdb.size())
5285 src.getDbSource(), src.getDbName() })));
5288 // and then build the rest of the individual menus
5289 ifetch = new JMenu(MessageManager.formatMessage(
5290 "label.source_from_db_source", new Object[]
5291 { src.getDbSource() }));
5293 String imname = null;
5295 for (DbSourceProxy sproxy : otherdb)
5297 String dbname = sproxy.getDbName();
5298 String sname = dbname.length() > 5
5299 ? dbname.substring(0, 5) + "..."
5301 String msname = dbname.length() > 10
5302 ? dbname.substring(0, 10) + "..."
5306 imname = MessageManager
5307 .formatMessage("label.from_msname", new Object[]
5310 fetchr = new JMenuItem(msname);
5311 final DbSourceProxy[] dassrc = { sproxy };
5312 fetchr.addActionListener(new ActionListener()
5316 public void actionPerformed(ActionEvent e)
5318 new Thread(new Runnable()
5324 boolean isNucleotide = alignPanel.alignFrame
5325 .getViewport().getAlignment()
5327 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5328 alignPanel.av.getSequenceSelection(),
5329 alignPanel.alignFrame, dassrc,
5330 alignPanel.alignFrame.featureSettings,
5333 .addListener(new FetchFinishedListenerI()
5336 public void finished()
5338 AlignFrame.this.setMenusForViewport();
5341 dbRefFetcher.fetchDBRefs(false);
5347 fetchr.setToolTipText(
5348 "<html>" + MessageManager.formatMessage(
5349 "label.fetch_retrieve_from", new Object[]
5353 if (++icomp >= mcomp || i == (otherdb.size()))
5355 ifetch.setText(MessageManager.formatMessage(
5356 "label.source_to_target", imname, sname));
5358 ifetch = new JMenu();
5366 if (comp >= mcomp || dbi >= (dbclasses.length))
5368 dfetch.setText(MessageManager.formatMessage(
5369 "label.source_to_target", mname, dbclass));
5371 dfetch = new JMenu();
5384 * Left justify the whole alignment.
5387 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5389 AlignmentI al = viewport.getAlignment();
5391 viewport.firePropertyChange("alignment", null, al);
5395 * Right justify the whole alignment.
5398 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5400 AlignmentI al = viewport.getAlignment();
5402 viewport.firePropertyChange("alignment", null, al);
5406 public void setShowSeqFeatures(boolean b)
5408 showSeqFeatures.setSelected(b);
5409 viewport.setShowSequenceFeatures(b);
5416 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5417 * awt.event.ActionEvent)
5420 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5422 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5423 alignPanel.paintAlignment(false, false);
5430 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5434 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5436 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5437 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5445 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5446 * .event.ActionEvent)
5449 protected void showGroupConservation_actionPerformed(ActionEvent e)
5451 viewport.setShowGroupConservation(showGroupConservation.getState());
5452 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5459 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5460 * .event.ActionEvent)
5463 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5465 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5466 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5473 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5474 * .event.ActionEvent)
5477 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5479 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5480 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5484 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5486 showSequenceLogo.setState(true);
5487 viewport.setShowSequenceLogo(true);
5488 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5489 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5493 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5495 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5502 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5503 * .event.ActionEvent)
5506 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5508 if (avc.makeGroupsFromSelection())
5510 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5511 alignPanel.updateAnnotation();
5512 alignPanel.paintAlignment(true, true);
5516 public void clearAlignmentSeqRep()
5518 // TODO refactor alignmentseqrep to controller
5519 if (viewport.getAlignment().hasSeqrep())
5521 viewport.getAlignment().setSeqrep(null);
5522 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5523 alignPanel.updateAnnotation();
5524 alignPanel.paintAlignment(true, true);
5529 protected void createGroup_actionPerformed(ActionEvent e)
5531 if (avc.createGroup())
5533 alignPanel.alignmentChanged();
5538 protected void unGroup_actionPerformed(ActionEvent e)
5542 alignPanel.alignmentChanged();
5547 * make the given alignmentPanel the currently selected tab
5549 * @param alignmentPanel
5551 public void setDisplayedView(AlignmentPanel alignmentPanel)
5553 if (!viewport.getSequenceSetId()
5554 .equals(alignmentPanel.av.getSequenceSetId()))
5556 throw new Error(MessageManager.getString(
5557 "error.implementation_error_cannot_show_view_alignment_frame"));
5559 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5560 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5562 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5567 * Action on selection of menu options to Show or Hide annotations.
5570 * @param forSequences
5571 * update sequence-related annotations
5572 * @param forAlignment
5573 * update non-sequence-related annotations
5576 protected void setAnnotationsVisibility(boolean visible,
5577 boolean forSequences, boolean forAlignment)
5579 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5580 .getAlignmentAnnotation();
5585 for (AlignmentAnnotation aa : anns)
5588 * don't display non-positional annotations on an alignment
5590 if (aa.annotations == null)
5594 boolean apply = (aa.sequenceRef == null && forAlignment)
5595 || (aa.sequenceRef != null && forSequences);
5598 aa.visible = visible;
5601 alignPanel.validateAnnotationDimensions(true);
5602 alignPanel.alignmentChanged();
5606 * Store selected annotation sort order for the view and repaint.
5609 protected void sortAnnotations_actionPerformed()
5611 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5613 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5614 alignPanel.paintAlignment(false, false);
5619 * @return alignment panels in this alignment frame
5621 public List<? extends AlignmentViewPanel> getAlignPanels()
5623 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5627 * Open a new alignment window, with the cDNA associated with this (protein)
5628 * alignment, aligned as is the protein.
5630 protected void viewAsCdna_actionPerformed()
5632 // TODO no longer a menu action - refactor as required
5633 final AlignmentI alignment = getViewport().getAlignment();
5634 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5635 if (mappings == null)
5639 List<SequenceI> cdnaSeqs = new ArrayList<>();
5640 for (SequenceI aaSeq : alignment.getSequences())
5642 for (AlignedCodonFrame acf : mappings)
5644 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5648 * There is a cDNA mapping for this protein sequence - add to new
5649 * alignment. It will share the same dataset sequence as other mapped
5650 * cDNA (no new mappings need to be created).
5652 final Sequence newSeq = new Sequence(dnaSeq);
5653 newSeq.setDatasetSequence(dnaSeq);
5654 cdnaSeqs.add(newSeq);
5658 if (cdnaSeqs.size() == 0)
5660 // show a warning dialog no mapped cDNA
5663 AlignmentI cdna = new Alignment(
5664 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5665 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5666 AlignFrame.DEFAULT_HEIGHT);
5667 cdna.alignAs(alignment);
5668 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5670 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5671 AlignFrame.DEFAULT_HEIGHT);
5675 * Set visibility of dna/protein complement view (available when shown in a
5681 protected void showComplement_actionPerformed(boolean show)
5683 SplitContainerI sf = getSplitViewContainer();
5686 sf.setComplementVisible(this, show);
5691 * Generate the reverse (optionally complemented) of the selected sequences,
5692 * and add them to the alignment
5695 protected void showReverse_actionPerformed(boolean complement)
5697 AlignmentI al = null;
5700 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5701 al = dna.reverseCdna(complement);
5702 viewport.addAlignment(al, "");
5703 addHistoryItem(new EditCommand(
5704 MessageManager.getString("label.add_sequences"), Action.PASTE,
5705 al.getSequencesArray(), 0, al.getWidth(),
5706 viewport.getAlignment()));
5707 } catch (Exception ex)
5709 System.err.println(ex.getMessage());
5715 * Try to run a script in the Groovy console, having first ensured that this
5716 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5717 * be targeted at this alignment.
5720 protected void runGroovy_actionPerformed()
5722 Jalview.setCurrentAlignFrame(this);
5723 groovy.ui.Console console = Desktop.getGroovyConsole();
5724 if (console != null)
5728 console.runScript();
5729 } catch (Exception ex)
5731 System.err.println((ex.toString()));
5732 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5733 MessageManager.getString("label.couldnt_run_groovy_script"),
5734 MessageManager.getString("label.groovy_support_failed"),
5735 JvOptionPane.ERROR_MESSAGE);
5740 System.err.println("Can't run Groovy script as console not found");
5745 * Hides columns containing (or not containing) a specified feature, provided
5746 * that would not leave all columns hidden
5748 * @param featureType
5749 * @param columnsContaining
5752 public boolean hideFeatureColumns(String featureType,
5753 boolean columnsContaining)
5755 boolean notForHiding = avc.markColumnsContainingFeatures(
5756 columnsContaining, false, false, featureType);
5759 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5760 false, featureType))
5762 getViewport().hideSelectedColumns();
5770 protected void selectHighlightedColumns_actionPerformed(
5771 ActionEvent actionEvent)
5773 // include key modifier check in case user selects from menu
5774 avc.markHighlightedColumns(
5775 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5776 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5777 | ActionEvent.CTRL_MASK)) != 0);
5781 * Rebuilds the Colour menu, including any user-defined colours which have
5782 * been loaded either on startup or during the session
5784 public void buildColourMenu()
5786 colourMenu.removeAll();
5788 colourMenu.add(applyToAllGroups);
5789 colourMenu.add(textColour);
5790 colourMenu.addSeparator();
5792 ColourMenuHelper.addMenuItems(colourMenu, this, viewport.getAlignment(),
5795 colourMenu.addSeparator();
5796 colourMenu.add(conservationMenuItem);
5797 colourMenu.add(modifyConservation);
5798 colourMenu.add(abovePIDThreshold);
5799 colourMenu.add(modifyPID);
5800 colourMenu.add(annotationColour);
5802 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5803 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5807 * Open a dialog (if not already open) that allows the user to select and
5808 * calculate PCA or Tree analysis
5810 protected void openTreePcaDialog()
5812 if (alignPanel.getCalculationDialog() == null)
5814 new CalculationChooser(AlignFrame.this);
5819 * Sets the status of the HMMER menu
5821 public void updateHMMERStatus()
5823 hmmerMenu.setEnabled(HmmerCommand.isHmmerAvailable());
5827 protected void loadVcf_actionPerformed()
5829 JalviewFileChooser chooser = new JalviewFileChooser(
5830 Cache.getProperty("LAST_DIRECTORY"));
5831 chooser.setFileView(new JalviewFileView());
5832 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5833 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5835 int value = chooser.showOpenDialog(null);
5837 if (value == JalviewFileChooser.APPROVE_OPTION)
5839 String choice = chooser.getSelectedFile().getPath();
5840 Cache.setProperty("LAST_DIRECTORY", choice);
5841 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5842 new VCFLoader(choice).loadVCF(seqs, this);
5848 class PrintThread extends Thread
5852 public PrintThread(AlignmentPanel ap)
5857 static PageFormat pf;
5862 PrinterJob printJob = PrinterJob.getPrinterJob();
5866 printJob.setPrintable(ap, pf);
5870 printJob.setPrintable(ap);
5873 if (printJob.printDialog())
5878 } catch (Exception PrintException)
5880 PrintException.printStackTrace();