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 createSVG(File f)
1576 alignPanel.makeSVG(f);
1580 public void pageSetup_actionPerformed(ActionEvent e)
1582 PrinterJob printJob = PrinterJob.getPrinterJob();
1583 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1593 public void printMenuItem_actionPerformed(ActionEvent e)
1595 // Putting in a thread avoids Swing painting problems
1596 PrintThread thread = new PrintThread(alignPanel);
1601 public void exportFeatures_actionPerformed(ActionEvent e)
1603 new AnnotationExporter(alignPanel).exportFeatures();
1607 public void exportAnnotations_actionPerformed(ActionEvent e)
1609 new AnnotationExporter(alignPanel).exportAnnotations();
1613 public void associatedData_actionPerformed(ActionEvent e)
1614 throws IOException, InterruptedException
1616 // Pick the tree file
1617 JalviewFileChooser chooser = new JalviewFileChooser(
1618 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1619 chooser.setFileView(new JalviewFileView());
1620 chooser.setDialogTitle(
1621 MessageManager.getString("label.load_jalview_annotations"));
1622 chooser.setToolTipText(
1623 MessageManager.getString("label.load_jalview_annotations"));
1625 int value = chooser.showOpenDialog(null);
1627 if (value == JalviewFileChooser.APPROVE_OPTION)
1629 String choice = chooser.getSelectedFile().getPath();
1630 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1631 loadJalviewDataFile(choice, null, null, null);
1637 * Close the current view or all views in the alignment frame. If the frame
1638 * only contains one view then the alignment will be removed from memory.
1640 * @param closeAllTabs
1643 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1645 if (alignPanels != null && alignPanels.size() < 2)
1647 closeAllTabs = true;
1652 if (alignPanels != null)
1656 if (this.isClosed())
1658 // really close all the windows - otherwise wait till
1659 // setClosed(true) is called
1660 for (int i = 0; i < alignPanels.size(); i++)
1662 AlignmentPanel ap = alignPanels.get(i);
1669 closeView(alignPanel);
1676 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1677 * be called recursively, with the frame now in 'closed' state
1679 this.setClosed(true);
1681 } catch (Exception ex)
1683 ex.printStackTrace();
1688 * Close the specified panel and close up tabs appropriately.
1690 * @param panelToClose
1692 public void closeView(AlignmentPanel panelToClose)
1694 int index = tabbedPane.getSelectedIndex();
1695 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1696 alignPanels.remove(panelToClose);
1697 panelToClose.closePanel();
1698 panelToClose = null;
1700 tabbedPane.removeTabAt(closedindex);
1701 tabbedPane.validate();
1703 if (index > closedindex || index == tabbedPane.getTabCount())
1705 // modify currently selected tab index if necessary.
1709 this.tabSelectionChanged(index);
1715 void updateEditMenuBar()
1718 if (viewport.getHistoryList().size() > 0)
1720 undoMenuItem.setEnabled(true);
1721 CommandI command = viewport.getHistoryList().peek();
1722 undoMenuItem.setText(MessageManager
1723 .formatMessage("label.undo_command", new Object[]
1724 { command.getDescription() }));
1728 undoMenuItem.setEnabled(false);
1729 undoMenuItem.setText(MessageManager.getString("action.undo"));
1732 if (viewport.getRedoList().size() > 0)
1734 redoMenuItem.setEnabled(true);
1736 CommandI command = viewport.getRedoList().peek();
1737 redoMenuItem.setText(MessageManager
1738 .formatMessage("label.redo_command", new Object[]
1739 { command.getDescription() }));
1743 redoMenuItem.setEnabled(false);
1744 redoMenuItem.setText(MessageManager.getString("action.redo"));
1749 public void addHistoryItem(CommandI command)
1751 if (command.getSize() > 0)
1753 viewport.addToHistoryList(command);
1754 viewport.clearRedoList();
1755 updateEditMenuBar();
1756 viewport.updateHiddenColumns();
1757 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1758 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1759 // viewport.getColumnSelection()
1760 // .getHiddenColumns().size() > 0);
1766 * @return alignment objects for all views
1768 AlignmentI[] getViewAlignments()
1770 if (alignPanels != null)
1772 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1774 for (AlignmentPanel ap : alignPanels)
1776 als[i++] = ap.av.getAlignment();
1780 if (viewport != null)
1782 return new AlignmentI[] { viewport.getAlignment() };
1794 protected void undoMenuItem_actionPerformed(ActionEvent e)
1796 if (viewport.getHistoryList().isEmpty())
1800 CommandI command = viewport.getHistoryList().pop();
1801 viewport.addToRedoList(command);
1802 command.undoCommand(getViewAlignments());
1804 AlignmentViewport originalSource = getOriginatingSource(command);
1805 updateEditMenuBar();
1807 if (originalSource != null)
1809 if (originalSource != viewport)
1812 "Implementation worry: mismatch of viewport origin for undo");
1814 originalSource.updateHiddenColumns();
1815 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1817 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1818 // viewport.getColumnSelection()
1819 // .getHiddenColumns().size() > 0);
1820 originalSource.firePropertyChange("alignment", null,
1821 originalSource.getAlignment().getSequences());
1832 protected void redoMenuItem_actionPerformed(ActionEvent e)
1834 if (viewport.getRedoList().size() < 1)
1839 CommandI command = viewport.getRedoList().pop();
1840 viewport.addToHistoryList(command);
1841 command.doCommand(getViewAlignments());
1843 AlignmentViewport originalSource = getOriginatingSource(command);
1844 updateEditMenuBar();
1846 if (originalSource != null)
1849 if (originalSource != viewport)
1852 "Implementation worry: mismatch of viewport origin for redo");
1854 originalSource.updateHiddenColumns();
1855 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1857 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1858 // viewport.getColumnSelection()
1859 // .getHiddenColumns().size() > 0);
1860 originalSource.firePropertyChange("alignment", null,
1861 originalSource.getAlignment().getSequences());
1865 AlignmentViewport getOriginatingSource(CommandI command)
1867 AlignmentViewport originalSource = null;
1868 // For sequence removal and addition, we need to fire
1869 // the property change event FROM the viewport where the
1870 // original alignment was altered
1871 AlignmentI al = null;
1872 if (command instanceof EditCommand)
1874 EditCommand editCommand = (EditCommand) command;
1875 al = editCommand.getAlignment();
1876 List<Component> comps = PaintRefresher.components
1877 .get(viewport.getSequenceSetId());
1879 for (Component comp : comps)
1881 if (comp instanceof AlignmentPanel)
1883 if (al == ((AlignmentPanel) comp).av.getAlignment())
1885 originalSource = ((AlignmentPanel) comp).av;
1892 if (originalSource == null)
1894 // The original view is closed, we must validate
1895 // the current view against the closed view first
1898 PaintRefresher.validateSequences(al, viewport.getAlignment());
1901 originalSource = viewport;
1904 return originalSource;
1913 public void moveSelectedSequences(boolean up)
1915 SequenceGroup sg = viewport.getSelectionGroup();
1921 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1922 viewport.getHiddenRepSequences(), up);
1923 alignPanel.paintAlignment(true, false);
1926 synchronized void slideSequences(boolean right, int size)
1928 List<SequenceI> sg = new ArrayList<>();
1929 if (viewport.cursorMode)
1931 sg.add(viewport.getAlignment()
1932 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1934 else if (viewport.getSelectionGroup() != null
1935 && viewport.getSelectionGroup().getSize() != viewport
1936 .getAlignment().getHeight())
1938 sg = viewport.getSelectionGroup()
1939 .getSequences(viewport.getHiddenRepSequences());
1947 List<SequenceI> invertGroup = new ArrayList<>();
1949 for (SequenceI seq : viewport.getAlignment().getSequences())
1951 if (!sg.contains(seq))
1953 invertGroup.add(seq);
1957 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1959 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1960 for (int i = 0; i < invertGroup.size(); i++)
1962 seqs2[i] = invertGroup.get(i);
1965 SlideSequencesCommand ssc;
1968 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1969 viewport.getGapCharacter());
1973 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1974 viewport.getGapCharacter());
1977 int groupAdjustment = 0;
1978 if (ssc.getGapsInsertedBegin() && right)
1980 if (viewport.cursorMode)
1982 alignPanel.getSeqPanel().moveCursor(size, 0);
1986 groupAdjustment = size;
1989 else if (!ssc.getGapsInsertedBegin() && !right)
1991 if (viewport.cursorMode)
1993 alignPanel.getSeqPanel().moveCursor(-size, 0);
1997 groupAdjustment = -size;
2001 if (groupAdjustment != 0)
2003 viewport.getSelectionGroup().setStartRes(
2004 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
2005 viewport.getSelectionGroup().setEndRes(
2006 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
2010 * just extend the last slide command if compatible; but not if in
2011 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
2013 boolean appendHistoryItem = false;
2014 Deque<CommandI> historyList = viewport.getHistoryList();
2015 boolean inSplitFrame = getSplitViewContainer() != null;
2016 if (!inSplitFrame && historyList != null && historyList.size() > 0
2017 && historyList.peek() instanceof SlideSequencesCommand)
2019 appendHistoryItem = ssc.appendSlideCommand(
2020 (SlideSequencesCommand) historyList.peek());
2023 if (!appendHistoryItem)
2025 addHistoryItem(ssc);
2038 protected void copy_actionPerformed(ActionEvent e)
2040 if (viewport.getSelectionGroup() == null)
2044 // TODO: preserve the ordering of displayed alignment annotation in any
2045 // internal paste (particularly sequence associated annotation)
2046 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2047 String[] omitHidden = null;
2049 if (viewport.hasHiddenColumns())
2051 omitHidden = viewport.getViewAsString(true);
2054 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2055 seqs, omitHidden, null);
2057 StringSelection ss = new StringSelection(output);
2061 jalview.gui.Desktop.internalCopy = true;
2062 // Its really worth setting the clipboard contents
2063 // to empty before setting the large StringSelection!!
2064 Toolkit.getDefaultToolkit().getSystemClipboard()
2065 .setContents(new StringSelection(""), null);
2067 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2069 } catch (OutOfMemoryError er)
2071 new OOMWarning("copying region", er);
2075 HiddenColumns hiddenColumns = null;
2076 if (viewport.hasHiddenColumns())
2078 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2079 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2081 // create new HiddenColumns object with copy of hidden regions
2082 // between startRes and endRes, offset by startRes
2083 hiddenColumns = new HiddenColumns(
2084 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2085 hiddenCutoff, hiddenOffset);
2088 Desktop.jalviewClipboard = new Object[] { seqs,
2089 viewport.getAlignment().getDataset(), hiddenColumns };
2090 statusBar.setText(MessageManager.formatMessage(
2091 "label.copied_sequences_to_clipboard", new Object[]
2092 { Integer.valueOf(seqs.length).toString() }));
2100 * @throws InterruptedException
2101 * @throws IOException
2104 protected void pasteNew_actionPerformed(ActionEvent e)
2105 throws IOException, InterruptedException
2115 * @throws InterruptedException
2116 * @throws IOException
2119 protected void pasteThis_actionPerformed(ActionEvent e)
2120 throws IOException, InterruptedException
2126 * Paste contents of Jalview clipboard
2128 * @param newAlignment
2129 * true to paste to a new alignment, otherwise add to this.
2130 * @throws InterruptedException
2131 * @throws IOException
2133 void paste(boolean newAlignment) throws IOException, InterruptedException
2135 boolean externalPaste = true;
2138 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2139 Transferable contents = c.getContents(this);
2141 if (contents == null)
2150 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2151 if (str.length() < 1)
2156 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2158 } catch (OutOfMemoryError er)
2160 new OOMWarning("Out of memory pasting sequences!!", er);
2164 SequenceI[] sequences;
2165 boolean annotationAdded = false;
2166 AlignmentI alignment = null;
2168 if (Desktop.jalviewClipboard != null)
2170 // The clipboard was filled from within Jalview, we must use the
2172 // And dataset from the copied alignment
2173 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2174 // be doubly sure that we create *new* sequence objects.
2175 sequences = new SequenceI[newseq.length];
2176 for (int i = 0; i < newseq.length; i++)
2178 sequences[i] = new Sequence(newseq[i]);
2180 alignment = new Alignment(sequences);
2181 externalPaste = false;
2185 // parse the clipboard as an alignment.
2186 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2188 sequences = alignment.getSequencesArray();
2192 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2198 if (Desktop.jalviewClipboard != null)
2200 // dataset is inherited
2201 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2205 // new dataset is constructed
2206 alignment.setDataset(null);
2208 alwidth = alignment.getWidth() + 1;
2212 AlignmentI pastedal = alignment; // preserve pasted alignment object
2213 // Add pasted sequences and dataset into existing alignment.
2214 alignment = viewport.getAlignment();
2215 alwidth = alignment.getWidth() + 1;
2216 // decide if we need to import sequences from an existing dataset
2217 boolean importDs = Desktop.jalviewClipboard != null
2218 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2219 // importDs==true instructs us to copy over new dataset sequences from
2220 // an existing alignment
2221 Vector newDs = (importDs) ? new Vector() : null; // used to create
2222 // minimum dataset set
2224 for (int i = 0; i < sequences.length; i++)
2228 newDs.addElement(null);
2230 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2232 if (importDs && ds != null)
2234 if (!newDs.contains(ds))
2236 newDs.setElementAt(ds, i);
2237 ds = new Sequence(ds);
2238 // update with new dataset sequence
2239 sequences[i].setDatasetSequence(ds);
2243 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2248 // copy and derive new dataset sequence
2249 sequences[i] = sequences[i].deriveSequence();
2250 alignment.getDataset()
2251 .addSequence(sequences[i].getDatasetSequence());
2252 // TODO: avoid creation of duplicate dataset sequences with a
2253 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2255 alignment.addSequence(sequences[i]); // merges dataset
2259 newDs.clear(); // tidy up
2261 if (alignment.getAlignmentAnnotation() != null)
2263 for (AlignmentAnnotation alan : alignment
2264 .getAlignmentAnnotation())
2266 if (alan.graphGroup > fgroup)
2268 fgroup = alan.graphGroup;
2272 if (pastedal.getAlignmentAnnotation() != null)
2274 // Add any annotation attached to alignment.
2275 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2276 for (int i = 0; i < alann.length; i++)
2278 annotationAdded = true;
2279 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2281 AlignmentAnnotation newann = new AlignmentAnnotation(
2283 if (newann.graphGroup > -1)
2285 if (newGraphGroups.size() <= newann.graphGroup
2286 || newGraphGroups.get(newann.graphGroup) == null)
2288 for (int q = newGraphGroups
2289 .size(); q <= newann.graphGroup; q++)
2291 newGraphGroups.add(q, null);
2293 newGraphGroups.set(newann.graphGroup,
2294 new Integer(++fgroup));
2296 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2300 newann.padAnnotation(alwidth);
2301 alignment.addAnnotation(newann);
2311 addHistoryItem(new EditCommand(
2312 MessageManager.getString("label.add_sequences"),
2313 Action.PASTE, sequences, 0, alignment.getWidth(),
2316 // Add any annotations attached to sequences
2317 for (int i = 0; i < sequences.length; i++)
2319 if (sequences[i].getAnnotation() != null)
2321 AlignmentAnnotation newann;
2322 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2324 annotationAdded = true;
2325 newann = sequences[i].getAnnotation()[a];
2326 newann.adjustForAlignment();
2327 newann.padAnnotation(alwidth);
2328 if (newann.graphGroup > -1)
2330 if (newann.graphGroup > -1)
2332 if (newGraphGroups.size() <= newann.graphGroup
2333 || newGraphGroups.get(newann.graphGroup) == null)
2335 for (int q = newGraphGroups
2336 .size(); q <= newann.graphGroup; q++)
2338 newGraphGroups.add(q, null);
2340 newGraphGroups.set(newann.graphGroup,
2341 new Integer(++fgroup));
2343 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2347 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2351 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2359 // propagate alignment changed.
2360 viewport.getRanges().setEndSeq(alignment.getHeight());
2361 if (annotationAdded)
2363 // Duplicate sequence annotation in all views.
2364 AlignmentI[] alview = this.getViewAlignments();
2365 for (int i = 0; i < sequences.length; i++)
2367 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2372 for (int avnum = 0; avnum < alview.length; avnum++)
2374 if (alview[avnum] != alignment)
2376 // duplicate in a view other than the one with input focus
2377 int avwidth = alview[avnum].getWidth() + 1;
2378 // this relies on sann being preserved after we
2379 // modify the sequence's annotation array for each duplication
2380 for (int a = 0; a < sann.length; a++)
2382 AlignmentAnnotation newann = new AlignmentAnnotation(
2384 sequences[i].addAlignmentAnnotation(newann);
2385 newann.padAnnotation(avwidth);
2386 alview[avnum].addAnnotation(newann); // annotation was
2387 // duplicated earlier
2388 // TODO JAL-1145 graphGroups are not updated for sequence
2389 // annotation added to several views. This may cause
2391 alview[avnum].setAnnotationIndex(newann, a);
2396 buildSortByAnnotationScoresMenu();
2398 viewport.firePropertyChange("alignment", null,
2399 alignment.getSequences());
2400 if (alignPanels != null)
2402 for (AlignmentPanel ap : alignPanels)
2404 ap.validateAnnotationDimensions(false);
2409 alignPanel.validateAnnotationDimensions(false);
2415 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2417 String newtitle = new String("Copied sequences");
2419 if (Desktop.jalviewClipboard != null
2420 && Desktop.jalviewClipboard[2] != null)
2422 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2423 af.viewport.setHiddenColumns(hc);
2426 // >>>This is a fix for the moment, until a better solution is
2428 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2429 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2430 .getFeatureRenderer());
2432 // TODO: maintain provenance of an alignment, rather than just make the
2433 // title a concatenation of operations.
2436 if (title.startsWith("Copied sequences"))
2442 newtitle = newtitle.concat("- from " + title);
2447 newtitle = new String("Pasted sequences");
2450 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2455 } catch (Exception ex)
2457 ex.printStackTrace();
2458 System.out.println("Exception whilst pasting: " + ex);
2459 // could be anything being pasted in here
2464 protected void expand_newalign(ActionEvent e)
2468 AlignmentI alignment = AlignmentUtils
2469 .expandContext(getViewport().getAlignment(), -1);
2470 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2472 String newtitle = new String("Flanking alignment");
2474 if (Desktop.jalviewClipboard != null
2475 && Desktop.jalviewClipboard[2] != null)
2477 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2478 af.viewport.setHiddenColumns(hc);
2481 // >>>This is a fix for the moment, until a better solution is
2483 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2484 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2485 .getFeatureRenderer());
2487 // TODO: maintain provenance of an alignment, rather than just make the
2488 // title a concatenation of operations.
2490 if (title.startsWith("Copied sequences"))
2496 newtitle = newtitle.concat("- from " + title);
2500 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2502 } catch (Exception ex)
2504 ex.printStackTrace();
2505 System.out.println("Exception whilst pasting: " + ex);
2506 // could be anything being pasted in here
2507 } catch (OutOfMemoryError oom)
2509 new OOMWarning("Viewing flanking region of alignment", oom);
2520 protected void cut_actionPerformed(ActionEvent e)
2522 copy_actionPerformed(null);
2523 delete_actionPerformed(null);
2533 protected void delete_actionPerformed(ActionEvent evt)
2536 SequenceGroup sg = viewport.getSelectionGroup();
2543 * If the cut affects all sequences, warn, remove highlighted columns
2545 if (sg.getSize() == viewport.getAlignment().getHeight())
2547 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2548 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2549 if (isEntireAlignWidth)
2551 int confirm = JvOptionPane.showConfirmDialog(this,
2552 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2553 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2554 JvOptionPane.OK_CANCEL_OPTION);
2556 if (confirm == JvOptionPane.CANCEL_OPTION
2557 || confirm == JvOptionPane.CLOSED_OPTION)
2562 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2563 sg.getEndRes() + 1);
2565 SequenceI[] cut = sg.getSequences()
2566 .toArray(new SequenceI[sg.getSize()]);
2568 addHistoryItem(new EditCommand(
2569 MessageManager.getString("label.cut_sequences"), Action.CUT,
2570 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2571 viewport.getAlignment()));
2573 viewport.setSelectionGroup(null);
2574 viewport.sendSelection();
2575 viewport.getAlignment().deleteGroup(sg);
2577 viewport.firePropertyChange("alignment", null,
2578 viewport.getAlignment().getSequences());
2579 if (viewport.getAlignment().getHeight() < 1)
2583 this.setClosed(true);
2584 } catch (Exception ex)
2597 protected void deleteGroups_actionPerformed(ActionEvent e)
2599 if (avc.deleteGroups())
2601 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2602 alignPanel.updateAnnotation();
2603 alignPanel.paintAlignment(true, true);
2614 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2616 SequenceGroup sg = new SequenceGroup();
2618 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2620 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2623 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2624 viewport.setSelectionGroup(sg);
2625 viewport.sendSelection();
2626 // JAL-2034 - should delegate to
2627 // alignPanel to decide if overview needs
2629 alignPanel.paintAlignment(false, false);
2630 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2640 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2642 if (viewport.cursorMode)
2644 alignPanel.getSeqPanel().keyboardNo1 = null;
2645 alignPanel.getSeqPanel().keyboardNo2 = null;
2647 viewport.setSelectionGroup(null);
2648 viewport.getColumnSelection().clear();
2649 viewport.setSelectionGroup(null);
2650 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2651 // JAL-2034 - should delegate to
2652 // alignPanel to decide if overview needs
2654 alignPanel.paintAlignment(false, false);
2655 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2656 viewport.sendSelection();
2666 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2668 SequenceGroup sg = viewport.getSelectionGroup();
2672 selectAllSequenceMenuItem_actionPerformed(null);
2677 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2679 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2681 // JAL-2034 - should delegate to
2682 // alignPanel to decide if overview needs
2685 alignPanel.paintAlignment(true, false);
2686 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2687 viewport.sendSelection();
2691 public void invertColSel_actionPerformed(ActionEvent e)
2693 viewport.invertColumnSelection();
2694 alignPanel.paintAlignment(true, false);
2695 viewport.sendSelection();
2705 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2707 trimAlignment(true);
2717 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2719 trimAlignment(false);
2722 void trimAlignment(boolean trimLeft)
2724 ColumnSelection colSel = viewport.getColumnSelection();
2727 if (!colSel.isEmpty())
2731 column = colSel.getMin();
2735 column = colSel.getMax();
2739 if (viewport.getSelectionGroup() != null)
2741 seqs = viewport.getSelectionGroup()
2742 .getSequencesAsArray(viewport.getHiddenRepSequences());
2746 seqs = viewport.getAlignment().getSequencesArray();
2749 TrimRegionCommand trimRegion;
2752 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2753 column, viewport.getAlignment());
2754 viewport.getRanges().setStartRes(0);
2758 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2759 column, viewport.getAlignment());
2762 statusBar.setText(MessageManager
2763 .formatMessage("label.removed_columns", new String[]
2764 { Integer.valueOf(trimRegion.getSize()).toString() }));
2766 addHistoryItem(trimRegion);
2768 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2770 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2771 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2773 viewport.getAlignment().deleteGroup(sg);
2777 viewport.firePropertyChange("alignment", null,
2778 viewport.getAlignment().getSequences());
2789 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2791 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2794 if (viewport.getSelectionGroup() != null)
2796 seqs = viewport.getSelectionGroup()
2797 .getSequencesAsArray(viewport.getHiddenRepSequences());
2798 start = viewport.getSelectionGroup().getStartRes();
2799 end = viewport.getSelectionGroup().getEndRes();
2803 seqs = viewport.getAlignment().getSequencesArray();
2806 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2807 "Remove Gapped Columns", seqs, start, end,
2808 viewport.getAlignment());
2810 addHistoryItem(removeGapCols);
2812 statusBar.setText(MessageManager
2813 .formatMessage("label.removed_empty_columns", new Object[]
2814 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2816 // This is to maintain viewport position on first residue
2817 // of first sequence
2818 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2819 ViewportRanges ranges = viewport.getRanges();
2820 int startRes = seq.findPosition(ranges.getStartRes());
2821 // ShiftList shifts;
2822 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2823 // edit.alColumnChanges=shifts.getInverse();
2824 // if (viewport.hasHiddenColumns)
2825 // viewport.getColumnSelection().compensateForEdits(shifts);
2826 ranges.setStartRes(seq.findIndex(startRes) - 1);
2827 viewport.firePropertyChange("alignment", null,
2828 viewport.getAlignment().getSequences());
2839 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2841 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2844 if (viewport.getSelectionGroup() != null)
2846 seqs = viewport.getSelectionGroup()
2847 .getSequencesAsArray(viewport.getHiddenRepSequences());
2848 start = viewport.getSelectionGroup().getStartRes();
2849 end = viewport.getSelectionGroup().getEndRes();
2853 seqs = viewport.getAlignment().getSequencesArray();
2856 // This is to maintain viewport position on first residue
2857 // of first sequence
2858 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2859 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2861 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2862 viewport.getAlignment()));
2864 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2866 viewport.firePropertyChange("alignment", null,
2867 viewport.getAlignment().getSequences());
2878 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2880 viewport.setPadGaps(padGapsMenuitem.isSelected());
2881 viewport.firePropertyChange("alignment", null,
2882 viewport.getAlignment().getSequences());
2892 public void findMenuItem_actionPerformed(ActionEvent e)
2898 * Create a new view of the current alignment.
2901 public void newView_actionPerformed(ActionEvent e)
2903 newView(null, true);
2907 * Creates and shows a new view of the current alignment.
2910 * title of newly created view; if null, one will be generated
2911 * @param copyAnnotation
2912 * if true then duplicate all annnotation, groups and settings
2913 * @return new alignment panel, already displayed.
2915 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2918 * Create a new AlignmentPanel (with its own, new Viewport)
2920 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel);
2921 if (!copyAnnotation)
2924 * remove all groups and annotation except for the automatic stuff
2926 newap.av.getAlignment().deleteAllGroups();
2927 newap.av.getAlignment().deleteAllAnnotations(false);
2930 newap.av.setGatherViewsHere(false);
2932 if (viewport.viewName == null)
2934 viewport.viewName = MessageManager
2935 .getString("label.view_name_original");
2939 * Views share the same edits undo and redo stacks
2941 newap.av.setHistoryList(viewport.getHistoryList());
2942 newap.av.setRedoList(viewport.getRedoList());
2945 * Views share the same mappings; need to deregister any new mappings
2946 * created by copyAlignPanel, and register the new reference to the shared
2949 newap.av.replaceMappings(viewport.getAlignment());
2952 * start up cDNA consensus (if applicable) now mappings are in place
2954 if (newap.av.initComplementConsensus())
2956 newap.refresh(true); // adjust layout of annotations
2959 newap.av.viewName = getNewViewName(viewTitle);
2961 addAlignmentPanel(newap, true);
2962 newap.alignmentChanged();
2964 if (alignPanels.size() == 2)
2966 viewport.setGatherViewsHere(true);
2968 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2973 * Make a new name for the view, ensuring it is unique within the current
2974 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2975 * these now use viewId. Unique view names are still desirable for usability.)
2980 protected String getNewViewName(String viewTitle)
2982 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2983 boolean addFirstIndex = false;
2984 if (viewTitle == null || viewTitle.trim().length() == 0)
2986 viewTitle = MessageManager.getString("action.view");
2987 addFirstIndex = true;
2991 index = 1;// we count from 1 if given a specific name
2993 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2995 List<Component> comps = PaintRefresher.components
2996 .get(viewport.getSequenceSetId());
2998 List<String> existingNames = getExistingViewNames(comps);
3000 while (existingNames.contains(newViewName))
3002 newViewName = viewTitle + " " + (++index);
3008 * Returns a list of distinct view names found in the given list of
3009 * components. View names are held on the viewport of an AlignmentPanel.
3014 protected List<String> getExistingViewNames(List<Component> comps)
3016 List<String> existingNames = new ArrayList<>();
3017 for (Component comp : comps)
3019 if (comp instanceof AlignmentPanel)
3021 AlignmentPanel ap = (AlignmentPanel) comp;
3022 if (!existingNames.contains(ap.av.viewName))
3024 existingNames.add(ap.av.viewName);
3028 return existingNames;
3032 * Explode tabbed views into separate windows.
3035 public void expandViews_actionPerformed(ActionEvent e)
3037 Desktop.explodeViews(this);
3041 * Gather views in separate windows back into a tabbed presentation.
3044 public void gatherViews_actionPerformed(ActionEvent e)
3046 Desktop.instance.gatherViews(this);
3056 public void font_actionPerformed(ActionEvent e)
3058 new FontChooser(alignPanel);
3068 protected void seqLimit_actionPerformed(ActionEvent e)
3070 viewport.setShowJVSuffix(seqLimits.isSelected());
3072 alignPanel.getIdPanel().getIdCanvas()
3073 .setPreferredSize(alignPanel.calculateIdWidth());
3074 alignPanel.paintAlignment(true, false);
3078 public void idRightAlign_actionPerformed(ActionEvent e)
3080 viewport.setRightAlignIds(idRightAlign.isSelected());
3081 alignPanel.paintAlignment(false, false);
3085 public void centreColumnLabels_actionPerformed(ActionEvent e)
3087 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3088 alignPanel.paintAlignment(false, false);
3094 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3097 protected void followHighlight_actionPerformed()
3100 * Set the 'follow' flag on the Viewport (and scroll to position if now
3103 final boolean state = this.followHighlightMenuItem.getState();
3104 viewport.setFollowHighlight(state);
3107 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
3118 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3120 viewport.setColourText(colourTextMenuItem.isSelected());
3121 alignPanel.paintAlignment(false, false);
3131 public void wrapMenuItem_actionPerformed(ActionEvent e)
3133 scaleAbove.setVisible(wrapMenuItem.isSelected());
3134 scaleLeft.setVisible(wrapMenuItem.isSelected());
3135 scaleRight.setVisible(wrapMenuItem.isSelected());
3136 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3137 alignPanel.updateLayout();
3141 public void showAllSeqs_actionPerformed(ActionEvent e)
3143 viewport.showAllHiddenSeqs();
3147 public void showAllColumns_actionPerformed(ActionEvent e)
3149 viewport.showAllHiddenColumns();
3150 alignPanel.paintAlignment(true, true);
3151 viewport.sendSelection();
3155 public void hideSelSequences_actionPerformed(ActionEvent e)
3157 viewport.hideAllSelectedSeqs();
3161 * called by key handler and the hide all/show all menu items
3166 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3169 boolean hide = false;
3170 SequenceGroup sg = viewport.getSelectionGroup();
3171 if (!toggleSeqs && !toggleCols)
3173 // Hide everything by the current selection - this is a hack - we do the
3174 // invert and then hide
3175 // first check that there will be visible columns after the invert.
3176 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3177 && sg.getStartRes() <= sg.getEndRes()))
3179 // now invert the sequence set, if required - empty selection implies
3180 // that no hiding is required.
3183 invertSequenceMenuItem_actionPerformed(null);
3184 sg = viewport.getSelectionGroup();
3188 viewport.expandColSelection(sg, true);
3189 // finally invert the column selection and get the new sequence
3191 invertColSel_actionPerformed(null);
3198 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3200 hideSelSequences_actionPerformed(null);
3203 else if (!(toggleCols && viewport.hasSelectedColumns()))
3205 showAllSeqs_actionPerformed(null);
3211 if (viewport.hasSelectedColumns())
3213 hideSelColumns_actionPerformed(null);
3216 viewport.setSelectionGroup(sg);
3221 showAllColumns_actionPerformed(null);
3230 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3231 * event.ActionEvent)
3234 public void hideAllButSelection_actionPerformed(ActionEvent e)
3236 toggleHiddenRegions(false, false);
3237 viewport.sendSelection();
3244 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3248 public void hideAllSelection_actionPerformed(ActionEvent e)
3250 SequenceGroup sg = viewport.getSelectionGroup();
3251 viewport.expandColSelection(sg, false);
3252 viewport.hideAllSelectedSeqs();
3253 viewport.hideSelectedColumns();
3254 alignPanel.paintAlignment(true, true);
3255 viewport.sendSelection();
3262 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3266 public void showAllhidden_actionPerformed(ActionEvent e)
3268 viewport.showAllHiddenColumns();
3269 viewport.showAllHiddenSeqs();
3270 alignPanel.paintAlignment(true, true);
3271 viewport.sendSelection();
3275 public void hideSelColumns_actionPerformed(ActionEvent e)
3277 viewport.hideSelectedColumns();
3278 alignPanel.paintAlignment(true, true);
3279 viewport.sendSelection();
3283 public void hiddenMarkers_actionPerformed(ActionEvent e)
3285 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3296 protected void scaleAbove_actionPerformed(ActionEvent e)
3298 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3299 // TODO: do we actually need to update overview for scale above change ?
3300 alignPanel.paintAlignment(true, false);
3310 protected void scaleLeft_actionPerformed(ActionEvent e)
3312 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3313 alignPanel.paintAlignment(true, false);
3323 protected void scaleRight_actionPerformed(ActionEvent e)
3325 viewport.setScaleRightWrapped(scaleRight.isSelected());
3326 alignPanel.paintAlignment(true, false);
3336 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3338 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3339 alignPanel.paintAlignment(false, false);
3349 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3351 viewport.setShowText(viewTextMenuItem.isSelected());
3352 alignPanel.paintAlignment(false, false);
3362 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3364 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3365 alignPanel.paintAlignment(false, false);
3368 public FeatureSettings featureSettings;
3371 public FeatureSettingsControllerI getFeatureSettingsUI()
3373 return featureSettings;
3377 public void featureSettings_actionPerformed(ActionEvent e)
3379 if (featureSettings != null)
3381 featureSettings.close();
3382 featureSettings = null;
3384 if (!showSeqFeatures.isSelected())
3386 // make sure features are actually displayed
3387 showSeqFeatures.setSelected(true);
3388 showSeqFeatures_actionPerformed(null);
3390 featureSettings = new FeatureSettings(this);
3394 * Set or clear 'Show Sequence Features'
3400 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3402 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3403 alignPanel.paintAlignment(true, true);
3407 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3408 * the annotations panel as a whole.
3410 * The options to show/hide all annotations should be enabled when the panel
3411 * is shown, and disabled when the panel is hidden.
3416 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3418 final boolean setVisible = annotationPanelMenuItem.isSelected();
3419 viewport.setShowAnnotation(setVisible);
3420 this.showAllSeqAnnotations.setEnabled(setVisible);
3421 this.hideAllSeqAnnotations.setEnabled(setVisible);
3422 this.showAllAlAnnotations.setEnabled(setVisible);
3423 this.hideAllAlAnnotations.setEnabled(setVisible);
3424 alignPanel.updateLayout();
3428 public void alignmentProperties()
3430 JEditorPane editPane = new JEditorPane("text/html", "");
3431 editPane.setEditable(false);
3432 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3435 MessageManager.formatMessage("label.html_content", new Object[]
3436 { contents.toString() }));
3437 JInternalFrame frame = new JInternalFrame();
3438 frame.getContentPane().add(new JScrollPane(editPane));
3440 Desktop.addInternalFrame(frame, MessageManager
3441 .formatMessage("label.alignment_properties", new Object[]
3442 { getTitle() }), 500, 400);
3452 public void overviewMenuItem_actionPerformed(ActionEvent e)
3454 if (alignPanel.overviewPanel != null)
3459 JInternalFrame frame = new JInternalFrame();
3460 final OverviewPanel overview = new OverviewPanel(alignPanel);
3461 frame.setContentPane(overview);
3462 Desktop.addInternalFrame(frame, MessageManager
3463 .formatMessage("label.overview_params", new Object[]
3464 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3467 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3468 frame.addInternalFrameListener(
3469 new javax.swing.event.InternalFrameAdapter()
3472 public void internalFrameClosed(
3473 javax.swing.event.InternalFrameEvent evt)
3476 alignPanel.setOverviewPanel(null);
3479 if (getKeyListeners().length > 0)
3481 frame.addKeyListener(getKeyListeners()[0]);
3484 alignPanel.setOverviewPanel(overview);
3488 public void textColour_actionPerformed()
3490 new TextColourChooser().chooseColour(alignPanel, null);
3494 * public void covariationColour_actionPerformed() {
3496 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3500 public void annotationColour_actionPerformed()
3502 new AnnotationColourChooser(viewport, alignPanel);
3506 public void annotationColumn_actionPerformed(ActionEvent e)
3508 new AnnotationColumnChooser(viewport, alignPanel);
3512 * Action on the user checking or unchecking the option to apply the selected
3513 * colour scheme to all groups. If unchecked, groups may have their own
3514 * independent colour schemes.
3519 public void applyToAllGroups_actionPerformed(boolean selected)
3521 viewport.setColourAppliesToAllGroups(selected);
3525 * Action on user selecting a colour from the colour menu
3528 * the name (not the menu item label!) of the colour scheme
3531 public void changeColour_actionPerformed(String name)
3534 * 'User Defined' opens a panel to configure or load a
3535 * user-defined colour scheme
3537 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3539 new UserDefinedColours(alignPanel);
3544 * otherwise set the chosen colour scheme (or null for 'None')
3546 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3547 viewport.getAlignment(), viewport.getHiddenRepSequences());
3552 * Actions on setting or changing the alignment colour scheme
3557 public void changeColour(ColourSchemeI cs)
3559 // TODO: pull up to controller method
3560 ColourMenuHelper.setColourSelected(colourMenu, cs);
3562 viewport.setGlobalColourScheme(cs);
3564 alignPanel.paintAlignment(true, true);
3568 * Show the PID threshold slider panel
3571 protected void modifyPID_actionPerformed()
3573 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3574 alignPanel.getViewName());
3575 SliderPanel.showPIDSlider();
3579 * Show the Conservation slider panel
3582 protected void modifyConservation_actionPerformed()
3584 SliderPanel.setConservationSlider(alignPanel,
3585 viewport.getResidueShading(), alignPanel.getViewName());
3586 SliderPanel.showConservationSlider();
3590 * Action on selecting or deselecting (Colour) By Conservation
3593 public void conservationMenuItem_actionPerformed(boolean selected)
3595 modifyConservation.setEnabled(selected);
3596 viewport.setConservationSelected(selected);
3597 viewport.getResidueShading().setConservationApplied(selected);
3599 changeColour(viewport.getGlobalColourScheme());
3602 modifyConservation_actionPerformed();
3606 SliderPanel.hideConservationSlider();
3611 * Action on selecting or deselecting (Colour) Above PID Threshold
3614 public void abovePIDThreshold_actionPerformed(boolean selected)
3616 modifyPID.setEnabled(selected);
3617 viewport.setAbovePIDThreshold(selected);
3620 viewport.getResidueShading().setThreshold(0,
3621 viewport.isIgnoreGapsConsensus());
3624 changeColour(viewport.getGlobalColourScheme());
3627 modifyPID_actionPerformed();
3631 SliderPanel.hidePIDSlider();
3642 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3644 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3645 AlignmentSorter.sortByPID(viewport.getAlignment(),
3646 viewport.getAlignment().getSequenceAt(0));
3647 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3648 viewport.getAlignment()));
3649 alignPanel.paintAlignment(true, false);
3659 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3661 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3662 AlignmentSorter.sortByID(viewport.getAlignment());
3664 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3665 alignPanel.paintAlignment(true, false);
3675 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3677 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3678 AlignmentSorter.sortByLength(viewport.getAlignment());
3679 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3680 viewport.getAlignment()));
3681 alignPanel.paintAlignment(true, false);
3691 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3693 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3694 AlignmentSorter.sortByGroup(viewport.getAlignment());
3695 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3696 viewport.getAlignment()));
3698 alignPanel.paintAlignment(true, false);
3708 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3710 new RedundancyPanel(alignPanel, this);
3720 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3722 if ((viewport.getSelectionGroup() == null)
3723 || (viewport.getSelectionGroup().getSize() < 2))
3725 JvOptionPane.showInternalMessageDialog(this,
3726 MessageManager.getString(
3727 "label.you_must_select_least_two_sequences"),
3728 MessageManager.getString("label.invalid_selection"),
3729 JvOptionPane.WARNING_MESSAGE);
3733 JInternalFrame frame = new JInternalFrame();
3734 frame.setContentPane(new PairwiseAlignPanel(viewport));
3735 Desktop.addInternalFrame(frame,
3736 MessageManager.getString("action.pairwise_alignment"), 600,
3742 public void autoCalculate_actionPerformed(ActionEvent e)
3744 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3745 if (viewport.autoCalculateConsensus)
3747 viewport.firePropertyChange("alignment", null,
3748 viewport.getAlignment().getSequences());
3753 public void sortByTreeOption_actionPerformed(ActionEvent e)
3755 viewport.sortByTree = sortByTree.isSelected();
3759 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3761 viewport.followSelection = listenToViewSelections.isSelected();
3765 * Constructs a tree panel and adds it to the desktop
3768 * tree type (NJ or AV)
3770 * name of score model used to compute the tree
3772 * parameters for the distance or similarity calculation
3774 void newTreePanel(String type, String modelName,
3775 SimilarityParamsI options)
3777 String frameTitle = "";
3780 boolean onSelection = false;
3781 if (viewport.getSelectionGroup() != null
3782 && viewport.getSelectionGroup().getSize() > 0)
3784 SequenceGroup sg = viewport.getSelectionGroup();
3786 /* Decide if the selection is a column region */
3787 for (SequenceI _s : sg.getSequences())
3789 if (_s.getLength() < sg.getEndRes())
3791 JvOptionPane.showMessageDialog(Desktop.desktop,
3792 MessageManager.getString(
3793 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3794 MessageManager.getString(
3795 "label.sequences_selection_not_aligned"),
3796 JvOptionPane.WARNING_MESSAGE);
3805 if (viewport.getAlignment().getHeight() < 2)
3811 tp = new TreePanel(alignPanel, type, modelName, options);
3812 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3814 frameTitle += " from ";
3816 if (viewport.viewName != null)
3818 frameTitle += viewport.viewName + " of ";
3821 frameTitle += this.title;
3823 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3834 public void addSortByOrderMenuItem(String title,
3835 final AlignmentOrder order)
3837 final JMenuItem item = new JMenuItem(MessageManager
3838 .formatMessage("action.by_title_param", new Object[]
3841 item.addActionListener(new java.awt.event.ActionListener()
3844 public void actionPerformed(ActionEvent e)
3846 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3848 // TODO: JBPNote - have to map order entries to curent SequenceI
3850 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3852 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3853 viewport.getAlignment()));
3855 alignPanel.paintAlignment(true, false);
3861 * Add a new sort by annotation score menu item
3864 * the menu to add the option to
3866 * the label used to retrieve scores for each sequence on the
3869 public void addSortByAnnotScoreMenuItem(JMenu sort,
3870 final String scoreLabel)
3872 final JMenuItem item = new JMenuItem(scoreLabel);
3874 item.addActionListener(new java.awt.event.ActionListener()
3877 public void actionPerformed(ActionEvent e)
3879 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3880 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3881 viewport.getAlignment());// ,viewport.getSelectionGroup());
3882 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3883 viewport.getAlignment()));
3884 alignPanel.paintAlignment(true, false);
3890 * last hash for alignment's annotation array - used to minimise cost of
3893 protected int _annotationScoreVectorHash;
3896 * search the alignment and rebuild the sort by annotation score submenu the
3897 * last alignment annotation vector hash is stored to minimize cost of
3898 * rebuilding in subsequence calls.
3902 public void buildSortByAnnotationScoresMenu()
3904 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3909 if (viewport.getAlignment().getAlignmentAnnotation()
3910 .hashCode() == _annotationScoreVectorHash)
3915 sortByAnnotScore.removeAll();
3916 Set<String> scoreSorts = new HashSet<>();
3917 for (SequenceI sqa : viewport.getAlignment().getSequences())
3919 AlignmentAnnotation[] anns = sqa.getAnnotation();
3920 for (int i = 0; anns != null && i < anns.length; i++)
3922 AlignmentAnnotation aa = anns[i];
3923 if (aa != null && aa.hasScore() && aa.sequenceRef != null)
3925 scoreSorts.add(aa.label);
3929 for (String label : scoreSorts)
3931 addSortByAnnotScoreMenuItem(sortByAnnotScore, label);
3933 sortByAnnotScore.setVisible(!scoreSorts.isEmpty());
3935 _annotationScoreVectorHash = viewport.getAlignment()
3936 .getAlignmentAnnotation().hashCode();
3940 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3941 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3942 * call. Listeners are added to remove the menu item when the treePanel is
3943 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3947 public void buildTreeSortMenu()
3949 sortByTreeMenu.removeAll();
3951 List<Component> comps = PaintRefresher.components
3952 .get(viewport.getSequenceSetId());
3953 List<TreePanel> treePanels = new ArrayList<>();
3954 for (Component comp : comps)
3956 if (comp instanceof TreePanel)
3958 treePanels.add((TreePanel) comp);
3962 if (treePanels.size() < 1)
3964 sortByTreeMenu.setVisible(false);
3968 sortByTreeMenu.setVisible(true);
3970 for (final TreePanel tp : treePanels)
3972 final JMenuItem item = new JMenuItem(tp.getTitle());
3973 item.addActionListener(new java.awt.event.ActionListener()
3976 public void actionPerformed(ActionEvent e)
3978 tp.sortByTree_actionPerformed();
3979 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3984 sortByTreeMenu.add(item);
3988 public boolean sortBy(AlignmentOrder alorder, String undoname)
3990 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3991 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3992 if (undoname != null)
3994 addHistoryItem(new OrderCommand(undoname, oldOrder,
3995 viewport.getAlignment()));
3997 alignPanel.paintAlignment(true, false);
4002 * Work out whether the whole set of sequences or just the selected set will
4003 * be submitted for multiple alignment.
4006 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4008 // Now, check we have enough sequences
4009 AlignmentView msa = null;
4011 if ((viewport.getSelectionGroup() != null)
4012 && (viewport.getSelectionGroup().getSize() > 1))
4014 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4015 // some common interface!
4017 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4018 * SequenceI[sz = seqs.getSize(false)];
4020 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4021 * seqs.getSequenceAt(i); }
4023 msa = viewport.getAlignmentView(true);
4025 else if (viewport.getSelectionGroup() != null
4026 && viewport.getSelectionGroup().getSize() == 1)
4028 int option = JvOptionPane.showConfirmDialog(this,
4029 MessageManager.getString("warn.oneseq_msainput_selection"),
4030 MessageManager.getString("label.invalid_selection"),
4031 JvOptionPane.OK_CANCEL_OPTION);
4032 if (option == JvOptionPane.OK_OPTION)
4034 msa = viewport.getAlignmentView(false);
4039 msa = viewport.getAlignmentView(false);
4045 * Decides what is submitted to a secondary structure prediction service: the
4046 * first sequence in the alignment, or in the current selection, or, if the
4047 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4048 * region or the whole alignment. (where the first sequence in the set is the
4049 * one that the prediction will be for).
4051 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4053 AlignmentView seqs = null;
4055 if ((viewport.getSelectionGroup() != null)
4056 && (viewport.getSelectionGroup().getSize() > 0))
4058 seqs = viewport.getAlignmentView(true);
4062 seqs = viewport.getAlignmentView(false);
4064 // limit sequences - JBPNote in future - could spawn multiple prediction
4066 // TODO: viewport.getAlignment().isAligned is a global state - the local
4067 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4068 if (!viewport.getAlignment().isAligned(false))
4070 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4071 // TODO: if seqs.getSequences().length>1 then should really have warned
4085 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4087 // Pick the tree file
4088 JalviewFileChooser chooser = new JalviewFileChooser(
4089 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4090 chooser.setFileView(new JalviewFileView());
4091 chooser.setDialogTitle(
4092 MessageManager.getString("label.select_newick_like_tree_file"));
4093 chooser.setToolTipText(
4094 MessageManager.getString("label.load_tree_file"));
4096 int value = chooser.showOpenDialog(null);
4098 if (value == JalviewFileChooser.APPROVE_OPTION)
4100 String filePath = chooser.getSelectedFile().getPath();
4101 Cache.setProperty("LAST_DIRECTORY", filePath);
4102 NewickFile fin = null;
4105 fin = new NewickFile(filePath, DataSourceType.FILE);
4106 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4107 } catch (Exception ex)
4109 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4110 MessageManager.getString("label.problem_reading_tree_file"),
4111 JvOptionPane.WARNING_MESSAGE);
4112 ex.printStackTrace();
4114 if (fin != null && fin.hasWarningMessage())
4116 JvOptionPane.showMessageDialog(Desktop.desktop,
4117 fin.getWarningMessage(),
4119 .getString("label.possible_problem_with_tree_file"),
4120 JvOptionPane.WARNING_MESSAGE);
4125 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4127 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4130 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4131 int h, int x, int y)
4133 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4137 * Add a treeviewer for the tree extracted from a Newick file object to the
4138 * current alignment view
4145 * Associated alignment input data (or null)
4154 * @return TreePanel handle
4156 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4157 AlignmentView input, int w, int h, int x, int y)
4159 TreePanel tp = null;
4165 if (nf.getTree() != null)
4167 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4173 tp.setLocation(x, y);
4176 Desktop.addInternalFrame(tp, treeTitle, w, h);
4178 } catch (Exception ex)
4180 ex.printStackTrace();
4186 private boolean buildingMenu = false;
4189 * Generates menu items and listener event actions for web service clients
4192 public void BuildWebServiceMenu()
4194 while (buildingMenu)
4198 System.err.println("Waiting for building menu to finish.");
4200 } catch (Exception e)
4204 final AlignFrame me = this;
4205 buildingMenu = true;
4206 new Thread(new Runnable()
4211 final List<JMenuItem> legacyItems = new ArrayList<>();
4214 // System.err.println("Building ws menu again "
4215 // + Thread.currentThread());
4216 // TODO: add support for context dependent disabling of services based
4218 // alignment and current selection
4219 // TODO: add additional serviceHandle parameter to specify abstract
4221 // class independently of AbstractName
4222 // TODO: add in rediscovery GUI function to restart discoverer
4223 // TODO: group services by location as well as function and/or
4225 // object broker mechanism.
4226 final Vector<JMenu> wsmenu = new Vector<>();
4227 final IProgressIndicator af = me;
4230 * do not i18n these strings - they are hard-coded in class
4231 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4232 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4234 final JMenu msawsmenu = new JMenu("Alignment");
4235 final JMenu secstrmenu = new JMenu(
4236 "Secondary Structure Prediction");
4237 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4238 final JMenu analymenu = new JMenu("Analysis");
4239 final JMenu dismenu = new JMenu("Protein Disorder");
4240 // JAL-940 - only show secondary structure prediction services from
4241 // the legacy server
4242 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4244 Discoverer.services != null && (Discoverer.services.size() > 0))
4246 // TODO: refactor to allow list of AbstractName/Handler bindings to
4248 // stored or retrieved from elsewhere
4249 // No MSAWS used any more:
4250 // Vector msaws = null; // (Vector)
4251 // Discoverer.services.get("MsaWS");
4252 Vector secstrpr = (Vector) Discoverer.services
4254 if (secstrpr != null)
4256 // Add any secondary structure prediction services
4257 for (int i = 0, j = secstrpr.size(); i < j; i++)
4259 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4261 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4262 .getServiceClient(sh);
4263 int p = secstrmenu.getItemCount();
4264 impl.attachWSMenuEntry(secstrmenu, me);
4265 int q = secstrmenu.getItemCount();
4266 for (int litm = p; litm < q; litm++)
4268 legacyItems.add(secstrmenu.getItem(litm));
4274 // Add all submenus in the order they should appear on the web
4276 wsmenu.add(msawsmenu);
4277 wsmenu.add(secstrmenu);
4278 wsmenu.add(dismenu);
4279 wsmenu.add(analymenu);
4280 // No search services yet
4281 // wsmenu.add(seqsrchmenu);
4283 javax.swing.SwingUtilities.invokeLater(new Runnable()
4290 webService.removeAll();
4291 // first, add discovered services onto the webservices menu
4292 if (wsmenu.size() > 0)
4294 for (int i = 0, j = wsmenu.size(); i < j; i++)
4296 webService.add(wsmenu.get(i));
4301 webService.add(me.webServiceNoServices);
4303 // TODO: move into separate menu builder class.
4304 boolean new_sspred = false;
4305 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4307 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4308 if (jws2servs != null)
4310 if (jws2servs.hasServices())
4312 jws2servs.attachWSMenuEntry(webService, me);
4313 for (Jws2Instance sv : jws2servs.getServices())
4315 if (sv.description.toLowerCase().contains("jpred"))
4317 for (JMenuItem jmi : legacyItems)
4319 jmi.setVisible(false);
4325 if (jws2servs.isRunning())
4327 JMenuItem tm = new JMenuItem(
4328 "Still discovering JABA Services");
4329 tm.setEnabled(false);
4334 build_urlServiceMenu(me.webService);
4335 build_fetchdbmenu(webService);
4336 for (JMenu item : wsmenu)
4338 if (item.getItemCount() == 0)
4340 item.setEnabled(false);
4344 item.setEnabled(true);
4347 } catch (Exception e)
4350 "Exception during web service menu building process.",
4355 } catch (Exception e)
4358 buildingMenu = false;
4365 * construct any groupURL type service menu entries.
4369 private void build_urlServiceMenu(JMenu webService)
4371 // TODO: remove this code when 2.7 is released
4372 // DEBUG - alignmentView
4374 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4375 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4377 * @Override public void actionPerformed(ActionEvent e) {
4378 * jalview.datamodel.AlignmentView
4379 * .testSelectionViews(af.viewport.getAlignment(),
4380 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4382 * }); webService.add(testAlView);
4384 // TODO: refactor to RestClient discoverer and merge menu entries for
4385 // rest-style services with other types of analysis/calculation service
4386 // SHmmr test client - still being implemented.
4387 // DEBUG - alignmentView
4389 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4392 client.attachWSMenuEntry(
4393 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4399 * Searches the alignment sequences for xRefs and builds the Show
4400 * Cross-References menu (formerly called Show Products), with database
4401 * sources for which cross-references are found (protein sources for a
4402 * nucleotide alignment and vice versa)
4404 * @return true if Show Cross-references menu should be enabled
4406 public boolean canShowProducts()
4408 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4409 AlignmentI dataset = viewport.getAlignment().getDataset();
4411 showProducts.removeAll();
4412 final boolean dna = viewport.getAlignment().isNucleotide();
4414 if (seqs == null || seqs.length == 0)
4416 // nothing to see here.
4420 boolean showp = false;
4423 List<String> ptypes = new CrossRef(seqs, dataset)
4424 .findXrefSourcesForSequences(dna);
4426 for (final String source : ptypes)
4429 final AlignFrame af = this;
4430 JMenuItem xtype = new JMenuItem(source);
4431 xtype.addActionListener(new ActionListener()
4434 public void actionPerformed(ActionEvent e)
4436 showProductsFor(af.viewport.getSequenceSelection(), dna,
4440 showProducts.add(xtype);
4442 showProducts.setVisible(showp);
4443 showProducts.setEnabled(showp);
4444 } catch (Exception e)
4447 "canShowProducts threw an exception - please report to help@jalview.org",
4455 * Finds and displays cross-references for the selected sequences (protein
4456 * products for nucleotide sequences, dna coding sequences for peptides).
4459 * the sequences to show cross-references for
4461 * true if from a nucleotide alignment (so showing proteins)
4463 * the database to show cross-references for
4465 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4466 final String source)
4468 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4473 * Construct and display a new frame containing the translation of this
4474 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4477 public void showTranslation_actionPerformed(ActionEvent e)
4479 AlignmentI al = null;
4482 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4484 al = dna.translateCdna();
4485 } catch (Exception ex)
4487 jalview.bin.Cache.log.error(
4488 "Exception during translation. Please report this !", ex);
4489 final String msg = MessageManager.getString(
4490 "label.error_when_translating_sequences_submit_bug_report");
4491 final String errorTitle = MessageManager
4492 .getString("label.implementation_error")
4493 + MessageManager.getString("label.translation_failed");
4494 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4495 JvOptionPane.ERROR_MESSAGE);
4498 if (al == null || al.getHeight() == 0)
4500 final String msg = MessageManager.getString(
4501 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4502 final String errorTitle = MessageManager
4503 .getString("label.translation_failed");
4504 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4505 JvOptionPane.WARNING_MESSAGE);
4509 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4510 af.setFileFormat(this.currentFileFormat);
4511 final String newTitle = MessageManager
4512 .formatMessage("label.translation_of_params", new Object[]
4513 { this.getTitle() });
4514 af.setTitle(newTitle);
4515 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4517 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4518 viewport.openSplitFrame(af, new Alignment(seqs));
4522 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4529 * Set the file format
4533 public void setFileFormat(FileFormatI format)
4535 this.currentFileFormat = format;
4539 * Try to load a features file onto the alignment.
4542 * contents or path to retrieve file
4544 * access mode of file (see jalview.io.AlignFile)
4545 * @return true if features file was parsed correctly.
4547 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4549 return avc.parseFeaturesFile(file, sourceType,
4550 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4555 public void refreshFeatureUI(boolean enableIfNecessary)
4557 // note - currently this is only still here rather than in the controller
4558 // because of the featureSettings hard reference that is yet to be
4560 if (enableIfNecessary)
4562 viewport.setShowSequenceFeatures(true);
4563 showSeqFeatures.setSelected(true);
4569 public void dragEnter(DropTargetDragEvent evt)
4574 public void dragExit(DropTargetEvent evt)
4579 public void dragOver(DropTargetDragEvent evt)
4584 public void dropActionChanged(DropTargetDragEvent evt)
4589 public void drop(DropTargetDropEvent evt)
4591 // JAL-1552 - acceptDrop required before getTransferable call for
4592 // Java's Transferable for native dnd
4593 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4594 Transferable t = evt.getTransferable();
4595 final AlignFrame thisaf = this;
4596 final List<String> files = new ArrayList<>();
4597 List<DataSourceType> protocols = new ArrayList<>();
4601 Desktop.transferFromDropTarget(files, protocols, evt, t);
4602 } catch (Exception e)
4604 e.printStackTrace();
4608 new Thread(new Runnable()
4615 // check to see if any of these files have names matching sequences
4618 SequenceIdMatcher idm = new SequenceIdMatcher(
4619 viewport.getAlignment().getSequencesArray());
4621 * Object[] { String,SequenceI}
4623 ArrayList<Object[]> filesmatched = new ArrayList<>();
4624 ArrayList<String> filesnotmatched = new ArrayList<>();
4625 for (int i = 0; i < files.size(); i++)
4627 String file = files.get(i).toString();
4629 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4630 if (protocol == DataSourceType.FILE)
4632 File fl = new File(file);
4633 pdbfn = fl.getName();
4635 else if (protocol == DataSourceType.URL)
4637 URL url = new URL(file);
4638 pdbfn = url.getFile();
4640 if (pdbfn.length() > 0)
4642 // attempt to find a match in the alignment
4643 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4644 int l = 0, c = pdbfn.indexOf(".");
4645 while (mtch == null && c != -1)
4650 } while ((c = pdbfn.indexOf(".", l)) > l);
4653 pdbfn = pdbfn.substring(0, l);
4655 mtch = idm.findAllIdMatches(pdbfn);
4659 FileFormatI type = null;
4662 type = new IdentifyFile().identify(file, protocol);
4663 } catch (Exception ex)
4667 if (type != null && type.isStructureFile())
4669 filesmatched.add(new Object[] { file, protocol, mtch });
4673 // File wasn't named like one of the sequences or wasn't a PDB
4675 filesnotmatched.add(file);
4679 if (filesmatched.size() > 0)
4681 boolean autoAssociate = Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4684 String msg = MessageManager.formatMessage(
4685 "label.automatically_associate_structure_files_with_sequences_same_name",
4687 { Integer.valueOf(filesmatched.size())
4689 String ttl = MessageManager.getString(
4690 "label.automatically_associate_structure_files_by_name");
4691 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4692 ttl, JvOptionPane.YES_NO_OPTION);
4693 autoAssociate = choice == JvOptionPane.YES_OPTION;
4697 for (Object[] fm : filesmatched)
4699 // try and associate
4700 // TODO: may want to set a standard ID naming formalism for
4701 // associating PDB files which have no IDs.
4702 for (SequenceI toassoc : (SequenceI[]) fm[2])
4704 PDBEntry pe = new AssociatePdbFileWithSeq()
4705 .associatePdbWithSeq((String) fm[0],
4706 (DataSourceType) fm[1], toassoc, false,
4710 System.err.println("Associated file : "
4711 + ((String) fm[0]) + " with "
4712 + toassoc.getDisplayId(true));
4716 // TODO: do we need to update overview ? only if features are
4718 alignPanel.paintAlignment(true, false);
4724 * add declined structures as sequences
4726 for (Object[] o : filesmatched)
4728 filesnotmatched.add((String) o[0]);
4732 if (filesnotmatched.size() > 0)
4734 if (assocfiles > 0 && (Cache.getDefault(
4735 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4736 || JvOptionPane.showConfirmDialog(thisaf,
4737 "<html>" + MessageManager.formatMessage(
4738 "label.ignore_unmatched_dropped_files_info",
4741 filesnotmatched.size())
4744 MessageManager.getString(
4745 "label.ignore_unmatched_dropped_files"),
4746 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4750 for (String fn : filesnotmatched)
4752 loadJalviewDataFile(fn, null, null, null);
4756 } catch (Exception ex)
4758 ex.printStackTrace();
4766 * Attempt to load a "dropped" file or URL string, by testing in turn for
4768 * <li>an Annotation file</li>
4769 * <li>a JNet file</li>
4770 * <li>a features file</li>
4771 * <li>else try to interpret as an alignment file</li>
4775 * either a filename or a URL string.
4776 * @throws InterruptedException
4777 * @throws IOException
4779 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4780 FileFormatI format, SequenceI assocSeq)
4784 if (sourceType == null)
4786 sourceType = FormatAdapter.checkProtocol(file);
4788 // if the file isn't identified, or not positively identified as some
4789 // other filetype (PFAM is default unidentified alignment file type) then
4790 // try to parse as annotation.
4791 boolean isAnnotation = (format == null
4792 || FileFormat.Pfam.equals(format))
4793 ? new AnnotationFile().annotateAlignmentView(viewport,
4799 // first see if its a T-COFFEE score file
4800 TCoffeeScoreFile tcf = null;
4803 tcf = new TCoffeeScoreFile(file, sourceType);
4806 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4810 new TCoffeeColourScheme(viewport.getAlignment()));
4811 isAnnotation = true;
4812 statusBar.setText(MessageManager.getString(
4813 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4817 // some problem - if no warning its probable that the ID matching
4818 // process didn't work
4819 JvOptionPane.showMessageDialog(Desktop.desktop,
4820 tcf.getWarningMessage() == null
4821 ? MessageManager.getString(
4822 "label.check_file_matches_sequence_ids_alignment")
4823 : tcf.getWarningMessage(),
4824 MessageManager.getString(
4825 "label.problem_reading_tcoffee_score_file"),
4826 JvOptionPane.WARNING_MESSAGE);
4833 } catch (Exception x)
4836 "Exception when processing data source as T-COFFEE score file",
4842 // try to see if its a JNet 'concise' style annotation file *before*
4844 // try to parse it as a features file
4847 format = new IdentifyFile().identify(file, sourceType);
4849 if (FileFormat.ScoreMatrix == format)
4851 ScoreMatrixFile sm = new ScoreMatrixFile(
4852 new FileParse(file, sourceType));
4854 // todo: i18n this message
4855 statusBar.setText(MessageManager.formatMessage(
4856 "label.successfully_loaded_matrix",
4857 sm.getMatrixName()));
4859 else if (FileFormat.Jnet.equals(format))
4861 JPredFile predictions = new JPredFile(file, sourceType);
4862 new JnetAnnotationMaker();
4863 JnetAnnotationMaker.add_annotation(predictions,
4864 viewport.getAlignment(), 0, false);
4865 viewport.getAlignment().setupJPredAlignment();
4866 isAnnotation = true;
4868 // else if (IdentifyFile.FeaturesFile.equals(format))
4869 else if (FileFormat.Features.equals(format))
4871 if (parseFeaturesFile(file, sourceType))
4873 alignPanel.paintAlignment(true, true);
4878 new FileLoader().LoadFile(viewport, file, sourceType, format);
4884 alignPanel.adjustAnnotationHeight();
4885 viewport.updateSequenceIdColours();
4886 buildSortByAnnotationScoresMenu();
4887 alignPanel.paintAlignment(true, true);
4889 } catch (Exception ex)
4891 ex.printStackTrace();
4892 } catch (OutOfMemoryError oom)
4897 } catch (Exception x)
4902 + (sourceType != null
4903 ? (sourceType == DataSourceType.PASTE
4905 : "using " + sourceType + " from "
4909 ? "(parsing as '" + format + "' file)"
4911 oom, Desktop.desktop);
4916 * Method invoked by the ChangeListener on the tabbed pane, in other words
4917 * when a different tabbed pane is selected by the user or programmatically.
4920 public void tabSelectionChanged(int index)
4924 alignPanel = alignPanels.get(index);
4925 viewport = alignPanel.av;
4926 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4927 setMenusFromViewport(viewport);
4931 * 'focus' any colour slider that is open to the selected viewport
4933 if (viewport.getConservationSelected())
4935 SliderPanel.setConservationSlider(alignPanel,
4936 viewport.getResidueShading(), alignPanel.getViewName());
4940 SliderPanel.hideConservationSlider();
4942 if (viewport.getAbovePIDThreshold())
4944 SliderPanel.setPIDSliderSource(alignPanel,
4945 viewport.getResidueShading(), alignPanel.getViewName());
4949 SliderPanel.hidePIDSlider();
4953 * If there is a frame linked to this one in a SplitPane, switch it to the
4954 * same view tab index. No infinite recursion of calls should happen, since
4955 * tabSelectionChanged() should not get invoked on setting the selected
4956 * index to an unchanged value. Guard against setting an invalid index
4957 * before the new view peer tab has been created.
4959 final AlignViewportI peer = viewport.getCodingComplement();
4962 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4963 .getAlignPanel().alignFrame;
4964 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4966 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4972 * On right mouse click on view tab, prompt for and set new view name.
4975 public void tabbedPane_mousePressed(MouseEvent e)
4977 if (e.isPopupTrigger())
4979 String msg = MessageManager.getString("label.enter_view_name");
4980 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4981 JvOptionPane.QUESTION_MESSAGE);
4985 viewport.viewName = reply;
4986 // TODO warn if reply is in getExistingViewNames()?
4987 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4992 public AlignViewport getCurrentView()
4998 * Open the dialog for regex description parsing.
5001 protected void extractScores_actionPerformed(ActionEvent e)
5003 ParseProperties pp = new jalview.analysis.ParseProperties(
5004 viewport.getAlignment());
5005 // TODO: verify regex and introduce GUI dialog for version 2.5
5006 // if (pp.getScoresFromDescription("col", "score column ",
5007 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5009 if (pp.getScoresFromDescription("description column",
5010 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5012 buildSortByAnnotationScoresMenu();
5020 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5024 protected void showDbRefs_actionPerformed(ActionEvent e)
5026 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5032 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5036 protected void showNpFeats_actionPerformed(ActionEvent e)
5038 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5042 * find the viewport amongst the tabs in this alignment frame and close that
5047 public boolean closeView(AlignViewportI av)
5051 this.closeMenuItem_actionPerformed(false);
5054 Component[] comp = tabbedPane.getComponents();
5055 for (int i = 0; comp != null && i < comp.length; i++)
5057 if (comp[i] instanceof AlignmentPanel)
5059 if (((AlignmentPanel) comp[i]).av == av)
5062 closeView((AlignmentPanel) comp[i]);
5070 protected void build_fetchdbmenu(JMenu webService)
5072 // Temporary hack - DBRef Fetcher always top level ws entry.
5073 // TODO We probably want to store a sequence database checklist in
5074 // preferences and have checkboxes.. rather than individual sources selected
5076 final JMenu rfetch = new JMenu(
5077 MessageManager.getString("action.fetch_db_references"));
5078 rfetch.setToolTipText(MessageManager.getString(
5079 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5080 webService.add(rfetch);
5082 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5083 MessageManager.getString("option.trim_retrieved_seqs"));
5084 trimrs.setToolTipText(
5085 MessageManager.getString("label.trim_retrieved_sequences"));
5087 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5088 trimrs.addActionListener(new ActionListener()
5091 public void actionPerformed(ActionEvent e)
5093 trimrs.setSelected(trimrs.isSelected());
5094 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5095 Boolean.valueOf(trimrs.isSelected()).toString());
5099 JMenuItem fetchr = new JMenuItem(
5100 MessageManager.getString("label.standard_databases"));
5101 fetchr.setToolTipText(
5102 MessageManager.getString("label.fetch_embl_uniprot"));
5103 fetchr.addActionListener(new ActionListener()
5107 public void actionPerformed(ActionEvent e)
5109 new Thread(new Runnable()
5114 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5115 .getAlignment().isNucleotide();
5116 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5117 alignPanel.av.getSequenceSelection(),
5118 alignPanel.alignFrame, null,
5119 alignPanel.alignFrame.featureSettings, isNucleotide);
5120 dbRefFetcher.addListener(new FetchFinishedListenerI()
5123 public void finished()
5125 AlignFrame.this.setMenusForViewport();
5128 dbRefFetcher.fetchDBRefs(false);
5136 final AlignFrame me = this;
5137 new Thread(new Runnable()
5142 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5143 .getSequenceFetcherSingleton(me);
5144 javax.swing.SwingUtilities.invokeLater(new Runnable()
5149 String[] dbclasses = sf.getOrderedSupportedSources();
5150 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5151 // jalview.util.QuickSort.sort(otherdb, otherdb);
5152 List<DbSourceProxy> otherdb;
5153 JMenu dfetch = new JMenu();
5154 JMenu ifetch = new JMenu();
5155 JMenuItem fetchr = null;
5156 int comp = 0, icomp = 0, mcomp = 15;
5157 String mname = null;
5159 for (String dbclass : dbclasses)
5161 otherdb = sf.getSourceProxy(dbclass);
5162 // add a single entry for this class, or submenu allowing 'fetch
5164 if (otherdb == null || otherdb.size() < 1)
5168 // List<DbSourceProxy> dbs=otherdb;
5169 // otherdb=new ArrayList<DbSourceProxy>();
5170 // for (DbSourceProxy db:dbs)
5172 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5176 mname = "From " + dbclass;
5178 if (otherdb.size() == 1)
5180 final DbSourceProxy[] dassource = otherdb
5181 .toArray(new DbSourceProxy[0]);
5182 DbSourceProxy src = otherdb.get(0);
5183 fetchr = new JMenuItem(src.getDbSource());
5184 fetchr.addActionListener(new ActionListener()
5188 public void actionPerformed(ActionEvent e)
5190 new Thread(new Runnable()
5196 boolean isNucleotide = alignPanel.alignFrame
5197 .getViewport().getAlignment()
5199 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5200 alignPanel.av.getSequenceSelection(),
5201 alignPanel.alignFrame, dassource,
5202 alignPanel.alignFrame.featureSettings,
5205 .addListener(new FetchFinishedListenerI()
5208 public void finished()
5210 AlignFrame.this.setMenusForViewport();
5213 dbRefFetcher.fetchDBRefs(false);
5219 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5220 MessageManager.formatMessage(
5221 "label.fetch_retrieve_from", new Object[]
5222 { src.getDbName() })));
5228 final DbSourceProxy[] dassource = otherdb
5229 .toArray(new DbSourceProxy[0]);
5231 DbSourceProxy src = otherdb.get(0);
5232 fetchr = new JMenuItem(MessageManager
5233 .formatMessage("label.fetch_all_param", new Object[]
5234 { src.getDbSource() }));
5235 fetchr.addActionListener(new ActionListener()
5238 public void actionPerformed(ActionEvent e)
5240 new Thread(new Runnable()
5246 boolean isNucleotide = alignPanel.alignFrame
5247 .getViewport().getAlignment()
5249 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5250 alignPanel.av.getSequenceSelection(),
5251 alignPanel.alignFrame, dassource,
5252 alignPanel.alignFrame.featureSettings,
5255 .addListener(new FetchFinishedListenerI()
5258 public void finished()
5260 AlignFrame.this.setMenusForViewport();
5263 dbRefFetcher.fetchDBRefs(false);
5269 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5270 MessageManager.formatMessage(
5271 "label.fetch_retrieve_from_all_sources",
5273 { Integer.valueOf(otherdb.size())
5275 src.getDbSource(), src.getDbName() })));
5278 // and then build the rest of the individual menus
5279 ifetch = new JMenu(MessageManager.formatMessage(
5280 "label.source_from_db_source", new Object[]
5281 { src.getDbSource() }));
5283 String imname = null;
5285 for (DbSourceProxy sproxy : otherdb)
5287 String dbname = sproxy.getDbName();
5288 String sname = dbname.length() > 5
5289 ? dbname.substring(0, 5) + "..."
5291 String msname = dbname.length() > 10
5292 ? dbname.substring(0, 10) + "..."
5296 imname = MessageManager
5297 .formatMessage("label.from_msname", new Object[]
5300 fetchr = new JMenuItem(msname);
5301 final DbSourceProxy[] dassrc = { sproxy };
5302 fetchr.addActionListener(new ActionListener()
5306 public void actionPerformed(ActionEvent e)
5308 new Thread(new Runnable()
5314 boolean isNucleotide = alignPanel.alignFrame
5315 .getViewport().getAlignment()
5317 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5318 alignPanel.av.getSequenceSelection(),
5319 alignPanel.alignFrame, dassrc,
5320 alignPanel.alignFrame.featureSettings,
5323 .addListener(new FetchFinishedListenerI()
5326 public void finished()
5328 AlignFrame.this.setMenusForViewport();
5331 dbRefFetcher.fetchDBRefs(false);
5337 fetchr.setToolTipText(
5338 "<html>" + MessageManager.formatMessage(
5339 "label.fetch_retrieve_from", new Object[]
5343 if (++icomp >= mcomp || i == (otherdb.size()))
5345 ifetch.setText(MessageManager.formatMessage(
5346 "label.source_to_target", imname, sname));
5348 ifetch = new JMenu();
5356 if (comp >= mcomp || dbi >= (dbclasses.length))
5358 dfetch.setText(MessageManager.formatMessage(
5359 "label.source_to_target", mname, dbclass));
5361 dfetch = new JMenu();
5374 * Left justify the whole alignment.
5377 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5379 AlignmentI al = viewport.getAlignment();
5381 viewport.firePropertyChange("alignment", null, al);
5385 * Right justify the whole alignment.
5388 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5390 AlignmentI al = viewport.getAlignment();
5392 viewport.firePropertyChange("alignment", null, al);
5396 public void setShowSeqFeatures(boolean b)
5398 showSeqFeatures.setSelected(b);
5399 viewport.setShowSequenceFeatures(b);
5406 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5407 * awt.event.ActionEvent)
5410 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5412 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5413 alignPanel.paintAlignment(false, false);
5420 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5424 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5426 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5427 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5435 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5436 * .event.ActionEvent)
5439 protected void showGroupConservation_actionPerformed(ActionEvent e)
5441 viewport.setShowGroupConservation(showGroupConservation.getState());
5442 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5449 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5450 * .event.ActionEvent)
5453 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5455 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5456 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5463 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5464 * .event.ActionEvent)
5467 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5469 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5470 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5474 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5476 showSequenceLogo.setState(true);
5477 viewport.setShowSequenceLogo(true);
5478 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5479 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5483 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5485 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5492 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5493 * .event.ActionEvent)
5496 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5498 if (avc.makeGroupsFromSelection())
5500 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5501 alignPanel.updateAnnotation();
5502 alignPanel.paintAlignment(true, true);
5506 public void clearAlignmentSeqRep()
5508 // TODO refactor alignmentseqrep to controller
5509 if (viewport.getAlignment().hasSeqrep())
5511 viewport.getAlignment().setSeqrep(null);
5512 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5513 alignPanel.updateAnnotation();
5514 alignPanel.paintAlignment(true, true);
5519 protected void createGroup_actionPerformed(ActionEvent e)
5521 if (avc.createGroup())
5523 alignPanel.alignmentChanged();
5528 protected void unGroup_actionPerformed(ActionEvent e)
5532 alignPanel.alignmentChanged();
5537 * make the given alignmentPanel the currently selected tab
5539 * @param alignmentPanel
5541 public void setDisplayedView(AlignmentPanel alignmentPanel)
5543 if (!viewport.getSequenceSetId()
5544 .equals(alignmentPanel.av.getSequenceSetId()))
5546 throw new Error(MessageManager.getString(
5547 "error.implementation_error_cannot_show_view_alignment_frame"));
5549 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5550 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5552 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5557 * Action on selection of menu options to Show or Hide annotations.
5560 * @param forSequences
5561 * update sequence-related annotations
5562 * @param forAlignment
5563 * update non-sequence-related annotations
5566 protected void setAnnotationsVisibility(boolean visible,
5567 boolean forSequences, boolean forAlignment)
5569 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5570 .getAlignmentAnnotation();
5575 for (AlignmentAnnotation aa : anns)
5578 * don't display non-positional annotations on an alignment
5580 if (aa.annotations == null)
5584 boolean apply = (aa.sequenceRef == null && forAlignment)
5585 || (aa.sequenceRef != null && forSequences);
5588 aa.visible = visible;
5591 alignPanel.validateAnnotationDimensions(true);
5592 alignPanel.alignmentChanged();
5596 * Store selected annotation sort order for the view and repaint.
5599 protected void sortAnnotations_actionPerformed()
5601 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5603 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5604 alignPanel.paintAlignment(false, false);
5609 * @return alignment panels in this alignment frame
5611 public List<? extends AlignmentViewPanel> getAlignPanels()
5613 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5617 * Open a new alignment window, with the cDNA associated with this (protein)
5618 * alignment, aligned as is the protein.
5620 protected void viewAsCdna_actionPerformed()
5622 // TODO no longer a menu action - refactor as required
5623 final AlignmentI alignment = getViewport().getAlignment();
5624 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5625 if (mappings == null)
5629 List<SequenceI> cdnaSeqs = new ArrayList<>();
5630 for (SequenceI aaSeq : alignment.getSequences())
5632 for (AlignedCodonFrame acf : mappings)
5634 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5638 * There is a cDNA mapping for this protein sequence - add to new
5639 * alignment. It will share the same dataset sequence as other mapped
5640 * cDNA (no new mappings need to be created).
5642 final Sequence newSeq = new Sequence(dnaSeq);
5643 newSeq.setDatasetSequence(dnaSeq);
5644 cdnaSeqs.add(newSeq);
5648 if (cdnaSeqs.size() == 0)
5650 // show a warning dialog no mapped cDNA
5653 AlignmentI cdna = new Alignment(
5654 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5655 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5656 AlignFrame.DEFAULT_HEIGHT);
5657 cdna.alignAs(alignment);
5658 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5660 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5661 AlignFrame.DEFAULT_HEIGHT);
5665 * Set visibility of dna/protein complement view (available when shown in a
5671 protected void showComplement_actionPerformed(boolean show)
5673 SplitContainerI sf = getSplitViewContainer();
5676 sf.setComplementVisible(this, show);
5681 * Generate the reverse (optionally complemented) of the selected sequences,
5682 * and add them to the alignment
5685 protected void showReverse_actionPerformed(boolean complement)
5687 AlignmentI al = null;
5690 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5691 al = dna.reverseCdna(complement);
5692 viewport.addAlignment(al, "");
5693 addHistoryItem(new EditCommand(
5694 MessageManager.getString("label.add_sequences"), Action.PASTE,
5695 al.getSequencesArray(), 0, al.getWidth(),
5696 viewport.getAlignment()));
5697 } catch (Exception ex)
5699 System.err.println(ex.getMessage());
5705 * Try to run a script in the Groovy console, having first ensured that this
5706 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5707 * be targeted at this alignment.
5710 protected void runGroovy_actionPerformed()
5712 Jalview.setCurrentAlignFrame(this);
5713 groovy.ui.Console console = Desktop.getGroovyConsole();
5714 if (console != null)
5718 console.runScript();
5719 } catch (Exception ex)
5721 System.err.println((ex.toString()));
5722 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5723 MessageManager.getString("label.couldnt_run_groovy_script"),
5724 MessageManager.getString("label.groovy_support_failed"),
5725 JvOptionPane.ERROR_MESSAGE);
5730 System.err.println("Can't run Groovy script as console not found");
5735 * Hides columns containing (or not containing) a specified feature, provided
5736 * that would not leave all columns hidden
5738 * @param featureType
5739 * @param columnsContaining
5742 public boolean hideFeatureColumns(String featureType,
5743 boolean columnsContaining)
5745 boolean notForHiding = avc.markColumnsContainingFeatures(
5746 columnsContaining, false, false, featureType);
5749 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5750 false, featureType))
5752 getViewport().hideSelectedColumns();
5760 protected void selectHighlightedColumns_actionPerformed(
5761 ActionEvent actionEvent)
5763 // include key modifier check in case user selects from menu
5764 avc.markHighlightedColumns(
5765 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5766 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5767 | ActionEvent.CTRL_MASK)) != 0);
5771 * Rebuilds the Colour menu, including any user-defined colours which have
5772 * been loaded either on startup or during the session
5774 public void buildColourMenu()
5776 colourMenu.removeAll();
5778 colourMenu.add(applyToAllGroups);
5779 colourMenu.add(textColour);
5780 colourMenu.addSeparator();
5782 ColourMenuHelper.addMenuItems(colourMenu, this, viewport.getAlignment(),
5785 colourMenu.addSeparator();
5786 colourMenu.add(conservationMenuItem);
5787 colourMenu.add(modifyConservation);
5788 colourMenu.add(abovePIDThreshold);
5789 colourMenu.add(modifyPID);
5790 colourMenu.add(annotationColour);
5792 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5793 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5797 * Open a dialog (if not already open) that allows the user to select and
5798 * calculate PCA or Tree analysis
5800 protected void openTreePcaDialog()
5802 if (alignPanel.getCalculationDialog() == null)
5804 new CalculationChooser(AlignFrame.this);
5809 * Sets the status of the HMMER menu
5811 public void updateHMMERStatus()
5813 hmmerMenu.setEnabled(HmmerCommand.isHmmerAvailable());
5817 protected void loadVcf_actionPerformed()
5819 JalviewFileChooser chooser = new JalviewFileChooser(
5820 Cache.getProperty("LAST_DIRECTORY"));
5821 chooser.setFileView(new JalviewFileView());
5822 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5823 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5825 int value = chooser.showOpenDialog(null);
5827 if (value == JalviewFileChooser.APPROVE_OPTION)
5829 String choice = chooser.getSelectedFile().getPath();
5830 Cache.setProperty("LAST_DIRECTORY", choice);
5831 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5832 new VCFLoader(choice).loadVCF(seqs, this);
5838 class PrintThread extends Thread
5842 public PrintThread(AlignmentPanel ap)
5847 static PageFormat pf;
5852 PrinterJob printJob = PrinterJob.getPrinterJob();
5856 printJob.setPrintable(ap, pf);
5860 printJob.setPrintable(ap);
5863 if (printJob.printDialog())
5868 } catch (Exception PrintException)
5870 PrintException.printStackTrace();