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 java.awt.BorderLayout;
24 import java.awt.Color;
25 import java.awt.Component;
26 import java.awt.Rectangle;
27 import java.awt.Toolkit;
28 import java.awt.datatransfer.Clipboard;
29 import java.awt.datatransfer.DataFlavor;
30 import java.awt.datatransfer.StringSelection;
31 import java.awt.datatransfer.Transferable;
32 import java.awt.dnd.DnDConstants;
33 import java.awt.dnd.DropTargetDragEvent;
34 import java.awt.dnd.DropTargetDropEvent;
35 import java.awt.dnd.DropTargetEvent;
36 import java.awt.dnd.DropTargetListener;
37 import java.awt.event.ActionEvent;
38 import java.awt.event.ActionListener;
39 import java.awt.event.FocusAdapter;
40 import java.awt.event.FocusEvent;
41 import java.awt.event.ItemEvent;
42 import java.awt.event.ItemListener;
43 import java.awt.event.KeyAdapter;
44 import java.awt.event.KeyEvent;
45 import java.awt.event.MouseEvent;
46 import java.awt.print.PageFormat;
47 import java.awt.print.PrinterJob;
48 import java.beans.PropertyChangeEvent;
50 import java.io.FileWriter;
51 import java.io.PrintWriter;
53 import java.util.ArrayList;
54 import java.util.Arrays;
55 import java.util.Deque;
56 import java.util.List;
57 import java.util.Vector;
59 import javax.swing.ButtonGroup;
60 import javax.swing.JCheckBoxMenuItem;
61 import javax.swing.JComponent;
62 import javax.swing.JEditorPane;
63 import javax.swing.JInternalFrame;
64 import javax.swing.JLabel;
65 import javax.swing.JLayeredPane;
66 import javax.swing.JMenu;
67 import javax.swing.JMenuItem;
68 import javax.swing.JPanel;
69 import javax.swing.JScrollPane;
70 import javax.swing.SwingUtilities;
72 import ext.vamsas.ServiceHandle;
73 import jalview.analysis.AlignmentSorter;
74 import jalview.analysis.AlignmentUtils;
75 import jalview.analysis.CrossRef;
76 import jalview.analysis.Dna;
77 import jalview.analysis.GeneticCodeI;
78 import jalview.analysis.ParseProperties;
79 import jalview.analysis.SequenceIdMatcher;
80 import jalview.api.AlignExportSettingsI;
81 import jalview.api.AlignViewControllerGuiI;
82 import jalview.api.AlignViewControllerI;
83 import jalview.api.AlignViewportI;
84 import jalview.api.AlignmentViewPanel;
85 import jalview.api.FeatureSettingsControllerI;
86 import jalview.api.FeatureSettingsModelI;
87 import jalview.api.SplitContainerI;
88 import jalview.api.ViewStyleI;
89 import jalview.api.analysis.SimilarityParamsI;
90 import jalview.bin.Cache;
91 import jalview.bin.Jalview;
92 import jalview.commands.CommandI;
93 import jalview.commands.EditCommand;
94 import jalview.commands.EditCommand.Action;
95 import jalview.commands.OrderCommand;
96 import jalview.commands.RemoveGapColCommand;
97 import jalview.commands.RemoveGapsCommand;
98 import jalview.commands.SlideSequencesCommand;
99 import jalview.commands.TrimRegionCommand;
100 import jalview.datamodel.AlignExportSettingsAdapter;
101 import jalview.datamodel.AlignedCodonFrame;
102 import jalview.datamodel.Alignment;
103 import jalview.datamodel.AlignmentAnnotation;
104 import jalview.datamodel.AlignmentExportData;
105 import jalview.datamodel.AlignmentI;
106 import jalview.datamodel.AlignmentOrder;
107 import jalview.datamodel.AlignmentView;
108 import jalview.datamodel.ColumnSelection;
109 import jalview.datamodel.HiddenColumns;
110 import jalview.datamodel.PDBEntry;
111 import jalview.datamodel.SeqCigar;
112 import jalview.datamodel.Sequence;
113 import jalview.datamodel.SequenceGroup;
114 import jalview.datamodel.SequenceI;
115 import jalview.gui.ColourMenuHelper.ColourChangeListener;
116 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
117 import jalview.hmmer.HMMAlign;
118 import jalview.hmmer.HMMBuild;
119 import jalview.hmmer.HMMERParamStore;
120 import jalview.hmmer.HMMERPreset;
121 import jalview.hmmer.HMMSearch;
122 import jalview.hmmer.HmmerCommand;
123 import jalview.hmmer.JackHMMER;
124 import jalview.io.AlignmentProperties;
125 import jalview.io.AnnotationFile;
126 import jalview.io.BackupFiles;
127 import jalview.io.BioJsHTMLOutput;
128 import jalview.io.DataSourceType;
129 import jalview.io.FileFormat;
130 import jalview.io.FileFormatI;
131 import jalview.io.FileFormats;
132 import jalview.io.FileLoader;
133 import jalview.io.FileParse;
134 import jalview.io.FormatAdapter;
135 import jalview.io.HtmlSvgOutput;
136 import jalview.io.IdentifyFile;
137 import jalview.io.JPredFile;
138 import jalview.io.JalviewFileChooser;
139 import jalview.io.JalviewFileView;
140 import jalview.io.JnetAnnotationMaker;
141 import jalview.io.NewickFile;
142 import jalview.io.ScoreMatrixFile;
143 import jalview.io.TCoffeeScoreFile;
144 import jalview.io.vcf.VCFLoader;
145 import jalview.jbgui.GAlignFrame;
146 import jalview.project.Jalview2XML;
147 import jalview.schemes.ColourSchemeI;
148 import jalview.schemes.ColourSchemes;
149 import jalview.schemes.ResidueColourScheme;
150 import jalview.schemes.TCoffeeColourScheme;
151 import jalview.util.ImageMaker.TYPE;
152 import jalview.util.MessageManager;
153 import jalview.util.Platform;
154 import jalview.viewmodel.AlignmentViewport;
155 import jalview.viewmodel.ViewportRanges;
156 import jalview.ws.DBRefFetcher;
157 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
158 import jalview.ws.api.ServiceWithParameters;
159 import jalview.ws.jws1.Discoverer;
160 import jalview.ws.jws2.Jws2Discoverer;
161 import jalview.ws.params.ArgumentI;
162 import jalview.ws.params.ParamDatastoreI;
163 import jalview.ws.params.WsParamSetI;
164 import jalview.ws.seqfetcher.DbSourceProxy;
165 import jalview.ws.slivkaws.SlivkaWSDiscoverer;
166 import java.io.IOException;
167 import java.util.HashSet;
168 import java.util.Set;
170 import javax.swing.JFileChooser;
171 import javax.swing.JOptionPane;
177 * @version $Revision$
179 @SuppressWarnings("serial")
180 public class AlignFrame extends GAlignFrame implements DropTargetListener,
181 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
183 public static final int DEFAULT_WIDTH = 700;
185 public static final int DEFAULT_HEIGHT = 500;
188 * The currently displayed panel (selected tabbed view if more than one)
190 public AlignmentPanel alignPanel;
192 AlignViewport viewport;
194 public AlignViewControllerI avc;
196 List<AlignmentPanel> alignPanels = new ArrayList<>();
199 * Last format used to load or save alignments in this window
201 FileFormatI currentFileFormat = null;
204 * Current filename for this alignment
206 String fileName = null;
209 * TODO: remove reference to 'FileObject' in AlignFrame - not correct mapping
214 * Creates a new AlignFrame object with specific width and height.
220 public AlignFrame(AlignmentI al, int width, int height)
222 this(al, null, width, height);
226 * Creates a new AlignFrame object with specific width, height and
232 * @param sequenceSetId
234 public AlignFrame(AlignmentI al, int width, int height,
235 String sequenceSetId)
237 this(al, null, width, height, sequenceSetId);
241 * Creates a new AlignFrame object with specific width, height and
247 * @param sequenceSetId
250 public AlignFrame(AlignmentI al, int width, int height,
251 String sequenceSetId, String viewId)
253 this(al, null, width, height, sequenceSetId, viewId);
257 * new alignment window with hidden columns
261 * @param hiddenColumns
262 * ColumnSelection or null
264 * Width of alignment frame
268 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
271 this(al, hiddenColumns, width, height, null);
275 * Create alignment frame for al with hiddenColumns, a specific width and
276 * height, and specific sequenceId
279 * @param hiddenColumns
282 * @param sequenceSetId
285 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
286 int height, String sequenceSetId)
288 this(al, hiddenColumns, width, height, sequenceSetId, null);
292 * Create alignment frame for al with hiddenColumns, a specific width and
293 * height, and specific sequenceId
296 * @param hiddenColumns
299 * @param sequenceSetId
304 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
305 int height, String sequenceSetId, String viewId)
307 setSize(width, height);
309 if (al.getDataset() == null)
314 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
316 alignPanel = new AlignmentPanel(this, viewport);
318 addAlignmentPanel(alignPanel, true);
322 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
323 HiddenColumns hiddenColumns, int width, int height)
325 setSize(width, height);
327 if (al.getDataset() == null)
332 viewport = new AlignViewport(al, hiddenColumns);
334 if (hiddenSeqs != null && hiddenSeqs.length > 0)
336 viewport.hideSequence(hiddenSeqs);
338 alignPanel = new AlignmentPanel(this, viewport);
339 addAlignmentPanel(alignPanel, true);
344 * Make a new AlignFrame from existing alignmentPanels
351 public AlignFrame(AlignmentPanel ap)
355 addAlignmentPanel(ap, false);
360 * initalise the alignframe from the underlying viewport data and the
365 // setBackground(Color.white); // BH 2019
367 if (!Jalview.isHeadlessMode())
369 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
372 avc = new jalview.controller.AlignViewController(this, viewport,
374 if (viewport.getAlignmentConservationAnnotation() == null)
376 // BLOSUM62Colour.setEnabled(false);
377 conservationMenuItem.setEnabled(false);
378 modifyConservation.setEnabled(false);
379 // PIDColour.setEnabled(false);
380 // abovePIDThreshold.setEnabled(false);
381 // modifyPID.setEnabled(false);
384 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
387 if (sortby.equals("Id"))
389 sortIDMenuItem_actionPerformed(null);
391 else if (sortby.equals("Pairwise Identity"))
393 sortPairwiseMenuItem_actionPerformed(null);
397 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
399 setMenusFromViewport(viewport);
400 buildSortByAnnotationScoresMenu();
401 calculateTree.addActionListener(new ActionListener()
405 public void actionPerformed(ActionEvent e)
412 if (Desktop.desktop != null)
414 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
415 if (!Platform.isJS())
417 addServiceListeners();
422 if (viewport.getWrapAlignment())
424 wrapMenuItem_actionPerformed(null);
427 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
429 this.overviewMenuItem_actionPerformed(null);
434 final List<AlignmentPanel> selviews = new ArrayList<>();
435 final List<AlignmentPanel> origview = new ArrayList<>();
436 final String menuLabel = MessageManager
437 .getString("label.copy_format_from");
438 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
439 new ViewSetProvider()
443 public AlignmentPanel[] getAllAlignmentPanels()
446 origview.add(alignPanel);
447 // make an array of all alignment panels except for this one
448 List<AlignmentPanel> aps = new ArrayList<>(
449 Arrays.asList(Desktop.getAlignmentPanels(null)));
450 aps.remove(AlignFrame.this.alignPanel);
451 return aps.toArray(new AlignmentPanel[aps.size()]);
453 }, selviews, new ItemListener()
457 public void itemStateChanged(ItemEvent e)
459 if (origview.size() > 0)
461 final AlignmentPanel ap = origview.get(0);
464 * Copy the ViewStyle of the selected panel to 'this one'.
465 * Don't change value of 'scaleProteinAsCdna' unless copying
468 ViewStyleI vs = selviews.get(0).getAlignViewport()
470 boolean fromSplitFrame = selviews.get(0)
471 .getAlignViewport().getCodingComplement() != null;
474 vs.setScaleProteinAsCdna(ap.getAlignViewport()
475 .getViewStyle().isScaleProteinAsCdna());
477 ap.getAlignViewport().setViewStyle(vs);
480 * Also rescale ViewStyle of SplitFrame complement if there is
481 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
482 * the whole ViewStyle (allow cDNA protein to have different
485 AlignViewportI complement = ap.getAlignViewport()
486 .getCodingComplement();
487 if (complement != null && vs.isScaleProteinAsCdna())
489 AlignFrame af = Desktop.getAlignFrameFor(complement);
490 ((SplitFrame) af.getSplitViewContainer())
492 af.setMenusForViewport();
496 ap.setSelected(true);
497 ap.alignFrame.setMenusForViewport();
502 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
503 .indexOf("devel") > -1
504 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
505 .indexOf("test") > -1)
507 formatMenu.add(vsel);
509 addFocusListener(new FocusAdapter()
512 public void focusGained(FocusEvent e)
514 Jalview.setCurrentAlignFrame(AlignFrame.this);
521 * Change the filename and format for the alignment, and enable the 'reload'
522 * button functionality.
529 public void setFileName(String file, FileFormatI format)
532 setFileFormat(format);
533 reload.setEnabled(true);
537 * JavaScript will have this, maybe others. More dependable than a file name
538 * and maintains a reference to the actual bytes loaded.
542 public void setFileObject(File file)
544 this.fileObject = file;
548 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
551 void addKeyListener()
553 addKeyListener(new KeyAdapter()
556 public void keyPressed(KeyEvent evt)
558 if (viewport.cursorMode
559 && ((evt.getKeyCode() >= KeyEvent.VK_0
560 && evt.getKeyCode() <= KeyEvent.VK_9)
561 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
562 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
563 && Character.isDigit(evt.getKeyChar()))
565 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
568 switch (evt.getKeyCode())
571 case 27: // escape key
572 deselectAllSequenceMenuItem_actionPerformed(null);
576 case KeyEvent.VK_DOWN:
577 if (evt.isAltDown() || !viewport.cursorMode)
579 moveSelectedSequences(false);
581 if (viewport.cursorMode)
583 alignPanel.getSeqPanel().moveCursor(0, 1);
588 if (evt.isAltDown() || !viewport.cursorMode)
590 moveSelectedSequences(true);
592 if (viewport.cursorMode)
594 alignPanel.getSeqPanel().moveCursor(0, -1);
599 case KeyEvent.VK_LEFT:
600 if (evt.isAltDown() || !viewport.cursorMode)
602 slideSequences(false,
603 alignPanel.getSeqPanel().getKeyboardNo1());
607 alignPanel.getSeqPanel().moveCursor(-1, 0);
612 case KeyEvent.VK_RIGHT:
613 if (evt.isAltDown() || !viewport.cursorMode)
615 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
619 alignPanel.getSeqPanel().moveCursor(1, 0);
623 case KeyEvent.VK_SPACE:
624 if (viewport.cursorMode)
626 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
627 || evt.isShiftDown() || evt.isAltDown());
631 // case KeyEvent.VK_A:
632 // if (viewport.cursorMode)
634 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
635 // //System.out.println("A");
639 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
640 * System.out.println("closing bracket"); } break;
642 case KeyEvent.VK_DELETE:
643 case KeyEvent.VK_BACK_SPACE:
644 if (!viewport.cursorMode)
646 cut_actionPerformed();
650 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
651 || evt.isShiftDown() || evt.isAltDown());
657 if (viewport.cursorMode)
659 alignPanel.getSeqPanel().setCursorRow();
663 if (viewport.cursorMode && !evt.isControlDown())
665 alignPanel.getSeqPanel().setCursorColumn();
669 if (viewport.cursorMode)
671 alignPanel.getSeqPanel().setCursorPosition();
675 case KeyEvent.VK_ENTER:
676 case KeyEvent.VK_COMMA:
677 if (viewport.cursorMode)
679 alignPanel.getSeqPanel().setCursorRowAndColumn();
684 if (viewport.cursorMode)
686 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
690 if (viewport.cursorMode)
692 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
697 viewport.cursorMode = !viewport.cursorMode;
698 setStatus(MessageManager
699 .formatMessage("label.keyboard_editing_mode", new String[]
700 { (viewport.cursorMode ? "on" : "off") }));
701 if (viewport.cursorMode)
703 ViewportRanges ranges = viewport.getRanges();
704 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
706 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
709 alignPanel.getSeqPanel().seqCanvas.repaint();
715 Help.showHelpWindow();
716 } catch (Exception ex)
718 ex.printStackTrace();
723 boolean toggleSeqs = !evt.isControlDown();
724 boolean toggleCols = !evt.isShiftDown();
725 toggleHiddenRegions(toggleSeqs, toggleCols);
730 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
731 boolean modifyExisting = true; // always modify, don't clear
732 // evt.isShiftDown();
733 boolean invertHighlighted = evt.isAltDown();
734 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
738 case KeyEvent.VK_PAGE_UP:
739 viewport.getRanges().pageUp();
741 case KeyEvent.VK_PAGE_DOWN:
742 viewport.getRanges().pageDown();
748 public void keyReleased(KeyEvent evt)
750 switch (evt.getKeyCode())
752 case KeyEvent.VK_LEFT:
753 if (evt.isAltDown() || !viewport.cursorMode)
755 viewport.firePropertyChange("alignment", null,
756 viewport.getAlignment().getSequences());
760 case KeyEvent.VK_RIGHT:
761 if (evt.isAltDown() || !viewport.cursorMode)
763 viewport.firePropertyChange("alignment", null,
764 viewport.getAlignment().getSequences());
772 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
774 ap.alignFrame = this;
775 avc = new jalview.controller.AlignViewController(this, viewport,
780 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
782 int aSize = alignPanels.size();
784 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
786 if (aSize == 1 && ap.av.getViewName() == null)
788 this.getContentPane().add(ap, BorderLayout.CENTER);
794 setInitialTabVisible();
797 expandViews.setEnabled(true);
798 gatherViews.setEnabled(true);
799 tabbedPane.addTab(ap.av.getViewName(), ap);
801 ap.setVisible(false);
806 if (ap.av.isPadGaps())
808 ap.av.getAlignment().padGaps();
810 ap.av.updateConservation(ap);
811 ap.av.updateConsensus(ap);
812 ap.av.updateStrucConsensus(ap);
813 ap.av.initInformationWorker(ap);
817 public void setInitialTabVisible()
819 expandViews.setEnabled(true);
820 gatherViews.setEnabled(true);
821 tabbedPane.setVisible(true);
822 AlignmentPanel first = alignPanels.get(0);
823 tabbedPane.addTab(first.av.getViewName(), first);
824 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
827 public AlignViewport getViewport()
832 /* Set up intrinsic listeners for dynamically generated GUI bits. */
833 private void addServiceListeners()
835 final java.beans.PropertyChangeListener thisListener;
836 Desktop.instance.addJalviewPropertyChangeListener("services",
837 thisListener = new java.beans.PropertyChangeListener()
840 public void propertyChange(PropertyChangeEvent evt)
842 // // System.out.println("Discoverer property change.");
843 // if (evt.getPropertyName().equals("services"))
845 SwingUtilities.invokeLater(new Runnable()
852 "Rebuild WS Menu for service change");
853 BuildWebServiceMenu();
860 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
863 public void internalFrameClosed(
864 javax.swing.event.InternalFrameEvent evt)
866 // System.out.println("deregistering discoverer listener");
867 Desktop.instance.removeJalviewPropertyChangeListener("services",
869 closeMenuItem_actionPerformed(true);
872 // Finally, build the menu once to get current service state
873 new Thread(new Runnable()
878 BuildWebServiceMenu();
884 * Configure menu items that vary according to whether the alignment is
885 * nucleotide or protein
887 public void setGUINucleotide()
889 AlignmentI al = getViewport().getAlignment();
890 boolean nucleotide = al.isNucleotide();
892 loadVcf.setVisible(nucleotide);
893 showTranslation.setVisible(nucleotide);
894 showReverse.setVisible(nucleotide);
895 showReverseComplement.setVisible(nucleotide);
896 conservationMenuItem.setEnabled(!nucleotide);
898 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
899 showGroupConservation.setEnabled(!nucleotide);
901 showComplementMenuItem
902 .setText(nucleotide ? MessageManager.getString("label.protein")
903 : MessageManager.getString("label.nucleotide"));
907 * set up menus for the current viewport. This may be called after any
908 * operation that affects the data in the current view (selection changed,
909 * etc) to update the menus to reflect the new state.
912 public void setMenusForViewport()
914 setMenusFromViewport(viewport);
918 * Need to call this method when tabs are selected for multiple views, or when
919 * loading from Jalview2XML.java
924 public void setMenusFromViewport(AlignViewport av)
926 padGapsMenuitem.setSelected(av.isPadGaps());
927 colourTextMenuItem.setSelected(av.isShowColourText());
928 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
929 modifyPID.setEnabled(abovePIDThreshold.isSelected());
930 conservationMenuItem.setSelected(av.getConservationSelected());
931 modifyConservation.setEnabled(conservationMenuItem.isSelected());
932 seqLimits.setSelected(av.getShowJVSuffix());
933 idRightAlign.setSelected(av.isRightAlignIds());
934 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
935 renderGapsMenuItem.setSelected(av.isRenderGaps());
936 wrapMenuItem.setSelected(av.getWrapAlignment());
937 scaleAbove.setVisible(av.getWrapAlignment());
938 scaleLeft.setVisible(av.getWrapAlignment());
939 scaleRight.setVisible(av.getWrapAlignment());
940 annotationPanelMenuItem.setState(av.isShowAnnotation());
942 * Show/hide annotations only enabled if annotation panel is shown
944 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
945 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
946 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
947 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
948 viewBoxesMenuItem.setSelected(av.getShowBoxes());
949 viewTextMenuItem.setSelected(av.getShowText());
950 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
951 showGroupConsensus.setSelected(av.isShowGroupConsensus());
952 showGroupConservation.setSelected(av.isShowGroupConservation());
953 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
954 showSequenceLogo.setSelected(av.isShowSequenceLogo());
955 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
956 showInformationHistogram.setSelected(av.isShowInformationHistogram());
957 showHMMSequenceLogo.setSelected(av.isShowHMMSequenceLogo());
958 normaliseHMMSequenceLogo.setSelected(av.isNormaliseHMMSequenceLogo());
960 ColourMenuHelper.setColourSelected(colourMenu,
961 av.getGlobalColourScheme());
963 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
964 hiddenMarkers.setState(av.getShowHiddenMarkers());
965 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
966 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
967 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
968 autoCalculate.setSelected(av.autoCalculateConsensus);
969 sortByTree.setSelected(av.sortByTree);
970 listenToViewSelections.setSelected(av.followSelection);
972 showProducts.setEnabled(canShowProducts());
973 setGroovyEnabled(Desktop.getGroovyConsole() != null);
979 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
983 public void setGroovyEnabled(boolean b)
985 runGroovy.setEnabled(b);
988 private IProgressIndicator progressBar;
993 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
996 public void setProgressBar(String message, long id)
998 progressBar.setProgressBar(message, id);
1002 public void registerHandler(final long id,
1003 final IProgressIndicatorHandler handler)
1005 progressBar.registerHandler(id, handler);
1010 * @return true if any progress bars are still active
1013 public boolean operationInProgress()
1015 return progressBar.operationInProgress();
1019 * Sets the text of the status bar. Note that setting a null or empty value
1020 * will cause the status bar to be hidden, with possibly undesirable flicker
1021 * of the screen layout.
1024 public void setStatus(String text)
1026 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1030 * Added so Castor Mapping file can obtain Jalview Version
1032 public String getVersion()
1034 return jalview.bin.Cache.getProperty("VERSION");
1037 public FeatureRenderer getFeatureRenderer()
1039 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1043 public void fetchSequence_actionPerformed()
1045 new SequenceFetcher(this);
1049 public void addFromFile_actionPerformed(ActionEvent e)
1051 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1055 public void hmmBuild_actionPerformed(boolean withDefaults)
1057 if (!alignmentIsSufficient(1))
1063 * get default parameters, and optionally show a dialog
1064 * to allow them to be modified
1066 ParamDatastoreI store = HMMERParamStore.forBuild(viewport);
1067 List<ArgumentI> args = store.getServiceParameters();
1071 WsParamSetI set = new HMMERPreset();
1072 WsJobParameters params = new WsJobParameters(store, set, args);
1073 if (params.showRunDialog())
1075 args = params.getJobParams();
1079 return; // user cancelled
1082 new Thread(new HMMBuild(this, args)).start();
1086 public void hmmAlign_actionPerformed(boolean withDefaults)
1088 if (!(checkForHMM() && alignmentIsSufficient(2)))
1094 * get default parameters, and optionally show a dialog
1095 * to allow them to be modified
1097 ParamDatastoreI store = HMMERParamStore.forAlign(viewport);
1098 List<ArgumentI> args = store.getServiceParameters();
1102 WsParamSetI set = new HMMERPreset();
1103 WsJobParameters params = new WsJobParameters(store, set, args);
1104 if (params.showRunDialog())
1106 args = params.getJobParams();
1110 return; // user cancelled
1113 new Thread(new HMMAlign(this, args)).start();
1117 public void hmmSearch_actionPerformed(boolean withDefaults)
1125 * get default parameters, and (if requested) show
1126 * dialog to allow modification
1128 ParamDatastoreI store = HMMERParamStore.forSearch(viewport);
1129 List<ArgumentI> args = store.getServiceParameters();
1133 WsParamSetI set = new HMMERPreset();
1134 WsJobParameters params = new WsJobParameters(store, set, args);
1135 if (params.showRunDialog())
1137 args = params.getJobParams();
1141 return; // user cancelled
1144 new Thread(new HMMSearch(this, args)).start();
1145 alignPanel.repaint();
1149 public void jackhmmer_actionPerformed(boolean withDefaults)
1153 * get default parameters, and (if requested) show
1154 * dialog to allow modification
1157 ParamDatastoreI store = HMMERParamStore.forJackhmmer(viewport);
1158 List<ArgumentI> args = store.getServiceParameters();
1162 WsParamSetI set = new HMMERPreset();
1163 WsJobParameters params = new WsJobParameters(store, set, args);
1164 if (params.showRunDialog())
1166 args = params.getJobParams();
1170 return; // user cancelled
1173 new Thread(new JackHMMER(this, args)).start();
1174 alignPanel.repaint();
1179 * Checks if the alignment has at least one hidden Markov model, if not shows
1180 * a dialog advising to run hmmbuild or load an HMM profile
1184 private boolean checkForHMM()
1186 if (viewport.getAlignment().getHmmSequences().isEmpty())
1188 JOptionPane.showMessageDialog(this,
1189 MessageManager.getString("warn.no_hmm"));
1196 protected void filterByEValue_actionPerformed()
1198 viewport.filterByEvalue(inputDouble("Enter E-Value Cutoff"));
1202 protected void filterByScore_actionPerformed()
1204 viewport.filterByScore(inputDouble("Enter Bit Score Threshold"));
1207 private double inputDouble(String message)
1211 while(d == null || d <= 0)
1213 str = JOptionPane.showInputDialog(this.alignPanel, message);
1216 d = Double.valueOf(str);
1218 catch (NumberFormatException e)
1226 * Checks if the alignment contains the required number of sequences.
1231 public boolean alignmentIsSufficient(int required)
1233 if (getViewport().getSequenceSelection().length < required)
1235 JOptionPane.showMessageDialog(this,
1236 MessageManager.getString("label.not_enough_sequences"));
1243 * Opens a file browser and adds the selected file, if in Fasta, Stockholm or
1244 * Pfam format, to the list held under preference key "HMMSEARCH_DBS" (as a
1245 * comma-separated list)
1248 public void addDatabase_actionPerformed() throws IOException
1250 if (Cache.getProperty(Preferences.HMMSEARCH_DBS) == null)
1252 Cache.setProperty(Preferences.HMMSEARCH_DBS, "");
1255 String path = openFileChooser(false);
1256 if (path != null && new File(path).exists())
1258 IdentifyFile identifier = new IdentifyFile();
1259 FileFormatI format = identifier.identify(path, DataSourceType.FILE);
1260 if (format == FileFormat.Fasta || format == FileFormat.Stockholm
1261 || format == FileFormat.Pfam)
1263 String currentDbPaths = Cache
1264 .getProperty(Preferences.HMMSEARCH_DBS);
1265 currentDbPaths += Preferences.COMMA + path;
1266 Cache.setProperty(Preferences.HMMSEARCH_DBS, currentDbPaths);
1270 JOptionPane.showMessageDialog(this,
1271 MessageManager.getString("warn.invalid_format"));
1277 * Opens a file chooser, optionally restricted to selecting folders
1278 * (directories) only. Answers the path to the selected file or folder, or
1279 * null if none is chosen.
1284 protected String openFileChooser(boolean forFolder)
1286 // TODO duplicates GPreferences method - relocate to JalviewFileChooser?
1287 String choice = null;
1288 JFileChooser chooser = new JFileChooser();
1291 chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1293 chooser.setDialogTitle(
1294 MessageManager.getString("label.open_local_file"));
1295 chooser.setToolTipText(MessageManager.getString("action.open"));
1297 int value = chooser.showOpenDialog(this);
1299 if (value == JFileChooser.APPROVE_OPTION)
1301 choice = chooser.getSelectedFile().getPath();
1307 public void reload_actionPerformed(ActionEvent e)
1309 if (fileName != null)
1311 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1312 // originating file's format
1313 // TODO: work out how to recover feature settings for correct view(s) when
1314 // file is reloaded.
1315 if (FileFormat.Jalview.equals(currentFileFormat))
1317 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1318 for (int i = 0; i < frames.length; i++)
1320 if (frames[i] instanceof AlignFrame && frames[i] != this
1321 && ((AlignFrame) frames[i]).fileName != null
1322 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1326 frames[i].setSelected(true);
1327 Desktop.instance.closeAssociatedWindows();
1328 } catch (java.beans.PropertyVetoException ex)
1334 Desktop.instance.closeAssociatedWindows();
1336 FileLoader loader = new FileLoader();
1337 DataSourceType protocol = fileName.startsWith("http:")
1338 ? DataSourceType.URL
1339 : DataSourceType.FILE;
1340 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1344 Rectangle bounds = this.getBounds();
1346 FileLoader loader = new FileLoader();
1348 AlignFrame newframe = null;
1350 if (fileObject == null)
1353 DataSourceType protocol = (fileName.startsWith("http:")
1354 ? DataSourceType.URL
1355 : DataSourceType.FILE);
1356 newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1361 newframe = loader.LoadFileWaitTillLoaded(fileObject,
1362 DataSourceType.FILE, currentFileFormat);
1365 newframe.setBounds(bounds);
1366 if (featureSettings != null && featureSettings.isShowing())
1368 final Rectangle fspos = featureSettings.frame.getBounds();
1369 // TODO: need a 'show feature settings' function that takes bounds -
1370 // need to refactor Desktop.addFrame
1371 newframe.featureSettings_actionPerformed(null);
1372 final FeatureSettings nfs = newframe.featureSettings;
1373 SwingUtilities.invokeLater(new Runnable()
1378 nfs.frame.setBounds(fspos);
1381 this.featureSettings.close();
1382 this.featureSettings = null;
1384 this.closeMenuItem_actionPerformed(true);
1390 public void addFromText_actionPerformed(ActionEvent e)
1393 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1397 public void addFromURL_actionPerformed(ActionEvent e)
1399 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1403 public void save_actionPerformed(ActionEvent e)
1405 if (fileName == null || (currentFileFormat == null)
1406 || fileName.startsWith("http"))
1408 saveAs_actionPerformed();
1412 saveAlignment(fileName, currentFileFormat);
1417 * Saves the alignment to a file with a name chosen by the user, if necessary
1418 * warning if a file would be overwritten
1421 public void saveAs_actionPerformed()
1423 String format = currentFileFormat == null ? null
1424 : currentFileFormat.getName();
1425 JalviewFileChooser chooser = JalviewFileChooser
1426 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1428 chooser.setFileView(new JalviewFileView());
1429 chooser.setDialogTitle(
1430 MessageManager.getString("label.save_alignment_to_file"));
1431 chooser.setToolTipText(MessageManager.getString("action.save"));
1433 int value = chooser.showSaveDialog(this);
1435 if (value != JalviewFileChooser.APPROVE_OPTION)
1439 currentFileFormat = chooser.getSelectedFormat();
1440 // todo is this (2005) test now obsolete - value is never null?
1441 while (currentFileFormat == null)
1443 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1445 .getString("label.select_file_format_before_saving"),
1446 MessageManager.getString("label.file_format_not_specified"),
1447 JvOptionPane.WARNING_MESSAGE);
1448 currentFileFormat = chooser.getSelectedFormat();
1449 value = chooser.showSaveDialog(this);
1450 if (value != JalviewFileChooser.APPROVE_OPTION)
1456 fileName = chooser.getSelectedFile().getPath();
1458 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1459 Cache.setProperty("LAST_DIRECTORY", fileName);
1460 saveAlignment(fileName, currentFileFormat);
1463 boolean lastSaveSuccessful = false;
1465 FileFormatI lastFormatSaved;
1467 String lastFilenameSaved;
1470 * Raise a dialog or status message for the last call to saveAlignment.
1472 * @return true if last call to saveAlignment(file, format) was successful.
1474 public boolean isSaveAlignmentSuccessful()
1477 if (!lastSaveSuccessful)
1479 JvOptionPane.showInternalMessageDialog(this, MessageManager
1480 .formatMessage("label.couldnt_save_file", new Object[]
1481 { lastFilenameSaved }),
1482 MessageManager.getString("label.error_saving_file"),
1483 JvOptionPane.WARNING_MESSAGE);
1488 setStatus(MessageManager.formatMessage(
1489 "label.successfully_saved_to_file_in_format", new Object[]
1490 { lastFilenameSaved, lastFormatSaved }));
1493 return lastSaveSuccessful;
1497 * Saves the alignment to the specified file path, in the specified format,
1498 * which may be an alignment format, or Jalview project format. If the
1499 * alignment has hidden regions, or the format is one capable of including
1500 * non-sequence data (features, annotations, groups), then the user may be
1501 * prompted to specify what to include in the output.
1506 public void saveAlignment(String file, FileFormatI format)
1508 lastSaveSuccessful = true;
1509 lastFilenameSaved = file;
1510 lastFormatSaved = format;
1512 if (FileFormat.Jalview.equals(format))
1514 String shortName = title;
1515 if (shortName.indexOf(File.separatorChar) > -1)
1517 shortName = shortName.substring(
1518 shortName.lastIndexOf(File.separatorChar) + 1);
1520 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file, shortName);
1522 statusBar.setText(MessageManager.formatMessage(
1523 "label.successfully_saved_to_file_in_format", new Object[]
1524 { fileName, format }));
1529 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1530 Runnable cancelAction = new Runnable()
1535 lastSaveSuccessful = false;
1538 Runnable outputAction = new Runnable()
1543 // todo defer this to inside formatSequences (or later)
1544 AlignmentExportData exportData = viewport
1545 .getAlignExportData(options);
1546 String output = new FormatAdapter(alignPanel, options)
1547 .formatSequences(format, exportData.getAlignment(),
1548 exportData.getOmitHidden(),
1549 exportData.getStartEndPostions(),
1550 viewport.getAlignment().getHiddenColumns());
1553 lastSaveSuccessful = false;
1557 // create backupfiles object and get new temp filename destination
1558 boolean doBackup = BackupFiles.getEnabled();
1559 BackupFiles backupfiles = doBackup ? new BackupFiles(file) : null;
1562 String tempFilePath = doBackup ? backupfiles.getTempFilePath() : file;
1563 PrintWriter out = new PrintWriter(
1564 new FileWriter(tempFilePath));
1568 AlignFrame.this.setTitle(file);
1569 statusBar.setText(MessageManager.formatMessage(
1570 "label.successfully_saved_to_file_in_format", new Object[]
1571 { fileName, format.getName() }));
1572 lastSaveSuccessful = true;
1573 } catch (Exception ex)
1575 lastSaveSuccessful = false;
1576 ex.printStackTrace();
1581 backupfiles.setWriteSuccess(lastSaveSuccessful);
1582 // do the backup file roll and rename the temp file to actual file
1583 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1590 * show dialog with export options if applicable; else just do it
1592 if (AlignExportOptions.isNeeded(viewport, format))
1594 AlignExportOptions choices = new AlignExportOptions(
1595 alignPanel.getAlignViewport(), format, options);
1596 choices.setResponseAction(0, outputAction);
1597 choices.setResponseAction(1, cancelAction);
1598 choices.showDialog();
1607 * Outputs the alignment to textbox in the requested format, if necessary
1608 * first prompting the user for whether to include hidden regions or
1611 * @param fileFormatName
1614 protected void outputText_actionPerformed(String fileFormatName)
1616 FileFormatI fileFormat = FileFormats.getInstance()
1617 .forName(fileFormatName);
1618 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1619 Runnable outputAction = new Runnable()
1624 // todo defer this to inside formatSequences (or later)
1625 AlignmentExportData exportData = viewport
1626 .getAlignExportData(options);
1627 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1628 cap.setForInput(null);
1631 FileFormatI format = fileFormat;
1632 cap.setText(new FormatAdapter(alignPanel, options)
1633 .formatSequences(format, exportData.getAlignment(),
1634 exportData.getOmitHidden(),
1635 exportData.getStartEndPostions(),
1636 viewport.getAlignment().getHiddenColumns()));
1637 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1638 "label.alignment_output_command", new Object[]
1639 { fileFormat.getName() }), 600, 500);
1640 } catch (OutOfMemoryError oom)
1642 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1650 * show dialog with export options if applicable; else just do it
1652 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1654 AlignExportOptions choices = new AlignExportOptions(
1655 alignPanel.getAlignViewport(), fileFormat, options);
1656 choices.setResponseAction(0, outputAction);
1657 choices.showDialog();
1672 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1674 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1675 htmlSVG.exportHTML(null);
1679 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1681 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1682 bjs.exportHTML(null);
1685 public void createImageMap(File file, String image)
1687 alignPanel.makePNGImageMap(file, image);
1691 * Creates a PNG image of the alignment and writes it to the given file. If
1692 * the file is null, the user is prompted to choose a file.
1697 public void createPNG(File f)
1699 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1703 * Creates an EPS image of the alignment and writes it to the given file. If
1704 * the file is null, the user is prompted to choose a file.
1709 public void createEPS(File f)
1711 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1715 * Creates an SVG image of the alignment and writes it to the given file. If
1716 * the file is null, the user is prompted to choose a file.
1721 public void createSVG(File f)
1723 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1727 public void pageSetup_actionPerformed(ActionEvent e)
1729 PrinterJob printJob = PrinterJob.getPrinterJob();
1730 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1740 public void printMenuItem_actionPerformed(ActionEvent e)
1742 // Putting in a thread avoids Swing painting problems
1743 PrintThread thread = new PrintThread(alignPanel);
1748 public void exportFeatures_actionPerformed(ActionEvent e)
1750 new AnnotationExporter(alignPanel).exportFeatures();
1754 public void exportAnnotations_actionPerformed(ActionEvent e)
1756 new AnnotationExporter(alignPanel).exportAnnotations();
1760 public void associatedData_actionPerformed(ActionEvent e)
1761 throws IOException, InterruptedException
1763 final JalviewFileChooser chooser = new JalviewFileChooser(
1764 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1765 chooser.setFileView(new JalviewFileView());
1766 String tooltip = MessageManager.getString("label.load_jalview_annotations");
1767 chooser.setDialogTitle(tooltip);
1768 chooser.setToolTipText(tooltip);
1769 chooser.setResponseHandler(0, new Runnable()
1774 String choice = chooser.getSelectedFile().getPath();
1775 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1776 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1780 chooser.showOpenDialog(this);
1784 * Close the current view or all views in the alignment frame. If the frame
1785 * only contains one view then the alignment will be removed from memory.
1787 * @param closeAllTabs
1790 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1792 if (alignPanels != null && alignPanels.size() < 2)
1794 closeAllTabs = true;
1799 if (alignPanels != null)
1803 if (this.isClosed())
1805 // really close all the windows - otherwise wait till
1806 // setClosed(true) is called
1807 for (int i = 0; i < alignPanels.size(); i++)
1809 AlignmentPanel ap = alignPanels.get(i);
1816 closeView(alignPanel);
1821 if (featureSettings != null && featureSettings.isOpen())
1823 featureSettings.close();
1824 featureSettings = null;
1827 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1828 * be called recursively, with the frame now in 'closed' state
1830 this.setClosed(true);
1832 } catch (Exception ex)
1834 ex.printStackTrace();
1839 * Close the specified panel and close up tabs appropriately.
1841 * @param panelToClose
1843 public void closeView(AlignmentPanel panelToClose)
1845 int index = tabbedPane.getSelectedIndex();
1846 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1847 alignPanels.remove(panelToClose);
1848 panelToClose.closePanel();
1849 panelToClose = null;
1851 tabbedPane.removeTabAt(closedindex);
1852 tabbedPane.validate();
1854 if (index > closedindex || index == tabbedPane.getTabCount())
1856 // modify currently selected tab index if necessary.
1860 this.tabSelectionChanged(index);
1866 void updateEditMenuBar()
1869 if (viewport.getHistoryList().size() > 0)
1871 undoMenuItem.setEnabled(true);
1872 CommandI command = viewport.getHistoryList().peek();
1873 undoMenuItem.setText(MessageManager
1874 .formatMessage("label.undo_command", new Object[]
1875 { command.getDescription() }));
1879 undoMenuItem.setEnabled(false);
1880 undoMenuItem.setText(MessageManager.getString("action.undo"));
1883 if (viewport.getRedoList().size() > 0)
1885 redoMenuItem.setEnabled(true);
1887 CommandI command = viewport.getRedoList().peek();
1888 redoMenuItem.setText(MessageManager
1889 .formatMessage("label.redo_command", new Object[]
1890 { command.getDescription() }));
1894 redoMenuItem.setEnabled(false);
1895 redoMenuItem.setText(MessageManager.getString("action.redo"));
1900 public void addHistoryItem(CommandI command)
1902 if (command.getSize() > 0)
1904 viewport.addToHistoryList(command);
1905 viewport.clearRedoList();
1906 updateEditMenuBar();
1907 viewport.updateHiddenColumns();
1908 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1909 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1910 // viewport.getColumnSelection()
1911 // .getHiddenColumns().size() > 0);
1917 * @return alignment objects for all views
1919 AlignmentI[] getViewAlignments()
1921 if (alignPanels != null)
1923 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1925 for (AlignmentPanel ap : alignPanels)
1927 als[i++] = ap.av.getAlignment();
1931 if (viewport != null)
1933 return new AlignmentI[] { viewport.getAlignment() };
1945 protected void undoMenuItem_actionPerformed(ActionEvent e)
1947 if (viewport.getHistoryList().isEmpty())
1951 CommandI command = viewport.getHistoryList().pop();
1952 viewport.addToRedoList(command);
1953 command.undoCommand(getViewAlignments());
1955 AlignmentViewport originalSource = getOriginatingSource(command);
1956 updateEditMenuBar();
1958 if (originalSource != null)
1960 if (originalSource != viewport)
1963 "Implementation worry: mismatch of viewport origin for undo");
1965 originalSource.updateHiddenColumns();
1966 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1968 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1969 // viewport.getColumnSelection()
1970 // .getHiddenColumns().size() > 0);
1971 originalSource.firePropertyChange("alignment", null,
1972 originalSource.getAlignment().getSequences());
1983 protected void redoMenuItem_actionPerformed(ActionEvent e)
1985 if (viewport.getRedoList().size() < 1)
1990 CommandI command = viewport.getRedoList().pop();
1991 viewport.addToHistoryList(command);
1992 command.doCommand(getViewAlignments());
1994 AlignmentViewport originalSource = getOriginatingSource(command);
1995 updateEditMenuBar();
1997 if (originalSource != null)
2000 if (originalSource != viewport)
2003 "Implementation worry: mismatch of viewport origin for redo");
2005 originalSource.updateHiddenColumns();
2006 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
2008 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2009 // viewport.getColumnSelection()
2010 // .getHiddenColumns().size() > 0);
2011 originalSource.firePropertyChange("alignment", null,
2012 originalSource.getAlignment().getSequences());
2016 AlignmentViewport getOriginatingSource(CommandI command)
2018 AlignmentViewport originalSource = null;
2019 // For sequence removal and addition, we need to fire
2020 // the property change event FROM the viewport where the
2021 // original alignment was altered
2022 AlignmentI al = null;
2023 if (command instanceof EditCommand)
2025 EditCommand editCommand = (EditCommand) command;
2026 al = editCommand.getAlignment();
2027 List<Component> comps = PaintRefresher.components
2028 .get(viewport.getSequenceSetId());
2030 for (Component comp : comps)
2032 if (comp instanceof AlignmentPanel)
2034 if (al == ((AlignmentPanel) comp).av.getAlignment())
2036 originalSource = ((AlignmentPanel) comp).av;
2043 if (originalSource == null)
2045 // The original view is closed, we must validate
2046 // the current view against the closed view first
2049 PaintRefresher.validateSequences(al, viewport.getAlignment());
2052 originalSource = viewport;
2055 return originalSource;
2064 public void moveSelectedSequences(boolean up)
2066 SequenceGroup sg = viewport.getSelectionGroup();
2072 viewport.getAlignment().moveSelectedSequencesByOne(sg,
2073 viewport.getHiddenRepSequences(), up);
2074 alignPanel.paintAlignment(true, false);
2077 synchronized void slideSequences(boolean right, int size)
2079 List<SequenceI> sg = new ArrayList<>();
2080 if (viewport.cursorMode)
2082 sg.add(viewport.getAlignment()
2083 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
2085 else if (viewport.getSelectionGroup() != null
2086 && viewport.getSelectionGroup().getSize() != viewport
2087 .getAlignment().getHeight())
2089 sg = viewport.getSelectionGroup()
2090 .getSequences(viewport.getHiddenRepSequences());
2098 List<SequenceI> invertGroup = new ArrayList<>();
2100 for (SequenceI seq : viewport.getAlignment().getSequences())
2102 if (!sg.contains(seq))
2104 invertGroup.add(seq);
2108 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
2110 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
2111 for (int i = 0; i < invertGroup.size(); i++)
2113 seqs2[i] = invertGroup.get(i);
2116 SlideSequencesCommand ssc;
2119 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
2120 viewport.getGapCharacter());
2124 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
2125 viewport.getGapCharacter());
2128 int groupAdjustment = 0;
2129 if (ssc.getGapsInsertedBegin() && right)
2131 if (viewport.cursorMode)
2133 alignPanel.getSeqPanel().moveCursor(size, 0);
2137 groupAdjustment = size;
2140 else if (!ssc.getGapsInsertedBegin() && !right)
2142 if (viewport.cursorMode)
2144 alignPanel.getSeqPanel().moveCursor(-size, 0);
2148 groupAdjustment = -size;
2152 if (groupAdjustment != 0)
2154 viewport.getSelectionGroup().setStartRes(
2155 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
2156 viewport.getSelectionGroup().setEndRes(
2157 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
2161 * just extend the last slide command if compatible; but not if in
2162 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
2164 boolean appendHistoryItem = false;
2165 Deque<CommandI> historyList = viewport.getHistoryList();
2166 boolean inSplitFrame = getSplitViewContainer() != null;
2167 if (!inSplitFrame && historyList != null && historyList.size() > 0
2168 && historyList.peek() instanceof SlideSequencesCommand)
2170 appendHistoryItem = ssc.appendSlideCommand(
2171 (SlideSequencesCommand) historyList.peek());
2174 if (!appendHistoryItem)
2176 addHistoryItem(ssc);
2189 protected void copy_actionPerformed()
2191 if (viewport.getSelectionGroup() == null)
2195 // TODO: preserve the ordering of displayed alignment annotation in any
2196 // internal paste (particularly sequence associated annotation)
2197 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2198 String[] omitHidden = null;
2200 if (viewport.hasHiddenColumns())
2202 omitHidden = viewport.getViewAsString(true);
2205 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2206 seqs, omitHidden, null);
2208 StringSelection ss = new StringSelection(output);
2212 jalview.gui.Desktop.internalCopy = true;
2213 // Its really worth setting the clipboard contents
2214 // to empty before setting the large StringSelection!!
2215 Toolkit.getDefaultToolkit().getSystemClipboard()
2216 .setContents(new StringSelection(""), null);
2218 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2220 } catch (OutOfMemoryError er)
2222 new OOMWarning("copying region", er);
2226 HiddenColumns hiddenColumns = null;
2227 if (viewport.hasHiddenColumns())
2229 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2230 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2232 // create new HiddenColumns object with copy of hidden regions
2233 // between startRes and endRes, offset by startRes
2234 hiddenColumns = new HiddenColumns(
2235 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2236 hiddenCutoff, hiddenOffset);
2239 Desktop.jalviewClipboard = new Object[] { seqs,
2240 viewport.getAlignment().getDataset(), hiddenColumns };
2241 setStatus(MessageManager.formatMessage(
2242 "label.copied_sequences_to_clipboard", new Object[]
2243 { Integer.valueOf(seqs.length).toString() }));
2251 * @throws InterruptedException
2252 * @throws IOException
2255 protected void pasteNew_actionPerformed(ActionEvent e)
2256 throws IOException, InterruptedException
2266 * @throws InterruptedException
2267 * @throws IOException
2270 protected void pasteThis_actionPerformed(ActionEvent e)
2271 throws IOException, InterruptedException
2277 * Paste contents of Jalview clipboard
2279 * @param newAlignment
2280 * true to paste to a new alignment, otherwise add to this.
2281 * @throws InterruptedException
2282 * @throws IOException
2284 void paste(boolean newAlignment) throws IOException, InterruptedException
2286 boolean externalPaste = true;
2289 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2290 Transferable contents = c.getContents(this);
2292 if (contents == null)
2301 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2302 if (str.length() < 1)
2307 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2309 } catch (OutOfMemoryError er)
2311 new OOMWarning("Out of memory pasting sequences!!", er);
2315 SequenceI[] sequences;
2316 boolean annotationAdded = false;
2317 AlignmentI alignment = null;
2319 if (Desktop.jalviewClipboard != null)
2321 // The clipboard was filled from within Jalview, we must use the
2323 // And dataset from the copied alignment
2324 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2325 // be doubly sure that we create *new* sequence objects.
2326 sequences = new SequenceI[newseq.length];
2327 for (int i = 0; i < newseq.length; i++)
2329 sequences[i] = new Sequence(newseq[i]);
2331 alignment = new Alignment(sequences);
2332 externalPaste = false;
2336 // parse the clipboard as an alignment.
2337 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2339 sequences = alignment.getSequencesArray();
2343 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2349 if (Desktop.jalviewClipboard != null)
2351 // dataset is inherited
2352 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2356 // new dataset is constructed
2357 alignment.setDataset(null);
2359 alwidth = alignment.getWidth() + 1;
2363 AlignmentI pastedal = alignment; // preserve pasted alignment object
2364 // Add pasted sequences and dataset into existing alignment.
2365 alignment = viewport.getAlignment();
2366 alwidth = alignment.getWidth() + 1;
2367 // decide if we need to import sequences from an existing dataset
2368 boolean importDs = Desktop.jalviewClipboard != null
2369 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2370 // importDs==true instructs us to copy over new dataset sequences from
2371 // an existing alignment
2372 Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2374 // minimum dataset set
2376 for (int i = 0; i < sequences.length; i++)
2380 newDs.addElement(null);
2382 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2384 if (importDs && ds != null)
2386 if (!newDs.contains(ds))
2388 newDs.setElementAt(ds, i);
2389 ds = new Sequence(ds);
2390 // update with new dataset sequence
2391 sequences[i].setDatasetSequence(ds);
2395 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2400 // copy and derive new dataset sequence
2401 sequences[i] = sequences[i].deriveSequence();
2402 alignment.getDataset()
2403 .addSequence(sequences[i].getDatasetSequence());
2404 // TODO: avoid creation of duplicate dataset sequences with a
2405 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2407 alignment.addSequence(sequences[i]); // merges dataset
2411 newDs.clear(); // tidy up
2413 if (alignment.getAlignmentAnnotation() != null)
2415 for (AlignmentAnnotation alan : alignment
2416 .getAlignmentAnnotation())
2418 if (alan.graphGroup > fgroup)
2420 fgroup = alan.graphGroup;
2424 if (pastedal.getAlignmentAnnotation() != null)
2426 // Add any annotation attached to alignment.
2427 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2428 for (int i = 0; i < alann.length; i++)
2430 annotationAdded = true;
2431 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2433 AlignmentAnnotation newann = new AlignmentAnnotation(
2435 if (newann.graphGroup > -1)
2437 if (newGraphGroups.size() <= newann.graphGroup
2438 || newGraphGroups.get(newann.graphGroup) == null)
2440 for (int q = newGraphGroups
2441 .size(); q <= newann.graphGroup; q++)
2443 newGraphGroups.add(q, null);
2445 newGraphGroups.set(newann.graphGroup,
2446 Integer.valueOf(++fgroup));
2448 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2452 newann.padAnnotation(alwidth);
2453 alignment.addAnnotation(newann);
2463 addHistoryItem(new EditCommand(
2464 MessageManager.getString("label.add_sequences"),
2465 Action.PASTE, sequences, 0, alignment.getWidth(),
2468 // Add any annotations attached to sequences
2469 for (int i = 0; i < sequences.length; i++)
2471 if (sequences[i].getAnnotation() != null)
2473 AlignmentAnnotation newann;
2474 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2476 annotationAdded = true;
2477 newann = sequences[i].getAnnotation()[a];
2478 newann.adjustForAlignment();
2479 newann.padAnnotation(alwidth);
2480 if (newann.graphGroup > -1)
2482 if (newann.graphGroup > -1)
2484 if (newGraphGroups.size() <= newann.graphGroup
2485 || newGraphGroups.get(newann.graphGroup) == null)
2487 for (int q = newGraphGroups
2488 .size(); q <= newann.graphGroup; q++)
2490 newGraphGroups.add(q, null);
2492 newGraphGroups.set(newann.graphGroup,
2493 Integer.valueOf(++fgroup));
2495 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2499 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2503 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2511 // propagate alignment changed.
2512 viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2513 if (annotationAdded)
2515 // Duplicate sequence annotation in all views.
2516 AlignmentI[] alview = this.getViewAlignments();
2517 for (int i = 0; i < sequences.length; i++)
2519 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2524 for (int avnum = 0; avnum < alview.length; avnum++)
2526 if (alview[avnum] != alignment)
2528 // duplicate in a view other than the one with input focus
2529 int avwidth = alview[avnum].getWidth() + 1;
2530 // this relies on sann being preserved after we
2531 // modify the sequence's annotation array for each duplication
2532 for (int a = 0; a < sann.length; a++)
2534 AlignmentAnnotation newann = new AlignmentAnnotation(
2536 sequences[i].addAlignmentAnnotation(newann);
2537 newann.padAnnotation(avwidth);
2538 alview[avnum].addAnnotation(newann); // annotation was
2539 // duplicated earlier
2540 // TODO JAL-1145 graphGroups are not updated for sequence
2541 // annotation added to several views. This may cause
2543 alview[avnum].setAnnotationIndex(newann, a);
2548 buildSortByAnnotationScoresMenu();
2550 viewport.firePropertyChange("alignment", null,
2551 alignment.getSequences());
2552 if (alignPanels != null)
2554 for (AlignmentPanel ap : alignPanels)
2556 ap.validateAnnotationDimensions(false);
2561 alignPanel.validateAnnotationDimensions(false);
2567 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2569 String newtitle = new String("Copied sequences");
2571 if (Desktop.jalviewClipboard != null
2572 && Desktop.jalviewClipboard[2] != null)
2574 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2575 af.viewport.setHiddenColumns(hc);
2578 // >>>This is a fix for the moment, until a better solution is
2580 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2581 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2582 .getFeatureRenderer());
2584 // TODO: maintain provenance of an alignment, rather than just make the
2585 // title a concatenation of operations.
2588 if (title.startsWith("Copied sequences"))
2594 newtitle = newtitle.concat("- from " + title);
2599 newtitle = new String("Pasted sequences");
2602 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2607 } catch (Exception ex)
2609 ex.printStackTrace();
2610 System.out.println("Exception whilst pasting: " + ex);
2611 // could be anything being pasted in here
2616 protected void expand_newalign(ActionEvent e)
2620 AlignmentI alignment = AlignmentUtils
2621 .expandContext(getViewport().getAlignment(), -1);
2622 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2624 String newtitle = new String("Flanking alignment");
2626 if (Desktop.jalviewClipboard != null
2627 && Desktop.jalviewClipboard[2] != null)
2629 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2630 af.viewport.setHiddenColumns(hc);
2633 // >>>This is a fix for the moment, until a better solution is
2635 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2636 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2637 .getFeatureRenderer());
2639 // TODO: maintain provenance of an alignment, rather than just make the
2640 // title a concatenation of operations.
2642 if (title.startsWith("Copied sequences"))
2648 newtitle = newtitle.concat("- from " + title);
2652 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2654 } catch (Exception ex)
2656 ex.printStackTrace();
2657 System.out.println("Exception whilst pasting: " + ex);
2658 // could be anything being pasted in here
2659 } catch (OutOfMemoryError oom)
2661 new OOMWarning("Viewing flanking region of alignment", oom);
2666 * Action Cut (delete and copy) the selected region
2669 protected void cut_actionPerformed()
2671 copy_actionPerformed();
2672 delete_actionPerformed();
2676 * Performs menu option to Delete the currently selected region
2679 protected void delete_actionPerformed()
2682 SequenceGroup sg = viewport.getSelectionGroup();
2688 Runnable okAction = new Runnable()
2693 SequenceI[] cut = sg.getSequences()
2694 .toArray(new SequenceI[sg.getSize()]);
2696 addHistoryItem(new EditCommand(
2697 MessageManager.getString("label.cut_sequences"), Action.CUT,
2698 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2699 viewport.getAlignment()));
2701 viewport.setSelectionGroup(null);
2702 viewport.sendSelection();
2703 viewport.getAlignment().deleteGroup(sg);
2705 viewport.firePropertyChange("alignment", null,
2706 viewport.getAlignment().getSequences());
2707 if (viewport.getAlignment().getHeight() < 1)
2711 AlignFrame.this.setClosed(true);
2712 } catch (Exception ex)
2719 * If the cut affects all sequences, prompt for confirmation
2721 boolean wholeHeight = sg.getSize() == viewport.getAlignment().getHeight();
2722 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2723 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2724 if (wholeHeight && wholeWidth)
2726 JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.desktop);
2727 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2728 Object[] options = new Object[] { MessageManager.getString("action.ok"),
2729 MessageManager.getString("action.cancel") };
2730 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2731 MessageManager.getString("label.delete_all"),
2732 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2733 options, options[0]);
2747 protected void deleteGroups_actionPerformed(ActionEvent e)
2749 if (avc.deleteGroups())
2751 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2752 alignPanel.updateAnnotation();
2753 alignPanel.paintAlignment(true, true);
2764 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2766 SequenceGroup sg = new SequenceGroup(
2767 viewport.getAlignment().getSequences());
2769 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2770 viewport.setSelectionGroup(sg);
2771 viewport.isSelectionGroupChanged(true);
2772 viewport.sendSelection();
2773 // JAL-2034 - should delegate to
2774 // alignPanel to decide if overview needs
2776 alignPanel.paintAlignment(false, false);
2777 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2787 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2789 if (viewport.cursorMode)
2791 alignPanel.getSeqPanel().keyboardNo1 = null;
2792 alignPanel.getSeqPanel().keyboardNo2 = null;
2794 viewport.setSelectionGroup(null);
2795 viewport.getColumnSelection().clear();
2796 viewport.setSelectionGroup(null);
2797 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2798 // JAL-2034 - should delegate to
2799 // alignPanel to decide if overview needs
2801 alignPanel.paintAlignment(false, false);
2802 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2803 viewport.sendSelection();
2813 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2815 SequenceGroup sg = viewport.getSelectionGroup();
2819 selectAllSequenceMenuItem_actionPerformed(null);
2824 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2826 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2828 // JAL-2034 - should delegate to
2829 // alignPanel to decide if overview needs
2832 alignPanel.paintAlignment(true, false);
2833 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2834 viewport.sendSelection();
2838 public void invertColSel_actionPerformed(ActionEvent e)
2840 viewport.invertColumnSelection();
2841 alignPanel.paintAlignment(true, false);
2842 viewport.sendSelection();
2852 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2854 trimAlignment(true);
2864 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2866 trimAlignment(false);
2869 void trimAlignment(boolean trimLeft)
2871 ColumnSelection colSel = viewport.getColumnSelection();
2874 if (!colSel.isEmpty())
2878 column = colSel.getMin();
2882 column = colSel.getMax();
2886 if (viewport.getSelectionGroup() != null)
2888 seqs = viewport.getSelectionGroup()
2889 .getSequencesAsArray(viewport.getHiddenRepSequences());
2893 seqs = viewport.getAlignment().getSequencesArray();
2896 TrimRegionCommand trimRegion;
2899 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2900 column, viewport.getAlignment());
2901 viewport.getRanges().setStartRes(0);
2905 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2906 column, viewport.getAlignment());
2909 setStatus(MessageManager
2910 .formatMessage("label.removed_columns", new String[]
2911 { Integer.valueOf(trimRegion.getSize()).toString() }));
2913 addHistoryItem(trimRegion);
2915 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2917 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2918 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2920 viewport.getAlignment().deleteGroup(sg);
2924 viewport.firePropertyChange("alignment", null,
2925 viewport.getAlignment().getSequences());
2936 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2938 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2941 if (viewport.getSelectionGroup() != null)
2943 seqs = viewport.getSelectionGroup()
2944 .getSequencesAsArray(viewport.getHiddenRepSequences());
2945 start = viewport.getSelectionGroup().getStartRes();
2946 end = viewport.getSelectionGroup().getEndRes();
2950 seqs = viewport.getAlignment().getSequencesArray();
2953 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2954 "Remove Gapped Columns", seqs, start, end,
2955 viewport.getAlignment());
2957 addHistoryItem(removeGapCols);
2959 setStatus(MessageManager
2960 .formatMessage("label.removed_empty_columns", new Object[]
2961 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2963 // This is to maintain viewport position on first residue
2964 // of first sequence
2965 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2966 ViewportRanges ranges = viewport.getRanges();
2967 int startRes = seq.findPosition(ranges.getStartRes());
2968 // ShiftList shifts;
2969 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2970 // edit.alColumnChanges=shifts.getInverse();
2971 // if (viewport.hasHiddenColumns)
2972 // viewport.getColumnSelection().compensateForEdits(shifts);
2973 ranges.setStartRes(seq.findIndex(startRes) - 1);
2974 viewport.firePropertyChange("alignment", null,
2975 viewport.getAlignment().getSequences());
2986 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2988 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2991 if (viewport.getSelectionGroup() != null)
2993 seqs = viewport.getSelectionGroup()
2994 .getSequencesAsArray(viewport.getHiddenRepSequences());
2995 start = viewport.getSelectionGroup().getStartRes();
2996 end = viewport.getSelectionGroup().getEndRes();
3000 seqs = viewport.getAlignment().getSequencesArray();
3003 // This is to maintain viewport position on first residue
3004 // of first sequence
3005 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3006 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
3008 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
3009 viewport.getAlignment()));
3011 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
3013 viewport.firePropertyChange("alignment", null,
3014 viewport.getAlignment().getSequences());
3025 public void padGapsMenuitem_actionPerformed(ActionEvent e)
3027 viewport.setPadGaps(padGapsMenuitem.isSelected());
3028 viewport.firePropertyChange("alignment", null,
3029 viewport.getAlignment().getSequences());
3039 public void findMenuItem_actionPerformed(ActionEvent e)
3045 * Create a new view of the current alignment.
3048 public void newView_actionPerformed(ActionEvent e)
3050 newView(null, true);
3054 * Creates and shows a new view of the current alignment.
3057 * title of newly created view; if null, one will be generated
3058 * @param copyAnnotation
3059 * if true then duplicate all annnotation, groups and settings
3060 * @return new alignment panel, already displayed.
3062 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
3065 * Create a new AlignmentPanel (with its own, new Viewport)
3067 AlignmentPanel newap = new jalview.project.Jalview2XML()
3068 .copyAlignPanel(alignPanel);
3069 if (!copyAnnotation)
3072 * remove all groups and annotation except for the automatic stuff
3074 newap.av.getAlignment().deleteAllGroups();
3075 newap.av.getAlignment().deleteAllAnnotations(false);
3078 newap.av.setGatherViewsHere(false);
3080 if (viewport.getViewName() == null)
3082 viewport.setViewName(MessageManager
3083 .getString("label.view_name_original"));
3087 * Views share the same edits undo and redo stacks
3089 newap.av.setHistoryList(viewport.getHistoryList());
3090 newap.av.setRedoList(viewport.getRedoList());
3093 * copy any visualisation settings that are not saved in the project
3095 newap.av.setColourAppliesToAllGroups(
3096 viewport.getColourAppliesToAllGroups());
3099 * Views share the same mappings; need to deregister any new mappings
3100 * created by copyAlignPanel, and register the new reference to the shared
3103 newap.av.replaceMappings(viewport.getAlignment());
3106 * start up cDNA consensus (if applicable) now mappings are in place
3108 if (newap.av.initComplementConsensus())
3110 newap.refresh(true); // adjust layout of annotations
3113 newap.av.setViewName(getNewViewName(viewTitle));
3115 addAlignmentPanel(newap, true);
3116 newap.alignmentChanged();
3118 if (alignPanels.size() == 2)
3120 viewport.setGatherViewsHere(true);
3122 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
3127 * Make a new name for the view, ensuring it is unique within the current
3128 * sequenceSetId. (This used to be essential for Jalview Project archives, but
3129 * these now use viewId. Unique view names are still desirable for usability.)
3134 protected String getNewViewName(String viewTitle)
3136 int index = Desktop.getViewCount(viewport.getSequenceSetId());
3137 boolean addFirstIndex = false;
3138 if (viewTitle == null || viewTitle.trim().length() == 0)
3140 viewTitle = MessageManager.getString("action.view");
3141 addFirstIndex = true;
3145 index = 1;// we count from 1 if given a specific name
3147 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
3149 List<Component> comps = PaintRefresher.components
3150 .get(viewport.getSequenceSetId());
3152 List<String> existingNames = getExistingViewNames(comps);
3154 while (existingNames.contains(newViewName))
3156 newViewName = viewTitle + " " + (++index);
3162 * Returns a list of distinct view names found in the given list of
3163 * components. View names are held on the viewport of an AlignmentPanel.
3168 protected List<String> getExistingViewNames(List<Component> comps)
3170 List<String> existingNames = new ArrayList<>();
3171 for (Component comp : comps)
3173 if (comp instanceof AlignmentPanel)
3175 AlignmentPanel ap = (AlignmentPanel) comp;
3176 if (!existingNames.contains(ap.av.getViewName()))
3178 existingNames.add(ap.av.getViewName());
3182 return existingNames;
3186 * Explode tabbed views into separate windows.
3189 public void expandViews_actionPerformed(ActionEvent e)
3191 Desktop.explodeViews(this);
3195 * Gather views in separate windows back into a tabbed presentation.
3198 public void gatherViews_actionPerformed(ActionEvent e)
3200 Desktop.instance.gatherViews(this);
3210 public void font_actionPerformed(ActionEvent e)
3212 new FontChooser(alignPanel);
3222 protected void seqLimit_actionPerformed(ActionEvent e)
3224 viewport.setShowJVSuffix(seqLimits.isSelected());
3226 alignPanel.getIdPanel().getIdCanvas()
3227 .setPreferredSize(alignPanel.calculateIdWidth());
3228 alignPanel.paintAlignment(true, false);
3232 public void idRightAlign_actionPerformed(ActionEvent e)
3234 viewport.setRightAlignIds(idRightAlign.isSelected());
3235 alignPanel.paintAlignment(false, false);
3239 public void centreColumnLabels_actionPerformed(ActionEvent e)
3241 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3242 alignPanel.paintAlignment(false, false);
3248 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3251 protected void followHighlight_actionPerformed()
3254 * Set the 'follow' flag on the Viewport (and scroll to position if now
3257 final boolean state = this.followHighlightMenuItem.getState();
3258 viewport.setFollowHighlight(state);
3261 alignPanel.scrollToPosition(viewport.getSearchResults());
3272 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3274 viewport.setColourText(colourTextMenuItem.isSelected());
3275 alignPanel.paintAlignment(false, false);
3285 public void wrapMenuItem_actionPerformed(ActionEvent e)
3287 scaleAbove.setVisible(wrapMenuItem.isSelected());
3288 scaleLeft.setVisible(wrapMenuItem.isSelected());
3289 scaleRight.setVisible(wrapMenuItem.isSelected());
3290 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3291 alignPanel.updateLayout();
3295 public void showAllSeqs_actionPerformed(ActionEvent e)
3297 viewport.showAllHiddenSeqs();
3301 public void showAllColumns_actionPerformed(ActionEvent e)
3303 viewport.showAllHiddenColumns();
3304 alignPanel.paintAlignment(true, true);
3305 viewport.sendSelection();
3309 public void hideSelSequences_actionPerformed(ActionEvent e)
3311 viewport.hideAllSelectedSeqs();
3315 * called by key handler and the hide all/show all menu items
3320 protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3323 boolean hide = false;
3324 SequenceGroup sg = viewport.getSelectionGroup();
3325 if (!toggleSeqs && !toggleCols)
3327 // Hide everything by the current selection - this is a hack - we do the
3328 // invert and then hide
3329 // first check that there will be visible columns after the invert.
3330 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3331 && sg.getStartRes() <= sg.getEndRes()))
3333 // now invert the sequence set, if required - empty selection implies
3334 // that no hiding is required.
3337 invertSequenceMenuItem_actionPerformed(null);
3338 sg = viewport.getSelectionGroup();
3342 viewport.expandColSelection(sg, true);
3343 // finally invert the column selection and get the new sequence
3345 invertColSel_actionPerformed(null);
3352 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3354 hideSelSequences_actionPerformed(null);
3357 else if (!(toggleCols && viewport.hasSelectedColumns()))
3359 showAllSeqs_actionPerformed(null);
3365 if (viewport.hasSelectedColumns())
3367 hideSelColumns_actionPerformed(null);
3370 viewport.setSelectionGroup(sg);
3375 showAllColumns_actionPerformed(null);
3384 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3385 * event.ActionEvent)
3388 public void hideAllButSelection_actionPerformed(ActionEvent e)
3390 toggleHiddenRegions(false, false);
3391 viewport.sendSelection();
3398 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3402 public void hideAllSelection_actionPerformed(ActionEvent e)
3404 SequenceGroup sg = viewport.getSelectionGroup();
3405 viewport.expandColSelection(sg, false);
3406 viewport.hideAllSelectedSeqs();
3407 viewport.hideSelectedColumns();
3408 alignPanel.updateLayout();
3409 alignPanel.paintAlignment(true, true);
3410 viewport.sendSelection();
3417 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3421 public void showAllhidden_actionPerformed(ActionEvent e)
3423 viewport.showAllHiddenColumns();
3424 viewport.showAllHiddenSeqs();
3425 alignPanel.paintAlignment(true, true);
3426 viewport.sendSelection();
3430 public void hideSelColumns_actionPerformed(ActionEvent e)
3432 viewport.hideSelectedColumns();
3433 alignPanel.updateLayout();
3434 alignPanel.paintAlignment(true, true);
3435 viewport.sendSelection();
3439 public void hiddenMarkers_actionPerformed(ActionEvent e)
3441 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3452 protected void scaleAbove_actionPerformed(ActionEvent e)
3454 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3455 alignPanel.updateLayout();
3456 alignPanel.paintAlignment(true, false);
3466 protected void scaleLeft_actionPerformed(ActionEvent e)
3468 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3469 alignPanel.updateLayout();
3470 alignPanel.paintAlignment(true, false);
3480 protected void scaleRight_actionPerformed(ActionEvent e)
3482 viewport.setScaleRightWrapped(scaleRight.isSelected());
3483 alignPanel.updateLayout();
3484 alignPanel.paintAlignment(true, false);
3494 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3496 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3497 alignPanel.paintAlignment(false, false);
3507 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3509 viewport.setShowText(viewTextMenuItem.isSelected());
3510 alignPanel.paintAlignment(false, false);
3520 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3522 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3523 alignPanel.paintAlignment(false, false);
3526 public FeatureSettings featureSettings;
3529 public FeatureSettingsControllerI getFeatureSettingsUI()
3531 return featureSettings;
3535 public void featureSettings_actionPerformed(ActionEvent e)
3537 showFeatureSettingsUI();
3541 public FeatureSettingsControllerI showFeatureSettingsUI()
3543 if (featureSettings != null)
3545 featureSettings.closeOldSettings();
3546 featureSettings = null;
3548 if (!showSeqFeatures.isSelected())
3550 // make sure features are actually displayed
3551 showSeqFeatures.setSelected(true);
3552 showSeqFeatures_actionPerformed(null);
3554 featureSettings = new FeatureSettings(this);
3555 return featureSettings;
3559 * Set or clear 'Show Sequence Features'
3565 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3567 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3568 alignPanel.paintAlignment(true, true);
3572 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3573 * the annotations panel as a whole.
3575 * The options to show/hide all annotations should be enabled when the panel
3576 * is shown, and disabled when the panel is hidden.
3581 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3583 final boolean setVisible = annotationPanelMenuItem.isSelected();
3584 viewport.setShowAnnotation(setVisible);
3585 this.showAllSeqAnnotations.setEnabled(setVisible);
3586 this.hideAllSeqAnnotations.setEnabled(setVisible);
3587 this.showAllAlAnnotations.setEnabled(setVisible);
3588 this.hideAllAlAnnotations.setEnabled(setVisible);
3589 alignPanel.updateLayout();
3593 public void alignmentProperties()
3596 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3599 String content = MessageManager.formatMessage("label.html_content",
3601 { contents.toString() });
3604 if (Platform.isJS())
3606 JLabel textLabel = new JLabel();
3607 textLabel.setText(content);
3608 textLabel.setBackground(Color.WHITE);
3610 pane = new JPanel(new BorderLayout());
3611 ((JPanel) pane).setOpaque(true);
3612 pane.setBackground(Color.WHITE);
3613 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3622 JEditorPane editPane = new JEditorPane("text/html", "");
3623 editPane.setEditable(false);
3624 editPane.setText(content);
3628 JInternalFrame frame = new JInternalFrame();
3630 frame.getContentPane().add(new JScrollPane(pane));
3632 Desktop.addInternalFrame(frame, MessageManager
3633 .formatMessage("label.alignment_properties", new Object[]
3634 { getTitle() }), 500, 400);
3644 public void overviewMenuItem_actionPerformed(ActionEvent e)
3646 if (alignPanel.overviewPanel != null)
3651 JInternalFrame frame = new JInternalFrame();
3652 final OverviewPanel overview = new OverviewPanel(alignPanel);
3653 frame.setContentPane(overview);
3654 Desktop.addInternalFrame(frame, MessageManager
3655 .formatMessage("label.overview_params", new Object[]
3656 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3659 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3660 frame.addInternalFrameListener(
3661 new javax.swing.event.InternalFrameAdapter()
3664 public void internalFrameClosed(
3665 javax.swing.event.InternalFrameEvent evt)
3668 alignPanel.setOverviewPanel(null);
3671 if (getKeyListeners().length > 0)
3673 frame.addKeyListener(getKeyListeners()[0]);
3676 alignPanel.setOverviewPanel(overview);
3680 public void textColour_actionPerformed()
3682 new TextColourChooser().chooseColour(alignPanel, null);
3686 * public void covariationColour_actionPerformed() {
3688 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3692 public void annotationColour_actionPerformed()
3694 new AnnotationColourChooser(viewport, alignPanel);
3698 public void annotationColumn_actionPerformed(ActionEvent e)
3700 new AnnotationColumnChooser(viewport, alignPanel);
3704 * Action on the user checking or unchecking the option to apply the selected
3705 * colour scheme to all groups. If unchecked, groups may have their own
3706 * independent colour schemes.
3711 public void applyToAllGroups_actionPerformed(boolean selected)
3713 viewport.setColourAppliesToAllGroups(selected);
3717 * Action on user selecting a colour from the colour menu
3720 * the name (not the menu item label!) of the colour scheme
3723 public void changeColour_actionPerformed(String name)
3726 * 'User Defined' opens a panel to configure or load a
3727 * user-defined colour scheme
3729 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3731 new UserDefinedColours(alignPanel);
3736 * otherwise set the chosen colour scheme (or null for 'None')
3738 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3740 viewport.getAlignment(), viewport.getHiddenRepSequences());
3745 * Actions on setting or changing the alignment colour scheme
3750 public void changeColour(ColourSchemeI cs)
3752 // TODO: pull up to controller method
3753 ColourMenuHelper.setColourSelected(colourMenu, cs);
3755 viewport.setGlobalColourScheme(cs);
3757 alignPanel.paintAlignment(true, true);
3761 * Show the PID threshold slider panel
3764 protected void modifyPID_actionPerformed()
3766 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3767 alignPanel.getViewName());
3768 SliderPanel.showPIDSlider();
3772 * Show the Conservation slider panel
3775 protected void modifyConservation_actionPerformed()
3777 SliderPanel.setConservationSlider(alignPanel,
3778 viewport.getResidueShading(), alignPanel.getViewName());
3779 SliderPanel.showConservationSlider();
3783 * Action on selecting or deselecting (Colour) By Conservation
3786 public void conservationMenuItem_actionPerformed(boolean selected)
3788 modifyConservation.setEnabled(selected);
3789 viewport.setConservationSelected(selected);
3790 viewport.getResidueShading().setConservationApplied(selected);
3792 changeColour(viewport.getGlobalColourScheme());
3795 modifyConservation_actionPerformed();
3799 SliderPanel.hideConservationSlider();
3804 * Action on selecting or deselecting (Colour) Above PID Threshold
3807 public void abovePIDThreshold_actionPerformed(boolean selected)
3809 modifyPID.setEnabled(selected);
3810 viewport.setAbovePIDThreshold(selected);
3813 viewport.getResidueShading().setThreshold(0,
3814 viewport.isIgnoreGapsConsensus());
3817 changeColour(viewport.getGlobalColourScheme());
3820 modifyPID_actionPerformed();
3824 SliderPanel.hidePIDSlider();
3835 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3837 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3838 AlignmentSorter.sortByPID(viewport.getAlignment(),
3839 viewport.getAlignment().getSequenceAt(0));
3840 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3841 viewport.getAlignment()));
3842 alignPanel.paintAlignment(true, false);
3852 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3854 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3855 AlignmentSorter.sortByID(viewport.getAlignment());
3857 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3858 alignPanel.paintAlignment(true, false);
3868 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3870 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3871 AlignmentSorter.sortByLength(viewport.getAlignment());
3872 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3873 viewport.getAlignment()));
3874 alignPanel.paintAlignment(true, false);
3884 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3886 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3887 AlignmentSorter.sortByGroup(viewport.getAlignment());
3888 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3889 viewport.getAlignment()));
3891 alignPanel.paintAlignment(true, false);
3895 public void sortEValueMenuItem_actionPerformed(ActionEvent e)
3897 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3898 AlignmentSorter.sortByEValue(viewport.getAlignment());
3899 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3900 viewport.getAlignment()));
3901 alignPanel.paintAlignment(true, false);
3906 public void sortBitScoreMenuItem_actionPerformed(ActionEvent e)
3908 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3909 AlignmentSorter.sortByBitScore(viewport.getAlignment());
3910 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3911 viewport.getAlignment()));
3912 alignPanel.paintAlignment(true, false);
3923 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3925 new RedundancyPanel(alignPanel, this);
3935 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3937 if ((viewport.getSelectionGroup() == null)
3938 || (viewport.getSelectionGroup().getSize() < 2))
3940 JvOptionPane.showInternalMessageDialog(this,
3941 MessageManager.getString(
3942 "label.you_must_select_least_two_sequences"),
3943 MessageManager.getString("label.invalid_selection"),
3944 JvOptionPane.WARNING_MESSAGE);
3948 JInternalFrame frame = new JInternalFrame();
3949 frame.setContentPane(new PairwiseAlignPanel(viewport));
3950 Desktop.addInternalFrame(frame,
3951 MessageManager.getString("action.pairwise_alignment"), 600,
3957 public void autoCalculate_actionPerformed(ActionEvent e)
3959 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3960 if (viewport.autoCalculateConsensus)
3962 viewport.firePropertyChange("alignment", null,
3963 viewport.getAlignment().getSequences());
3968 public void sortByTreeOption_actionPerformed(ActionEvent e)
3970 viewport.sortByTree = sortByTree.isSelected();
3974 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3976 viewport.followSelection = listenToViewSelections.isSelected();
3980 * Constructs a tree panel and adds it to the desktop
3983 * tree type (NJ or AV)
3985 * name of score model used to compute the tree
3987 * parameters for the distance or similarity calculation
3989 void newTreePanel(String type, String modelName,
3990 SimilarityParamsI options)
3992 String frameTitle = "";
3995 boolean onSelection = false;
3996 if (viewport.getSelectionGroup() != null
3997 && viewport.getSelectionGroup().getSize() > 0)
3999 SequenceGroup sg = viewport.getSelectionGroup();
4001 /* Decide if the selection is a column region */
4002 for (SequenceI _s : sg.getSequences())
4004 if (_s.getLength() < sg.getEndRes())
4006 JvOptionPane.showMessageDialog(Desktop.desktop,
4007 MessageManager.getString(
4008 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
4009 MessageManager.getString(
4010 "label.sequences_selection_not_aligned"),
4011 JvOptionPane.WARNING_MESSAGE);
4020 if (viewport.getAlignment().getHeight() < 2)
4026 tp = new TreePanel(alignPanel, type, modelName, options);
4027 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
4029 frameTitle += " from ";
4031 if (viewport.getViewName() != null)
4033 frameTitle += viewport.getViewName() + " of ";
4036 frameTitle += this.title;
4038 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
4049 public void addSortByOrderMenuItem(String title,
4050 final AlignmentOrder order)
4052 final JMenuItem item = new JMenuItem(MessageManager
4053 .formatMessage("action.by_title_param", new Object[]
4056 item.addActionListener(new java.awt.event.ActionListener()
4059 public void actionPerformed(ActionEvent e)
4061 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4063 // TODO: JBPNote - have to map order entries to curent SequenceI
4065 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4067 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
4068 viewport.getAlignment()));
4070 alignPanel.paintAlignment(true, false);
4076 * Add a new sort by annotation score menu item
4079 * the menu to add the option to
4081 * the label used to retrieve scores for each sequence on the
4084 public void addSortByAnnotScoreMenuItem(JMenu sort,
4085 final String scoreLabel)
4087 final JMenuItem item = new JMenuItem(scoreLabel);
4089 item.addActionListener(new java.awt.event.ActionListener()
4092 public void actionPerformed(ActionEvent e)
4094 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4095 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4096 viewport.getAlignment());// ,viewport.getSelectionGroup());
4097 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4098 viewport.getAlignment()));
4099 alignPanel.paintAlignment(true, false);
4105 * last hash for alignment's annotation array - used to minimise cost of
4108 protected int _annotationScoreVectorHash;
4111 * search the alignment and rebuild the sort by annotation score submenu the
4112 * last alignment annotation vector hash is stored to minimize cost of
4113 * rebuilding in subsequence calls.
4117 public void buildSortByAnnotationScoresMenu()
4119 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4124 if (viewport.getAlignment().getAlignmentAnnotation()
4125 .hashCode() == _annotationScoreVectorHash)
4130 sortByAnnotScore.removeAll();
4131 Set<String> scoreSorts = new HashSet<>();
4132 for (SequenceI sqa : viewport.getAlignment().getSequences())
4134 AlignmentAnnotation[] anns = sqa.getAnnotation();
4135 for (int i = 0; anns != null && i < anns.length; i++)
4137 AlignmentAnnotation aa = anns[i];
4138 if (aa != null && aa.hasScore() && aa.sequenceRef != null)
4140 scoreSorts.add(aa.label);
4144 for (String label : scoreSorts)
4146 addSortByAnnotScoreMenuItem(sortByAnnotScore, label);
4148 sortByAnnotScore.setVisible(!scoreSorts.isEmpty());
4150 _annotationScoreVectorHash = viewport.getAlignment()
4151 .getAlignmentAnnotation().hashCode();
4155 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4156 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4157 * call. Listeners are added to remove the menu item when the treePanel is
4158 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4162 public void buildTreeSortMenu()
4164 sortByTreeMenu.removeAll();
4166 List<Component> comps = PaintRefresher.components
4167 .get(viewport.getSequenceSetId());
4168 List<TreePanel> treePanels = new ArrayList<>();
4169 for (Component comp : comps)
4171 if (comp instanceof TreePanel)
4173 treePanels.add((TreePanel) comp);
4177 if (treePanels.size() < 1)
4179 sortByTreeMenu.setVisible(false);
4183 sortByTreeMenu.setVisible(true);
4185 for (final TreePanel tp : treePanels)
4187 final JMenuItem item = new JMenuItem(tp.getTitle());
4188 item.addActionListener(new java.awt.event.ActionListener()
4191 public void actionPerformed(ActionEvent e)
4193 tp.sortByTree_actionPerformed();
4194 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4199 sortByTreeMenu.add(item);
4203 public boolean sortBy(AlignmentOrder alorder, String undoname)
4205 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4206 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4207 if (undoname != null)
4209 addHistoryItem(new OrderCommand(undoname, oldOrder,
4210 viewport.getAlignment()));
4212 alignPanel.paintAlignment(true, false);
4217 * Work out whether the whole set of sequences or just the selected set will
4218 * be submitted for multiple alignment.
4221 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4223 // Now, check we have enough sequences
4224 AlignmentView msa = null;
4226 if ((viewport.getSelectionGroup() != null)
4227 && (viewport.getSelectionGroup().getSize() > 1))
4229 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4230 // some common interface!
4232 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4233 * SequenceI[sz = seqs.getSize(false)];
4235 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4236 * seqs.getSequenceAt(i); }
4238 msa = viewport.getAlignmentView(true);
4240 else if (viewport.getSelectionGroup() != null
4241 && viewport.getSelectionGroup().getSize() == 1)
4243 int option = JvOptionPane.showConfirmDialog(this,
4244 MessageManager.getString("warn.oneseq_msainput_selection"),
4245 MessageManager.getString("label.invalid_selection"),
4246 JvOptionPane.OK_CANCEL_OPTION);
4247 if (option == JvOptionPane.OK_OPTION)
4249 msa = viewport.getAlignmentView(false);
4254 msa = viewport.getAlignmentView(false);
4260 * Decides what is submitted to a secondary structure prediction service: the
4261 * first sequence in the alignment, or in the current selection, or, if the
4262 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4263 * region or the whole alignment. (where the first sequence in the set is the
4264 * one that the prediction will be for).
4266 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4268 AlignmentView seqs = null;
4270 if ((viewport.getSelectionGroup() != null)
4271 && (viewport.getSelectionGroup().getSize() > 0))
4273 seqs = viewport.getAlignmentView(true);
4277 seqs = viewport.getAlignmentView(false);
4279 // limit sequences - JBPNote in future - could spawn multiple prediction
4281 // TODO: viewport.getAlignment().isAligned is a global state - the local
4282 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4283 if (!viewport.getAlignment().isAligned(false))
4285 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4286 // TODO: if seqs.getSequences().length>1 then should really have warned
4300 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4302 // Pick the tree file
4303 JalviewFileChooser chooser = new JalviewFileChooser(
4304 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4305 chooser.setFileView(new JalviewFileView());
4306 chooser.setDialogTitle(
4307 MessageManager.getString("label.select_newick_like_tree_file"));
4308 chooser.setToolTipText(
4309 MessageManager.getString("label.load_tree_file"));
4311 chooser.setResponseHandler(0,new Runnable()
4316 String filePath = chooser.getSelectedFile().getPath();
4317 Cache.setProperty("LAST_DIRECTORY", filePath);
4318 NewickFile fin = null;
4321 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4322 DataSourceType.FILE));
4323 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4324 } catch (Exception ex)
4326 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4328 .getString("label.problem_reading_tree_file"),
4329 JvOptionPane.WARNING_MESSAGE);
4330 ex.printStackTrace();
4332 if (fin != null && fin.hasWarningMessage())
4334 JvOptionPane.showMessageDialog(Desktop.desktop,
4335 fin.getWarningMessage(),
4336 MessageManager.getString(
4337 "label.possible_problem_with_tree_file"),
4338 JvOptionPane.WARNING_MESSAGE);
4342 chooser.showOpenDialog(this);
4345 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4347 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4350 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4351 int h, int x, int y)
4353 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4357 * Add a treeviewer for the tree extracted from a Newick file object to the
4358 * current alignment view
4365 * Associated alignment input data (or null)
4374 * @return TreePanel handle
4376 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4377 AlignmentView input, int w, int h, int x, int y)
4379 TreePanel tp = null;
4385 if (nf.getTree() != null)
4387 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4393 tp.setLocation(x, y);
4396 Desktop.addInternalFrame(tp, treeTitle, w, h);
4398 } catch (Exception ex)
4400 ex.printStackTrace();
4406 private boolean buildingMenu = false;
4409 * Generates menu items and listener event actions for web service clients
4412 public void BuildWebServiceMenu()
4414 while (buildingMenu)
4418 System.err.println("Waiting for building menu to finish.");
4420 } catch (Exception e)
4424 final AlignFrame me = this;
4425 buildingMenu = true;
4426 new Thread(new Runnable()
4431 final List<JMenuItem> legacyItems = new ArrayList<>();
4434 // System.err.println("Building ws menu again "
4435 // + Thread.currentThread());
4436 // TODO: add support for context dependent disabling of services based
4438 // alignment and current selection
4439 // TODO: add additional serviceHandle parameter to specify abstract
4441 // class independently of AbstractName
4442 // TODO: add in rediscovery GUI function to restart discoverer
4443 // TODO: group services by location as well as function and/or
4445 // object broker mechanism.
4446 final Vector<JMenu> wsmenu = new Vector<>();
4447 final IProgressIndicator af = me;
4450 * do not i18n these strings - they are hard-coded in class
4451 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4452 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4454 final JMenu msawsmenu = new JMenu("Alignment");
4455 final JMenu secstrmenu = new JMenu(
4456 "Secondary Structure Prediction");
4457 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4458 final JMenu analymenu = new JMenu("Analysis");
4459 final JMenu dismenu = new JMenu("Protein Disorder");
4460 // JAL-940 - only show secondary structure prediction services from
4461 // the legacy server
4462 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4464 Discoverer.services != null && (Discoverer.services.size() > 0))
4466 // TODO: refactor to allow list of AbstractName/Handler bindings to
4468 // stored or retrieved from elsewhere
4469 // No MSAWS used any more:
4470 // Vector msaws = null; // (Vector)
4471 // Discoverer.services.get("MsaWS");
4472 Vector<ServiceHandle> secstrpr = Discoverer.services
4474 if (secstrpr != null)
4476 // Add any secondary structure prediction services
4477 for (int i = 0, j = secstrpr.size(); i < j; i++)
4479 final ext.vamsas.ServiceHandle sh = secstrpr
4481 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4482 .getServiceClient(sh);
4483 int p = secstrmenu.getItemCount();
4484 impl.attachWSMenuEntry(secstrmenu, me);
4485 int q = secstrmenu.getItemCount();
4486 for (int litm = p; litm < q; litm++)
4488 legacyItems.add(secstrmenu.getItem(litm));
4494 // Add all submenus in the order they should appear on the web
4496 wsmenu.add(msawsmenu);
4497 wsmenu.add(secstrmenu);
4498 wsmenu.add(dismenu);
4499 wsmenu.add(analymenu);
4500 // No search services yet
4501 // wsmenu.add(seqsrchmenu);
4503 javax.swing.SwingUtilities.invokeLater(new Runnable()
4510 webService.removeAll();
4511 // first, add discovered services onto the webservices menu
4512 if (wsmenu.size() > 0)
4514 for (int i = 0, j = wsmenu.size(); i < j; i++)
4516 webService.add(wsmenu.get(i));
4521 webService.add(me.webServiceNoServices);
4523 // TODO: move into separate menu builder class.
4524 boolean new_sspred = false;
4525 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4527 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4528 if (jws2servs != null)
4530 if (jws2servs.hasServices())
4532 jws2servs.attachWSMenuEntry(webService, me);
4533 for (ServiceWithParameters sv : jws2servs.getServices())
4535 if (sv.getName().toLowerCase().contains("jpred"))
4537 for (JMenuItem jmi : legacyItems)
4539 jmi.setVisible(false);
4545 if (jws2servs.isRunning())
4547 JMenuItem tm = new JMenuItem(
4548 "Still discovering JABA Services");
4549 tm.setEnabled(false);
4554 build_urlServiceMenu(me.webService);
4557 // TODO Mateusz - follow pattern for adding web service
4558 // JMenuItems for slivka-based services
4560 SlivkaWSDiscoverer slivkaDiscoverer = SlivkaWSDiscoverer.getInstance();
4561 if (slivkaDiscoverer.hasServices())
4563 slivkaDiscoverer.attachWSMenuEntry(webService, me);
4565 if (slivkaDiscoverer.isRunning())
4568 JMenuItem tm = new JMenuItem(
4569 "Still discovering Slivka Services");
4570 tm.setEnabled(false);
4578 build_fetchdbmenu(webService);
4579 for (JMenu item : wsmenu)
4581 if (item.getItemCount() == 0)
4583 item.setEnabled(false);
4587 item.setEnabled(true);
4590 } catch (Exception e)
4593 "Exception during web service menu building process.",
4598 } catch (Exception e)
4601 buildingMenu = false;
4608 * construct any groupURL type service menu entries.
4612 protected void build_urlServiceMenu(JMenu webService)
4614 // TODO: remove this code when 2.7 is released
4615 // DEBUG - alignmentView
4617 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4618 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4620 * @Override public void actionPerformed(ActionEvent e) {
4621 * jalview.datamodel.AlignmentView
4622 * .testSelectionViews(af.viewport.getAlignment(),
4623 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4625 * }); webService.add(testAlView);
4627 // TODO: refactor to RestClient discoverer and merge menu entries for
4628 // rest-style services with other types of analysis/calculation service
4629 // SHmmr test client - still being implemented.
4630 // DEBUG - alignmentView
4632 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4635 client.attachWSMenuEntry(
4636 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4642 * Searches the alignment sequences for xRefs and builds the Show
4643 * Cross-References menu (formerly called Show Products), with database
4644 * sources for which cross-references are found (protein sources for a
4645 * nucleotide alignment and vice versa)
4647 * @return true if Show Cross-references menu should be enabled
4649 public boolean canShowProducts()
4651 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4652 AlignmentI dataset = viewport.getAlignment().getDataset();
4654 showProducts.removeAll();
4655 final boolean dna = viewport.getAlignment().isNucleotide();
4657 if (seqs == null || seqs.length == 0)
4659 // nothing to see here.
4663 boolean showp = false;
4666 List<String> ptypes = new CrossRef(seqs, dataset)
4667 .findXrefSourcesForSequences(dna);
4669 for (final String source : ptypes)
4672 final AlignFrame af = this;
4673 JMenuItem xtype = new JMenuItem(source);
4674 xtype.addActionListener(new ActionListener()
4677 public void actionPerformed(ActionEvent e)
4679 showProductsFor(af.viewport.getSequenceSelection(), dna,
4683 showProducts.add(xtype);
4685 showProducts.setVisible(showp);
4686 showProducts.setEnabled(showp);
4687 } catch (Exception e)
4690 "canShowProducts threw an exception - please report to help@jalview.org",
4698 * Finds and displays cross-references for the selected sequences (protein
4699 * products for nucleotide sequences, dna coding sequences for peptides).
4702 * the sequences to show cross-references for
4704 * true if from a nucleotide alignment (so showing proteins)
4706 * the database to show cross-references for
4708 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4709 final String source)
4711 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4716 * Construct and display a new frame containing the translation of this
4717 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4720 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4722 AlignmentI al = null;
4725 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4727 al = dna.translateCdna(codeTable);
4728 } catch (Exception ex)
4730 jalview.bin.Cache.log.error(
4731 "Exception during translation. Please report this !", ex);
4732 final String msg = MessageManager.getString(
4733 "label.error_when_translating_sequences_submit_bug_report");
4734 final String errorTitle = MessageManager
4735 .getString("label.implementation_error")
4736 + MessageManager.getString("label.translation_failed");
4737 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4738 JvOptionPane.ERROR_MESSAGE);
4741 if (al == null || al.getHeight() == 0)
4743 final String msg = MessageManager.getString(
4744 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4745 final String errorTitle = MessageManager
4746 .getString("label.translation_failed");
4747 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4748 JvOptionPane.WARNING_MESSAGE);
4752 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4753 af.setFileFormat(this.currentFileFormat);
4754 final String newTitle = MessageManager
4755 .formatMessage("label.translation_of_params", new Object[]
4756 { this.getTitle(), codeTable.getId() });
4757 af.setTitle(newTitle);
4758 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4760 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4761 viewport.openSplitFrame(af, new Alignment(seqs));
4765 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4772 * Set the file format
4776 public void setFileFormat(FileFormatI format)
4778 this.currentFileFormat = format;
4782 * Try to load a features file onto the alignment.
4785 * contents or path to retrieve file or a File object
4787 * access mode of file (see jalview.io.AlignFile)
4788 * @return true if features file was parsed correctly.
4790 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4793 return avc.parseFeaturesFile(file, sourceType,
4794 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4799 public void refreshFeatureUI(boolean enableIfNecessary)
4801 // note - currently this is only still here rather than in the controller
4802 // because of the featureSettings hard reference that is yet to be
4804 if (enableIfNecessary)
4806 viewport.setShowSequenceFeatures(true);
4807 showSeqFeatures.setSelected(true);
4813 public void dragEnter(DropTargetDragEvent evt)
4818 public void dragExit(DropTargetEvent evt)
4823 public void dragOver(DropTargetDragEvent evt)
4828 public void dropActionChanged(DropTargetDragEvent evt)
4833 public void drop(DropTargetDropEvent evt)
4835 // JAL-1552 - acceptDrop required before getTransferable call for
4836 // Java's Transferable for native dnd
4837 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4838 Transferable t = evt.getTransferable();
4840 final AlignFrame thisaf = this;
4841 final List<Object> files = new ArrayList<>();
4842 List<DataSourceType> protocols = new ArrayList<>();
4846 Desktop.transferFromDropTarget(files, protocols, evt, t);
4847 } catch (Exception e)
4849 e.printStackTrace();
4853 new Thread(new Runnable()
4860 // check to see if any of these files have names matching sequences
4863 SequenceIdMatcher idm = new SequenceIdMatcher(
4864 viewport.getAlignment().getSequencesArray());
4866 * Object[] { String,SequenceI}
4868 ArrayList<Object[]> filesmatched = new ArrayList<>();
4869 ArrayList<Object> filesnotmatched = new ArrayList<>();
4870 for (int i = 0; i < files.size(); i++)
4873 Object file = files.get(i);
4874 String fileName = file.toString();
4876 DataSourceType protocol = (file instanceof File
4877 ? DataSourceType.FILE
4878 : FormatAdapter.checkProtocol(fileName));
4879 if (protocol == DataSourceType.FILE)
4882 if (file instanceof File) {
4884 Platform.cacheFileData(fl);
4886 fl = new File(fileName);
4888 pdbfn = fl.getName();
4890 else if (protocol == DataSourceType.URL)
4892 URL url = new URL(fileName);
4893 pdbfn = url.getFile();
4895 if (pdbfn.length() > 0)
4897 // attempt to find a match in the alignment
4898 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4899 int l = 0, c = pdbfn.indexOf(".");
4900 while (mtch == null && c != -1)
4905 } while ((c = pdbfn.indexOf(".", l)) > l);
4908 pdbfn = pdbfn.substring(0, l);
4910 mtch = idm.findAllIdMatches(pdbfn);
4917 type = new IdentifyFile().identify(file, protocol);
4918 } catch (Exception ex)
4922 if (type != null && type.isStructureFile())
4924 filesmatched.add(new Object[] { file, protocol, mtch });
4928 // File wasn't named like one of the sequences or wasn't a PDB
4930 filesnotmatched.add(file);
4934 if (filesmatched.size() > 0)
4936 boolean autoAssociate = Cache
4937 .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4940 String msg = MessageManager.formatMessage(
4941 "label.automatically_associate_structure_files_with_sequences_same_name",
4943 { Integer.valueOf(filesmatched.size())
4945 String ttl = MessageManager.getString(
4946 "label.automatically_associate_structure_files_by_name");
4947 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4948 ttl, JvOptionPane.YES_NO_OPTION);
4949 autoAssociate = choice == JvOptionPane.YES_OPTION;
4953 for (Object[] fm : filesmatched)
4955 // try and associate
4956 // TODO: may want to set a standard ID naming formalism for
4957 // associating PDB files which have no IDs.
4958 for (SequenceI toassoc : (SequenceI[]) fm[2])
4960 PDBEntry pe = new AssociatePdbFileWithSeq()
4961 .associatePdbWithSeq(fm[0].toString(),
4962 (DataSourceType) fm[1], toassoc, false,
4966 System.err.println("Associated file : "
4967 + (fm[0].toString()) + " with "
4968 + toassoc.getDisplayId(true));
4972 // TODO: do we need to update overview ? only if features are
4974 alignPanel.paintAlignment(true, false);
4980 * add declined structures as sequences
4982 for (Object[] o : filesmatched)
4984 filesnotmatched.add(o[0]);
4988 if (filesnotmatched.size() > 0)
4990 if (assocfiles > 0 && (Cache.getDefault(
4991 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4992 || JvOptionPane.showConfirmDialog(thisaf,
4993 "<html>" + MessageManager.formatMessage(
4994 "label.ignore_unmatched_dropped_files_info",
4997 filesnotmatched.size())
5000 MessageManager.getString(
5001 "label.ignore_unmatched_dropped_files"),
5002 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
5006 for (Object fn : filesnotmatched)
5008 loadJalviewDataFile(fn, null, null, null);
5012 } catch (Exception ex)
5014 ex.printStackTrace();
5022 * Attempt to load a "dropped" file or URL string, by testing in turn for
5024 * <li>an Annotation file</li>
5025 * <li>a JNet file</li>
5026 * <li>a features file</li>
5027 * <li>else try to interpret as an alignment file</li>
5031 * either a filename or a URL string.
5032 * @throws InterruptedException
5033 * @throws IOException
5035 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
5036 FileFormatI format, SequenceI assocSeq)
5038 // BH 2018 was String file
5041 if (sourceType == null)
5043 sourceType = FormatAdapter.checkProtocol(file);
5045 // if the file isn't identified, or not positively identified as some
5046 // other filetype (PFAM is default unidentified alignment file type) then
5047 // try to parse as annotation.
5048 boolean isAnnotation = (format == null
5049 || FileFormat.Pfam.equals(format))
5050 ? new AnnotationFile().annotateAlignmentView(viewport,
5056 // first see if its a T-COFFEE score file
5057 TCoffeeScoreFile tcf = null;
5060 tcf = new TCoffeeScoreFile(file, sourceType);
5063 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5067 new TCoffeeColourScheme(viewport.getAlignment()));
5068 isAnnotation = true;
5069 setStatus(MessageManager.getString(
5070 "label.successfully_pasted_tcoffee_scores_to_alignment"));
5074 // some problem - if no warning its probable that the ID matching
5075 // process didn't work
5076 JvOptionPane.showMessageDialog(Desktop.desktop,
5077 tcf.getWarningMessage() == null
5078 ? MessageManager.getString(
5079 "label.check_file_matches_sequence_ids_alignment")
5080 : tcf.getWarningMessage(),
5081 MessageManager.getString(
5082 "label.problem_reading_tcoffee_score_file"),
5083 JvOptionPane.WARNING_MESSAGE);
5090 } catch (Exception x)
5093 "Exception when processing data source as T-COFFEE score file",
5099 // try to see if its a JNet 'concise' style annotation file *before*
5101 // try to parse it as a features file
5104 format = new IdentifyFile().identify(file, sourceType);
5106 if (FileFormat.ScoreMatrix == format)
5108 ScoreMatrixFile sm = new ScoreMatrixFile(
5109 new FileParse(file, sourceType));
5111 // todo: i18n this message
5112 setStatus(MessageManager.formatMessage(
5113 "label.successfully_loaded_matrix",
5114 sm.getMatrixName()));
5116 else if (FileFormat.Jnet.equals(format))
5118 JPredFile predictions = new JPredFile(file, sourceType);
5119 new JnetAnnotationMaker();
5120 JnetAnnotationMaker.add_annotation(predictions,
5121 viewport.getAlignment(), 0, false);
5122 viewport.getAlignment().setupJPredAlignment();
5123 isAnnotation = true;
5125 // else if (IdentifyFile.FeaturesFile.equals(format))
5126 else if (FileFormat.Features.equals(format))
5128 if (parseFeaturesFile(file, sourceType))
5130 SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
5131 if (splitFrame != null)
5133 splitFrame.repaint();
5137 alignPanel.paintAlignment(true, true);
5143 new FileLoader().LoadFile(viewport, file, sourceType, format);
5149 alignPanel.adjustAnnotationHeight();
5150 viewport.updateSequenceIdColours();
5151 buildSortByAnnotationScoresMenu();
5152 alignPanel.paintAlignment(true, true);
5154 } catch (Exception ex)
5156 ex.printStackTrace();
5157 } catch (OutOfMemoryError oom)
5162 } catch (Exception x)
5167 + (sourceType != null
5168 ? (sourceType == DataSourceType.PASTE
5170 : "using " + sourceType + " from "
5174 ? "(parsing as '" + format + "' file)"
5176 oom, Desktop.desktop);
5181 * Method invoked by the ChangeListener on the tabbed pane, in other words
5182 * when a different tabbed pane is selected by the user or programmatically.
5185 public void tabSelectionChanged(int index)
5189 alignPanel = alignPanels.get(index);
5190 viewport = alignPanel.av;
5191 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5192 setMenusFromViewport(viewport);
5193 if (featureSettings != null && featureSettings.isOpen()
5194 && featureSettings.fr.getViewport() != viewport)
5196 if (viewport.isShowSequenceFeatures())
5198 // refresh the featureSettings to reflect UI change
5199 showFeatureSettingsUI();
5203 // close feature settings for this view.
5204 featureSettings.close();
5211 * 'focus' any colour slider that is open to the selected viewport
5213 if (viewport.getConservationSelected())
5215 SliderPanel.setConservationSlider(alignPanel,
5216 viewport.getResidueShading(), alignPanel.getViewName());
5220 SliderPanel.hideConservationSlider();
5222 if (viewport.getAbovePIDThreshold())
5224 SliderPanel.setPIDSliderSource(alignPanel,
5225 viewport.getResidueShading(), alignPanel.getViewName());
5229 SliderPanel.hidePIDSlider();
5233 * If there is a frame linked to this one in a SplitPane, switch it to the
5234 * same view tab index. No infinite recursion of calls should happen, since
5235 * tabSelectionChanged() should not get invoked on setting the selected
5236 * index to an unchanged value. Guard against setting an invalid index
5237 * before the new view peer tab has been created.
5239 final AlignViewportI peer = viewport.getCodingComplement();
5242 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
5243 .getAlignPanel().alignFrame;
5244 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5246 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5252 * On right mouse click on view tab, prompt for and set new view name.
5255 public void tabbedPane_mousePressed(MouseEvent e)
5257 if (e.isPopupTrigger())
5259 String msg = MessageManager.getString("label.enter_view_name");
5260 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
5261 String reply = JvOptionPane.showInputDialog(msg, ttl);
5265 viewport.setViewName(reply);
5266 // TODO warn if reply is in getExistingViewNames()?
5267 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5272 public AlignViewport getCurrentView()
5278 * Open the dialog for regex description parsing.
5281 protected void extractScores_actionPerformed(ActionEvent e)
5283 ParseProperties pp = new jalview.analysis.ParseProperties(
5284 viewport.getAlignment());
5285 // TODO: verify regex and introduce GUI dialog for version 2.5
5286 // if (pp.getScoresFromDescription("col", "score column ",
5287 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5289 if (pp.getScoresFromDescription("description column",
5290 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5292 buildSortByAnnotationScoresMenu();
5300 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5304 protected void showDbRefs_actionPerformed(ActionEvent e)
5306 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5312 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5316 protected void showNpFeats_actionPerformed(ActionEvent e)
5318 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5322 * find the viewport amongst the tabs in this alignment frame and close that
5327 public boolean closeView(AlignViewportI av)
5331 this.closeMenuItem_actionPerformed(false);
5334 Component[] comp = tabbedPane.getComponents();
5335 for (int i = 0; comp != null && i < comp.length; i++)
5337 if (comp[i] instanceof AlignmentPanel)
5339 if (((AlignmentPanel) comp[i]).av == av)
5342 closeView((AlignmentPanel) comp[i]);
5350 protected void build_fetchdbmenu(JMenu webService)
5352 // Temporary hack - DBRef Fetcher always top level ws entry.
5353 // TODO We probably want to store a sequence database checklist in
5354 // preferences and have checkboxes.. rather than individual sources selected
5356 final JMenu rfetch = new JMenu(
5357 MessageManager.getString("action.fetch_db_references"));
5358 rfetch.setToolTipText(MessageManager.getString(
5359 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5360 webService.add(rfetch);
5362 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5363 MessageManager.getString("option.trim_retrieved_seqs"));
5364 trimrs.setToolTipText(
5365 MessageManager.getString("label.trim_retrieved_sequences"));
5367 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5368 trimrs.addActionListener(new ActionListener()
5371 public void actionPerformed(ActionEvent e)
5373 trimrs.setSelected(trimrs.isSelected());
5374 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5375 Boolean.valueOf(trimrs.isSelected()).toString());
5379 JMenuItem fetchr = new JMenuItem(
5380 MessageManager.getString("label.standard_databases"));
5381 fetchr.setToolTipText(
5382 MessageManager.getString("label.fetch_embl_uniprot"));
5383 fetchr.addActionListener(new ActionListener()
5387 public void actionPerformed(ActionEvent e)
5389 new Thread(new Runnable()
5394 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5395 .getAlignment().isNucleotide();
5396 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5397 alignPanel.av.getSequenceSelection(),
5398 alignPanel.alignFrame, null,
5399 alignPanel.alignFrame.featureSettings, isNucleotide);
5400 dbRefFetcher.addListener(new FetchFinishedListenerI()
5403 public void finished()
5406 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5407 .getFeatureSettingsModels())
5410 alignPanel.av.mergeFeaturesStyle(srcSettings);
5412 AlignFrame.this.setMenusForViewport();
5415 dbRefFetcher.fetchDBRefs(false);
5423 new Thread(new Runnable()
5428 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5429 .getSequenceFetcherSingleton();
5430 javax.swing.SwingUtilities.invokeLater(new Runnable()
5435 String[] dbclasses = sf.getNonAlignmentSources();
5436 List<DbSourceProxy> otherdb;
5437 JMenu dfetch = new JMenu();
5438 JMenu ifetch = new JMenu();
5439 JMenuItem fetchr = null;
5440 int comp = 0, icomp = 0, mcomp = 15;
5441 String mname = null;
5443 for (String dbclass : dbclasses)
5445 otherdb = sf.getSourceProxy(dbclass);
5446 // add a single entry for this class, or submenu allowing 'fetch
5448 if (otherdb == null || otherdb.size() < 1)
5454 mname = "From " + dbclass;
5456 if (otherdb.size() == 1)
5458 final DbSourceProxy[] dassource = otherdb
5459 .toArray(new DbSourceProxy[0]);
5460 DbSourceProxy src = otherdb.get(0);
5461 fetchr = new JMenuItem(src.getDbSource());
5462 fetchr.addActionListener(new ActionListener()
5466 public void actionPerformed(ActionEvent e)
5468 new Thread(new Runnable()
5474 boolean isNucleotide = alignPanel.alignFrame
5475 .getViewport().getAlignment()
5477 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5478 alignPanel.av.getSequenceSelection(),
5479 alignPanel.alignFrame, dassource,
5480 alignPanel.alignFrame.featureSettings,
5483 .addListener(new FetchFinishedListenerI()
5486 public void finished()
5488 FeatureSettingsModelI srcSettings = dassource[0]
5489 .getFeatureColourScheme();
5490 alignPanel.av.mergeFeaturesStyle(
5492 AlignFrame.this.setMenusForViewport();
5495 dbRefFetcher.fetchDBRefs(false);
5501 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5502 MessageManager.formatMessage(
5503 "label.fetch_retrieve_from", new Object[]
5504 { src.getDbName() })));
5510 final DbSourceProxy[] dassource = otherdb
5511 .toArray(new DbSourceProxy[0]);
5513 DbSourceProxy src = otherdb.get(0);
5514 fetchr = new JMenuItem(MessageManager
5515 .formatMessage("label.fetch_all_param", new Object[]
5516 { src.getDbSource() }));
5517 fetchr.addActionListener(new ActionListener()
5520 public void actionPerformed(ActionEvent e)
5522 new Thread(new Runnable()
5528 boolean isNucleotide = alignPanel.alignFrame
5529 .getViewport().getAlignment()
5531 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5532 alignPanel.av.getSequenceSelection(),
5533 alignPanel.alignFrame, dassource,
5534 alignPanel.alignFrame.featureSettings,
5537 .addListener(new FetchFinishedListenerI()
5540 public void finished()
5542 AlignFrame.this.setMenusForViewport();
5545 dbRefFetcher.fetchDBRefs(false);
5551 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5552 MessageManager.formatMessage(
5553 "label.fetch_retrieve_from_all_sources",
5555 { Integer.valueOf(otherdb.size())
5557 src.getDbSource(), src.getDbName() })));
5560 // and then build the rest of the individual menus
5561 ifetch = new JMenu(MessageManager.formatMessage(
5562 "label.source_from_db_source", new Object[]
5563 { src.getDbSource() }));
5565 String imname = null;
5567 for (DbSourceProxy sproxy : otherdb)
5569 String dbname = sproxy.getDbName();
5570 String sname = dbname.length() > 5
5571 ? dbname.substring(0, 5) + "..."
5573 String msname = dbname.length() > 10
5574 ? dbname.substring(0, 10) + "..."
5578 imname = MessageManager
5579 .formatMessage("label.from_msname", new Object[]
5582 fetchr = new JMenuItem(msname);
5583 final DbSourceProxy[] dassrc = { sproxy };
5584 fetchr.addActionListener(new ActionListener()
5588 public void actionPerformed(ActionEvent e)
5590 new Thread(new Runnable()
5596 boolean isNucleotide = alignPanel.alignFrame
5597 .getViewport().getAlignment()
5599 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5600 alignPanel.av.getSequenceSelection(),
5601 alignPanel.alignFrame, dassrc,
5602 alignPanel.alignFrame.featureSettings,
5605 .addListener(new FetchFinishedListenerI()
5608 public void finished()
5610 AlignFrame.this.setMenusForViewport();
5613 dbRefFetcher.fetchDBRefs(false);
5619 fetchr.setToolTipText(
5620 "<html>" + MessageManager.formatMessage(
5621 "label.fetch_retrieve_from", new Object[]
5625 if (++icomp >= mcomp || i == (otherdb.size()))
5627 ifetch.setText(MessageManager.formatMessage(
5628 "label.source_to_target", imname, sname));
5630 ifetch = new JMenu();
5638 if (comp >= mcomp || dbi >= (dbclasses.length))
5640 dfetch.setText(MessageManager.formatMessage(
5641 "label.source_to_target", mname, dbclass));
5643 dfetch = new JMenu();
5656 * Left justify the whole alignment.
5659 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5661 AlignmentI al = viewport.getAlignment();
5663 viewport.firePropertyChange("alignment", null, al);
5667 * Right justify the whole alignment.
5670 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5672 AlignmentI al = viewport.getAlignment();
5674 viewport.firePropertyChange("alignment", null, al);
5678 public void setShowSeqFeatures(boolean b)
5680 showSeqFeatures.setSelected(b);
5681 viewport.setShowSequenceFeatures(b);
5688 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5689 * awt.event.ActionEvent)
5692 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5694 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5695 alignPanel.paintAlignment(false, false);
5702 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5706 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5708 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5709 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5717 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5718 * .event.ActionEvent)
5721 protected void showGroupConservation_actionPerformed(ActionEvent e)
5723 viewport.setShowGroupConservation(showGroupConservation.getState());
5724 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5731 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5732 * .event.ActionEvent)
5735 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5737 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5738 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5745 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5746 * .event.ActionEvent)
5749 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5751 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5752 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5756 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5758 showSequenceLogo.setState(true);
5759 viewport.setShowSequenceLogo(true);
5760 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5761 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5765 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5767 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5774 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5775 * .event.ActionEvent)
5778 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5780 if (avc.makeGroupsFromSelection())
5782 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5783 alignPanel.updateAnnotation();
5784 alignPanel.paintAlignment(true,
5785 viewport.needToUpdateStructureViews());
5789 public void clearAlignmentSeqRep()
5791 // TODO refactor alignmentseqrep to controller
5792 if (viewport.getAlignment().hasSeqrep())
5794 viewport.getAlignment().setSeqrep(null);
5795 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5796 alignPanel.updateAnnotation();
5797 alignPanel.paintAlignment(true, true);
5802 protected void createGroup_actionPerformed(ActionEvent e)
5804 if (avc.createGroup())
5806 if (applyAutoAnnotationSettings.isSelected())
5808 alignPanel.updateAnnotation(true, false);
5810 alignPanel.alignmentChanged();
5815 protected void unGroup_actionPerformed(ActionEvent e)
5819 alignPanel.alignmentChanged();
5824 * make the given alignmentPanel the currently selected tab
5826 * @param alignmentPanel
5828 public void setDisplayedView(AlignmentPanel alignmentPanel)
5830 if (!viewport.getSequenceSetId()
5831 .equals(alignmentPanel.av.getSequenceSetId()))
5833 throw new Error(MessageManager.getString(
5834 "error.implementation_error_cannot_show_view_alignment_frame"));
5836 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5837 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5839 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5844 * Action on selection of menu options to Show or Hide annotations.
5847 * @param forSequences
5848 * update sequence-related annotations
5849 * @param forAlignment
5850 * update non-sequence-related annotations
5853 protected void setAnnotationsVisibility(boolean visible,
5854 boolean forSequences, boolean forAlignment)
5856 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5857 .getAlignmentAnnotation();
5862 for (AlignmentAnnotation aa : anns)
5865 * don't display non-positional annotations on an alignment
5867 if (aa.annotations == null)
5871 boolean apply = (aa.sequenceRef == null && forAlignment)
5872 || (aa.sequenceRef != null && forSequences);
5875 aa.visible = visible;
5878 alignPanel.validateAnnotationDimensions(true);
5879 alignPanel.alignmentChanged();
5883 * Store selected annotation sort order for the view and repaint.
5886 protected void sortAnnotations_actionPerformed()
5888 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5890 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5891 alignPanel.paintAlignment(false, false);
5896 * @return alignment panels in this alignment frame
5898 public List<? extends AlignmentViewPanel> getAlignPanels()
5900 // alignPanels is never null
5901 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5906 * Open a new alignment window, with the cDNA associated with this (protein)
5907 * alignment, aligned as is the protein.
5909 protected void viewAsCdna_actionPerformed()
5911 // TODO no longer a menu action - refactor as required
5912 final AlignmentI alignment = getViewport().getAlignment();
5913 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5914 if (mappings == null)
5918 List<SequenceI> cdnaSeqs = new ArrayList<>();
5919 for (SequenceI aaSeq : alignment.getSequences())
5921 for (AlignedCodonFrame acf : mappings)
5923 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5927 * There is a cDNA mapping for this protein sequence - add to new
5928 * alignment. It will share the same dataset sequence as other mapped
5929 * cDNA (no new mappings need to be created).
5931 final Sequence newSeq = new Sequence(dnaSeq);
5932 newSeq.setDatasetSequence(dnaSeq);
5933 cdnaSeqs.add(newSeq);
5937 if (cdnaSeqs.size() == 0)
5939 // show a warning dialog no mapped cDNA
5942 AlignmentI cdna = new Alignment(
5943 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5944 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5945 AlignFrame.DEFAULT_HEIGHT);
5946 cdna.alignAs(alignment);
5947 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5949 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5950 AlignFrame.DEFAULT_HEIGHT);
5954 * Set visibility of dna/protein complement view (available when shown in a
5960 protected void showComplement_actionPerformed(boolean show)
5962 SplitContainerI sf = getSplitViewContainer();
5965 sf.setComplementVisible(this, show);
5970 * Generate the reverse (optionally complemented) of the selected sequences,
5971 * and add them to the alignment
5974 protected void showReverse_actionPerformed(boolean complement)
5976 AlignmentI al = null;
5979 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5980 al = dna.reverseCdna(complement);
5981 viewport.addAlignment(al, "");
5982 addHistoryItem(new EditCommand(
5983 MessageManager.getString("label.add_sequences"), Action.PASTE,
5984 al.getSequencesArray(), 0, al.getWidth(),
5985 viewport.getAlignment()));
5986 } catch (Exception ex)
5988 System.err.println(ex.getMessage());
5994 * Try to run a script in the Groovy console, having first ensured that this
5995 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5996 * be targeted at this alignment.
5999 protected void runGroovy_actionPerformed()
6001 Jalview.setCurrentAlignFrame(this);
6002 groovy.ui.Console console = Desktop.getGroovyConsole();
6003 if (console != null)
6007 console.runScript();
6008 } catch (Exception ex)
6010 System.err.println((ex.toString()));
6011 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
6012 MessageManager.getString("label.couldnt_run_groovy_script"),
6013 MessageManager.getString("label.groovy_support_failed"),
6014 JvOptionPane.ERROR_MESSAGE);
6019 System.err.println("Can't run Groovy script as console not found");
6024 * Hides columns containing (or not containing) a specified feature, provided
6025 * that would not leave all columns hidden
6027 * @param featureType
6028 * @param columnsContaining
6031 public boolean hideFeatureColumns(String featureType,
6032 boolean columnsContaining)
6034 boolean notForHiding = avc.markColumnsContainingFeatures(
6035 columnsContaining, false, false, featureType);
6038 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
6039 false, featureType))
6041 getViewport().hideSelectedColumns();
6049 protected void selectHighlightedColumns_actionPerformed(
6050 ActionEvent actionEvent)
6052 // include key modifier check in case user selects from menu
6053 avc.markHighlightedColumns(
6054 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
6055 (actionEvent.getModifiers() & (ActionEvent.META_MASK
6056 | ActionEvent.CTRL_MASK)) != 0);
6060 * Rebuilds the Colour menu, including any user-defined colours which have
6061 * been loaded either on startup or during the session
6063 public void buildColourMenu()
6065 colourMenu.removeAll();
6067 colourMenu.add(applyToAllGroups);
6068 colourMenu.add(textColour);
6069 colourMenu.addSeparator();
6071 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
6072 viewport.getAlignment(), false);
6074 colourMenu.add(annotationColour);
6075 bg.add(annotationColour);
6076 colourMenu.addSeparator();
6077 colourMenu.add(conservationMenuItem);
6078 colourMenu.add(modifyConservation);
6079 colourMenu.add(abovePIDThreshold);
6080 colourMenu.add(modifyPID);
6082 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
6083 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
6087 * Open a dialog (if not already open) that allows the user to select and
6088 * calculate PCA or Tree analysis
6090 protected void openTreePcaDialog()
6092 if (alignPanel.getCalculationDialog() == null)
6094 new CalculationChooser(AlignFrame.this);
6099 * Sets the status of the HMMER menu
6101 public void updateHMMERStatus()
6103 hmmerMenu.setEnabled(HmmerCommand.isHmmerAvailable());
6107 protected void loadVcf_actionPerformed()
6109 JalviewFileChooser chooser = new JalviewFileChooser(
6110 Cache.getProperty("LAST_DIRECTORY"));
6111 chooser.setFileView(new JalviewFileView());
6112 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
6113 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
6114 final AlignFrame us = this;
6115 chooser.setResponseHandler(0, new Runnable()
6120 String choice = chooser.getSelectedFile().getPath();
6121 Cache.setProperty("LAST_DIRECTORY", choice);
6122 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
6123 new VCFLoader(choice).loadVCF(seqs, us);
6126 chooser.showOpenDialog(null);
6130 private Rectangle lastFeatureSettingsBounds = null;
6132 public void setFeatureSettingsGeometry(Rectangle bounds)
6134 lastFeatureSettingsBounds = bounds;
6138 public Rectangle getFeatureSettingsGeometry()
6140 return lastFeatureSettingsBounds;
6144 class PrintThread extends Thread
6148 public PrintThread(AlignmentPanel ap)
6153 static PageFormat pf;
6158 PrinterJob printJob = PrinterJob.getPrinterJob();
6162 printJob.setPrintable(ap, pf);
6166 printJob.setPrintable(ap);
6169 if (printJob.printDialog())
6174 } catch (Exception PrintException)
6176 PrintException.printStackTrace();