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.util.StringUtils;
98 import jalview.viewmodel.AlignmentViewport;
99 import jalview.viewmodel.ViewportRanges;
100 import jalview.ws.DBRefFetcher;
101 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
102 import jalview.ws.jws1.Discoverer;
103 import jalview.ws.jws2.Jws2Discoverer;
104 import jalview.ws.jws2.jabaws2.Jws2Instance;
105 import jalview.ws.params.ArgumentI;
106 import jalview.ws.params.ParamDatastoreI;
107 import jalview.ws.params.WsParamSetI;
108 import jalview.ws.seqfetcher.DbSourceProxy;
110 import java.awt.BorderLayout;
111 import java.awt.Component;
112 import java.awt.Rectangle;
113 import java.awt.Toolkit;
114 import java.awt.datatransfer.Clipboard;
115 import java.awt.datatransfer.DataFlavor;
116 import java.awt.datatransfer.StringSelection;
117 import java.awt.datatransfer.Transferable;
118 import java.awt.dnd.DnDConstants;
119 import java.awt.dnd.DropTargetDragEvent;
120 import java.awt.dnd.DropTargetDropEvent;
121 import java.awt.dnd.DropTargetEvent;
122 import java.awt.dnd.DropTargetListener;
123 import java.awt.event.ActionEvent;
124 import java.awt.event.ActionListener;
125 import java.awt.event.FocusAdapter;
126 import java.awt.event.FocusEvent;
127 import java.awt.event.ItemEvent;
128 import java.awt.event.ItemListener;
129 import java.awt.event.KeyAdapter;
130 import java.awt.event.KeyEvent;
131 import java.awt.event.MouseEvent;
132 import java.awt.print.PageFormat;
133 import java.awt.print.PrinterJob;
134 import java.beans.PropertyChangeEvent;
136 import java.io.FileWriter;
137 import java.io.IOException;
138 import java.io.PrintWriter;
140 import java.util.ArrayList;
141 import java.util.Arrays;
142 import java.util.Deque;
143 import java.util.Enumeration;
144 import java.util.Hashtable;
145 import java.util.List;
146 import java.util.Scanner;
147 import java.util.Vector;
149 import javax.swing.JCheckBoxMenuItem;
150 import javax.swing.JEditorPane;
151 import javax.swing.JFileChooser;
152 import javax.swing.JInternalFrame;
153 import javax.swing.JLayeredPane;
154 import javax.swing.JMenu;
155 import javax.swing.JMenuItem;
156 import javax.swing.JOptionPane;
157 import javax.swing.JScrollPane;
158 import javax.swing.SwingUtilities;
164 * @version $Revision$
166 public class AlignFrame extends GAlignFrame implements DropTargetListener,
167 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
169 public static final int DEFAULT_WIDTH = 700;
171 public static final int DEFAULT_HEIGHT = 500;
174 * The currently displayed panel (selected tabbed view if more than one)
176 public AlignmentPanel alignPanel;
178 AlignViewport viewport;
180 public AlignViewControllerI avc;
182 List<AlignmentPanel> alignPanels = new ArrayList<>();
185 * Last format used to load or save alignments in this window
187 FileFormatI currentFileFormat = null;
190 * Current filename for this alignment
192 String fileName = null;
196 * Creates a new AlignFrame object with specific width and height.
202 public AlignFrame(AlignmentI al, int width, int height)
204 this(al, null, width, height);
208 * Creates a new AlignFrame object with specific width, height and
214 * @param sequenceSetId
216 public AlignFrame(AlignmentI al, int width, int height,
217 String sequenceSetId)
219 this(al, null, width, height, sequenceSetId);
223 * Creates a new AlignFrame object with specific width, height and
229 * @param sequenceSetId
232 public AlignFrame(AlignmentI al, int width, int height,
233 String sequenceSetId, String viewId)
235 this(al, null, width, height, sequenceSetId, viewId);
239 * new alignment window with hidden columns
243 * @param hiddenColumns
244 * ColumnSelection or null
246 * Width of alignment frame
250 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
253 this(al, hiddenColumns, width, height, null);
257 * Create alignment frame for al with hiddenColumns, a specific width and
258 * height, and specific sequenceId
261 * @param hiddenColumns
264 * @param sequenceSetId
267 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
268 int height, String sequenceSetId)
270 this(al, hiddenColumns, width, height, sequenceSetId, null);
274 * Create alignment frame for al with hiddenColumns, a specific width and
275 * height, and specific sequenceId
278 * @param hiddenColumns
281 * @param sequenceSetId
286 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
287 int height, String sequenceSetId, String viewId)
289 setSize(width, height);
291 if (al.getDataset() == null)
296 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
298 alignPanel = new AlignmentPanel(this, viewport);
300 addAlignmentPanel(alignPanel, true);
304 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
305 HiddenColumns hiddenColumns, int width, int height)
307 setSize(width, height);
309 if (al.getDataset() == null)
314 viewport = new AlignViewport(al, hiddenColumns);
316 if (hiddenSeqs != null && hiddenSeqs.length > 0)
318 viewport.hideSequence(hiddenSeqs);
320 alignPanel = new AlignmentPanel(this, viewport);
321 addAlignmentPanel(alignPanel, true);
326 * Make a new AlignFrame from existing alignmentPanels
333 public AlignFrame(AlignmentPanel ap)
337 addAlignmentPanel(ap, false);
342 * initalise the alignframe from the underlying viewport data and the
347 if (!Jalview.isHeadlessMode())
349 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
352 avc = new jalview.controller.AlignViewController(this, viewport,
354 if (viewport.getAlignmentConservationAnnotation() == null)
356 // BLOSUM62Colour.setEnabled(false);
357 conservationMenuItem.setEnabled(false);
358 modifyConservation.setEnabled(false);
359 // PIDColour.setEnabled(false);
360 // abovePIDThreshold.setEnabled(false);
361 // modifyPID.setEnabled(false);
364 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
367 if (sortby.equals("Id"))
369 sortIDMenuItem_actionPerformed(null);
371 else if (sortby.equals("Pairwise Identity"))
373 sortPairwiseMenuItem_actionPerformed(null);
377 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
379 setMenusFromViewport(viewport);
380 buildSortByAnnotationScoresMenu();
381 calculateTree.addActionListener(new ActionListener()
385 public void actionPerformed(ActionEvent e)
392 if (Desktop.desktop != null)
394 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
395 addServiceListeners();
399 if (viewport.getWrapAlignment())
401 wrapMenuItem_actionPerformed(null);
404 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
406 this.overviewMenuItem_actionPerformed(null);
411 final List<AlignmentPanel> selviews = new ArrayList<>();
412 final List<AlignmentPanel> origview = new ArrayList<>();
413 final String menuLabel = MessageManager
414 .getString("label.copy_format_from");
415 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
416 new ViewSetProvider()
420 public AlignmentPanel[] getAllAlignmentPanels()
423 origview.add(alignPanel);
424 // make an array of all alignment panels except for this one
425 List<AlignmentPanel> aps = new ArrayList<>(
426 Arrays.asList(Desktop.getAlignmentPanels(null)));
427 aps.remove(AlignFrame.this.alignPanel);
428 return aps.toArray(new AlignmentPanel[aps.size()]);
430 }, selviews, new ItemListener()
434 public void itemStateChanged(ItemEvent e)
436 if (origview.size() > 0)
438 final AlignmentPanel ap = origview.get(0);
441 * Copy the ViewStyle of the selected panel to 'this one'.
442 * Don't change value of 'scaleProteinAsCdna' unless copying
445 ViewStyleI vs = selviews.get(0).getAlignViewport()
447 boolean fromSplitFrame = selviews.get(0)
448 .getAlignViewport().getCodingComplement() != null;
451 vs.setScaleProteinAsCdna(ap.getAlignViewport()
452 .getViewStyle().isScaleProteinAsCdna());
454 ap.getAlignViewport().setViewStyle(vs);
457 * Also rescale ViewStyle of SplitFrame complement if there is
458 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
459 * the whole ViewStyle (allow cDNA protein to have different
462 AlignViewportI complement = ap.getAlignViewport()
463 .getCodingComplement();
464 if (complement != null && vs.isScaleProteinAsCdna())
466 AlignFrame af = Desktop.getAlignFrameFor(complement);
467 ((SplitFrame) af.getSplitViewContainer())
469 af.setMenusForViewport();
473 ap.setSelected(true);
474 ap.alignFrame.setMenusForViewport();
479 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
480 .indexOf("devel") > -1
481 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
482 .indexOf("test") > -1)
484 formatMenu.add(vsel);
486 addFocusListener(new FocusAdapter()
489 public void focusGained(FocusEvent e)
491 Jalview.setCurrentAlignFrame(AlignFrame.this);
498 * Change the filename and format for the alignment, and enable the 'reload'
499 * button functionality.
506 public void setFileName(String file, FileFormatI format)
509 setFileFormat(format);
510 reload.setEnabled(true);
514 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
517 void addKeyListener()
519 addKeyListener(new KeyAdapter()
522 public void keyPressed(KeyEvent evt)
524 if (viewport.cursorMode
525 && ((evt.getKeyCode() >= KeyEvent.VK_0
526 && evt.getKeyCode() <= KeyEvent.VK_9)
527 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
528 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
529 && Character.isDigit(evt.getKeyChar()))
531 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
534 switch (evt.getKeyCode())
537 case 27: // escape key
538 deselectAllSequenceMenuItem_actionPerformed(null);
542 case KeyEvent.VK_DOWN:
543 if (evt.isAltDown() || !viewport.cursorMode)
545 moveSelectedSequences(false);
547 if (viewport.cursorMode)
549 alignPanel.getSeqPanel().moveCursor(0, 1);
554 if (evt.isAltDown() || !viewport.cursorMode)
556 moveSelectedSequences(true);
558 if (viewport.cursorMode)
560 alignPanel.getSeqPanel().moveCursor(0, -1);
565 case KeyEvent.VK_LEFT:
566 if (evt.isAltDown() || !viewport.cursorMode)
568 slideSequences(false,
569 alignPanel.getSeqPanel().getKeyboardNo1());
573 alignPanel.getSeqPanel().moveCursor(-1, 0);
578 case KeyEvent.VK_RIGHT:
579 if (evt.isAltDown() || !viewport.cursorMode)
581 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
585 alignPanel.getSeqPanel().moveCursor(1, 0);
589 case KeyEvent.VK_SPACE:
590 if (viewport.cursorMode)
592 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
593 || evt.isShiftDown() || evt.isAltDown());
597 // case KeyEvent.VK_A:
598 // if (viewport.cursorMode)
600 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
601 // //System.out.println("A");
605 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
606 * System.out.println("closing bracket"); } break;
608 case KeyEvent.VK_DELETE:
609 case KeyEvent.VK_BACK_SPACE:
610 if (!viewport.cursorMode)
612 cut_actionPerformed(null);
616 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
617 || evt.isShiftDown() || evt.isAltDown());
623 if (viewport.cursorMode)
625 alignPanel.getSeqPanel().setCursorRow();
629 if (viewport.cursorMode && !evt.isControlDown())
631 alignPanel.getSeqPanel().setCursorColumn();
635 if (viewport.cursorMode)
637 alignPanel.getSeqPanel().setCursorPosition();
641 case KeyEvent.VK_ENTER:
642 case KeyEvent.VK_COMMA:
643 if (viewport.cursorMode)
645 alignPanel.getSeqPanel().setCursorRowAndColumn();
650 if (viewport.cursorMode)
652 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
656 if (viewport.cursorMode)
658 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
663 viewport.cursorMode = !viewport.cursorMode;
664 statusBar.setText(MessageManager
665 .formatMessage("label.keyboard_editing_mode", new String[]
666 { (viewport.cursorMode ? "on" : "off") }));
667 if (viewport.cursorMode)
669 ViewportRanges ranges = viewport.getRanges();
670 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
672 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
675 alignPanel.getSeqPanel().seqCanvas.repaint();
681 Help.showHelpWindow();
682 } catch (Exception ex)
684 ex.printStackTrace();
689 boolean toggleSeqs = !evt.isControlDown();
690 boolean toggleCols = !evt.isShiftDown();
691 toggleHiddenRegions(toggleSeqs, toggleCols);
696 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
697 boolean modifyExisting = true; // always modify, don't clear
698 // evt.isShiftDown();
699 boolean invertHighlighted = evt.isAltDown();
700 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
704 case KeyEvent.VK_PAGE_UP:
705 viewport.getRanges().pageUp();
707 case KeyEvent.VK_PAGE_DOWN:
708 viewport.getRanges().pageDown();
714 public void keyReleased(KeyEvent evt)
716 switch (evt.getKeyCode())
718 case KeyEvent.VK_LEFT:
719 if (evt.isAltDown() || !viewport.cursorMode)
721 viewport.firePropertyChange("alignment", null,
722 viewport.getAlignment().getSequences());
726 case KeyEvent.VK_RIGHT:
727 if (evt.isAltDown() || !viewport.cursorMode)
729 viewport.firePropertyChange("alignment", null,
730 viewport.getAlignment().getSequences());
738 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
740 ap.alignFrame = this;
741 avc = new jalview.controller.AlignViewController(this, viewport,
746 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
748 int aSize = alignPanels.size();
750 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
752 if (aSize == 1 && ap.av.viewName == null)
754 this.getContentPane().add(ap, BorderLayout.CENTER);
760 setInitialTabVisible();
763 expandViews.setEnabled(true);
764 gatherViews.setEnabled(true);
765 tabbedPane.addTab(ap.av.viewName, ap);
767 ap.setVisible(false);
772 if (ap.av.isPadGaps())
774 ap.av.getAlignment().padGaps();
776 ap.av.updateConservation(ap);
777 ap.av.updateConsensus(ap);
778 ap.av.updateStrucConsensus(ap);
779 ap.av.initInformationWorker(ap);
783 public void setInitialTabVisible()
785 expandViews.setEnabled(true);
786 gatherViews.setEnabled(true);
787 tabbedPane.setVisible(true);
788 AlignmentPanel first = alignPanels.get(0);
789 tabbedPane.addTab(first.av.viewName, first);
790 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
793 public AlignViewport getViewport()
798 /* Set up intrinsic listeners for dynamically generated GUI bits. */
799 private void addServiceListeners()
801 final java.beans.PropertyChangeListener thisListener;
802 Desktop.instance.addJalviewPropertyChangeListener("services",
803 thisListener = new java.beans.PropertyChangeListener()
806 public void propertyChange(PropertyChangeEvent evt)
808 // // System.out.println("Discoverer property change.");
809 // if (evt.getPropertyName().equals("services"))
811 SwingUtilities.invokeLater(new Runnable()
818 "Rebuild WS Menu for service change");
819 BuildWebServiceMenu();
826 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
829 public void internalFrameClosed(
830 javax.swing.event.InternalFrameEvent evt)
832 // System.out.println("deregistering discoverer listener");
833 Desktop.instance.removeJalviewPropertyChangeListener("services",
835 closeMenuItem_actionPerformed(true);
838 // Finally, build the menu once to get current service state
839 new Thread(new Runnable()
844 BuildWebServiceMenu();
850 * Configure menu items that vary according to whether the alignment is
851 * nucleotide or protein
853 public void setGUINucleotide()
855 AlignmentI al = getViewport().getAlignment();
856 boolean nucleotide = al.isNucleotide();
858 loadVcf.setVisible(nucleotide);
859 showTranslation.setVisible(nucleotide);
860 showReverse.setVisible(nucleotide);
861 showReverseComplement.setVisible(nucleotide);
862 conservationMenuItem.setEnabled(!nucleotide);
864 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
865 showGroupConservation.setEnabled(!nucleotide);
867 showComplementMenuItem
868 .setText(nucleotide ? MessageManager.getString("label.protein")
869 : MessageManager.getString("label.nucleotide"));
873 * set up menus for the current viewport. This may be called after any
874 * operation that affects the data in the current view (selection changed,
875 * etc) to update the menus to reflect the new state.
878 public void setMenusForViewport()
880 setMenusFromViewport(viewport);
884 * Need to call this method when tabs are selected for multiple views, or when
885 * loading from Jalview2XML.java
890 void setMenusFromViewport(AlignViewport av)
892 padGapsMenuitem.setSelected(av.isPadGaps());
893 colourTextMenuItem.setSelected(av.isShowColourText());
894 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
895 modifyPID.setEnabled(abovePIDThreshold.isSelected());
896 conservationMenuItem.setSelected(av.getConservationSelected());
897 modifyConservation.setEnabled(conservationMenuItem.isSelected());
898 seqLimits.setSelected(av.getShowJVSuffix());
899 idRightAlign.setSelected(av.isRightAlignIds());
900 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
901 renderGapsMenuItem.setSelected(av.isRenderGaps());
902 wrapMenuItem.setSelected(av.getWrapAlignment());
903 scaleAbove.setVisible(av.getWrapAlignment());
904 scaleLeft.setVisible(av.getWrapAlignment());
905 scaleRight.setVisible(av.getWrapAlignment());
906 annotationPanelMenuItem.setState(av.isShowAnnotation());
908 * Show/hide annotations only enabled if annotation panel is shown
910 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
911 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
912 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
913 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
914 viewBoxesMenuItem.setSelected(av.getShowBoxes());
915 viewTextMenuItem.setSelected(av.getShowText());
916 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
917 showGroupConsensus.setSelected(av.isShowGroupConsensus());
918 showGroupConservation.setSelected(av.isShowGroupConservation());
919 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
920 showSequenceLogo.setSelected(av.isShowSequenceLogo());
921 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
922 showInformationHistogram.setSelected(av.isShowInformationHistogram());
923 showHMMSequenceLogo.setSelected(av.isShowHMMSequenceLogo());
924 normaliseHMMSequenceLogo.setSelected(av.isNormaliseHMMSequenceLogo());
926 ColourMenuHelper.setColourSelected(colourMenu,
927 av.getGlobalColourScheme());
929 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
930 hiddenMarkers.setState(av.getShowHiddenMarkers());
931 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
932 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
933 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
934 autoCalculate.setSelected(av.autoCalculateConsensus);
935 sortByTree.setSelected(av.sortByTree);
936 listenToViewSelections.setSelected(av.followSelection);
938 showProducts.setEnabled(canShowProducts());
939 setGroovyEnabled(Desktop.getGroovyConsole() != null);
945 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
949 public void setGroovyEnabled(boolean b)
951 runGroovy.setEnabled(b);
954 private IProgressIndicator progressBar;
959 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
962 public void setProgressBar(String message, long id)
964 progressBar.setProgressBar(message, id);
968 public void registerHandler(final long id,
969 final IProgressIndicatorHandler handler)
971 progressBar.registerHandler(id, handler);
976 * @return true if any progress bars are still active
979 public boolean operationInProgress()
981 return progressBar.operationInProgress();
985 public void setStatus(String text)
987 statusBar.setText(text);
991 * Added so Castor Mapping file can obtain Jalview Version
993 public String getVersion()
995 return jalview.bin.Cache.getProperty("VERSION");
998 public FeatureRenderer getFeatureRenderer()
1000 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1004 public void fetchSequence_actionPerformed(ActionEvent e)
1006 new jalview.gui.SequenceFetcher(this);
1010 public void addFromFile_actionPerformed(ActionEvent e)
1012 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1016 public void hmmBuild_actionPerformed(boolean withDefaults)
1018 if (!alignmentIsSufficient(1))
1024 * get default parameters, and optionally show a dialog
1025 * to allow them to be modified
1027 ParamDatastoreI store = HMMERParamStore.forBuild(viewport);
1028 List<ArgumentI> args = store.getServiceParameters();
1032 WsParamSetI set = new HMMERPreset();
1033 WsJobParameters params = new WsJobParameters(store, set, args);
1034 if (params.showRunDialog())
1036 args = params.getJobParams();
1040 return; // user cancelled
1043 new Thread(new HMMBuild(this, args)).start();
1047 public void hmmAlign_actionPerformed(boolean withDefaults)
1049 if (!(checkForHMM() && alignmentIsSufficient(2)))
1055 * get default parameters, and optionally show a dialog
1056 * to allow them to be modified
1058 ParamDatastoreI store = HMMERParamStore.forAlign(viewport);
1059 List<ArgumentI> args = store.getServiceParameters();
1063 WsParamSetI set = new HMMERPreset();
1064 WsJobParameters params = new WsJobParameters(store, set, args);
1065 if (params.showRunDialog())
1067 args = params.getJobParams();
1071 return; // user cancelled
1074 new Thread(new HMMAlign(this, args)).start();
1078 public void hmmSearch_actionPerformed(boolean withDefaults)
1086 * get default parameters, and (if requested) show
1087 * dialog to allow modification
1089 ParamDatastoreI store = HMMERParamStore.forSearch(viewport);
1090 List<ArgumentI> args = store.getServiceParameters();
1094 WsParamSetI set = new HMMERPreset();
1095 WsJobParameters params = new WsJobParameters(store, set, args);
1096 if (params.showRunDialog())
1098 args = params.getJobParams();
1102 return; // user cancelled
1105 new Thread(new HMMSearch(this, args)).start();
1106 alignPanel.repaint();
1110 * Checks if the alignment has at least one hidden Markov model, if not shows
1111 * a dialog advising to run hmmbuild or load an HMM profile
1115 private boolean checkForHMM()
1117 if (viewport.getAlignment().getHmmSequences().isEmpty())
1119 JOptionPane.showMessageDialog(this,
1120 MessageManager.getString("warn.no_hmm"));
1127 * Checks if the alignment contains the required number of sequences.
1132 public boolean alignmentIsSufficient(int required)
1134 if (getViewport().getAlignment().getSequences().size() < required)
1136 JOptionPane.showMessageDialog(this,
1137 MessageManager.getString("label.not_enough_sequences"));
1144 public void addDatabase_actionPerformed() throws IOException
1146 if (Cache.getProperty(Preferences.HMMSEARCH_DB_PATHS) == null)
1148 Cache.setProperty(Preferences.HMMSEARCH_DBS, "");
1149 Cache.setProperty(Preferences.HMMSEARCH_DB_PATHS, "");
1152 String path = openFileChooser(false);
1153 if (path != null && new File(path).exists())
1155 IdentifyFile identifier = new IdentifyFile();
1156 FileFormatI format = identifier.identify(path, DataSourceType.FILE);
1157 if (format == FileFormat.Fasta || format == FileFormat.Stockholm
1158 || format == FileFormat.Pfam)
1160 String currentDbs = Cache.getProperty(Preferences.HMMSEARCH_DBS);
1161 String currentDbPaths = Cache
1162 .getProperty(Preferences.HMMSEARCH_DB_PATHS);
1163 currentDbPaths += " " + path;
1165 String fileName = StringUtils.getLastToken(path, File.separator);
1166 Scanner scanner = new Scanner(fileName).useDelimiter(".");
1167 String name = scanner.next();
1169 currentDbs += " " + path; // TODO remove path from file name
1172 Cache.setProperty(Preferences.HMMSEARCH_DB_PATHS, currentDbPaths);
1173 Cache.setProperty(Preferences.HMMSEARCH_DBS, currentDbPaths);
1177 JOptionPane.showMessageDialog(this,
1178 MessageManager.getString("warn.invalid_format"));
1184 * Opens a file chooser, optionally restricted to selecting folders
1185 * (directories) only. Answers the path to the selected file or folder, or
1186 * null if none is chosen.
1191 protected String openFileChooser(boolean forFolder)
1193 // TODO duplicates GPreferences method - relocate to JalviewFileChooser?
1194 String choice = null;
1195 JFileChooser chooser = new JFileChooser();
1198 chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1200 chooser.setDialogTitle(
1201 MessageManager.getString("label.open_local_file"));
1202 chooser.setToolTipText(MessageManager.getString("action.open"));
1204 int value = chooser.showOpenDialog(this);
1206 if (value == JFileChooser.APPROVE_OPTION)
1208 choice = chooser.getSelectedFile().getPath();
1214 public void reload_actionPerformed(ActionEvent e)
1216 if (fileName != null)
1218 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1219 // originating file's format
1220 // TODO: work out how to recover feature settings for correct view(s) when
1221 // file is reloaded.
1222 if (FileFormat.Jalview.equals(currentFileFormat))
1224 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1225 for (int i = 0; i < frames.length; i++)
1227 if (frames[i] instanceof AlignFrame && frames[i] != this
1228 && ((AlignFrame) frames[i]).fileName != null
1229 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1233 frames[i].setSelected(true);
1234 Desktop.instance.closeAssociatedWindows();
1235 } catch (java.beans.PropertyVetoException ex)
1241 Desktop.instance.closeAssociatedWindows();
1243 FileLoader loader = new FileLoader();
1244 DataSourceType protocol = fileName.startsWith("http:")
1245 ? DataSourceType.URL
1246 : DataSourceType.FILE;
1247 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1251 Rectangle bounds = this.getBounds();
1253 FileLoader loader = new FileLoader();
1254 DataSourceType protocol = fileName.startsWith("http:")
1255 ? DataSourceType.URL
1256 : DataSourceType.FILE;
1257 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1258 protocol, currentFileFormat);
1260 newframe.setBounds(bounds);
1261 if (featureSettings != null && featureSettings.isShowing())
1263 final Rectangle fspos = featureSettings.frame.getBounds();
1264 // TODO: need a 'show feature settings' function that takes bounds -
1265 // need to refactor Desktop.addFrame
1266 newframe.featureSettings_actionPerformed(null);
1267 final FeatureSettings nfs = newframe.featureSettings;
1268 SwingUtilities.invokeLater(new Runnable()
1273 nfs.frame.setBounds(fspos);
1276 this.featureSettings.close();
1277 this.featureSettings = null;
1279 this.closeMenuItem_actionPerformed(true);
1285 public void addFromText_actionPerformed(ActionEvent e)
1288 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1292 public void addFromURL_actionPerformed(ActionEvent e)
1294 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1298 public void save_actionPerformed(ActionEvent e)
1300 if (fileName == null || (currentFileFormat == null)
1301 || fileName.startsWith("http"))
1303 saveAs_actionPerformed(null);
1307 saveAlignment(fileName, currentFileFormat);
1318 public void saveAs_actionPerformed(ActionEvent e)
1320 String format = currentFileFormat == null ? null
1321 : currentFileFormat.getName();
1322 JalviewFileChooser chooser = JalviewFileChooser
1323 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1325 chooser.setFileView(new JalviewFileView());
1326 chooser.setDialogTitle(
1327 MessageManager.getString("label.save_alignment_to_file"));
1328 chooser.setToolTipText(MessageManager.getString("action.save"));
1330 int value = chooser.showSaveDialog(this);
1332 if (value == JalviewFileChooser.APPROVE_OPTION)
1334 currentFileFormat = chooser.getSelectedFormat();
1335 while (currentFileFormat == null)
1337 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1338 MessageManager.getString(
1339 "label.select_file_format_before_saving"),
1340 MessageManager.getString("label.file_format_not_specified"),
1341 JvOptionPane.WARNING_MESSAGE);
1342 currentFileFormat = chooser.getSelectedFormat();
1343 value = chooser.showSaveDialog(this);
1344 if (value != JalviewFileChooser.APPROVE_OPTION)
1350 fileName = chooser.getSelectedFile().getPath();
1352 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1354 Cache.setProperty("LAST_DIRECTORY", fileName);
1355 saveAlignment(fileName, currentFileFormat);
1359 public boolean saveAlignment(String file, FileFormatI format)
1361 boolean success = true;
1363 if (FileFormat.Jalview.equals(format))
1365 String shortName = title;
1367 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1369 shortName = shortName.substring(
1370 shortName.lastIndexOf(java.io.File.separatorChar) + 1);
1373 success = new Jalview2XML().saveAlignment(this, file, shortName);
1375 statusBar.setText(MessageManager.formatMessage(
1376 "label.successfully_saved_to_file_in_format", new Object[]
1377 { fileName, format }));
1382 AlignmentExportData exportData = getAlignmentForExport(format,
1384 if (exportData.getSettings().isCancelled())
1388 FormatAdapter f = new FormatAdapter(alignPanel,
1389 exportData.getSettings());
1390 String output = f.formatSequences(format, exportData.getAlignment(), // class
1394 // occur in the distant future
1395 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1396 f.getCacheSuffixDefault(format),
1397 viewport.getAlignment().getHiddenColumns());
1407 PrintWriter out = new PrintWriter(new FileWriter(file));
1411 this.setTitle(file);
1412 statusBar.setText(MessageManager.formatMessage(
1413 "label.successfully_saved_to_file_in_format", new Object[]
1414 { fileName, format.getName() }));
1415 } catch (Exception ex)
1418 ex.printStackTrace();
1425 JvOptionPane.showInternalMessageDialog(this, MessageManager
1426 .formatMessage("label.couldnt_save_file", new Object[]
1428 MessageManager.getString("label.error_saving_file"),
1429 JvOptionPane.WARNING_MESSAGE);
1435 private void warningMessage(String warning, String title)
1437 if (new jalview.util.Platform().isHeadless())
1439 System.err.println("Warning: " + title + "\nWarning: " + warning);
1444 JvOptionPane.showInternalMessageDialog(this, warning, title,
1445 JvOptionPane.WARNING_MESSAGE);
1457 protected void outputText_actionPerformed(ActionEvent e)
1459 FileFormatI fileFormat = FileFormats.getInstance()
1460 .forName(e.getActionCommand());
1461 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1463 if (exportData.getSettings().isCancelled())
1467 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1468 cap.setForInput(null);
1471 FileFormatI format = fileFormat;
1472 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1473 .formatSequences(format, exportData.getAlignment(),
1474 exportData.getOmitHidden(),
1475 exportData.getStartEndPostions(),
1476 viewport.getAlignment().getHiddenColumns()));
1477 Desktop.addInternalFrame(cap, MessageManager
1478 .formatMessage("label.alignment_output_command", new Object[]
1479 { e.getActionCommand() }), 600, 500);
1480 } catch (OutOfMemoryError oom)
1482 new OOMWarning("Outputting alignment as " + e.getActionCommand(),
1489 public static AlignmentExportData getAlignmentForExport(
1490 FileFormatI format, AlignViewportI viewport,
1491 AlignExportSettingI exportSettings)
1493 AlignmentI alignmentToExport = null;
1494 AlignExportSettingI settings = exportSettings;
1495 String[] omitHidden = null;
1497 HiddenSequences hiddenSeqs = viewport.getAlignment()
1498 .getHiddenSequences();
1500 alignmentToExport = viewport.getAlignment();
1502 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1503 if (settings == null)
1505 settings = new AlignExportSettings(hasHiddenSeqs,
1506 viewport.hasHiddenColumns(), format);
1508 // settings.isExportAnnotations();
1510 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1512 omitHidden = viewport.getViewAsString(false,
1513 settings.isExportHiddenSequences());
1516 int[] alignmentStartEnd = new int[2];
1517 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1519 alignmentToExport = hiddenSeqs.getFullAlignment();
1523 alignmentToExport = viewport.getAlignment();
1525 alignmentStartEnd = viewport.getAlignment().getHiddenColumns()
1526 .getVisibleStartAndEndIndex(alignmentToExport.getWidth());
1527 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1528 omitHidden, alignmentStartEnd, settings);
1539 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1541 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1542 htmlSVG.exportHTML(null);
1546 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1548 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1549 bjs.exportHTML(null);
1552 public void createImageMap(File file, String image)
1554 alignPanel.makePNGImageMap(file, image);
1564 public void createPNG(File f)
1566 alignPanel.makePNG(f);
1576 public void createEPS(File f)
1578 alignPanel.makeEPS(f);
1582 public void createSVG(File f)
1584 alignPanel.makeSVG(f);
1588 public void pageSetup_actionPerformed(ActionEvent e)
1590 PrinterJob printJob = PrinterJob.getPrinterJob();
1591 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1601 public void printMenuItem_actionPerformed(ActionEvent e)
1603 // Putting in a thread avoids Swing painting problems
1604 PrintThread thread = new PrintThread(alignPanel);
1609 public void exportFeatures_actionPerformed(ActionEvent e)
1611 new AnnotationExporter(alignPanel).exportFeatures();
1615 public void exportAnnotations_actionPerformed(ActionEvent e)
1617 new AnnotationExporter(alignPanel).exportAnnotations();
1621 public void associatedData_actionPerformed(ActionEvent e)
1622 throws IOException, InterruptedException
1624 // Pick the tree file
1625 JalviewFileChooser chooser = new JalviewFileChooser(
1626 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1627 chooser.setFileView(new JalviewFileView());
1628 chooser.setDialogTitle(
1629 MessageManager.getString("label.load_jalview_annotations"));
1630 chooser.setToolTipText(
1631 MessageManager.getString("label.load_jalview_annotations"));
1633 int value = chooser.showOpenDialog(null);
1635 if (value == JalviewFileChooser.APPROVE_OPTION)
1637 String choice = chooser.getSelectedFile().getPath();
1638 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1639 loadJalviewDataFile(choice, null, null, null);
1645 * Close the current view or all views in the alignment frame. If the frame
1646 * only contains one view then the alignment will be removed from memory.
1648 * @param closeAllTabs
1651 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1653 if (alignPanels != null && alignPanels.size() < 2)
1655 closeAllTabs = true;
1660 if (alignPanels != null)
1664 if (this.isClosed())
1666 // really close all the windows - otherwise wait till
1667 // setClosed(true) is called
1668 for (int i = 0; i < alignPanels.size(); i++)
1670 AlignmentPanel ap = alignPanels.get(i);
1677 closeView(alignPanel);
1684 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1685 * be called recursively, with the frame now in 'closed' state
1687 this.setClosed(true);
1689 } catch (Exception ex)
1691 ex.printStackTrace();
1696 * Close the specified panel and close up tabs appropriately.
1698 * @param panelToClose
1700 public void closeView(AlignmentPanel panelToClose)
1702 int index = tabbedPane.getSelectedIndex();
1703 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1704 alignPanels.remove(panelToClose);
1705 panelToClose.closePanel();
1706 panelToClose = null;
1708 tabbedPane.removeTabAt(closedindex);
1709 tabbedPane.validate();
1711 if (index > closedindex || index == tabbedPane.getTabCount())
1713 // modify currently selected tab index if necessary.
1717 this.tabSelectionChanged(index);
1723 void updateEditMenuBar()
1726 if (viewport.getHistoryList().size() > 0)
1728 undoMenuItem.setEnabled(true);
1729 CommandI command = viewport.getHistoryList().peek();
1730 undoMenuItem.setText(MessageManager
1731 .formatMessage("label.undo_command", new Object[]
1732 { command.getDescription() }));
1736 undoMenuItem.setEnabled(false);
1737 undoMenuItem.setText(MessageManager.getString("action.undo"));
1740 if (viewport.getRedoList().size() > 0)
1742 redoMenuItem.setEnabled(true);
1744 CommandI command = viewport.getRedoList().peek();
1745 redoMenuItem.setText(MessageManager
1746 .formatMessage("label.redo_command", new Object[]
1747 { command.getDescription() }));
1751 redoMenuItem.setEnabled(false);
1752 redoMenuItem.setText(MessageManager.getString("action.redo"));
1757 public void addHistoryItem(CommandI command)
1759 if (command.getSize() > 0)
1761 viewport.addToHistoryList(command);
1762 viewport.clearRedoList();
1763 updateEditMenuBar();
1764 viewport.updateHiddenColumns();
1765 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1766 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1767 // viewport.getColumnSelection()
1768 // .getHiddenColumns().size() > 0);
1774 * @return alignment objects for all views
1776 AlignmentI[] getViewAlignments()
1778 if (alignPanels != null)
1780 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1782 for (AlignmentPanel ap : alignPanels)
1784 als[i++] = ap.av.getAlignment();
1788 if (viewport != null)
1790 return new AlignmentI[] { viewport.getAlignment() };
1802 protected void undoMenuItem_actionPerformed(ActionEvent e)
1804 if (viewport.getHistoryList().isEmpty())
1808 CommandI command = viewport.getHistoryList().pop();
1809 viewport.addToRedoList(command);
1810 command.undoCommand(getViewAlignments());
1812 AlignmentViewport originalSource = getOriginatingSource(command);
1813 updateEditMenuBar();
1815 if (originalSource != null)
1817 if (originalSource != viewport)
1820 "Implementation worry: mismatch of viewport origin for undo");
1822 originalSource.updateHiddenColumns();
1823 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1825 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1826 // viewport.getColumnSelection()
1827 // .getHiddenColumns().size() > 0);
1828 originalSource.firePropertyChange("alignment", null,
1829 originalSource.getAlignment().getSequences());
1840 protected void redoMenuItem_actionPerformed(ActionEvent e)
1842 if (viewport.getRedoList().size() < 1)
1847 CommandI command = viewport.getRedoList().pop();
1848 viewport.addToHistoryList(command);
1849 command.doCommand(getViewAlignments());
1851 AlignmentViewport originalSource = getOriginatingSource(command);
1852 updateEditMenuBar();
1854 if (originalSource != null)
1857 if (originalSource != viewport)
1860 "Implementation worry: mismatch of viewport origin for redo");
1862 originalSource.updateHiddenColumns();
1863 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1865 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1866 // viewport.getColumnSelection()
1867 // .getHiddenColumns().size() > 0);
1868 originalSource.firePropertyChange("alignment", null,
1869 originalSource.getAlignment().getSequences());
1873 AlignmentViewport getOriginatingSource(CommandI command)
1875 AlignmentViewport originalSource = null;
1876 // For sequence removal and addition, we need to fire
1877 // the property change event FROM the viewport where the
1878 // original alignment was altered
1879 AlignmentI al = null;
1880 if (command instanceof EditCommand)
1882 EditCommand editCommand = (EditCommand) command;
1883 al = editCommand.getAlignment();
1884 List<Component> comps = PaintRefresher.components
1885 .get(viewport.getSequenceSetId());
1887 for (Component comp : comps)
1889 if (comp instanceof AlignmentPanel)
1891 if (al == ((AlignmentPanel) comp).av.getAlignment())
1893 originalSource = ((AlignmentPanel) comp).av;
1900 if (originalSource == null)
1902 // The original view is closed, we must validate
1903 // the current view against the closed view first
1906 PaintRefresher.validateSequences(al, viewport.getAlignment());
1909 originalSource = viewport;
1912 return originalSource;
1921 public void moveSelectedSequences(boolean up)
1923 SequenceGroup sg = viewport.getSelectionGroup();
1929 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1930 viewport.getHiddenRepSequences(), up);
1931 alignPanel.paintAlignment(true, false);
1934 synchronized void slideSequences(boolean right, int size)
1936 List<SequenceI> sg = new ArrayList<>();
1937 if (viewport.cursorMode)
1939 sg.add(viewport.getAlignment()
1940 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1942 else if (viewport.getSelectionGroup() != null
1943 && viewport.getSelectionGroup().getSize() != viewport
1944 .getAlignment().getHeight())
1946 sg = viewport.getSelectionGroup()
1947 .getSequences(viewport.getHiddenRepSequences());
1955 List<SequenceI> invertGroup = new ArrayList<>();
1957 for (SequenceI seq : viewport.getAlignment().getSequences())
1959 if (!sg.contains(seq))
1961 invertGroup.add(seq);
1965 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1967 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1968 for (int i = 0; i < invertGroup.size(); i++)
1970 seqs2[i] = invertGroup.get(i);
1973 SlideSequencesCommand ssc;
1976 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1977 viewport.getGapCharacter());
1981 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1982 viewport.getGapCharacter());
1985 int groupAdjustment = 0;
1986 if (ssc.getGapsInsertedBegin() && right)
1988 if (viewport.cursorMode)
1990 alignPanel.getSeqPanel().moveCursor(size, 0);
1994 groupAdjustment = size;
1997 else if (!ssc.getGapsInsertedBegin() && !right)
1999 if (viewport.cursorMode)
2001 alignPanel.getSeqPanel().moveCursor(-size, 0);
2005 groupAdjustment = -size;
2009 if (groupAdjustment != 0)
2011 viewport.getSelectionGroup().setStartRes(
2012 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
2013 viewport.getSelectionGroup().setEndRes(
2014 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
2018 * just extend the last slide command if compatible; but not if in
2019 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
2021 boolean appendHistoryItem = false;
2022 Deque<CommandI> historyList = viewport.getHistoryList();
2023 boolean inSplitFrame = getSplitViewContainer() != null;
2024 if (!inSplitFrame && historyList != null && historyList.size() > 0
2025 && historyList.peek() instanceof SlideSequencesCommand)
2027 appendHistoryItem = ssc.appendSlideCommand(
2028 (SlideSequencesCommand) historyList.peek());
2031 if (!appendHistoryItem)
2033 addHistoryItem(ssc);
2046 protected void copy_actionPerformed(ActionEvent e)
2048 if (viewport.getSelectionGroup() == null)
2052 // TODO: preserve the ordering of displayed alignment annotation in any
2053 // internal paste (particularly sequence associated annotation)
2054 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2055 String[] omitHidden = null;
2057 if (viewport.hasHiddenColumns())
2059 omitHidden = viewport.getViewAsString(true);
2062 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2063 seqs, omitHidden, null);
2065 StringSelection ss = new StringSelection(output);
2069 jalview.gui.Desktop.internalCopy = true;
2070 // Its really worth setting the clipboard contents
2071 // to empty before setting the large StringSelection!!
2072 Toolkit.getDefaultToolkit().getSystemClipboard()
2073 .setContents(new StringSelection(""), null);
2075 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2077 } catch (OutOfMemoryError er)
2079 new OOMWarning("copying region", er);
2083 HiddenColumns hiddenColumns = null;
2084 if (viewport.hasHiddenColumns())
2086 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2087 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2089 // create new HiddenColumns object with copy of hidden regions
2090 // between startRes and endRes, offset by startRes
2091 hiddenColumns = new HiddenColumns(
2092 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2093 hiddenCutoff, hiddenOffset);
2096 Desktop.jalviewClipboard = new Object[] { seqs,
2097 viewport.getAlignment().getDataset(), hiddenColumns };
2098 statusBar.setText(MessageManager.formatMessage(
2099 "label.copied_sequences_to_clipboard", new Object[]
2100 { Integer.valueOf(seqs.length).toString() }));
2108 * @throws InterruptedException
2109 * @throws IOException
2112 protected void pasteNew_actionPerformed(ActionEvent e)
2113 throws IOException, InterruptedException
2123 * @throws InterruptedException
2124 * @throws IOException
2127 protected void pasteThis_actionPerformed(ActionEvent e)
2128 throws IOException, InterruptedException
2134 * Paste contents of Jalview clipboard
2136 * @param newAlignment
2137 * true to paste to a new alignment, otherwise add to this.
2138 * @throws InterruptedException
2139 * @throws IOException
2141 void paste(boolean newAlignment) throws IOException, InterruptedException
2143 boolean externalPaste = true;
2146 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2147 Transferable contents = c.getContents(this);
2149 if (contents == null)
2158 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2159 if (str.length() < 1)
2164 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2166 } catch (OutOfMemoryError er)
2168 new OOMWarning("Out of memory pasting sequences!!", er);
2172 SequenceI[] sequences;
2173 boolean annotationAdded = false;
2174 AlignmentI alignment = null;
2176 if (Desktop.jalviewClipboard != null)
2178 // The clipboard was filled from within Jalview, we must use the
2180 // And dataset from the copied alignment
2181 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2182 // be doubly sure that we create *new* sequence objects.
2183 sequences = new SequenceI[newseq.length];
2184 for (int i = 0; i < newseq.length; i++)
2186 sequences[i] = new Sequence(newseq[i]);
2188 alignment = new Alignment(sequences);
2189 externalPaste = false;
2193 // parse the clipboard as an alignment.
2194 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2196 sequences = alignment.getSequencesArray();
2200 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2206 if (Desktop.jalviewClipboard != null)
2208 // dataset is inherited
2209 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2213 // new dataset is constructed
2214 alignment.setDataset(null);
2216 alwidth = alignment.getWidth() + 1;
2220 AlignmentI pastedal = alignment; // preserve pasted alignment object
2221 // Add pasted sequences and dataset into existing alignment.
2222 alignment = viewport.getAlignment();
2223 alwidth = alignment.getWidth() + 1;
2224 // decide if we need to import sequences from an existing dataset
2225 boolean importDs = Desktop.jalviewClipboard != null
2226 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2227 // importDs==true instructs us to copy over new dataset sequences from
2228 // an existing alignment
2229 Vector newDs = (importDs) ? new Vector() : null; // used to create
2230 // minimum dataset set
2232 for (int i = 0; i < sequences.length; i++)
2236 newDs.addElement(null);
2238 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2240 if (importDs && ds != null)
2242 if (!newDs.contains(ds))
2244 newDs.setElementAt(ds, i);
2245 ds = new Sequence(ds);
2246 // update with new dataset sequence
2247 sequences[i].setDatasetSequence(ds);
2251 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2256 // copy and derive new dataset sequence
2257 sequences[i] = sequences[i].deriveSequence();
2258 alignment.getDataset()
2259 .addSequence(sequences[i].getDatasetSequence());
2260 // TODO: avoid creation of duplicate dataset sequences with a
2261 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2263 alignment.addSequence(sequences[i]); // merges dataset
2267 newDs.clear(); // tidy up
2269 if (alignment.getAlignmentAnnotation() != null)
2271 for (AlignmentAnnotation alan : alignment
2272 .getAlignmentAnnotation())
2274 if (alan.graphGroup > fgroup)
2276 fgroup = alan.graphGroup;
2280 if (pastedal.getAlignmentAnnotation() != null)
2282 // Add any annotation attached to alignment.
2283 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2284 for (int i = 0; i < alann.length; i++)
2286 annotationAdded = true;
2287 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2289 AlignmentAnnotation newann = new AlignmentAnnotation(
2291 if (newann.graphGroup > -1)
2293 if (newGraphGroups.size() <= newann.graphGroup
2294 || newGraphGroups.get(newann.graphGroup) == null)
2296 for (int q = newGraphGroups
2297 .size(); q <= newann.graphGroup; q++)
2299 newGraphGroups.add(q, null);
2301 newGraphGroups.set(newann.graphGroup,
2302 new Integer(++fgroup));
2304 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2308 newann.padAnnotation(alwidth);
2309 alignment.addAnnotation(newann);
2319 addHistoryItem(new EditCommand(
2320 MessageManager.getString("label.add_sequences"),
2321 Action.PASTE, sequences, 0, alignment.getWidth(),
2324 // Add any annotations attached to sequences
2325 for (int i = 0; i < sequences.length; i++)
2327 if (sequences[i].getAnnotation() != null)
2329 AlignmentAnnotation newann;
2330 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2332 annotationAdded = true;
2333 newann = sequences[i].getAnnotation()[a];
2334 newann.adjustForAlignment();
2335 newann.padAnnotation(alwidth);
2336 if (newann.graphGroup > -1)
2338 if (newann.graphGroup > -1)
2340 if (newGraphGroups.size() <= newann.graphGroup
2341 || newGraphGroups.get(newann.graphGroup) == null)
2343 for (int q = newGraphGroups
2344 .size(); q <= newann.graphGroup; q++)
2346 newGraphGroups.add(q, null);
2348 newGraphGroups.set(newann.graphGroup,
2349 new Integer(++fgroup));
2351 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2355 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2359 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2367 // propagate alignment changed.
2368 viewport.getRanges().setEndSeq(alignment.getHeight());
2369 if (annotationAdded)
2371 // Duplicate sequence annotation in all views.
2372 AlignmentI[] alview = this.getViewAlignments();
2373 for (int i = 0; i < sequences.length; i++)
2375 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2380 for (int avnum = 0; avnum < alview.length; avnum++)
2382 if (alview[avnum] != alignment)
2384 // duplicate in a view other than the one with input focus
2385 int avwidth = alview[avnum].getWidth() + 1;
2386 // this relies on sann being preserved after we
2387 // modify the sequence's annotation array for each duplication
2388 for (int a = 0; a < sann.length; a++)
2390 AlignmentAnnotation newann = new AlignmentAnnotation(
2392 sequences[i].addAlignmentAnnotation(newann);
2393 newann.padAnnotation(avwidth);
2394 alview[avnum].addAnnotation(newann); // annotation was
2395 // duplicated earlier
2396 // TODO JAL-1145 graphGroups are not updated for sequence
2397 // annotation added to several views. This may cause
2399 alview[avnum].setAnnotationIndex(newann, a);
2404 buildSortByAnnotationScoresMenu();
2406 viewport.firePropertyChange("alignment", null,
2407 alignment.getSequences());
2408 if (alignPanels != null)
2410 for (AlignmentPanel ap : alignPanels)
2412 ap.validateAnnotationDimensions(false);
2417 alignPanel.validateAnnotationDimensions(false);
2423 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2425 String newtitle = new String("Copied sequences");
2427 if (Desktop.jalviewClipboard != null
2428 && Desktop.jalviewClipboard[2] != null)
2430 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2431 af.viewport.setHiddenColumns(hc);
2434 // >>>This is a fix for the moment, until a better solution is
2436 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2437 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2438 .getFeatureRenderer());
2440 // TODO: maintain provenance of an alignment, rather than just make the
2441 // title a concatenation of operations.
2444 if (title.startsWith("Copied sequences"))
2450 newtitle = newtitle.concat("- from " + title);
2455 newtitle = new String("Pasted sequences");
2458 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2463 } catch (Exception ex)
2465 ex.printStackTrace();
2466 System.out.println("Exception whilst pasting: " + ex);
2467 // could be anything being pasted in here
2472 protected void expand_newalign(ActionEvent e)
2476 AlignmentI alignment = AlignmentUtils
2477 .expandContext(getViewport().getAlignment(), -1);
2478 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2480 String newtitle = new String("Flanking alignment");
2482 if (Desktop.jalviewClipboard != null
2483 && Desktop.jalviewClipboard[2] != null)
2485 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2486 af.viewport.setHiddenColumns(hc);
2489 // >>>This is a fix for the moment, until a better solution is
2491 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2492 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2493 .getFeatureRenderer());
2495 // TODO: maintain provenance of an alignment, rather than just make the
2496 // title a concatenation of operations.
2498 if (title.startsWith("Copied sequences"))
2504 newtitle = newtitle.concat("- from " + title);
2508 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2510 } catch (Exception ex)
2512 ex.printStackTrace();
2513 System.out.println("Exception whilst pasting: " + ex);
2514 // could be anything being pasted in here
2515 } catch (OutOfMemoryError oom)
2517 new OOMWarning("Viewing flanking region of alignment", oom);
2528 protected void cut_actionPerformed(ActionEvent e)
2530 copy_actionPerformed(null);
2531 delete_actionPerformed(null);
2541 protected void delete_actionPerformed(ActionEvent evt)
2544 SequenceGroup sg = viewport.getSelectionGroup();
2551 * If the cut affects all sequences, warn, remove highlighted columns
2553 if (sg.getSize() == viewport.getAlignment().getHeight())
2555 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2556 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2557 if (isEntireAlignWidth)
2559 int confirm = JvOptionPane.showConfirmDialog(this,
2560 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2561 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2562 JvOptionPane.OK_CANCEL_OPTION);
2564 if (confirm == JvOptionPane.CANCEL_OPTION
2565 || confirm == JvOptionPane.CLOSED_OPTION)
2570 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2571 sg.getEndRes() + 1);
2573 SequenceI[] cut = sg.getSequences()
2574 .toArray(new SequenceI[sg.getSize()]);
2576 addHistoryItem(new EditCommand(
2577 MessageManager.getString("label.cut_sequences"), Action.CUT,
2578 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2579 viewport.getAlignment()));
2581 viewport.setSelectionGroup(null);
2582 viewport.sendSelection();
2583 viewport.getAlignment().deleteGroup(sg);
2585 viewport.firePropertyChange("alignment", null,
2586 viewport.getAlignment().getSequences());
2587 if (viewport.getAlignment().getHeight() < 1)
2591 this.setClosed(true);
2592 } catch (Exception ex)
2605 protected void deleteGroups_actionPerformed(ActionEvent e)
2607 if (avc.deleteGroups())
2609 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2610 alignPanel.updateAnnotation();
2611 alignPanel.paintAlignment(true, true);
2622 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2624 SequenceGroup sg = new SequenceGroup();
2626 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2628 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2631 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2632 viewport.setSelectionGroup(sg);
2633 viewport.sendSelection();
2634 // JAL-2034 - should delegate to
2635 // alignPanel to decide if overview needs
2637 alignPanel.paintAlignment(false, false);
2638 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2648 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2650 if (viewport.cursorMode)
2652 alignPanel.getSeqPanel().keyboardNo1 = null;
2653 alignPanel.getSeqPanel().keyboardNo2 = null;
2655 viewport.setSelectionGroup(null);
2656 viewport.getColumnSelection().clear();
2657 viewport.setSelectionGroup(null);
2658 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2659 // JAL-2034 - should delegate to
2660 // alignPanel to decide if overview needs
2662 alignPanel.paintAlignment(false, false);
2663 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2664 viewport.sendSelection();
2674 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2676 SequenceGroup sg = viewport.getSelectionGroup();
2680 selectAllSequenceMenuItem_actionPerformed(null);
2685 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2687 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2689 // JAL-2034 - should delegate to
2690 // alignPanel to decide if overview needs
2693 alignPanel.paintAlignment(true, false);
2694 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2695 viewport.sendSelection();
2699 public void invertColSel_actionPerformed(ActionEvent e)
2701 viewport.invertColumnSelection();
2702 alignPanel.paintAlignment(true, false);
2703 viewport.sendSelection();
2713 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2715 trimAlignment(true);
2725 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2727 trimAlignment(false);
2730 void trimAlignment(boolean trimLeft)
2732 ColumnSelection colSel = viewport.getColumnSelection();
2735 if (!colSel.isEmpty())
2739 column = colSel.getMin();
2743 column = colSel.getMax();
2747 if (viewport.getSelectionGroup() != null)
2749 seqs = viewport.getSelectionGroup()
2750 .getSequencesAsArray(viewport.getHiddenRepSequences());
2754 seqs = viewport.getAlignment().getSequencesArray();
2757 TrimRegionCommand trimRegion;
2760 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2761 column, viewport.getAlignment());
2762 viewport.getRanges().setStartRes(0);
2766 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2767 column, viewport.getAlignment());
2770 statusBar.setText(MessageManager
2771 .formatMessage("label.removed_columns", new String[]
2772 { Integer.valueOf(trimRegion.getSize()).toString() }));
2774 addHistoryItem(trimRegion);
2776 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2778 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2779 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2781 viewport.getAlignment().deleteGroup(sg);
2785 viewport.firePropertyChange("alignment", null,
2786 viewport.getAlignment().getSequences());
2797 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2799 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2802 if (viewport.getSelectionGroup() != null)
2804 seqs = viewport.getSelectionGroup()
2805 .getSequencesAsArray(viewport.getHiddenRepSequences());
2806 start = viewport.getSelectionGroup().getStartRes();
2807 end = viewport.getSelectionGroup().getEndRes();
2811 seqs = viewport.getAlignment().getSequencesArray();
2814 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2815 "Remove Gapped Columns", seqs, start, end,
2816 viewport.getAlignment());
2818 addHistoryItem(removeGapCols);
2820 statusBar.setText(MessageManager
2821 .formatMessage("label.removed_empty_columns", new Object[]
2822 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2824 // This is to maintain viewport position on first residue
2825 // of first sequence
2826 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2827 ViewportRanges ranges = viewport.getRanges();
2828 int startRes = seq.findPosition(ranges.getStartRes());
2829 // ShiftList shifts;
2830 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2831 // edit.alColumnChanges=shifts.getInverse();
2832 // if (viewport.hasHiddenColumns)
2833 // viewport.getColumnSelection().compensateForEdits(shifts);
2834 ranges.setStartRes(seq.findIndex(startRes) - 1);
2835 viewport.firePropertyChange("alignment", null,
2836 viewport.getAlignment().getSequences());
2847 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2849 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2852 if (viewport.getSelectionGroup() != null)
2854 seqs = viewport.getSelectionGroup()
2855 .getSequencesAsArray(viewport.getHiddenRepSequences());
2856 start = viewport.getSelectionGroup().getStartRes();
2857 end = viewport.getSelectionGroup().getEndRes();
2861 seqs = viewport.getAlignment().getSequencesArray();
2864 // This is to maintain viewport position on first residue
2865 // of first sequence
2866 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2867 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2869 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2870 viewport.getAlignment()));
2872 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2874 viewport.firePropertyChange("alignment", null,
2875 viewport.getAlignment().getSequences());
2886 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2888 viewport.setPadGaps(padGapsMenuitem.isSelected());
2889 viewport.firePropertyChange("alignment", null,
2890 viewport.getAlignment().getSequences());
2900 public void findMenuItem_actionPerformed(ActionEvent e)
2906 * Create a new view of the current alignment.
2909 public void newView_actionPerformed(ActionEvent e)
2911 newView(null, true);
2915 * Creates and shows a new view of the current alignment.
2918 * title of newly created view; if null, one will be generated
2919 * @param copyAnnotation
2920 * if true then duplicate all annnotation, groups and settings
2921 * @return new alignment panel, already displayed.
2923 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2926 * Create a new AlignmentPanel (with its own, new Viewport)
2928 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel);
2929 if (!copyAnnotation)
2932 * remove all groups and annotation except for the automatic stuff
2934 newap.av.getAlignment().deleteAllGroups();
2935 newap.av.getAlignment().deleteAllAnnotations(false);
2938 newap.av.setGatherViewsHere(false);
2940 if (viewport.viewName == null)
2942 viewport.viewName = MessageManager
2943 .getString("label.view_name_original");
2947 * Views share the same edits undo and redo stacks
2949 newap.av.setHistoryList(viewport.getHistoryList());
2950 newap.av.setRedoList(viewport.getRedoList());
2953 * Views share the same mappings; need to deregister any new mappings
2954 * created by copyAlignPanel, and register the new reference to the shared
2957 newap.av.replaceMappings(viewport.getAlignment());
2960 * start up cDNA consensus (if applicable) now mappings are in place
2962 if (newap.av.initComplementConsensus())
2964 newap.refresh(true); // adjust layout of annotations
2967 newap.av.viewName = getNewViewName(viewTitle);
2969 addAlignmentPanel(newap, true);
2970 newap.alignmentChanged();
2972 if (alignPanels.size() == 2)
2974 viewport.setGatherViewsHere(true);
2976 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2981 * Make a new name for the view, ensuring it is unique within the current
2982 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2983 * these now use viewId. Unique view names are still desirable for usability.)
2988 protected String getNewViewName(String viewTitle)
2990 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2991 boolean addFirstIndex = false;
2992 if (viewTitle == null || viewTitle.trim().length() == 0)
2994 viewTitle = MessageManager.getString("action.view");
2995 addFirstIndex = true;
2999 index = 1;// we count from 1 if given a specific name
3001 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
3003 List<Component> comps = PaintRefresher.components
3004 .get(viewport.getSequenceSetId());
3006 List<String> existingNames = getExistingViewNames(comps);
3008 while (existingNames.contains(newViewName))
3010 newViewName = viewTitle + " " + (++index);
3016 * Returns a list of distinct view names found in the given list of
3017 * components. View names are held on the viewport of an AlignmentPanel.
3022 protected List<String> getExistingViewNames(List<Component> comps)
3024 List<String> existingNames = new ArrayList<>();
3025 for (Component comp : comps)
3027 if (comp instanceof AlignmentPanel)
3029 AlignmentPanel ap = (AlignmentPanel) comp;
3030 if (!existingNames.contains(ap.av.viewName))
3032 existingNames.add(ap.av.viewName);
3036 return existingNames;
3040 * Explode tabbed views into separate windows.
3043 public void expandViews_actionPerformed(ActionEvent e)
3045 Desktop.explodeViews(this);
3049 * Gather views in separate windows back into a tabbed presentation.
3052 public void gatherViews_actionPerformed(ActionEvent e)
3054 Desktop.instance.gatherViews(this);
3064 public void font_actionPerformed(ActionEvent e)
3066 new FontChooser(alignPanel);
3076 protected void seqLimit_actionPerformed(ActionEvent e)
3078 viewport.setShowJVSuffix(seqLimits.isSelected());
3080 alignPanel.getIdPanel().getIdCanvas()
3081 .setPreferredSize(alignPanel.calculateIdWidth());
3082 alignPanel.paintAlignment(true, false);
3086 public void idRightAlign_actionPerformed(ActionEvent e)
3088 viewport.setRightAlignIds(idRightAlign.isSelected());
3089 alignPanel.paintAlignment(false, false);
3093 public void centreColumnLabels_actionPerformed(ActionEvent e)
3095 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3096 alignPanel.paintAlignment(false, false);
3102 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3105 protected void followHighlight_actionPerformed()
3108 * Set the 'follow' flag on the Viewport (and scroll to position if now
3111 final boolean state = this.followHighlightMenuItem.getState();
3112 viewport.setFollowHighlight(state);
3115 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
3126 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3128 viewport.setColourText(colourTextMenuItem.isSelected());
3129 alignPanel.paintAlignment(false, false);
3139 public void wrapMenuItem_actionPerformed(ActionEvent e)
3141 scaleAbove.setVisible(wrapMenuItem.isSelected());
3142 scaleLeft.setVisible(wrapMenuItem.isSelected());
3143 scaleRight.setVisible(wrapMenuItem.isSelected());
3144 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3145 alignPanel.updateLayout();
3149 public void showAllSeqs_actionPerformed(ActionEvent e)
3151 viewport.showAllHiddenSeqs();
3155 public void showAllColumns_actionPerformed(ActionEvent e)
3157 viewport.showAllHiddenColumns();
3158 alignPanel.paintAlignment(true, true);
3159 viewport.sendSelection();
3163 public void hideSelSequences_actionPerformed(ActionEvent e)
3165 viewport.hideAllSelectedSeqs();
3169 * called by key handler and the hide all/show all menu items
3174 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3177 boolean hide = false;
3178 SequenceGroup sg = viewport.getSelectionGroup();
3179 if (!toggleSeqs && !toggleCols)
3181 // Hide everything by the current selection - this is a hack - we do the
3182 // invert and then hide
3183 // first check that there will be visible columns after the invert.
3184 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3185 && sg.getStartRes() <= sg.getEndRes()))
3187 // now invert the sequence set, if required - empty selection implies
3188 // that no hiding is required.
3191 invertSequenceMenuItem_actionPerformed(null);
3192 sg = viewport.getSelectionGroup();
3196 viewport.expandColSelection(sg, true);
3197 // finally invert the column selection and get the new sequence
3199 invertColSel_actionPerformed(null);
3206 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3208 hideSelSequences_actionPerformed(null);
3211 else if (!(toggleCols && viewport.hasSelectedColumns()))
3213 showAllSeqs_actionPerformed(null);
3219 if (viewport.hasSelectedColumns())
3221 hideSelColumns_actionPerformed(null);
3224 viewport.setSelectionGroup(sg);
3229 showAllColumns_actionPerformed(null);
3238 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3239 * event.ActionEvent)
3242 public void hideAllButSelection_actionPerformed(ActionEvent e)
3244 toggleHiddenRegions(false, false);
3245 viewport.sendSelection();
3252 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3256 public void hideAllSelection_actionPerformed(ActionEvent e)
3258 SequenceGroup sg = viewport.getSelectionGroup();
3259 viewport.expandColSelection(sg, false);
3260 viewport.hideAllSelectedSeqs();
3261 viewport.hideSelectedColumns();
3262 alignPanel.paintAlignment(true, true);
3263 viewport.sendSelection();
3270 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3274 public void showAllhidden_actionPerformed(ActionEvent e)
3276 viewport.showAllHiddenColumns();
3277 viewport.showAllHiddenSeqs();
3278 alignPanel.paintAlignment(true, true);
3279 viewport.sendSelection();
3283 public void hideSelColumns_actionPerformed(ActionEvent e)
3285 viewport.hideSelectedColumns();
3286 alignPanel.paintAlignment(true, true);
3287 viewport.sendSelection();
3291 public void hiddenMarkers_actionPerformed(ActionEvent e)
3293 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3304 protected void scaleAbove_actionPerformed(ActionEvent e)
3306 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3307 // TODO: do we actually need to update overview for scale above change ?
3308 alignPanel.paintAlignment(true, false);
3318 protected void scaleLeft_actionPerformed(ActionEvent e)
3320 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3321 alignPanel.paintAlignment(true, false);
3331 protected void scaleRight_actionPerformed(ActionEvent e)
3333 viewport.setScaleRightWrapped(scaleRight.isSelected());
3334 alignPanel.paintAlignment(true, false);
3344 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3346 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3347 alignPanel.paintAlignment(false, false);
3357 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3359 viewport.setShowText(viewTextMenuItem.isSelected());
3360 alignPanel.paintAlignment(false, false);
3370 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3372 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3373 alignPanel.paintAlignment(false, false);
3376 public FeatureSettings featureSettings;
3379 public FeatureSettingsControllerI getFeatureSettingsUI()
3381 return featureSettings;
3385 public void featureSettings_actionPerformed(ActionEvent e)
3387 if (featureSettings != null)
3389 featureSettings.close();
3390 featureSettings = null;
3392 if (!showSeqFeatures.isSelected())
3394 // make sure features are actually displayed
3395 showSeqFeatures.setSelected(true);
3396 showSeqFeatures_actionPerformed(null);
3398 featureSettings = new FeatureSettings(this);
3402 * Set or clear 'Show Sequence Features'
3408 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3410 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3411 alignPanel.paintAlignment(true, true);
3415 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3416 * the annotations panel as a whole.
3418 * The options to show/hide all annotations should be enabled when the panel
3419 * is shown, and disabled when the panel is hidden.
3424 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3426 final boolean setVisible = annotationPanelMenuItem.isSelected();
3427 viewport.setShowAnnotation(setVisible);
3428 this.showAllSeqAnnotations.setEnabled(setVisible);
3429 this.hideAllSeqAnnotations.setEnabled(setVisible);
3430 this.showAllAlAnnotations.setEnabled(setVisible);
3431 this.hideAllAlAnnotations.setEnabled(setVisible);
3432 alignPanel.updateLayout();
3436 public void alignmentProperties()
3438 JEditorPane editPane = new JEditorPane("text/html", "");
3439 editPane.setEditable(false);
3440 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3443 MessageManager.formatMessage("label.html_content", new Object[]
3444 { contents.toString() }));
3445 JInternalFrame frame = new JInternalFrame();
3446 frame.getContentPane().add(new JScrollPane(editPane));
3448 Desktop.addInternalFrame(frame, MessageManager
3449 .formatMessage("label.alignment_properties", new Object[]
3450 { getTitle() }), 500, 400);
3460 public void overviewMenuItem_actionPerformed(ActionEvent e)
3462 if (alignPanel.overviewPanel != null)
3467 JInternalFrame frame = new JInternalFrame();
3468 final OverviewPanel overview = new OverviewPanel(alignPanel);
3469 frame.setContentPane(overview);
3470 Desktop.addInternalFrame(frame, MessageManager
3471 .formatMessage("label.overview_params", new Object[]
3472 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3475 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3476 frame.addInternalFrameListener(
3477 new javax.swing.event.InternalFrameAdapter()
3480 public void internalFrameClosed(
3481 javax.swing.event.InternalFrameEvent evt)
3484 alignPanel.setOverviewPanel(null);
3488 alignPanel.setOverviewPanel(overview);
3492 public void textColour_actionPerformed()
3494 new TextColourChooser().chooseColour(alignPanel, null);
3498 * public void covariationColour_actionPerformed() {
3500 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3504 public void annotationColour_actionPerformed()
3506 new AnnotationColourChooser(viewport, alignPanel);
3510 public void annotationColumn_actionPerformed(ActionEvent e)
3512 new AnnotationColumnChooser(viewport, alignPanel);
3516 * Action on the user checking or unchecking the option to apply the selected
3517 * colour scheme to all groups. If unchecked, groups may have their own
3518 * independent colour schemes.
3523 public void applyToAllGroups_actionPerformed(boolean selected)
3525 viewport.setColourAppliesToAllGroups(selected);
3529 * Action on user selecting a colour from the colour menu
3532 * the name (not the menu item label!) of the colour scheme
3535 public void changeColour_actionPerformed(String name)
3538 * 'User Defined' opens a panel to configure or load a
3539 * user-defined colour scheme
3541 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3543 new UserDefinedColours(alignPanel);
3548 * otherwise set the chosen colour scheme (or null for 'None')
3550 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3551 viewport.getAlignment(), viewport.getHiddenRepSequences());
3556 * Actions on setting or changing the alignment colour scheme
3561 public void changeColour(ColourSchemeI cs)
3563 // TODO: pull up to controller method
3564 ColourMenuHelper.setColourSelected(colourMenu, cs);
3566 viewport.setGlobalColourScheme(cs);
3568 alignPanel.paintAlignment(true, true);
3572 * Show the PID threshold slider panel
3575 protected void modifyPID_actionPerformed()
3577 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3578 alignPanel.getViewName());
3579 SliderPanel.showPIDSlider();
3583 * Show the Conservation slider panel
3586 protected void modifyConservation_actionPerformed()
3588 SliderPanel.setConservationSlider(alignPanel,
3589 viewport.getResidueShading(), alignPanel.getViewName());
3590 SliderPanel.showConservationSlider();
3594 * Action on selecting or deselecting (Colour) By Conservation
3597 public void conservationMenuItem_actionPerformed(boolean selected)
3599 modifyConservation.setEnabled(selected);
3600 viewport.setConservationSelected(selected);
3601 viewport.getResidueShading().setConservationApplied(selected);
3603 changeColour(viewport.getGlobalColourScheme());
3606 modifyConservation_actionPerformed();
3610 SliderPanel.hideConservationSlider();
3615 * Action on selecting or deselecting (Colour) Above PID Threshold
3618 public void abovePIDThreshold_actionPerformed(boolean selected)
3620 modifyPID.setEnabled(selected);
3621 viewport.setAbovePIDThreshold(selected);
3624 viewport.getResidueShading().setThreshold(0,
3625 viewport.isIgnoreGapsConsensus());
3628 changeColour(viewport.getGlobalColourScheme());
3631 modifyPID_actionPerformed();
3635 SliderPanel.hidePIDSlider();
3646 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3648 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3649 AlignmentSorter.sortByPID(viewport.getAlignment(),
3650 viewport.getAlignment().getSequenceAt(0));
3651 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3652 viewport.getAlignment()));
3653 alignPanel.paintAlignment(true, false);
3663 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3665 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3666 AlignmentSorter.sortByID(viewport.getAlignment());
3668 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3669 alignPanel.paintAlignment(true, false);
3679 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3681 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3682 AlignmentSorter.sortByLength(viewport.getAlignment());
3683 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3684 viewport.getAlignment()));
3685 alignPanel.paintAlignment(true, false);
3695 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3697 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3698 AlignmentSorter.sortByGroup(viewport.getAlignment());
3699 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3700 viewport.getAlignment()));
3702 alignPanel.paintAlignment(true, false);
3712 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3714 new RedundancyPanel(alignPanel, this);
3724 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3726 if ((viewport.getSelectionGroup() == null)
3727 || (viewport.getSelectionGroup().getSize() < 2))
3729 JvOptionPane.showInternalMessageDialog(this,
3730 MessageManager.getString(
3731 "label.you_must_select_least_two_sequences"),
3732 MessageManager.getString("label.invalid_selection"),
3733 JvOptionPane.WARNING_MESSAGE);
3737 JInternalFrame frame = new JInternalFrame();
3738 frame.setContentPane(new PairwiseAlignPanel(viewport));
3739 Desktop.addInternalFrame(frame,
3740 MessageManager.getString("action.pairwise_alignment"), 600,
3746 public void autoCalculate_actionPerformed(ActionEvent e)
3748 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3749 if (viewport.autoCalculateConsensus)
3751 viewport.firePropertyChange("alignment", null,
3752 viewport.getAlignment().getSequences());
3757 public void sortByTreeOption_actionPerformed(ActionEvent e)
3759 viewport.sortByTree = sortByTree.isSelected();
3763 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3765 viewport.followSelection = listenToViewSelections.isSelected();
3769 * Constructs a tree panel and adds it to the desktop
3772 * tree type (NJ or AV)
3774 * name of score model used to compute the tree
3776 * parameters for the distance or similarity calculation
3778 void newTreePanel(String type, String modelName,
3779 SimilarityParamsI options)
3781 String frameTitle = "";
3784 boolean onSelection = false;
3785 if (viewport.getSelectionGroup() != null
3786 && viewport.getSelectionGroup().getSize() > 0)
3788 SequenceGroup sg = viewport.getSelectionGroup();
3790 /* Decide if the selection is a column region */
3791 for (SequenceI _s : sg.getSequences())
3793 if (_s.getLength() < sg.getEndRes())
3795 JvOptionPane.showMessageDialog(Desktop.desktop,
3796 MessageManager.getString(
3797 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3798 MessageManager.getString(
3799 "label.sequences_selection_not_aligned"),
3800 JvOptionPane.WARNING_MESSAGE);
3809 if (viewport.getAlignment().getHeight() < 2)
3815 tp = new TreePanel(alignPanel, type, modelName, options);
3816 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3818 frameTitle += " from ";
3820 if (viewport.viewName != null)
3822 frameTitle += viewport.viewName + " of ";
3825 frameTitle += this.title;
3827 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3838 public void addSortByOrderMenuItem(String title,
3839 final AlignmentOrder order)
3841 final JMenuItem item = new JMenuItem(MessageManager
3842 .formatMessage("action.by_title_param", new Object[]
3845 item.addActionListener(new java.awt.event.ActionListener()
3848 public void actionPerformed(ActionEvent e)
3850 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3852 // TODO: JBPNote - have to map order entries to curent SequenceI
3854 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3856 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3857 viewport.getAlignment()));
3859 alignPanel.paintAlignment(true, false);
3865 * Add a new sort by annotation score menu item
3868 * the menu to add the option to
3870 * the label used to retrieve scores for each sequence on the
3873 public void addSortByAnnotScoreMenuItem(JMenu sort,
3874 final String scoreLabel)
3876 final JMenuItem item = new JMenuItem(scoreLabel);
3878 item.addActionListener(new java.awt.event.ActionListener()
3881 public void actionPerformed(ActionEvent e)
3883 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3884 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3885 viewport.getAlignment());// ,viewport.getSelectionGroup());
3886 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3887 viewport.getAlignment()));
3888 alignPanel.paintAlignment(true, false);
3894 * last hash for alignment's annotation array - used to minimise cost of
3897 protected int _annotationScoreVectorHash;
3900 * search the alignment and rebuild the sort by annotation score submenu the
3901 * last alignment annotation vector hash is stored to minimize cost of
3902 * rebuilding in subsequence calls.
3906 public void buildSortByAnnotationScoresMenu()
3908 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3913 if (viewport.getAlignment().getAlignmentAnnotation()
3914 .hashCode() != _annotationScoreVectorHash)
3916 sortByAnnotScore.removeAll();
3917 // almost certainly a quicker way to do this - but we keep it simple
3918 Hashtable scoreSorts = new Hashtable();
3919 AlignmentAnnotation aann[];
3920 for (SequenceI sqa : viewport.getAlignment().getSequences())
3922 aann = sqa.getAnnotation();
3923 for (int i = 0; aann != null && i < aann.length; i++)
3925 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3927 scoreSorts.put(aann[i].label, aann[i].label);
3931 Enumeration labels = scoreSorts.keys();
3932 while (labels.hasMoreElements())
3934 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3935 (String) labels.nextElement());
3937 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3940 _annotationScoreVectorHash = viewport.getAlignment()
3941 .getAlignmentAnnotation().hashCode();
3946 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3947 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3948 * call. Listeners are added to remove the menu item when the treePanel is
3949 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3953 public void buildTreeSortMenu()
3955 sortByTreeMenu.removeAll();
3957 List<Component> comps = PaintRefresher.components
3958 .get(viewport.getSequenceSetId());
3959 List<TreePanel> treePanels = new ArrayList<>();
3960 for (Component comp : comps)
3962 if (comp instanceof TreePanel)
3964 treePanels.add((TreePanel) comp);
3968 if (treePanels.size() < 1)
3970 sortByTreeMenu.setVisible(false);
3974 sortByTreeMenu.setVisible(true);
3976 for (final TreePanel tp : treePanels)
3978 final JMenuItem item = new JMenuItem(tp.getTitle());
3979 item.addActionListener(new java.awt.event.ActionListener()
3982 public void actionPerformed(ActionEvent e)
3984 tp.sortByTree_actionPerformed();
3985 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3990 sortByTreeMenu.add(item);
3994 public boolean sortBy(AlignmentOrder alorder, String undoname)
3996 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3997 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3998 if (undoname != null)
4000 addHistoryItem(new OrderCommand(undoname, oldOrder,
4001 viewport.getAlignment()));
4003 alignPanel.paintAlignment(true, false);
4008 * Work out whether the whole set of sequences or just the selected set will
4009 * be submitted for multiple alignment.
4012 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4014 // Now, check we have enough sequences
4015 AlignmentView msa = null;
4017 if ((viewport.getSelectionGroup() != null)
4018 && (viewport.getSelectionGroup().getSize() > 1))
4020 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4021 // some common interface!
4023 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4024 * SequenceI[sz = seqs.getSize(false)];
4026 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4027 * seqs.getSequenceAt(i); }
4029 msa = viewport.getAlignmentView(true);
4031 else if (viewport.getSelectionGroup() != null
4032 && viewport.getSelectionGroup().getSize() == 1)
4034 int option = JvOptionPane.showConfirmDialog(this,
4035 MessageManager.getString("warn.oneseq_msainput_selection"),
4036 MessageManager.getString("label.invalid_selection"),
4037 JvOptionPane.OK_CANCEL_OPTION);
4038 if (option == JvOptionPane.OK_OPTION)
4040 msa = viewport.getAlignmentView(false);
4045 msa = viewport.getAlignmentView(false);
4051 * Decides what is submitted to a secondary structure prediction service: the
4052 * first sequence in the alignment, or in the current selection, or, if the
4053 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4054 * region or the whole alignment. (where the first sequence in the set is the
4055 * one that the prediction will be for).
4057 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4059 AlignmentView seqs = null;
4061 if ((viewport.getSelectionGroup() != null)
4062 && (viewport.getSelectionGroup().getSize() > 0))
4064 seqs = viewport.getAlignmentView(true);
4068 seqs = viewport.getAlignmentView(false);
4070 // limit sequences - JBPNote in future - could spawn multiple prediction
4072 // TODO: viewport.getAlignment().isAligned is a global state - the local
4073 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4074 if (!viewport.getAlignment().isAligned(false))
4076 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4077 // TODO: if seqs.getSequences().length>1 then should really have warned
4091 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4093 // Pick the tree file
4094 JalviewFileChooser chooser = new JalviewFileChooser(
4095 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4096 chooser.setFileView(new JalviewFileView());
4097 chooser.setDialogTitle(
4098 MessageManager.getString("label.select_newick_like_tree_file"));
4099 chooser.setToolTipText(
4100 MessageManager.getString("label.load_tree_file"));
4102 int value = chooser.showOpenDialog(null);
4104 if (value == JalviewFileChooser.APPROVE_OPTION)
4106 String filePath = chooser.getSelectedFile().getPath();
4107 Cache.setProperty("LAST_DIRECTORY", filePath);
4108 NewickFile fin = null;
4111 fin = new NewickFile(filePath, DataSourceType.FILE);
4112 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4113 } catch (Exception ex)
4115 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4116 MessageManager.getString("label.problem_reading_tree_file"),
4117 JvOptionPane.WARNING_MESSAGE);
4118 ex.printStackTrace();
4120 if (fin != null && fin.hasWarningMessage())
4122 JvOptionPane.showMessageDialog(Desktop.desktop,
4123 fin.getWarningMessage(),
4125 .getString("label.possible_problem_with_tree_file"),
4126 JvOptionPane.WARNING_MESSAGE);
4131 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4133 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4136 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4137 int h, int x, int y)
4139 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4143 * Add a treeviewer for the tree extracted from a Newick file object to the
4144 * current alignment view
4151 * Associated alignment input data (or null)
4160 * @return TreePanel handle
4162 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4163 AlignmentView input, int w, int h, int x, int y)
4165 TreePanel tp = null;
4171 if (nf.getTree() != null)
4173 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4179 tp.setLocation(x, y);
4182 Desktop.addInternalFrame(tp, treeTitle, w, h);
4184 } catch (Exception ex)
4186 ex.printStackTrace();
4192 private boolean buildingMenu = false;
4195 * Generates menu items and listener event actions for web service clients
4198 public void BuildWebServiceMenu()
4200 while (buildingMenu)
4204 System.err.println("Waiting for building menu to finish.");
4206 } catch (Exception e)
4210 final AlignFrame me = this;
4211 buildingMenu = true;
4212 new Thread(new Runnable()
4217 final List<JMenuItem> legacyItems = new ArrayList<>();
4220 // System.err.println("Building ws menu again "
4221 // + Thread.currentThread());
4222 // TODO: add support for context dependent disabling of services based
4224 // alignment and current selection
4225 // TODO: add additional serviceHandle parameter to specify abstract
4227 // class independently of AbstractName
4228 // TODO: add in rediscovery GUI function to restart discoverer
4229 // TODO: group services by location as well as function and/or
4231 // object broker mechanism.
4232 final Vector<JMenu> wsmenu = new Vector<>();
4233 final IProgressIndicator af = me;
4236 * do not i18n these strings - they are hard-coded in class
4237 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4238 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4240 final JMenu msawsmenu = new JMenu("Alignment");
4241 final JMenu secstrmenu = new JMenu(
4242 "Secondary Structure Prediction");
4243 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4244 final JMenu analymenu = new JMenu("Analysis");
4245 final JMenu dismenu = new JMenu("Protein Disorder");
4246 // JAL-940 - only show secondary structure prediction services from
4247 // the legacy server
4248 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4250 Discoverer.services != null && (Discoverer.services.size() > 0))
4252 // TODO: refactor to allow list of AbstractName/Handler bindings to
4254 // stored or retrieved from elsewhere
4255 // No MSAWS used any more:
4256 // Vector msaws = null; // (Vector)
4257 // Discoverer.services.get("MsaWS");
4258 Vector secstrpr = (Vector) Discoverer.services
4260 if (secstrpr != null)
4262 // Add any secondary structure prediction services
4263 for (int i = 0, j = secstrpr.size(); i < j; i++)
4265 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4267 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4268 .getServiceClient(sh);
4269 int p = secstrmenu.getItemCount();
4270 impl.attachWSMenuEntry(secstrmenu, me);
4271 int q = secstrmenu.getItemCount();
4272 for (int litm = p; litm < q; litm++)
4274 legacyItems.add(secstrmenu.getItem(litm));
4280 // Add all submenus in the order they should appear on the web
4282 wsmenu.add(msawsmenu);
4283 wsmenu.add(secstrmenu);
4284 wsmenu.add(dismenu);
4285 wsmenu.add(analymenu);
4286 // No search services yet
4287 // wsmenu.add(seqsrchmenu);
4289 javax.swing.SwingUtilities.invokeLater(new Runnable()
4296 webService.removeAll();
4297 // first, add discovered services onto the webservices menu
4298 if (wsmenu.size() > 0)
4300 for (int i = 0, j = wsmenu.size(); i < j; i++)
4302 webService.add(wsmenu.get(i));
4307 webService.add(me.webServiceNoServices);
4309 // TODO: move into separate menu builder class.
4310 boolean new_sspred = false;
4311 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4313 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4314 if (jws2servs != null)
4316 if (jws2servs.hasServices())
4318 jws2servs.attachWSMenuEntry(webService, me);
4319 for (Jws2Instance sv : jws2servs.getServices())
4321 if (sv.description.toLowerCase().contains("jpred"))
4323 for (JMenuItem jmi : legacyItems)
4325 jmi.setVisible(false);
4331 if (jws2servs.isRunning())
4333 JMenuItem tm = new JMenuItem(
4334 "Still discovering JABA Services");
4335 tm.setEnabled(false);
4340 build_urlServiceMenu(me.webService);
4341 build_fetchdbmenu(webService);
4342 for (JMenu item : wsmenu)
4344 if (item.getItemCount() == 0)
4346 item.setEnabled(false);
4350 item.setEnabled(true);
4353 } catch (Exception e)
4356 "Exception during web service menu building process.",
4361 } catch (Exception e)
4364 buildingMenu = false;
4371 * construct any groupURL type service menu entries.
4375 private void build_urlServiceMenu(JMenu webService)
4377 // TODO: remove this code when 2.7 is released
4378 // DEBUG - alignmentView
4380 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4381 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4383 * @Override public void actionPerformed(ActionEvent e) {
4384 * jalview.datamodel.AlignmentView
4385 * .testSelectionViews(af.viewport.getAlignment(),
4386 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4388 * }); webService.add(testAlView);
4390 // TODO: refactor to RestClient discoverer and merge menu entries for
4391 // rest-style services with other types of analysis/calculation service
4392 // SHmmr test client - still being implemented.
4393 // DEBUG - alignmentView
4395 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4398 client.attachWSMenuEntry(
4399 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4405 * Searches the alignment sequences for xRefs and builds the Show
4406 * Cross-References menu (formerly called Show Products), with database
4407 * sources for which cross-references are found (protein sources for a
4408 * nucleotide alignment and vice versa)
4410 * @return true if Show Cross-references menu should be enabled
4412 public boolean canShowProducts()
4414 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4415 AlignmentI dataset = viewport.getAlignment().getDataset();
4417 showProducts.removeAll();
4418 final boolean dna = viewport.getAlignment().isNucleotide();
4420 if (seqs == null || seqs.length == 0)
4422 // nothing to see here.
4426 boolean showp = false;
4429 List<String> ptypes = new CrossRef(seqs, dataset)
4430 .findXrefSourcesForSequences(dna);
4432 for (final String source : ptypes)
4435 final AlignFrame af = this;
4436 JMenuItem xtype = new JMenuItem(source);
4437 xtype.addActionListener(new ActionListener()
4440 public void actionPerformed(ActionEvent e)
4442 showProductsFor(af.viewport.getSequenceSelection(), dna,
4446 showProducts.add(xtype);
4448 showProducts.setVisible(showp);
4449 showProducts.setEnabled(showp);
4450 } catch (Exception e)
4453 "canShowProducts threw an exception - please report to help@jalview.org",
4461 * Finds and displays cross-references for the selected sequences (protein
4462 * products for nucleotide sequences, dna coding sequences for peptides).
4465 * the sequences to show cross-references for
4467 * true if from a nucleotide alignment (so showing proteins)
4469 * the database to show cross-references for
4471 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4472 final String source)
4474 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4479 * Construct and display a new frame containing the translation of this
4480 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4483 public void showTranslation_actionPerformed(ActionEvent e)
4485 AlignmentI al = null;
4488 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4490 al = dna.translateCdna();
4491 } catch (Exception ex)
4493 jalview.bin.Cache.log.error(
4494 "Exception during translation. Please report this !", ex);
4495 final String msg = MessageManager.getString(
4496 "label.error_when_translating_sequences_submit_bug_report");
4497 final String errorTitle = MessageManager
4498 .getString("label.implementation_error")
4499 + MessageManager.getString("label.translation_failed");
4500 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4501 JvOptionPane.ERROR_MESSAGE);
4504 if (al == null || al.getHeight() == 0)
4506 final String msg = MessageManager.getString(
4507 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4508 final String errorTitle = MessageManager
4509 .getString("label.translation_failed");
4510 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4511 JvOptionPane.WARNING_MESSAGE);
4515 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4516 af.setFileFormat(this.currentFileFormat);
4517 final String newTitle = MessageManager
4518 .formatMessage("label.translation_of_params", new Object[]
4519 { this.getTitle() });
4520 af.setTitle(newTitle);
4521 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4523 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4524 viewport.openSplitFrame(af, new Alignment(seqs));
4528 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4535 * Set the file format
4539 public void setFileFormat(FileFormatI format)
4541 this.currentFileFormat = format;
4545 * Try to load a features file onto the alignment.
4548 * contents or path to retrieve file
4550 * access mode of file (see jalview.io.AlignFile)
4551 * @return true if features file was parsed correctly.
4553 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4555 return avc.parseFeaturesFile(file, sourceType,
4556 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4561 public void refreshFeatureUI(boolean enableIfNecessary)
4563 // note - currently this is only still here rather than in the controller
4564 // because of the featureSettings hard reference that is yet to be
4566 if (enableIfNecessary)
4568 viewport.setShowSequenceFeatures(true);
4569 showSeqFeatures.setSelected(true);
4575 public void dragEnter(DropTargetDragEvent evt)
4580 public void dragExit(DropTargetEvent evt)
4585 public void dragOver(DropTargetDragEvent evt)
4590 public void dropActionChanged(DropTargetDragEvent evt)
4595 public void drop(DropTargetDropEvent evt)
4597 // JAL-1552 - acceptDrop required before getTransferable call for
4598 // Java's Transferable for native dnd
4599 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4600 Transferable t = evt.getTransferable();
4601 final AlignFrame thisaf = this;
4602 final List<String> files = new ArrayList<>();
4603 List<DataSourceType> protocols = new ArrayList<>();
4607 Desktop.transferFromDropTarget(files, protocols, evt, t);
4608 } catch (Exception e)
4610 e.printStackTrace();
4614 new Thread(new Runnable()
4621 // check to see if any of these files have names matching sequences
4624 SequenceIdMatcher idm = new SequenceIdMatcher(
4625 viewport.getAlignment().getSequencesArray());
4627 * Object[] { String,SequenceI}
4629 ArrayList<Object[]> filesmatched = new ArrayList<>();
4630 ArrayList<String> filesnotmatched = new ArrayList<>();
4631 for (int i = 0; i < files.size(); i++)
4633 String file = files.get(i).toString();
4635 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4636 if (protocol == DataSourceType.FILE)
4638 File fl = new File(file);
4639 pdbfn = fl.getName();
4641 else if (protocol == DataSourceType.URL)
4643 URL url = new URL(file);
4644 pdbfn = url.getFile();
4646 if (pdbfn.length() > 0)
4648 // attempt to find a match in the alignment
4649 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4650 int l = 0, c = pdbfn.indexOf(".");
4651 while (mtch == null && c != -1)
4656 } while ((c = pdbfn.indexOf(".", l)) > l);
4659 pdbfn = pdbfn.substring(0, l);
4661 mtch = idm.findAllIdMatches(pdbfn);
4665 FileFormatI type = null;
4668 type = new IdentifyFile().identify(file, protocol);
4669 } catch (Exception ex)
4673 if (type != null && type.isStructureFile())
4675 filesmatched.add(new Object[] { file, protocol, mtch });
4679 // File wasn't named like one of the sequences or wasn't a PDB
4681 filesnotmatched.add(file);
4685 if (filesmatched.size() > 0)
4687 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4688 || JvOptionPane.showConfirmDialog(thisaf,
4689 MessageManager.formatMessage(
4690 "label.automatically_associate_structure_files_with_sequences_same_name",
4692 { Integer.valueOf(filesmatched.size())
4694 MessageManager.getString(
4695 "label.automatically_associate_structure_files_by_name"),
4696 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION)
4699 for (Object[] fm : filesmatched)
4701 // try and associate
4702 // TODO: may want to set a standard ID naming formalism for
4703 // associating PDB files which have no IDs.
4704 for (SequenceI toassoc : (SequenceI[]) fm[2])
4706 PDBEntry pe = new AssociatePdbFileWithSeq()
4707 .associatePdbWithSeq((String) fm[0],
4708 (DataSourceType) fm[1], toassoc, false,
4712 System.err.println("Associated file : "
4713 + ((String) fm[0]) + " with "
4714 + toassoc.getDisplayId(true));
4718 // TODO: do we need to update overview ? only if features are
4720 alignPanel.paintAlignment(true, false);
4724 if (filesnotmatched.size() > 0)
4726 if (assocfiles > 0 && (Cache.getDefault(
4727 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4728 || JvOptionPane.showConfirmDialog(thisaf,
4729 "<html>" + MessageManager.formatMessage(
4730 "label.ignore_unmatched_dropped_files_info",
4733 filesnotmatched.size())
4736 MessageManager.getString(
4737 "label.ignore_unmatched_dropped_files"),
4738 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4742 for (String fn : filesnotmatched)
4744 loadJalviewDataFile(fn, null, null, null);
4748 } catch (Exception ex)
4750 ex.printStackTrace();
4758 * Attempt to load a "dropped" file or URL string, by testing in turn for
4760 * <li>an Annotation file</li>
4761 * <li>a JNet file</li>
4762 * <li>a features file</li>
4763 * <li>else try to interpret as an alignment file</li>
4767 * either a filename or a URL string.
4768 * @throws InterruptedException
4769 * @throws IOException
4771 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4772 FileFormatI format, SequenceI assocSeq)
4776 if (sourceType == null)
4778 sourceType = FormatAdapter.checkProtocol(file);
4780 // if the file isn't identified, or not positively identified as some
4781 // other filetype (PFAM is default unidentified alignment file type) then
4782 // try to parse as annotation.
4783 boolean isAnnotation = (format == null
4784 || FileFormat.Pfam.equals(format))
4785 ? new AnnotationFile().annotateAlignmentView(viewport,
4791 // first see if its a T-COFFEE score file
4792 TCoffeeScoreFile tcf = null;
4795 tcf = new TCoffeeScoreFile(file, sourceType);
4798 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4802 new TCoffeeColourScheme(viewport.getAlignment()));
4803 isAnnotation = true;
4804 statusBar.setText(MessageManager.getString(
4805 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4809 // some problem - if no warning its probable that the ID matching
4810 // process didn't work
4811 JvOptionPane.showMessageDialog(Desktop.desktop,
4812 tcf.getWarningMessage() == null
4813 ? MessageManager.getString(
4814 "label.check_file_matches_sequence_ids_alignment")
4815 : tcf.getWarningMessage(),
4816 MessageManager.getString(
4817 "label.problem_reading_tcoffee_score_file"),
4818 JvOptionPane.WARNING_MESSAGE);
4825 } catch (Exception x)
4828 "Exception when processing data source as T-COFFEE score file",
4834 // try to see if its a JNet 'concise' style annotation file *before*
4836 // try to parse it as a features file
4839 format = new IdentifyFile().identify(file, sourceType);
4841 if (FileFormat.ScoreMatrix == format)
4843 ScoreMatrixFile sm = new ScoreMatrixFile(
4844 new FileParse(file, sourceType));
4846 // todo: i18n this message
4847 statusBar.setText(MessageManager.formatMessage(
4848 "label.successfully_loaded_matrix",
4849 sm.getMatrixName()));
4851 else if (FileFormat.Jnet.equals(format))
4853 JPredFile predictions = new JPredFile(file, sourceType);
4854 new JnetAnnotationMaker();
4855 JnetAnnotationMaker.add_annotation(predictions,
4856 viewport.getAlignment(), 0, false);
4857 viewport.getAlignment().setupJPredAlignment();
4858 isAnnotation = true;
4860 // else if (IdentifyFile.FeaturesFile.equals(format))
4861 else if (FileFormat.Features.equals(format))
4863 if (parseFeaturesFile(file, sourceType))
4865 alignPanel.paintAlignment(true, true);
4870 new FileLoader().LoadFile(viewport, file, sourceType, format);
4876 alignPanel.adjustAnnotationHeight();
4877 viewport.updateSequenceIdColours();
4878 buildSortByAnnotationScoresMenu();
4879 alignPanel.paintAlignment(true, true);
4881 } catch (Exception ex)
4883 ex.printStackTrace();
4884 } catch (OutOfMemoryError oom)
4889 } catch (Exception x)
4894 + (sourceType != null
4895 ? (sourceType == DataSourceType.PASTE
4897 : "using " + sourceType + " from "
4901 ? "(parsing as '" + format + "' file)"
4903 oom, Desktop.desktop);
4908 * Method invoked by the ChangeListener on the tabbed pane, in other words
4909 * when a different tabbed pane is selected by the user or programmatically.
4912 public void tabSelectionChanged(int index)
4916 alignPanel = alignPanels.get(index);
4917 viewport = alignPanel.av;
4918 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4919 setMenusFromViewport(viewport);
4923 * 'focus' any colour slider that is open to the selected viewport
4925 if (viewport.getConservationSelected())
4927 SliderPanel.setConservationSlider(alignPanel,
4928 viewport.getResidueShading(), alignPanel.getViewName());
4932 SliderPanel.hideConservationSlider();
4934 if (viewport.getAbovePIDThreshold())
4936 SliderPanel.setPIDSliderSource(alignPanel,
4937 viewport.getResidueShading(), alignPanel.getViewName());
4941 SliderPanel.hidePIDSlider();
4945 * If there is a frame linked to this one in a SplitPane, switch it to the
4946 * same view tab index. No infinite recursion of calls should happen, since
4947 * tabSelectionChanged() should not get invoked on setting the selected
4948 * index to an unchanged value. Guard against setting an invalid index
4949 * before the new view peer tab has been created.
4951 final AlignViewportI peer = viewport.getCodingComplement();
4954 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4955 .getAlignPanel().alignFrame;
4956 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4958 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4964 * On right mouse click on view tab, prompt for and set new view name.
4967 public void tabbedPane_mousePressed(MouseEvent e)
4969 if (e.isPopupTrigger())
4971 String msg = MessageManager.getString("label.enter_view_name");
4972 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4973 JvOptionPane.QUESTION_MESSAGE);
4977 viewport.viewName = reply;
4978 // TODO warn if reply is in getExistingViewNames()?
4979 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4984 public AlignViewport getCurrentView()
4990 * Open the dialog for regex description parsing.
4993 protected void extractScores_actionPerformed(ActionEvent e)
4995 ParseProperties pp = new jalview.analysis.ParseProperties(
4996 viewport.getAlignment());
4997 // TODO: verify regex and introduce GUI dialog for version 2.5
4998 // if (pp.getScoresFromDescription("col", "score column ",
4999 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5001 if (pp.getScoresFromDescription("description column",
5002 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5004 buildSortByAnnotationScoresMenu();
5012 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5016 protected void showDbRefs_actionPerformed(ActionEvent e)
5018 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5024 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5028 protected void showNpFeats_actionPerformed(ActionEvent e)
5030 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5034 * find the viewport amongst the tabs in this alignment frame and close that
5039 public boolean closeView(AlignViewportI av)
5043 this.closeMenuItem_actionPerformed(false);
5046 Component[] comp = tabbedPane.getComponents();
5047 for (int i = 0; comp != null && i < comp.length; i++)
5049 if (comp[i] instanceof AlignmentPanel)
5051 if (((AlignmentPanel) comp[i]).av == av)
5054 closeView((AlignmentPanel) comp[i]);
5062 protected void build_fetchdbmenu(JMenu webService)
5064 // Temporary hack - DBRef Fetcher always top level ws entry.
5065 // TODO We probably want to store a sequence database checklist in
5066 // preferences and have checkboxes.. rather than individual sources selected
5068 final JMenu rfetch = new JMenu(
5069 MessageManager.getString("action.fetch_db_references"));
5070 rfetch.setToolTipText(MessageManager.getString(
5071 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5072 webService.add(rfetch);
5074 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5075 MessageManager.getString("option.trim_retrieved_seqs"));
5076 trimrs.setToolTipText(
5077 MessageManager.getString("label.trim_retrieved_sequences"));
5079 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5080 trimrs.addActionListener(new ActionListener()
5083 public void actionPerformed(ActionEvent e)
5085 trimrs.setSelected(trimrs.isSelected());
5086 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5087 Boolean.valueOf(trimrs.isSelected()).toString());
5091 JMenuItem fetchr = new JMenuItem(
5092 MessageManager.getString("label.standard_databases"));
5093 fetchr.setToolTipText(
5094 MessageManager.getString("label.fetch_embl_uniprot"));
5095 fetchr.addActionListener(new ActionListener()
5099 public void actionPerformed(ActionEvent e)
5101 new Thread(new Runnable()
5106 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5107 .getAlignment().isNucleotide();
5108 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5109 alignPanel.av.getSequenceSelection(),
5110 alignPanel.alignFrame, null,
5111 alignPanel.alignFrame.featureSettings, isNucleotide);
5112 dbRefFetcher.addListener(new FetchFinishedListenerI()
5115 public void finished()
5117 AlignFrame.this.setMenusForViewport();
5120 dbRefFetcher.fetchDBRefs(false);
5128 final AlignFrame me = this;
5129 new Thread(new Runnable()
5134 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5135 .getSequenceFetcherSingleton(me);
5136 javax.swing.SwingUtilities.invokeLater(new Runnable()
5141 String[] dbclasses = sf.getOrderedSupportedSources();
5142 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5143 // jalview.util.QuickSort.sort(otherdb, otherdb);
5144 List<DbSourceProxy> otherdb;
5145 JMenu dfetch = new JMenu();
5146 JMenu ifetch = new JMenu();
5147 JMenuItem fetchr = null;
5148 int comp = 0, icomp = 0, mcomp = 15;
5149 String mname = null;
5151 for (String dbclass : dbclasses)
5153 otherdb = sf.getSourceProxy(dbclass);
5154 // add a single entry for this class, or submenu allowing 'fetch
5156 if (otherdb == null || otherdb.size() < 1)
5160 // List<DbSourceProxy> dbs=otherdb;
5161 // otherdb=new ArrayList<DbSourceProxy>();
5162 // for (DbSourceProxy db:dbs)
5164 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5168 mname = "From " + dbclass;
5170 if (otherdb.size() == 1)
5172 final DbSourceProxy[] dassource = otherdb
5173 .toArray(new DbSourceProxy[0]);
5174 DbSourceProxy src = otherdb.get(0);
5175 fetchr = new JMenuItem(src.getDbSource());
5176 fetchr.addActionListener(new ActionListener()
5180 public void actionPerformed(ActionEvent e)
5182 new Thread(new Runnable()
5188 boolean isNucleotide = alignPanel.alignFrame
5189 .getViewport().getAlignment()
5191 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5192 alignPanel.av.getSequenceSelection(),
5193 alignPanel.alignFrame, dassource,
5194 alignPanel.alignFrame.featureSettings,
5197 .addListener(new FetchFinishedListenerI()
5200 public void finished()
5202 AlignFrame.this.setMenusForViewport();
5205 dbRefFetcher.fetchDBRefs(false);
5211 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5212 MessageManager.formatMessage(
5213 "label.fetch_retrieve_from", new Object[]
5214 { src.getDbName() })));
5220 final DbSourceProxy[] dassource = otherdb
5221 .toArray(new DbSourceProxy[0]);
5223 DbSourceProxy src = otherdb.get(0);
5224 fetchr = new JMenuItem(MessageManager
5225 .formatMessage("label.fetch_all_param", new Object[]
5226 { src.getDbSource() }));
5227 fetchr.addActionListener(new ActionListener()
5230 public void actionPerformed(ActionEvent e)
5232 new Thread(new Runnable()
5238 boolean isNucleotide = alignPanel.alignFrame
5239 .getViewport().getAlignment()
5241 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5242 alignPanel.av.getSequenceSelection(),
5243 alignPanel.alignFrame, dassource,
5244 alignPanel.alignFrame.featureSettings,
5247 .addListener(new FetchFinishedListenerI()
5250 public void finished()
5252 AlignFrame.this.setMenusForViewport();
5255 dbRefFetcher.fetchDBRefs(false);
5261 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5262 MessageManager.formatMessage(
5263 "label.fetch_retrieve_from_all_sources",
5265 { Integer.valueOf(otherdb.size())
5267 src.getDbSource(), src.getDbName() })));
5270 // and then build the rest of the individual menus
5271 ifetch = new JMenu(MessageManager.formatMessage(
5272 "label.source_from_db_source", new Object[]
5273 { src.getDbSource() }));
5275 String imname = null;
5277 for (DbSourceProxy sproxy : otherdb)
5279 String dbname = sproxy.getDbName();
5280 String sname = dbname.length() > 5
5281 ? dbname.substring(0, 5) + "..."
5283 String msname = dbname.length() > 10
5284 ? dbname.substring(0, 10) + "..."
5288 imname = MessageManager
5289 .formatMessage("label.from_msname", new Object[]
5292 fetchr = new JMenuItem(msname);
5293 final DbSourceProxy[] dassrc = { sproxy };
5294 fetchr.addActionListener(new ActionListener()
5298 public void actionPerformed(ActionEvent e)
5300 new Thread(new Runnable()
5306 boolean isNucleotide = alignPanel.alignFrame
5307 .getViewport().getAlignment()
5309 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5310 alignPanel.av.getSequenceSelection(),
5311 alignPanel.alignFrame, dassrc,
5312 alignPanel.alignFrame.featureSettings,
5315 .addListener(new FetchFinishedListenerI()
5318 public void finished()
5320 AlignFrame.this.setMenusForViewport();
5323 dbRefFetcher.fetchDBRefs(false);
5329 fetchr.setToolTipText(
5330 "<html>" + MessageManager.formatMessage(
5331 "label.fetch_retrieve_from", new Object[]
5335 if (++icomp >= mcomp || i == (otherdb.size()))
5337 ifetch.setText(MessageManager.formatMessage(
5338 "label.source_to_target", imname, sname));
5340 ifetch = new JMenu();
5348 if (comp >= mcomp || dbi >= (dbclasses.length))
5350 dfetch.setText(MessageManager.formatMessage(
5351 "label.source_to_target", mname, dbclass));
5353 dfetch = new JMenu();
5366 * Left justify the whole alignment.
5369 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5371 AlignmentI al = viewport.getAlignment();
5373 viewport.firePropertyChange("alignment", null, al);
5377 * Right justify the whole alignment.
5380 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5382 AlignmentI al = viewport.getAlignment();
5384 viewport.firePropertyChange("alignment", null, al);
5388 public void setShowSeqFeatures(boolean b)
5390 showSeqFeatures.setSelected(b);
5391 viewport.setShowSequenceFeatures(b);
5398 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5399 * awt.event.ActionEvent)
5402 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5404 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5405 alignPanel.paintAlignment(false, false);
5412 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5416 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5418 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5419 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5427 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5428 * .event.ActionEvent)
5431 protected void showGroupConservation_actionPerformed(ActionEvent e)
5433 viewport.setShowGroupConservation(showGroupConservation.getState());
5434 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5441 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5442 * .event.ActionEvent)
5445 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5447 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5448 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5455 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5456 * .event.ActionEvent)
5459 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5461 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5462 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5466 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5468 showSequenceLogo.setState(true);
5469 viewport.setShowSequenceLogo(true);
5470 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5471 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5475 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5477 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5484 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5485 * .event.ActionEvent)
5488 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5490 if (avc.makeGroupsFromSelection())
5492 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5493 alignPanel.updateAnnotation();
5494 alignPanel.paintAlignment(true, true);
5498 public void clearAlignmentSeqRep()
5500 // TODO refactor alignmentseqrep to controller
5501 if (viewport.getAlignment().hasSeqrep())
5503 viewport.getAlignment().setSeqrep(null);
5504 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5505 alignPanel.updateAnnotation();
5506 alignPanel.paintAlignment(true, true);
5511 protected void createGroup_actionPerformed(ActionEvent e)
5513 if (avc.createGroup())
5515 alignPanel.alignmentChanged();
5520 protected void unGroup_actionPerformed(ActionEvent e)
5524 alignPanel.alignmentChanged();
5529 * make the given alignmentPanel the currently selected tab
5531 * @param alignmentPanel
5533 public void setDisplayedView(AlignmentPanel alignmentPanel)
5535 if (!viewport.getSequenceSetId()
5536 .equals(alignmentPanel.av.getSequenceSetId()))
5538 throw new Error(MessageManager.getString(
5539 "error.implementation_error_cannot_show_view_alignment_frame"));
5541 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5542 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5544 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5549 * Action on selection of menu options to Show or Hide annotations.
5552 * @param forSequences
5553 * update sequence-related annotations
5554 * @param forAlignment
5555 * update non-sequence-related annotations
5558 protected void setAnnotationsVisibility(boolean visible,
5559 boolean forSequences, boolean forAlignment)
5561 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5562 .getAlignmentAnnotation();
5567 for (AlignmentAnnotation aa : anns)
5570 * don't display non-positional annotations on an alignment
5572 if (aa.annotations == null)
5576 boolean apply = (aa.sequenceRef == null && forAlignment)
5577 || (aa.sequenceRef != null && forSequences);
5580 aa.visible = visible;
5583 alignPanel.validateAnnotationDimensions(true);
5584 alignPanel.alignmentChanged();
5588 * Store selected annotation sort order for the view and repaint.
5591 protected void sortAnnotations_actionPerformed()
5593 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5595 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5596 alignPanel.paintAlignment(false, false);
5601 * @return alignment panels in this alignment frame
5603 public List<? extends AlignmentViewPanel> getAlignPanels()
5605 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5609 * Open a new alignment window, with the cDNA associated with this (protein)
5610 * alignment, aligned as is the protein.
5612 protected void viewAsCdna_actionPerformed()
5614 // TODO no longer a menu action - refactor as required
5615 final AlignmentI alignment = getViewport().getAlignment();
5616 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5617 if (mappings == null)
5621 List<SequenceI> cdnaSeqs = new ArrayList<>();
5622 for (SequenceI aaSeq : alignment.getSequences())
5624 for (AlignedCodonFrame acf : mappings)
5626 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5630 * There is a cDNA mapping for this protein sequence - add to new
5631 * alignment. It will share the same dataset sequence as other mapped
5632 * cDNA (no new mappings need to be created).
5634 final Sequence newSeq = new Sequence(dnaSeq);
5635 newSeq.setDatasetSequence(dnaSeq);
5636 cdnaSeqs.add(newSeq);
5640 if (cdnaSeqs.size() == 0)
5642 // show a warning dialog no mapped cDNA
5645 AlignmentI cdna = new Alignment(
5646 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5647 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5648 AlignFrame.DEFAULT_HEIGHT);
5649 cdna.alignAs(alignment);
5650 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5652 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5653 AlignFrame.DEFAULT_HEIGHT);
5657 * Set visibility of dna/protein complement view (available when shown in a
5663 protected void showComplement_actionPerformed(boolean show)
5665 SplitContainerI sf = getSplitViewContainer();
5668 sf.setComplementVisible(this, show);
5673 * Generate the reverse (optionally complemented) of the selected sequences,
5674 * and add them to the alignment
5677 protected void showReverse_actionPerformed(boolean complement)
5679 AlignmentI al = null;
5682 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5683 al = dna.reverseCdna(complement);
5684 viewport.addAlignment(al, "");
5685 addHistoryItem(new EditCommand(
5686 MessageManager.getString("label.add_sequences"), Action.PASTE,
5687 al.getSequencesArray(), 0, al.getWidth(),
5688 viewport.getAlignment()));
5689 } catch (Exception ex)
5691 System.err.println(ex.getMessage());
5697 * Try to run a script in the Groovy console, having first ensured that this
5698 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5699 * be targeted at this alignment.
5702 protected void runGroovy_actionPerformed()
5704 Jalview.setCurrentAlignFrame(this);
5705 groovy.ui.Console console = Desktop.getGroovyConsole();
5706 if (console != null)
5710 console.runScript();
5711 } catch (Exception ex)
5713 System.err.println((ex.toString()));
5714 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5715 MessageManager.getString("label.couldnt_run_groovy_script"),
5716 MessageManager.getString("label.groovy_support_failed"),
5717 JvOptionPane.ERROR_MESSAGE);
5722 System.err.println("Can't run Groovy script as console not found");
5727 * Hides columns containing (or not containing) a specified feature, provided
5728 * that would not leave all columns hidden
5730 * @param featureType
5731 * @param columnsContaining
5734 public boolean hideFeatureColumns(String featureType,
5735 boolean columnsContaining)
5737 boolean notForHiding = avc.markColumnsContainingFeatures(
5738 columnsContaining, false, false, featureType);
5741 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5742 false, featureType))
5744 getViewport().hideSelectedColumns();
5752 protected void selectHighlightedColumns_actionPerformed(
5753 ActionEvent actionEvent)
5755 // include key modifier check in case user selects from menu
5756 avc.markHighlightedColumns(
5757 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5758 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5759 | ActionEvent.CTRL_MASK)) != 0);
5763 * Rebuilds the Colour menu, including any user-defined colours which have
5764 * been loaded either on startup or during the session
5766 public void buildColourMenu()
5768 colourMenu.removeAll();
5770 colourMenu.add(applyToAllGroups);
5771 colourMenu.add(textColour);
5772 colourMenu.addSeparator();
5774 ColourMenuHelper.addMenuItems(colourMenu, this, viewport.getAlignment(),
5777 colourMenu.addSeparator();
5778 colourMenu.add(conservationMenuItem);
5779 colourMenu.add(modifyConservation);
5780 colourMenu.add(abovePIDThreshold);
5781 colourMenu.add(modifyPID);
5782 colourMenu.add(annotationColour);
5784 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5785 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5789 * Open a dialog (if not already open) that allows the user to select and
5790 * calculate PCA or Tree analysis
5792 protected void openTreePcaDialog()
5794 if (alignPanel.getCalculationDialog() == null)
5796 new CalculationChooser(AlignFrame.this);
5801 * Sets the status of the HMMER menu
5803 public void updateHMMERStatus()
5805 hmmerMenu.setEnabled(HmmerCommand.isHmmerAvailable());
5809 public void hmmerMenu_actionPerformed(ActionEvent e)
5811 SequenceGroup grp = getViewport().getSelectionGroup();
5814 hmmBuild.setText(MessageManager.getString("label.hmmbuild") + " from "
5819 hmmBuild.setText(MessageManager.getString("label.hmmbuild")
5820 + " from Alignment");
5825 protected void loadVcf_actionPerformed()
5827 JalviewFileChooser chooser = new JalviewFileChooser(
5828 Cache.getProperty("LAST_DIRECTORY"));
5829 chooser.setFileView(new JalviewFileView());
5830 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5831 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5833 int value = chooser.showOpenDialog(null);
5835 if (value == JalviewFileChooser.APPROVE_OPTION)
5837 String choice = chooser.getSelectedFile().getPath();
5838 Cache.setProperty("LAST_DIRECTORY", choice);
5839 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5840 new VCFLoader(choice).loadVCF(seqs, this);
5846 class PrintThread extends Thread
5850 public PrintThread(AlignmentPanel ap)
5855 static PageFormat pf;
5860 PrinterJob printJob = PrinterJob.getPrinterJob();
5864 printJob.setPrintable(ap, pf);
5868 printJob.setPrintable(ap);
5871 if (printJob.printDialog())
5876 } catch (Exception PrintException)
5878 PrintException.printStackTrace();