2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AlignmentSorter;
24 import jalview.analysis.AlignmentUtils;
25 import jalview.analysis.CrossRef;
26 import jalview.analysis.Dna;
27 import jalview.analysis.ParseProperties;
28 import jalview.analysis.SequenceIdMatcher;
29 import jalview.api.AlignExportSettingsI;
30 import jalview.api.AlignViewControllerGuiI;
31 import jalview.api.AlignViewControllerI;
32 import jalview.api.AlignViewportI;
33 import jalview.api.AlignmentViewPanel;
34 import jalview.api.FeatureSettingsControllerI;
35 import jalview.api.SplitContainerI;
36 import jalview.api.ViewStyleI;
37 import jalview.api.analysis.SimilarityParamsI;
38 import jalview.bin.Cache;
39 import jalview.bin.Jalview;
40 import jalview.commands.CommandI;
41 import jalview.commands.EditCommand;
42 import jalview.commands.EditCommand.Action;
43 import jalview.commands.OrderCommand;
44 import jalview.commands.RemoveGapColCommand;
45 import jalview.commands.RemoveGapsCommand;
46 import jalview.commands.SlideSequencesCommand;
47 import jalview.commands.TrimRegionCommand;
48 import jalview.datamodel.AlignExportSettingsAdapter;
49 import jalview.datamodel.AlignedCodonFrame;
50 import jalview.datamodel.Alignment;
51 import jalview.datamodel.AlignmentAnnotation;
52 import jalview.datamodel.AlignmentExportData;
53 import jalview.datamodel.AlignmentI;
54 import jalview.datamodel.AlignmentOrder;
55 import jalview.datamodel.AlignmentView;
56 import jalview.datamodel.ColumnSelection;
57 import jalview.datamodel.HiddenColumns;
58 import jalview.datamodel.PDBEntry;
59 import jalview.datamodel.SeqCigar;
60 import jalview.datamodel.Sequence;
61 import jalview.datamodel.SequenceGroup;
62 import jalview.datamodel.SequenceI;
63 import jalview.gui.ColourMenuHelper.ColourChangeListener;
64 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
65 import jalview.io.AlignmentProperties;
66 import jalview.io.AnnotationFile;
67 import jalview.io.BioJsHTMLOutput;
68 import jalview.io.DataSourceType;
69 import jalview.io.FileFormat;
70 import jalview.io.FileFormatI;
71 import jalview.io.FileFormats;
72 import jalview.io.FileLoader;
73 import jalview.io.FileParse;
74 import jalview.io.FormatAdapter;
75 import jalview.io.HtmlSvgOutput;
76 import jalview.io.IdentifyFile;
77 import jalview.io.JPredFile;
78 import jalview.io.JalviewFileChooser;
79 import jalview.io.JalviewFileView;
80 import jalview.io.JnetAnnotationMaker;
81 import jalview.io.NewickFile;
82 import jalview.io.ScoreMatrixFile;
83 import jalview.io.TCoffeeScoreFile;
84 import jalview.io.vcf.VCFLoader;
85 import jalview.jbgui.GAlignFrame;
86 import jalview.schemes.ColourSchemeI;
87 import jalview.schemes.ColourSchemes;
88 import jalview.schemes.ResidueColourScheme;
89 import jalview.schemes.TCoffeeColourScheme;
90 import jalview.util.ImageMaker.TYPE;
91 import jalview.util.MessageManager;
92 import jalview.viewmodel.AlignmentViewport;
93 import jalview.viewmodel.ViewportRanges;
94 import jalview.ws.DBRefFetcher;
95 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
96 import jalview.ws.jws1.Discoverer;
97 import jalview.ws.jws2.Jws2Discoverer;
98 import jalview.ws.jws2.jabaws2.Jws2Instance;
99 import jalview.ws.seqfetcher.DbSourceProxy;
101 import java.awt.BorderLayout;
102 import java.awt.Color;
103 import java.awt.Component;
104 import java.awt.Rectangle;
105 import java.awt.Toolkit;
106 import java.awt.datatransfer.Clipboard;
107 import java.awt.datatransfer.DataFlavor;
108 import java.awt.datatransfer.StringSelection;
109 import java.awt.datatransfer.Transferable;
110 import java.awt.dnd.DnDConstants;
111 import java.awt.dnd.DropTargetDragEvent;
112 import java.awt.dnd.DropTargetDropEvent;
113 import java.awt.dnd.DropTargetEvent;
114 import java.awt.dnd.DropTargetListener;
115 import java.awt.event.ActionEvent;
116 import java.awt.event.ActionListener;
117 import java.awt.event.FocusAdapter;
118 import java.awt.event.FocusEvent;
119 import java.awt.event.ItemEvent;
120 import java.awt.event.ItemListener;
121 import java.awt.event.KeyAdapter;
122 import java.awt.event.KeyEvent;
123 import java.awt.event.MouseEvent;
124 import java.awt.print.PageFormat;
125 import java.awt.print.PrinterJob;
126 import java.beans.PropertyChangeEvent;
128 import java.io.FileWriter;
129 import java.io.PrintWriter;
131 import java.util.ArrayList;
132 import java.util.Arrays;
133 import java.util.Deque;
134 import java.util.Enumeration;
135 import java.util.Hashtable;
136 import java.util.List;
137 import java.util.Vector;
139 import javax.swing.JCheckBoxMenuItem;
140 import javax.swing.JComponent;
141 import javax.swing.JEditorPane;
142 import javax.swing.JInternalFrame;
143 import javax.swing.JLabel;
144 import javax.swing.JLayeredPane;
145 import javax.swing.JMenu;
146 import javax.swing.JMenuItem;
147 import javax.swing.JPanel;
148 import javax.swing.JScrollPane;
149 import javax.swing.SwingUtilities;
155 * @version $Revision$
157 public class AlignFrame extends GAlignFrame implements DropTargetListener,
158 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
161 public static final int DEFAULT_WIDTH = 700;
163 public static final int DEFAULT_HEIGHT = 500;
166 * The currently displayed panel (selected tabbed view if more than one)
168 public AlignmentPanel alignPanel;
170 AlignViewport viewport;
172 public AlignViewControllerI avc;
174 List<AlignmentPanel> alignPanels = new ArrayList<>();
177 * Last format used to load or save alignments in this window
179 FileFormatI currentFileFormat = null;
182 * Current filename for this alignment
184 String fileName = null;
189 * Creates a new AlignFrame object with specific width and height.
195 public AlignFrame(AlignmentI al, int width, int height)
197 this(al, null, width, height);
201 * Creates a new AlignFrame object with specific width, height and
207 * @param sequenceSetId
209 public AlignFrame(AlignmentI al, int width, int height,
210 String sequenceSetId)
212 this(al, null, width, height, sequenceSetId);
216 * Creates a new AlignFrame object with specific width, height and
222 * @param sequenceSetId
225 public AlignFrame(AlignmentI al, int width, int height,
226 String sequenceSetId, String viewId)
228 this(al, null, width, height, sequenceSetId, viewId);
232 * new alignment window with hidden columns
236 * @param hiddenColumns
237 * ColumnSelection or null
239 * Width of alignment frame
243 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
246 this(al, hiddenColumns, width, height, null);
250 * Create alignment frame for al with hiddenColumns, a specific width and
251 * height, and specific sequenceId
254 * @param hiddenColumns
257 * @param sequenceSetId
260 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
261 int height, String sequenceSetId)
263 this(al, hiddenColumns, width, height, sequenceSetId, null);
267 * Create alignment frame for al with hiddenColumns, a specific width and
268 * height, and specific sequenceId
271 * @param hiddenColumns
274 * @param sequenceSetId
279 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
280 int height, String sequenceSetId, String viewId)
282 setSize(width, height);
284 if (al.getDataset() == null)
289 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
291 alignPanel = new AlignmentPanel(this, viewport);
293 addAlignmentPanel(alignPanel, true);
297 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
298 HiddenColumns hiddenColumns, int width, int height)
300 setSize(width, height);
302 if (al.getDataset() == null)
307 viewport = new AlignViewport(al, hiddenColumns);
309 if (hiddenSeqs != null && hiddenSeqs.length > 0)
311 viewport.hideSequence(hiddenSeqs);
313 alignPanel = new AlignmentPanel(this, viewport);
314 addAlignmentPanel(alignPanel, true);
319 * Make a new AlignFrame from existing alignmentPanels
326 public AlignFrame(AlignmentPanel ap)
330 addAlignmentPanel(ap, false);
335 * initalise the alignframe from the underlying viewport data and the
340 // setBackground(Color.white); // BH 2019
342 if (!Jalview.isHeadlessMode())
344 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
347 avc = new jalview.controller.AlignViewController(this, viewport,
349 if (viewport.getAlignmentConservationAnnotation() == null)
351 // BLOSUM62Colour.setEnabled(false);
352 conservationMenuItem.setEnabled(false);
353 modifyConservation.setEnabled(false);
354 // PIDColour.setEnabled(false);
355 // abovePIDThreshold.setEnabled(false);
356 // modifyPID.setEnabled(false);
359 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
362 if (sortby.equals("Id"))
364 sortIDMenuItem_actionPerformed(null);
366 else if (sortby.equals("Pairwise Identity"))
368 sortPairwiseMenuItem_actionPerformed(null);
372 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
374 setMenusFromViewport(viewport);
375 buildSortByAnnotationScoresMenu();
376 calculateTree.addActionListener(new ActionListener()
380 public void actionPerformed(ActionEvent e)
387 if (Desktop.desktop != null)
389 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
391 * BH 2018 ignore service listeners
397 addServiceListeners();
402 if (viewport.getWrapAlignment())
404 wrapMenuItem_actionPerformed(null);
407 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
409 this.overviewMenuItem_actionPerformed(null);
414 final List<AlignmentPanel> selviews = new ArrayList<>();
415 final List<AlignmentPanel> origview = new ArrayList<>();
416 final String menuLabel = MessageManager
417 .getString("label.copy_format_from");
418 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
419 new ViewSetProvider()
423 public AlignmentPanel[] getAllAlignmentPanels()
426 origview.add(alignPanel);
427 // make an array of all alignment panels except for this one
428 List<AlignmentPanel> aps = new ArrayList<>(
429 Arrays.asList(Desktop.getAlignmentPanels(null)));
430 aps.remove(AlignFrame.this.alignPanel);
431 return aps.toArray(new AlignmentPanel[aps.size()]);
433 }, selviews, new ItemListener()
437 public void itemStateChanged(ItemEvent e)
439 if (origview.size() > 0)
441 final AlignmentPanel ap = origview.get(0);
444 * Copy the ViewStyle of the selected panel to 'this one'.
445 * Don't change value of 'scaleProteinAsCdna' unless copying
448 ViewStyleI vs = selviews.get(0).getAlignViewport()
450 boolean fromSplitFrame = selviews.get(0)
451 .getAlignViewport().getCodingComplement() != null;
454 vs.setScaleProteinAsCdna(ap.getAlignViewport()
455 .getViewStyle().isScaleProteinAsCdna());
457 ap.getAlignViewport().setViewStyle(vs);
460 * Also rescale ViewStyle of SplitFrame complement if there is
461 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
462 * the whole ViewStyle (allow cDNA protein to have different
465 AlignViewportI complement = ap.getAlignViewport()
466 .getCodingComplement();
467 if (complement != null && vs.isScaleProteinAsCdna())
469 AlignFrame af = Desktop.getAlignFrameFor(complement);
470 ((SplitFrame) af.getSplitViewContainer())
472 af.setMenusForViewport();
476 ap.setSelected(true);
477 ap.alignFrame.setMenusForViewport();
482 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
483 .indexOf("devel") > -1
484 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
485 .indexOf("test") > -1)
487 formatMenu.add(vsel);
489 addFocusListener(new FocusAdapter()
492 public void focusGained(FocusEvent e)
494 Jalview.setCurrentAlignFrame(AlignFrame.this);
501 * Change the filename and format for the alignment, and enable the 'reload'
502 * button functionality.
509 public void setFileName(String file, FileFormatI format)
512 setFileFormat(format);
513 reload.setEnabled(true);
517 * JavaScript will have this, maybe others. More dependable than a file name
518 * and maintains a reference to the actual bytes loaded.
522 public void setFileObject(File file)
524 this.fileObject = file;
528 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
531 void addKeyListener()
533 addKeyListener(new KeyAdapter()
536 public void keyPressed(KeyEvent evt)
538 if (viewport.cursorMode
539 && ((evt.getKeyCode() >= KeyEvent.VK_0
540 && evt.getKeyCode() <= KeyEvent.VK_9)
541 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
542 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
543 && Character.isDigit(evt.getKeyChar()))
545 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
548 switch (evt.getKeyCode())
551 case 27: // escape key
552 deselectAllSequenceMenuItem_actionPerformed(null);
556 case KeyEvent.VK_DOWN:
557 if (evt.isAltDown() || !viewport.cursorMode)
559 moveSelectedSequences(false);
561 if (viewport.cursorMode)
563 alignPanel.getSeqPanel().moveCursor(0, 1);
568 if (evt.isAltDown() || !viewport.cursorMode)
570 moveSelectedSequences(true);
572 if (viewport.cursorMode)
574 alignPanel.getSeqPanel().moveCursor(0, -1);
579 case KeyEvent.VK_LEFT:
580 if (evt.isAltDown() || !viewport.cursorMode)
582 slideSequences(false,
583 alignPanel.getSeqPanel().getKeyboardNo1());
587 alignPanel.getSeqPanel().moveCursor(-1, 0);
592 case KeyEvent.VK_RIGHT:
593 if (evt.isAltDown() || !viewport.cursorMode)
595 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
599 alignPanel.getSeqPanel().moveCursor(1, 0);
603 case KeyEvent.VK_SPACE:
604 if (viewport.cursorMode)
606 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
607 || evt.isShiftDown() || evt.isAltDown());
611 // case KeyEvent.VK_A:
612 // if (viewport.cursorMode)
614 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
615 // //System.out.println("A");
619 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
620 * System.out.println("closing bracket"); } break;
622 case KeyEvent.VK_DELETE:
623 case KeyEvent.VK_BACK_SPACE:
624 if (!viewport.cursorMode)
626 cut_actionPerformed(null);
630 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
631 || evt.isShiftDown() || evt.isAltDown());
637 if (viewport.cursorMode)
639 alignPanel.getSeqPanel().setCursorRow();
643 if (viewport.cursorMode && !evt.isControlDown())
645 alignPanel.getSeqPanel().setCursorColumn();
649 if (viewport.cursorMode)
651 alignPanel.getSeqPanel().setCursorPosition();
655 case KeyEvent.VK_ENTER:
656 case KeyEvent.VK_COMMA:
657 if (viewport.cursorMode)
659 alignPanel.getSeqPanel().setCursorRowAndColumn();
664 if (viewport.cursorMode)
666 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
670 if (viewport.cursorMode)
672 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
677 viewport.cursorMode = !viewport.cursorMode;
678 setStatus(MessageManager
679 .formatMessage("label.keyboard_editing_mode", new String[]
680 { (viewport.cursorMode ? "on" : "off") }));
681 if (viewport.cursorMode)
683 ViewportRanges ranges = viewport.getRanges();
684 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
686 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
689 alignPanel.getSeqPanel().seqCanvas.repaint();
695 Help.showHelpWindow();
696 } catch (Exception ex)
698 ex.printStackTrace();
703 boolean toggleSeqs = !evt.isControlDown();
704 boolean toggleCols = !evt.isShiftDown();
705 toggleHiddenRegions(toggleSeqs, toggleCols);
710 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
711 boolean modifyExisting = true; // always modify, don't clear
712 // evt.isShiftDown();
713 boolean invertHighlighted = evt.isAltDown();
714 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
718 case KeyEvent.VK_PAGE_UP:
719 viewport.getRanges().pageUp();
721 case KeyEvent.VK_PAGE_DOWN:
722 viewport.getRanges().pageDown();
728 public void keyReleased(KeyEvent evt)
730 switch (evt.getKeyCode())
732 case KeyEvent.VK_LEFT:
733 if (evt.isAltDown() || !viewport.cursorMode)
735 viewport.firePropertyChange("alignment", null,
736 viewport.getAlignment().getSequences());
740 case KeyEvent.VK_RIGHT:
741 if (evt.isAltDown() || !viewport.cursorMode)
743 viewport.firePropertyChange("alignment", null,
744 viewport.getAlignment().getSequences());
752 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
754 ap.alignFrame = this;
755 avc = new jalview.controller.AlignViewController(this, viewport,
760 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
762 int aSize = alignPanels.size();
764 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
766 if (aSize == 1 && ap.av.getViewName() == null)
768 this.getContentPane().add(ap, BorderLayout.CENTER);
774 setInitialTabVisible();
777 expandViews.setEnabled(true);
778 gatherViews.setEnabled(true);
779 tabbedPane.addTab(ap.av.getViewName(), ap);
781 ap.setVisible(false);
786 if (ap.av.isPadGaps())
788 ap.av.getAlignment().padGaps();
790 ap.av.updateConservation(ap);
791 ap.av.updateConsensus(ap);
792 ap.av.updateStrucConsensus(ap);
796 public void setInitialTabVisible()
798 expandViews.setEnabled(true);
799 gatherViews.setEnabled(true);
800 tabbedPane.setVisible(true);
801 AlignmentPanel first = alignPanels.get(0);
802 tabbedPane.addTab(first.av.getViewName(), first);
803 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
806 public AlignViewport getViewport()
811 /* Set up intrinsic listeners for dynamically generated GUI bits. */
812 private void addServiceListeners()
814 final java.beans.PropertyChangeListener thisListener;
815 Desktop.instance.addJalviewPropertyChangeListener("services",
816 thisListener = new java.beans.PropertyChangeListener()
819 public void propertyChange(PropertyChangeEvent evt)
821 // // System.out.println("Discoverer property change.");
822 // if (evt.getPropertyName().equals("services"))
824 SwingUtilities.invokeLater(new Runnable()
831 "Rebuild WS Menu for service change");
832 BuildWebServiceMenu();
839 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
842 public void internalFrameClosed(
843 javax.swing.event.InternalFrameEvent evt)
845 // System.out.println("deregistering discoverer listener");
846 Desktop.instance.removeJalviewPropertyChangeListener("services",
848 closeMenuItem_actionPerformed(true);
851 // Finally, build the menu once to get current service state
852 new Thread(new Runnable()
857 BuildWebServiceMenu();
863 * Configure menu items that vary according to whether the alignment is
864 * nucleotide or protein
866 public void setGUINucleotide()
868 AlignmentI al = getViewport().getAlignment();
869 boolean nucleotide = al.isNucleotide();
871 loadVcf.setVisible(nucleotide);
872 showTranslation.setVisible(nucleotide);
873 showReverse.setVisible(nucleotide);
874 showReverseComplement.setVisible(nucleotide);
875 conservationMenuItem.setEnabled(!nucleotide);
877 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
878 showGroupConservation.setEnabled(!nucleotide);
880 showComplementMenuItem
881 .setText(nucleotide ? MessageManager.getString("label.protein")
882 : MessageManager.getString("label.nucleotide"));
886 * set up menus for the current viewport. This may be called after any
887 * operation that affects the data in the current view (selection changed,
888 * etc) to update the menus to reflect the new state.
891 public void setMenusForViewport()
893 setMenusFromViewport(viewport);
897 * Need to call this method when tabs are selected for multiple views, or when
898 * loading from Jalview2XML.java
903 public void setMenusFromViewport(AlignViewport av)
905 padGapsMenuitem.setSelected(av.isPadGaps());
906 colourTextMenuItem.setSelected(av.isShowColourText());
907 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
908 modifyPID.setEnabled(abovePIDThreshold.isSelected());
909 conservationMenuItem.setSelected(av.getConservationSelected());
910 modifyConservation.setEnabled(conservationMenuItem.isSelected());
911 seqLimits.setSelected(av.getShowJVSuffix());
912 idRightAlign.setSelected(av.isRightAlignIds());
913 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
914 renderGapsMenuItem.setSelected(av.isRenderGaps());
915 wrapMenuItem.setSelected(av.getWrapAlignment());
916 scaleAbove.setVisible(av.getWrapAlignment());
917 scaleLeft.setVisible(av.getWrapAlignment());
918 scaleRight.setVisible(av.getWrapAlignment());
919 annotationPanelMenuItem.setState(av.isShowAnnotation());
921 * Show/hide annotations only enabled if annotation panel is shown
923 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
924 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
925 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
926 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
927 viewBoxesMenuItem.setSelected(av.getShowBoxes());
928 viewTextMenuItem.setSelected(av.getShowText());
929 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
930 showGroupConsensus.setSelected(av.isShowGroupConsensus());
931 showGroupConservation.setSelected(av.isShowGroupConservation());
932 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
933 showSequenceLogo.setSelected(av.isShowSequenceLogo());
934 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
936 ColourMenuHelper.setColourSelected(colourMenu,
937 av.getGlobalColourScheme());
939 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
940 hiddenMarkers.setState(av.getShowHiddenMarkers());
941 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
942 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
943 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
944 autoCalculate.setSelected(av.autoCalculateConsensus);
945 sortByTree.setSelected(av.sortByTree);
946 listenToViewSelections.setSelected(av.followSelection);
948 showProducts.setEnabled(canShowProducts());
949 setGroovyEnabled(Desktop.getGroovyConsole() != null);
955 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
959 public void setGroovyEnabled(boolean b)
961 runGroovy.setEnabled(b);
964 private IProgressIndicator progressBar;
969 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
972 public void setProgressBar(String message, long id)
974 progressBar.setProgressBar(message, id);
978 public void registerHandler(final long id,
979 final IProgressIndicatorHandler handler)
981 progressBar.registerHandler(id, handler);
986 * @return true if any progress bars are still active
989 public boolean operationInProgress()
991 return progressBar.operationInProgress();
995 public void setStatus(String text)
997 // BH note: If text width and height are 0, then the layout manager
998 // will dispense of it and change the frame height.
999 // In JavaScript, we use \u00A0 -- unicode "non-breaking space"
1000 // which is the unicode encoding of
1002 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1006 * Added so Castor Mapping file can obtain Jalview Version
1008 public String getVersion()
1010 return jalview.bin.Cache.getProperty("VERSION");
1013 public FeatureRenderer getFeatureRenderer()
1015 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1019 public void fetchSequence_actionPerformed()
1021 new SequenceFetcher(this);
1025 public void addFromFile_actionPerformed(ActionEvent e)
1027 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1031 public void reload_actionPerformed(ActionEvent e)
1033 if (fileName != null)
1035 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1036 // originating file's format
1037 // TODO: work out how to recover feature settings for correct view(s) when
1038 // file is reloaded.
1039 if (FileFormat.Jalview.equals(currentFileFormat))
1041 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1042 for (int i = 0; i < frames.length; i++)
1044 if (frames[i] instanceof AlignFrame && frames[i] != this
1045 && ((AlignFrame) frames[i]).fileName != null
1046 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1050 frames[i].setSelected(true);
1051 Desktop.instance.closeAssociatedWindows();
1052 } catch (java.beans.PropertyVetoException ex)
1058 Desktop.instance.closeAssociatedWindows();
1060 FileLoader loader = new FileLoader();
1061 DataSourceType protocol = fileName.startsWith("http:")
1062 ? DataSourceType.URL
1063 : DataSourceType.FILE;
1064 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1068 Rectangle bounds = this.getBounds();
1070 FileLoader loader = new FileLoader();
1072 AlignFrame newframe = null;
1074 if (fileObject == null)
1077 DataSourceType protocol = (fileName.startsWith("http:")
1078 ? DataSourceType.URL
1079 : DataSourceType.FILE);
1080 newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1085 newframe = loader.LoadFileWaitTillLoaded(fileObject,
1086 DataSourceType.FILE, currentFileFormat);
1089 newframe.setBounds(bounds);
1090 if (featureSettings != null && featureSettings.isShowing())
1092 final Rectangle fspos = featureSettings.frame.getBounds();
1093 // TODO: need a 'show feature settings' function that takes bounds -
1094 // need to refactor Desktop.addFrame
1095 newframe.featureSettings_actionPerformed(null);
1096 final FeatureSettings nfs = newframe.featureSettings;
1097 SwingUtilities.invokeLater(new Runnable()
1102 nfs.frame.setBounds(fspos);
1105 this.featureSettings.close();
1106 this.featureSettings = null;
1108 this.closeMenuItem_actionPerformed(true);
1114 public void addFromText_actionPerformed(ActionEvent e)
1117 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1121 public void addFromURL_actionPerformed(ActionEvent e)
1123 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1127 public void save_actionPerformed(ActionEvent e)
1129 if (fileName == null || (currentFileFormat == null)
1130 || fileName.startsWith("http"))
1132 saveAs_actionPerformed();
1136 saveAlignment(fileName, currentFileFormat);
1141 * Saves the alignment to a file with a name chosen by the user, if necessary
1142 * warning if a file would be overwritten
1145 public void saveAs_actionPerformed()
1147 String format = currentFileFormat == null ? null
1148 : currentFileFormat.getName();
1149 JalviewFileChooser chooser = JalviewFileChooser
1150 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1152 chooser.setFileView(new JalviewFileView());
1153 chooser.setDialogTitle(
1154 MessageManager.getString("label.save_alignment_to_file"));
1155 chooser.setToolTipText(MessageManager.getString("action.save"));
1157 int value = chooser.showSaveDialog(this);
1159 if (value != JalviewFileChooser.APPROVE_OPTION)
1163 currentFileFormat = chooser.getSelectedFormat();
1164 // todo is this (2005) test now obsolete - value is never null?
1165 while (currentFileFormat == null)
1167 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1169 .getString("label.select_file_format_before_saving"),
1170 MessageManager.getString("label.file_format_not_specified"),
1171 JvOptionPane.WARNING_MESSAGE);
1172 currentFileFormat = chooser.getSelectedFormat();
1173 value = chooser.showSaveDialog(this);
1174 if (value != JalviewFileChooser.APPROVE_OPTION)
1180 fileName = chooser.getSelectedFile().getPath();
1182 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1183 Cache.setProperty("LAST_DIRECTORY", fileName);
1184 saveAlignment(fileName, currentFileFormat);
1187 boolean lastSaveSuccessful = false;
1189 FileFormatI lastFormatSaved;
1191 String lastFilenameSaved;
1194 * Raise a dialog or status message for the last call to saveAlignment.
1196 * @return true if last call to saveAlignment(file, format) was successful.
1198 public boolean isSaveAlignmentSuccessful()
1201 if (!lastSaveSuccessful)
1203 JvOptionPane.showInternalMessageDialog(this, MessageManager
1204 .formatMessage("label.couldnt_save_file", new Object[]
1205 { lastFilenameSaved }),
1206 MessageManager.getString("label.error_saving_file"),
1207 JvOptionPane.WARNING_MESSAGE);
1212 setStatus(MessageManager.formatMessage(
1213 "label.successfully_saved_to_file_in_format", new Object[]
1214 { lastFilenameSaved, lastFormatSaved }));
1217 return lastSaveSuccessful;
1221 * Saves the alignment to the specified file path, in the specified format,
1222 * which may be an alignment format, or Jalview project format. If the
1223 * alignment has hidden regions, or the format is one capable of including
1224 * non-sequence data (features, annotations, groups), then the user may be
1225 * prompted to specify what to include in the output.
1230 public void saveAlignment(String file, FileFormatI format)
1232 lastSaveSuccessful = false;
1233 lastFilenameSaved = file;
1234 lastFormatSaved = format;
1236 if (FileFormat.Jalview.equals(format))
1238 String shortName = title;
1239 if (shortName.indexOf(File.separatorChar) > -1)
1241 shortName = shortName.substring(
1242 shortName.lastIndexOf(File.separatorChar) + 1);
1244 lastSaveSuccessful = new jalview.project.Jalview2XML().saveAlignment(this, file,
1247 statusBar.setText(MessageManager.formatMessage(
1248 "label.successfully_saved_to_file_in_format", new Object[]
1249 { fileName, format }));
1254 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1255 Runnable cancelAction = new Runnable()
1260 lastSaveSuccessful = false;
1263 Runnable outputAction = new Runnable()
1268 // todo defer this to inside formatSequences (or later)
1269 AlignmentExportData exportData = viewport
1270 .getAlignExportData(options);
1271 String output = new FormatAdapter(alignPanel, options)
1272 .formatSequences(format, exportData.getAlignment(),
1273 exportData.getOmitHidden(),
1274 exportData.getStartEndPostions(),
1275 viewport.getAlignment().getHiddenColumns());
1278 lastSaveSuccessful = false;
1284 PrintWriter out = new PrintWriter(new FileWriter(file));
1287 AlignFrame.this.setTitle(file);
1288 setStatus(MessageManager.formatMessage(
1289 "label.successfully_saved_to_file_in_format",
1291 { fileName, format.getName() }));
1292 } catch (Exception ex)
1294 lastSaveSuccessful = false;
1295 ex.printStackTrace();
1302 * show dialog with export options if applicable; else just do it
1304 if (AlignExportOptions.isNeeded(viewport, format))
1306 AlignExportOptions choices = new AlignExportOptions(
1307 alignPanel.getAlignViewport(), format, options);
1308 choices.setResponseAction(0, outputAction);
1309 choices.setResponseAction(1, cancelAction);
1310 choices.showDialog();
1319 * Outputs the alignment to textbox in the requested format, if necessary
1320 * first prompting the user for whether to include hidden regions or
1323 * @param fileFormatName
1326 protected void outputText_actionPerformed(String fileFormatName)
1328 FileFormatI fileFormat = FileFormats.getInstance()
1329 .forName(fileFormatName);
1330 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1331 Runnable outputAction = new Runnable()
1336 // todo defer this to inside formatSequences (or later)
1337 AlignmentExportData exportData = viewport
1338 .getAlignExportData(options);
1339 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1340 cap.setForInput(null);
1343 FileFormatI format = fileFormat;
1344 cap.setText(new FormatAdapter(alignPanel, options)
1345 .formatSequences(format, exportData.getAlignment(),
1346 exportData.getOmitHidden(),
1347 exportData.getStartEndPostions(),
1348 viewport.getAlignment().getHiddenColumns()));
1349 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1350 "label.alignment_output_command", new Object[]
1351 { fileFormat.getName() }), 600, 500);
1352 } catch (OutOfMemoryError oom)
1354 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1362 * show dialog with export options if applicable; else just do it
1364 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1366 AlignExportOptions choices = new AlignExportOptions(
1367 alignPanel.getAlignViewport(), fileFormat, options);
1368 choices.setResponseAction(0, outputAction);
1369 choices.showDialog();
1384 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1386 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1387 htmlSVG.exportHTML(null);
1391 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1393 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1394 bjs.exportHTML(null);
1397 public void createImageMap(File file, String image)
1399 alignPanel.makePNGImageMap(file, image);
1403 * Creates a PNG image of the alignment and writes it to the given file. If
1404 * the file is null, the user is prompted to choose a file.
1409 public void createPNG(File f)
1411 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1415 * Creates an EPS image of the alignment and writes it to the given file. If
1416 * the file is null, the user is prompted to choose a file.
1421 public void createEPS(File f)
1423 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1427 * Creates an SVG image of the alignment and writes it to the given file. If
1428 * the file is null, the user is prompted to choose a file.
1433 public void createSVG(File f)
1435 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1439 public void pageSetup_actionPerformed(ActionEvent e)
1441 PrinterJob printJob = PrinterJob.getPrinterJob();
1442 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1452 public void printMenuItem_actionPerformed(ActionEvent e)
1454 // Putting in a thread avoids Swing painting problems
1455 PrintThread thread = new PrintThread(alignPanel);
1460 public void exportFeatures_actionPerformed(ActionEvent e)
1462 new AnnotationExporter(alignPanel).exportFeatures();
1466 public void exportAnnotations_actionPerformed(ActionEvent e)
1468 new AnnotationExporter(alignPanel).exportAnnotations();
1472 public void associatedData_actionPerformed(ActionEvent e)
1474 final JalviewFileChooser chooser = new JalviewFileChooser(
1475 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1476 chooser.setFileView(new JalviewFileView());
1477 chooser.setDialogTitle(
1478 MessageManager.getString("label.load_jalview_annotations"));
1479 chooser.setToolTipText(
1480 MessageManager.getString("label.load_jalview_annotations"));
1481 chooser.setResponseHandler(0, new Runnable()
1486 String choice = chooser.getSelectedFile().getPath();
1487 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1488 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1492 chooser.showOpenDialog(this);
1496 * Close the current view or all views in the alignment frame. If the frame
1497 * only contains one view then the alignment will be removed from memory.
1499 * @param closeAllTabs
1502 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1504 if (alignPanels != null && alignPanels.size() < 2)
1506 closeAllTabs = true;
1511 if (alignPanels != null)
1515 if (this.isClosed())
1517 // really close all the windows - otherwise wait till
1518 // setClosed(true) is called
1519 for (int i = 0; i < alignPanels.size(); i++)
1521 AlignmentPanel ap = alignPanels.get(i);
1528 closeView(alignPanel);
1535 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1536 * be called recursively, with the frame now in 'closed' state
1538 this.setClosed(true);
1540 } catch (Exception ex)
1542 ex.printStackTrace();
1547 * Close the specified panel and close up tabs appropriately.
1549 * @param panelToClose
1551 public void closeView(AlignmentPanel panelToClose)
1553 int index = tabbedPane.getSelectedIndex();
1554 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1555 alignPanels.remove(panelToClose);
1556 panelToClose.closePanel();
1557 panelToClose = null;
1559 tabbedPane.removeTabAt(closedindex);
1560 tabbedPane.validate();
1562 if (index > closedindex || index == tabbedPane.getTabCount())
1564 // modify currently selected tab index if necessary.
1568 this.tabSelectionChanged(index);
1574 void updateEditMenuBar()
1577 if (viewport.getHistoryList().size() > 0)
1579 undoMenuItem.setEnabled(true);
1580 CommandI command = viewport.getHistoryList().peek();
1581 undoMenuItem.setText(MessageManager
1582 .formatMessage("label.undo_command", new Object[]
1583 { command.getDescription() }));
1587 undoMenuItem.setEnabled(false);
1588 undoMenuItem.setText(MessageManager.getString("action.undo"));
1591 if (viewport.getRedoList().size() > 0)
1593 redoMenuItem.setEnabled(true);
1595 CommandI command = viewport.getRedoList().peek();
1596 redoMenuItem.setText(MessageManager
1597 .formatMessage("label.redo_command", new Object[]
1598 { command.getDescription() }));
1602 redoMenuItem.setEnabled(false);
1603 redoMenuItem.setText(MessageManager.getString("action.redo"));
1608 public void addHistoryItem(CommandI command)
1610 if (command.getSize() > 0)
1612 viewport.addToHistoryList(command);
1613 viewport.clearRedoList();
1614 updateEditMenuBar();
1615 viewport.updateHiddenColumns();
1616 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1617 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1618 // viewport.getColumnSelection()
1619 // .getHiddenColumns().size() > 0);
1625 * @return alignment objects for all views
1627 AlignmentI[] getViewAlignments()
1629 if (alignPanels != null)
1631 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1633 for (AlignmentPanel ap : alignPanels)
1635 als[i++] = ap.av.getAlignment();
1639 if (viewport != null)
1641 return new AlignmentI[] { viewport.getAlignment() };
1653 protected void undoMenuItem_actionPerformed(ActionEvent e)
1655 if (viewport.getHistoryList().isEmpty())
1659 CommandI command = viewport.getHistoryList().pop();
1660 viewport.addToRedoList(command);
1661 command.undoCommand(getViewAlignments());
1663 AlignmentViewport originalSource = getOriginatingSource(command);
1664 updateEditMenuBar();
1666 if (originalSource != null)
1668 if (originalSource != viewport)
1671 "Implementation worry: mismatch of viewport origin for undo");
1673 originalSource.updateHiddenColumns();
1674 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1676 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1677 // viewport.getColumnSelection()
1678 // .getHiddenColumns().size() > 0);
1679 originalSource.firePropertyChange("alignment", null,
1680 originalSource.getAlignment().getSequences());
1691 protected void redoMenuItem_actionPerformed(ActionEvent e)
1693 if (viewport.getRedoList().size() < 1)
1698 CommandI command = viewport.getRedoList().pop();
1699 viewport.addToHistoryList(command);
1700 command.doCommand(getViewAlignments());
1702 AlignmentViewport originalSource = getOriginatingSource(command);
1703 updateEditMenuBar();
1705 if (originalSource != null)
1708 if (originalSource != viewport)
1711 "Implementation worry: mismatch of viewport origin for redo");
1713 originalSource.updateHiddenColumns();
1714 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1716 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1717 // viewport.getColumnSelection()
1718 // .getHiddenColumns().size() > 0);
1719 originalSource.firePropertyChange("alignment", null,
1720 originalSource.getAlignment().getSequences());
1724 AlignmentViewport getOriginatingSource(CommandI command)
1726 AlignmentViewport originalSource = null;
1727 // For sequence removal and addition, we need to fire
1728 // the property change event FROM the viewport where the
1729 // original alignment was altered
1730 AlignmentI al = null;
1731 if (command instanceof EditCommand)
1733 EditCommand editCommand = (EditCommand) command;
1734 al = editCommand.getAlignment();
1735 List<Component> comps = PaintRefresher.components
1736 .get(viewport.getSequenceSetId());
1738 for (Component comp : comps)
1740 if (comp instanceof AlignmentPanel)
1742 if (al == ((AlignmentPanel) comp).av.getAlignment())
1744 originalSource = ((AlignmentPanel) comp).av;
1751 if (originalSource == null)
1753 // The original view is closed, we must validate
1754 // the current view against the closed view first
1757 PaintRefresher.validateSequences(al, viewport.getAlignment());
1760 originalSource = viewport;
1763 return originalSource;
1772 public void moveSelectedSequences(boolean up)
1774 SequenceGroup sg = viewport.getSelectionGroup();
1780 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1781 viewport.getHiddenRepSequences(), up);
1782 alignPanel.paintAlignment(true, false);
1785 synchronized void slideSequences(boolean right, int size)
1787 List<SequenceI> sg = new ArrayList<>();
1788 if (viewport.cursorMode)
1790 sg.add(viewport.getAlignment()
1791 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1793 else if (viewport.getSelectionGroup() != null
1794 && viewport.getSelectionGroup().getSize() != viewport
1795 .getAlignment().getHeight())
1797 sg = viewport.getSelectionGroup()
1798 .getSequences(viewport.getHiddenRepSequences());
1806 List<SequenceI> invertGroup = new ArrayList<>();
1808 for (SequenceI seq : viewport.getAlignment().getSequences())
1810 if (!sg.contains(seq))
1812 invertGroup.add(seq);
1816 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1818 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1819 for (int i = 0; i < invertGroup.size(); i++)
1821 seqs2[i] = invertGroup.get(i);
1824 SlideSequencesCommand ssc;
1827 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1828 viewport.getGapCharacter());
1832 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1833 viewport.getGapCharacter());
1836 int groupAdjustment = 0;
1837 if (ssc.getGapsInsertedBegin() && right)
1839 if (viewport.cursorMode)
1841 alignPanel.getSeqPanel().moveCursor(size, 0);
1845 groupAdjustment = size;
1848 else if (!ssc.getGapsInsertedBegin() && !right)
1850 if (viewport.cursorMode)
1852 alignPanel.getSeqPanel().moveCursor(-size, 0);
1856 groupAdjustment = -size;
1860 if (groupAdjustment != 0)
1862 viewport.getSelectionGroup().setStartRes(
1863 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1864 viewport.getSelectionGroup().setEndRes(
1865 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1869 * just extend the last slide command if compatible; but not if in
1870 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1872 boolean appendHistoryItem = false;
1873 Deque<CommandI> historyList = viewport.getHistoryList();
1874 boolean inSplitFrame = getSplitViewContainer() != null;
1875 if (!inSplitFrame && historyList != null && historyList.size() > 0
1876 && historyList.peek() instanceof SlideSequencesCommand)
1878 appendHistoryItem = ssc.appendSlideCommand(
1879 (SlideSequencesCommand) historyList.peek());
1882 if (!appendHistoryItem)
1884 addHistoryItem(ssc);
1897 protected void copy_actionPerformed(ActionEvent e)
1899 if (viewport.getSelectionGroup() == null)
1903 // TODO: preserve the ordering of displayed alignment annotation in any
1904 // internal paste (particularly sequence associated annotation)
1905 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1906 String[] omitHidden = null;
1908 if (viewport.hasHiddenColumns())
1910 omitHidden = viewport.getViewAsString(true);
1913 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1914 seqs, omitHidden, null);
1916 StringSelection ss = new StringSelection(output);
1920 jalview.gui.Desktop.internalCopy = true;
1921 // Its really worth setting the clipboard contents
1922 // to empty before setting the large StringSelection!!
1923 Toolkit.getDefaultToolkit().getSystemClipboard()
1924 .setContents(new StringSelection(""), null);
1926 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1928 } catch (OutOfMemoryError er)
1930 new OOMWarning("copying region", er);
1934 HiddenColumns hiddenColumns = null;
1935 if (viewport.hasHiddenColumns())
1937 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1938 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1940 // create new HiddenColumns object with copy of hidden regions
1941 // between startRes and endRes, offset by startRes
1942 hiddenColumns = new HiddenColumns(
1943 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
1944 hiddenCutoff, hiddenOffset);
1947 Desktop.jalviewClipboard = new Object[] { seqs,
1948 viewport.getAlignment().getDataset(), hiddenColumns };
1949 setStatus(MessageManager.formatMessage(
1950 "label.copied_sequences_to_clipboard", new Object[]
1951 { Integer.valueOf(seqs.length).toString() }));
1961 protected void pasteNew_actionPerformed(ActionEvent e)
1973 protected void pasteThis_actionPerformed(ActionEvent e)
1979 * Paste contents of Jalview clipboard
1981 * @param newAlignment
1982 * true to paste to a new alignment, otherwise add to this.
1984 void paste(boolean newAlignment)
1986 boolean externalPaste = true;
1989 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1990 Transferable contents = c.getContents(this);
1992 if (contents == null)
2001 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2002 if (str.length() < 1)
2007 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2009 } catch (OutOfMemoryError er)
2011 new OOMWarning("Out of memory pasting sequences!!", er);
2015 SequenceI[] sequences;
2016 boolean annotationAdded = false;
2017 AlignmentI alignment = null;
2019 if (Desktop.jalviewClipboard != null)
2021 // The clipboard was filled from within Jalview, we must use the
2023 // And dataset from the copied alignment
2024 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2025 // be doubly sure that we create *new* sequence objects.
2026 sequences = new SequenceI[newseq.length];
2027 for (int i = 0; i < newseq.length; i++)
2029 sequences[i] = new Sequence(newseq[i]);
2031 alignment = new Alignment(sequences);
2032 externalPaste = false;
2036 // parse the clipboard as an alignment.
2037 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2039 sequences = alignment.getSequencesArray();
2043 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2049 if (Desktop.jalviewClipboard != null)
2051 // dataset is inherited
2052 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2056 // new dataset is constructed
2057 alignment.setDataset(null);
2059 alwidth = alignment.getWidth() + 1;
2063 AlignmentI pastedal = alignment; // preserve pasted alignment object
2064 // Add pasted sequences and dataset into existing alignment.
2065 alignment = viewport.getAlignment();
2066 alwidth = alignment.getWidth() + 1;
2067 // decide if we need to import sequences from an existing dataset
2068 boolean importDs = Desktop.jalviewClipboard != null
2069 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2070 // importDs==true instructs us to copy over new dataset sequences from
2071 // an existing alignment
2072 Vector newDs = (importDs) ? new Vector() : null; // used to create
2073 // minimum dataset set
2075 for (int i = 0; i < sequences.length; i++)
2079 newDs.addElement(null);
2081 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2083 if (importDs && ds != null)
2085 if (!newDs.contains(ds))
2087 newDs.setElementAt(ds, i);
2088 ds = new Sequence(ds);
2089 // update with new dataset sequence
2090 sequences[i].setDatasetSequence(ds);
2094 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2099 // copy and derive new dataset sequence
2100 sequences[i] = sequences[i].deriveSequence();
2101 alignment.getDataset()
2102 .addSequence(sequences[i].getDatasetSequence());
2103 // TODO: avoid creation of duplicate dataset sequences with a
2104 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2106 alignment.addSequence(sequences[i]); // merges dataset
2110 newDs.clear(); // tidy up
2112 if (alignment.getAlignmentAnnotation() != null)
2114 for (AlignmentAnnotation alan : alignment
2115 .getAlignmentAnnotation())
2117 if (alan.graphGroup > fgroup)
2119 fgroup = alan.graphGroup;
2123 if (pastedal.getAlignmentAnnotation() != null)
2125 // Add any annotation attached to alignment.
2126 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2127 for (int i = 0; i < alann.length; i++)
2129 annotationAdded = true;
2130 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2132 AlignmentAnnotation newann = new AlignmentAnnotation(
2134 if (newann.graphGroup > -1)
2136 if (newGraphGroups.size() <= newann.graphGroup
2137 || newGraphGroups.get(newann.graphGroup) == null)
2139 for (int q = newGraphGroups
2140 .size(); q <= newann.graphGroup; q++)
2142 newGraphGroups.add(q, null);
2144 newGraphGroups.set(newann.graphGroup,
2145 new Integer(++fgroup));
2147 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2151 newann.padAnnotation(alwidth);
2152 alignment.addAnnotation(newann);
2162 addHistoryItem(new EditCommand(
2163 MessageManager.getString("label.add_sequences"),
2164 Action.PASTE, sequences, 0, alignment.getWidth(),
2167 // Add any annotations attached to sequences
2168 for (int i = 0; i < sequences.length; i++)
2170 if (sequences[i].getAnnotation() != null)
2172 AlignmentAnnotation newann;
2173 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2175 annotationAdded = true;
2176 newann = sequences[i].getAnnotation()[a];
2177 newann.adjustForAlignment();
2178 newann.padAnnotation(alwidth);
2179 if (newann.graphGroup > -1)
2181 if (newann.graphGroup > -1)
2183 if (newGraphGroups.size() <= newann.graphGroup
2184 || newGraphGroups.get(newann.graphGroup) == null)
2186 for (int q = newGraphGroups
2187 .size(); q <= newann.graphGroup; q++)
2189 newGraphGroups.add(q, null);
2191 newGraphGroups.set(newann.graphGroup,
2192 new Integer(++fgroup));
2194 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2198 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2202 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2210 // propagate alignment changed.
2211 viewport.getRanges().setEndSeq(alignment.getHeight());
2212 if (annotationAdded)
2214 // Duplicate sequence annotation in all views.
2215 AlignmentI[] alview = this.getViewAlignments();
2216 for (int i = 0; i < sequences.length; i++)
2218 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2223 for (int avnum = 0; avnum < alview.length; avnum++)
2225 if (alview[avnum] != alignment)
2227 // duplicate in a view other than the one with input focus
2228 int avwidth = alview[avnum].getWidth() + 1;
2229 // this relies on sann being preserved after we
2230 // modify the sequence's annotation array for each duplication
2231 for (int a = 0; a < sann.length; a++)
2233 AlignmentAnnotation newann = new AlignmentAnnotation(
2235 sequences[i].addAlignmentAnnotation(newann);
2236 newann.padAnnotation(avwidth);
2237 alview[avnum].addAnnotation(newann); // annotation was
2238 // duplicated earlier
2239 // TODO JAL-1145 graphGroups are not updated for sequence
2240 // annotation added to several views. This may cause
2242 alview[avnum].setAnnotationIndex(newann, a);
2247 buildSortByAnnotationScoresMenu();
2249 viewport.firePropertyChange("alignment", null,
2250 alignment.getSequences());
2251 if (alignPanels != null)
2253 for (AlignmentPanel ap : alignPanels)
2255 ap.validateAnnotationDimensions(false);
2260 alignPanel.validateAnnotationDimensions(false);
2266 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2268 String newtitle = new String("Copied sequences");
2270 if (Desktop.jalviewClipboard != null
2271 && Desktop.jalviewClipboard[2] != null)
2273 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2274 af.viewport.setHiddenColumns(hc);
2277 // >>>This is a fix for the moment, until a better solution is
2279 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2280 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2281 .getFeatureRenderer());
2283 // TODO: maintain provenance of an alignment, rather than just make the
2284 // title a concatenation of operations.
2287 if (title.startsWith("Copied sequences"))
2293 newtitle = newtitle.concat("- from " + title);
2298 newtitle = new String("Pasted sequences");
2301 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2306 } catch (Exception ex)
2308 ex.printStackTrace();
2309 System.out.println("Exception whilst pasting: " + ex);
2310 // could be anything being pasted in here
2316 protected void expand_newalign(ActionEvent e)
2320 AlignmentI alignment = AlignmentUtils
2321 .expandContext(getViewport().getAlignment(), -1);
2322 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2324 String newtitle = new String("Flanking alignment");
2326 if (Desktop.jalviewClipboard != null
2327 && Desktop.jalviewClipboard[2] != null)
2329 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2330 af.viewport.setHiddenColumns(hc);
2333 // >>>This is a fix for the moment, until a better solution is
2335 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2336 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2337 .getFeatureRenderer());
2339 // TODO: maintain provenance of an alignment, rather than just make the
2340 // title a concatenation of operations.
2342 if (title.startsWith("Copied sequences"))
2348 newtitle = newtitle.concat("- from " + title);
2352 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2354 } catch (Exception ex)
2356 ex.printStackTrace();
2357 System.out.println("Exception whilst pasting: " + ex);
2358 // could be anything being pasted in here
2359 } catch (OutOfMemoryError oom)
2361 new OOMWarning("Viewing flanking region of alignment", oom);
2372 protected void cut_actionPerformed(ActionEvent e)
2374 copy_actionPerformed(null);
2375 delete_actionPerformed(null);
2385 protected void delete_actionPerformed(ActionEvent evt)
2388 SequenceGroup sg = viewport.getSelectionGroup();
2395 * If the cut affects all sequences, warn, remove highlighted columns
2397 if (sg.getSize() == viewport.getAlignment().getHeight())
2399 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2400 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2401 if (isEntireAlignWidth)
2403 int confirm = JvOptionPane.showConfirmDialog(this,
2404 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2405 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2406 JvOptionPane.OK_CANCEL_OPTION);
2408 if (confirm == JvOptionPane.CANCEL_OPTION
2409 || confirm == JvOptionPane.CLOSED_OPTION)
2414 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2415 sg.getEndRes() + 1);
2417 SequenceI[] cut = sg.getSequences()
2418 .toArray(new SequenceI[sg.getSize()]);
2420 addHistoryItem(new EditCommand(
2421 MessageManager.getString("label.cut_sequences"), Action.CUT,
2422 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2423 viewport.getAlignment()));
2425 viewport.setSelectionGroup(null);
2426 viewport.sendSelection();
2427 viewport.getAlignment().deleteGroup(sg);
2429 viewport.firePropertyChange("alignment", null,
2430 viewport.getAlignment().getSequences());
2431 if (viewport.getAlignment().getHeight() < 1)
2435 this.setClosed(true);
2436 } catch (Exception ex)
2449 protected void deleteGroups_actionPerformed(ActionEvent e)
2451 if (avc.deleteGroups())
2453 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2454 alignPanel.updateAnnotation();
2455 alignPanel.paintAlignment(true, true);
2466 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2468 SequenceGroup sg = new SequenceGroup();
2470 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2472 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2475 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2476 viewport.setSelectionGroup(sg);
2477 viewport.sendSelection();
2478 // JAL-2034 - should delegate to
2479 // alignPanel to decide if overview needs
2481 alignPanel.paintAlignment(false, false);
2482 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2492 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2494 if (viewport.cursorMode)
2496 alignPanel.getSeqPanel().keyboardNo1 = null;
2497 alignPanel.getSeqPanel().keyboardNo2 = null;
2499 viewport.setSelectionGroup(null);
2500 viewport.getColumnSelection().clear();
2501 viewport.setSelectionGroup(null);
2502 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2503 // JAL-2034 - should delegate to
2504 // alignPanel to decide if overview needs
2506 alignPanel.paintAlignment(false, false);
2507 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2508 viewport.sendSelection();
2518 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2520 SequenceGroup sg = viewport.getSelectionGroup();
2524 selectAllSequenceMenuItem_actionPerformed(null);
2529 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2531 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2533 // JAL-2034 - should delegate to
2534 // alignPanel to decide if overview needs
2537 alignPanel.paintAlignment(true, false);
2538 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2539 viewport.sendSelection();
2543 public void invertColSel_actionPerformed(ActionEvent e)
2545 viewport.invertColumnSelection();
2546 alignPanel.paintAlignment(true, false);
2547 viewport.sendSelection();
2557 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2559 trimAlignment(true);
2569 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2571 trimAlignment(false);
2574 void trimAlignment(boolean trimLeft)
2576 ColumnSelection colSel = viewport.getColumnSelection();
2579 if (!colSel.isEmpty())
2583 column = colSel.getMin();
2587 column = colSel.getMax();
2591 if (viewport.getSelectionGroup() != null)
2593 seqs = viewport.getSelectionGroup()
2594 .getSequencesAsArray(viewport.getHiddenRepSequences());
2598 seqs = viewport.getAlignment().getSequencesArray();
2601 TrimRegionCommand trimRegion;
2604 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2605 column, viewport.getAlignment());
2606 viewport.getRanges().setStartRes(0);
2610 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2611 column, viewport.getAlignment());
2614 setStatus(MessageManager
2615 .formatMessage("label.removed_columns", new String[]
2616 { Integer.valueOf(trimRegion.getSize()).toString() }));
2618 addHistoryItem(trimRegion);
2620 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2622 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2623 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2625 viewport.getAlignment().deleteGroup(sg);
2629 viewport.firePropertyChange("alignment", null,
2630 viewport.getAlignment().getSequences());
2641 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2643 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2646 if (viewport.getSelectionGroup() != null)
2648 seqs = viewport.getSelectionGroup()
2649 .getSequencesAsArray(viewport.getHiddenRepSequences());
2650 start = viewport.getSelectionGroup().getStartRes();
2651 end = viewport.getSelectionGroup().getEndRes();
2655 seqs = viewport.getAlignment().getSequencesArray();
2658 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2659 "Remove Gapped Columns", seqs, start, end,
2660 viewport.getAlignment());
2662 addHistoryItem(removeGapCols);
2664 setStatus(MessageManager
2665 .formatMessage("label.removed_empty_columns", new Object[]
2666 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2668 // This is to maintain viewport position on first residue
2669 // of first sequence
2670 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2671 ViewportRanges ranges = viewport.getRanges();
2672 int startRes = seq.findPosition(ranges.getStartRes());
2673 // ShiftList shifts;
2674 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2675 // edit.alColumnChanges=shifts.getInverse();
2676 // if (viewport.hasHiddenColumns)
2677 // viewport.getColumnSelection().compensateForEdits(shifts);
2678 ranges.setStartRes(seq.findIndex(startRes) - 1);
2679 viewport.firePropertyChange("alignment", null,
2680 viewport.getAlignment().getSequences());
2691 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2693 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2696 if (viewport.getSelectionGroup() != null)
2698 seqs = viewport.getSelectionGroup()
2699 .getSequencesAsArray(viewport.getHiddenRepSequences());
2700 start = viewport.getSelectionGroup().getStartRes();
2701 end = viewport.getSelectionGroup().getEndRes();
2705 seqs = viewport.getAlignment().getSequencesArray();
2708 // This is to maintain viewport position on first residue
2709 // of first sequence
2710 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2711 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2713 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2714 viewport.getAlignment()));
2716 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2718 viewport.firePropertyChange("alignment", null,
2719 viewport.getAlignment().getSequences());
2730 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2732 viewport.setPadGaps(padGapsMenuitem.isSelected());
2733 viewport.firePropertyChange("alignment", null,
2734 viewport.getAlignment().getSequences());
2744 public void findMenuItem_actionPerformed(ActionEvent e)
2750 * Create a new view of the current alignment.
2753 public void newView_actionPerformed(ActionEvent e)
2755 newView(null, true);
2759 * Creates and shows a new view of the current alignment.
2762 * title of newly created view; if null, one will be generated
2763 * @param copyAnnotation
2764 * if true then duplicate all annnotation, groups and settings
2765 * @return new alignment panel, already displayed.
2767 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2770 * Create a new AlignmentPanel (with its own, new Viewport)
2772 AlignmentPanel newap = new jalview.project.Jalview2XML()
2773 .copyAlignPanel(alignPanel);
2774 if (!copyAnnotation)
2777 * remove all groups and annotation except for the automatic stuff
2779 newap.av.getAlignment().deleteAllGroups();
2780 newap.av.getAlignment().deleteAllAnnotations(false);
2783 newap.av.setGatherViewsHere(false);
2785 if (viewport.getViewName() == null)
2787 viewport.setViewName(MessageManager
2788 .getString("label.view_name_original"));
2792 * Views share the same edits undo and redo stacks
2794 newap.av.setHistoryList(viewport.getHistoryList());
2795 newap.av.setRedoList(viewport.getRedoList());
2798 * Views share the same mappings; need to deregister any new mappings
2799 * created by copyAlignPanel, and register the new reference to the shared
2802 newap.av.replaceMappings(viewport.getAlignment());
2805 * start up cDNA consensus (if applicable) now mappings are in place
2807 if (newap.av.initComplementConsensus())
2809 newap.refresh(true); // adjust layout of annotations
2812 newap.av.setViewName(getNewViewName(viewTitle));
2814 addAlignmentPanel(newap, true);
2815 newap.alignmentChanged();
2817 if (alignPanels.size() == 2)
2819 viewport.setGatherViewsHere(true);
2821 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2826 * Make a new name for the view, ensuring it is unique within the current
2827 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2828 * these now use viewId. Unique view names are still desirable for usability.)
2833 protected String getNewViewName(String viewTitle)
2835 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2836 boolean addFirstIndex = false;
2837 if (viewTitle == null || viewTitle.trim().length() == 0)
2839 viewTitle = MessageManager.getString("action.view");
2840 addFirstIndex = true;
2844 index = 1;// we count from 1 if given a specific name
2846 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2848 List<Component> comps = PaintRefresher.components
2849 .get(viewport.getSequenceSetId());
2851 List<String> existingNames = getExistingViewNames(comps);
2853 while (existingNames.contains(newViewName))
2855 newViewName = viewTitle + " " + (++index);
2861 * Returns a list of distinct view names found in the given list of
2862 * components. View names are held on the viewport of an AlignmentPanel.
2867 protected List<String> getExistingViewNames(List<Component> comps)
2869 List<String> existingNames = new ArrayList<>();
2870 for (Component comp : comps)
2872 if (comp instanceof AlignmentPanel)
2874 AlignmentPanel ap = (AlignmentPanel) comp;
2875 if (!existingNames.contains(ap.av.getViewName()))
2877 existingNames.add(ap.av.getViewName());
2881 return existingNames;
2885 * Explode tabbed views into separate windows.
2888 public void expandViews_actionPerformed(ActionEvent e)
2890 Desktop.explodeViews(this);
2894 * Gather views in separate windows back into a tabbed presentation.
2897 public void gatherViews_actionPerformed(ActionEvent e)
2899 Desktop.instance.gatherViews(this);
2909 public void font_actionPerformed(ActionEvent e)
2911 new FontChooser(alignPanel);
2921 protected void seqLimit_actionPerformed(ActionEvent e)
2923 viewport.setShowJVSuffix(seqLimits.isSelected());
2925 alignPanel.getIdPanel().getIdCanvas()
2926 .setPreferredSize(alignPanel.calculateIdWidth());
2927 alignPanel.paintAlignment(true, false);
2931 public void idRightAlign_actionPerformed(ActionEvent e)
2933 viewport.setRightAlignIds(idRightAlign.isSelected());
2934 alignPanel.paintAlignment(false, false);
2938 public void centreColumnLabels_actionPerformed(ActionEvent e)
2940 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2941 alignPanel.paintAlignment(false, false);
2947 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2950 protected void followHighlight_actionPerformed()
2953 * Set the 'follow' flag on the Viewport (and scroll to position if now
2956 final boolean state = this.followHighlightMenuItem.getState();
2957 viewport.setFollowHighlight(state);
2960 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2971 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2973 viewport.setColourText(colourTextMenuItem.isSelected());
2974 alignPanel.paintAlignment(false, false);
2984 public void wrapMenuItem_actionPerformed(ActionEvent e)
2986 scaleAbove.setVisible(wrapMenuItem.isSelected());
2987 scaleLeft.setVisible(wrapMenuItem.isSelected());
2988 scaleRight.setVisible(wrapMenuItem.isSelected());
2989 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2990 alignPanel.updateLayout();
2994 public void showAllSeqs_actionPerformed(ActionEvent e)
2996 viewport.showAllHiddenSeqs();
3000 public void showAllColumns_actionPerformed(ActionEvent e)
3002 viewport.showAllHiddenColumns();
3003 alignPanel.paintAlignment(true, true);
3004 viewport.sendSelection();
3008 public void hideSelSequences_actionPerformed(ActionEvent e)
3010 viewport.hideAllSelectedSeqs();
3014 * called by key handler and the hide all/show all menu items
3019 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3022 boolean hide = false;
3023 SequenceGroup sg = viewport.getSelectionGroup();
3024 if (!toggleSeqs && !toggleCols)
3026 // Hide everything by the current selection - this is a hack - we do the
3027 // invert and then hide
3028 // first check that there will be visible columns after the invert.
3029 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3030 && sg.getStartRes() <= sg.getEndRes()))
3032 // now invert the sequence set, if required - empty selection implies
3033 // that no hiding is required.
3036 invertSequenceMenuItem_actionPerformed(null);
3037 sg = viewport.getSelectionGroup();
3041 viewport.expandColSelection(sg, true);
3042 // finally invert the column selection and get the new sequence
3044 invertColSel_actionPerformed(null);
3051 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3053 hideSelSequences_actionPerformed(null);
3056 else if (!(toggleCols && viewport.hasSelectedColumns()))
3058 showAllSeqs_actionPerformed(null);
3064 if (viewport.hasSelectedColumns())
3066 hideSelColumns_actionPerformed(null);
3069 viewport.setSelectionGroup(sg);
3074 showAllColumns_actionPerformed(null);
3083 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3084 * event.ActionEvent)
3087 public void hideAllButSelection_actionPerformed(ActionEvent e)
3089 toggleHiddenRegions(false, false);
3090 viewport.sendSelection();
3097 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3101 public void hideAllSelection_actionPerformed(ActionEvent e)
3103 SequenceGroup sg = viewport.getSelectionGroup();
3104 viewport.expandColSelection(sg, false);
3105 viewport.hideAllSelectedSeqs();
3106 viewport.hideSelectedColumns();
3107 alignPanel.paintAlignment(true, true);
3108 viewport.sendSelection();
3115 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3119 public void showAllhidden_actionPerformed(ActionEvent e)
3121 viewport.showAllHiddenColumns();
3122 viewport.showAllHiddenSeqs();
3123 alignPanel.paintAlignment(true, true);
3124 viewport.sendSelection();
3128 public void hideSelColumns_actionPerformed(ActionEvent e)
3130 viewport.hideSelectedColumns();
3131 alignPanel.paintAlignment(true, true);
3132 viewport.sendSelection();
3136 public void hiddenMarkers_actionPerformed(ActionEvent e)
3138 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3149 protected void scaleAbove_actionPerformed(ActionEvent e)
3151 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3152 // TODO: do we actually need to update overview for scale above change ?
3153 alignPanel.paintAlignment(true, false);
3163 protected void scaleLeft_actionPerformed(ActionEvent e)
3165 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3166 alignPanel.paintAlignment(true, false);
3176 protected void scaleRight_actionPerformed(ActionEvent e)
3178 viewport.setScaleRightWrapped(scaleRight.isSelected());
3179 alignPanel.paintAlignment(true, false);
3189 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3191 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3192 alignPanel.paintAlignment(false, false);
3202 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3204 viewport.setShowText(viewTextMenuItem.isSelected());
3205 alignPanel.paintAlignment(false, false);
3215 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3217 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3218 alignPanel.paintAlignment(false, false);
3221 public FeatureSettings featureSettings;
3224 public FeatureSettingsControllerI getFeatureSettingsUI()
3226 return featureSettings;
3230 public void featureSettings_actionPerformed(ActionEvent e)
3232 if (featureSettings != null)
3234 featureSettings.close();
3235 featureSettings = null;
3237 if (!showSeqFeatures.isSelected())
3239 // make sure features are actually displayed
3240 showSeqFeatures.setSelected(true);
3241 showSeqFeatures_actionPerformed(null);
3243 featureSettings = new FeatureSettings(this);
3247 * Set or clear 'Show Sequence Features'
3253 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3255 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3256 alignPanel.paintAlignment(true, true);
3260 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3261 * the annotations panel as a whole.
3263 * The options to show/hide all annotations should be enabled when the panel
3264 * is shown, and disabled when the panel is hidden.
3269 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3271 final boolean setVisible = annotationPanelMenuItem.isSelected();
3272 viewport.setShowAnnotation(setVisible);
3273 this.showAllSeqAnnotations.setEnabled(setVisible);
3274 this.hideAllSeqAnnotations.setEnabled(setVisible);
3275 this.showAllAlAnnotations.setEnabled(setVisible);
3276 this.hideAllAlAnnotations.setEnabled(setVisible);
3277 alignPanel.updateLayout();
3281 public void alignmentProperties()
3284 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3287 String content = MessageManager.formatMessage("label.html_content",
3289 { contents.toString() });
3294 JLabel textLabel = new JLabel();
3295 textLabel.setText(content);
3296 textLabel.setBackground(Color.WHITE);
3298 pane = new JPanel(new BorderLayout());
3299 ((JPanel) pane).setOpaque(true);
3300 pane.setBackground(Color.WHITE);
3301 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3305 JEditorPane editPane = new JEditorPane("text/html", "");
3306 editPane.setEditable(false);
3307 editPane.setText(content);
3311 JInternalFrame frame = new JInternalFrame();
3313 frame.getContentPane().add(new JScrollPane(pane));
3315 Desktop.addInternalFrame(frame, MessageManager
3316 .formatMessage("label.alignment_properties", new Object[]
3317 { getTitle() }), 500, 400);
3327 public void overviewMenuItem_actionPerformed(ActionEvent e)
3329 if (alignPanel.overviewPanel != null)
3334 JInternalFrame frame = new JInternalFrame();
3335 final OverviewPanel overview = new OverviewPanel(alignPanel);
3336 frame.setContentPane(overview);
3337 Desktop.addInternalFrame(frame, MessageManager
3338 .formatMessage("label.overview_params", new Object[]
3339 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3342 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3343 frame.addInternalFrameListener(
3344 new javax.swing.event.InternalFrameAdapter()
3347 public void internalFrameClosed(
3348 javax.swing.event.InternalFrameEvent evt)
3351 alignPanel.setOverviewPanel(null);
3354 if (getKeyListeners().length > 0)
3356 frame.addKeyListener(getKeyListeners()[0]);
3359 alignPanel.setOverviewPanel(overview);
3363 public void textColour_actionPerformed()
3365 new TextColourChooser().chooseColour(alignPanel, null);
3369 * public void covariationColour_actionPerformed() {
3371 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3375 public void annotationColour_actionPerformed()
3377 new AnnotationColourChooser(viewport, alignPanel);
3381 public void annotationColumn_actionPerformed(ActionEvent e)
3383 new AnnotationColumnChooser(viewport, alignPanel);
3387 * Action on the user checking or unchecking the option to apply the selected
3388 * colour scheme to all groups. If unchecked, groups may have their own
3389 * independent colour schemes.
3394 public void applyToAllGroups_actionPerformed(boolean selected)
3396 viewport.setColourAppliesToAllGroups(selected);
3400 * Action on user selecting a colour from the colour menu
3403 * the name (not the menu item label!) of the colour scheme
3406 public void changeColour_actionPerformed(String name)
3409 * 'User Defined' opens a panel to configure or load a
3410 * user-defined colour scheme
3412 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3414 new UserDefinedColours(alignPanel);
3419 * otherwise set the chosen colour scheme (or null for 'None')
3421 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3422 viewport.getAlignment(), viewport.getHiddenRepSequences());
3427 * Actions on setting or changing the alignment colour scheme
3432 public void changeColour(ColourSchemeI cs)
3434 // TODO: pull up to controller method
3435 ColourMenuHelper.setColourSelected(colourMenu, cs);
3437 viewport.setGlobalColourScheme(cs);
3439 alignPanel.paintAlignment(true, true);
3443 * Show the PID threshold slider panel
3446 protected void modifyPID_actionPerformed()
3448 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3449 alignPanel.getViewName());
3450 SliderPanel.showPIDSlider();
3454 * Show the Conservation slider panel
3457 protected void modifyConservation_actionPerformed()
3459 SliderPanel.setConservationSlider(alignPanel,
3460 viewport.getResidueShading(), alignPanel.getViewName());
3461 SliderPanel.showConservationSlider();
3465 * Action on selecting or deselecting (Colour) By Conservation
3468 public void conservationMenuItem_actionPerformed(boolean selected)
3470 modifyConservation.setEnabled(selected);
3471 viewport.setConservationSelected(selected);
3472 viewport.getResidueShading().setConservationApplied(selected);
3474 changeColour(viewport.getGlobalColourScheme());
3477 modifyConservation_actionPerformed();
3481 SliderPanel.hideConservationSlider();
3486 * Action on selecting or deselecting (Colour) Above PID Threshold
3489 public void abovePIDThreshold_actionPerformed(boolean selected)
3491 modifyPID.setEnabled(selected);
3492 viewport.setAbovePIDThreshold(selected);
3495 viewport.getResidueShading().setThreshold(0,
3496 viewport.isIgnoreGapsConsensus());
3499 changeColour(viewport.getGlobalColourScheme());
3502 modifyPID_actionPerformed();
3506 SliderPanel.hidePIDSlider();
3517 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3519 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3520 AlignmentSorter.sortByPID(viewport.getAlignment(),
3521 viewport.getAlignment().getSequenceAt(0));
3522 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3523 viewport.getAlignment()));
3524 alignPanel.paintAlignment(true, false);
3534 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3536 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3537 AlignmentSorter.sortByID(viewport.getAlignment());
3539 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3540 alignPanel.paintAlignment(true, false);
3550 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3552 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3553 AlignmentSorter.sortByLength(viewport.getAlignment());
3554 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3555 viewport.getAlignment()));
3556 alignPanel.paintAlignment(true, false);
3566 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3568 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3569 AlignmentSorter.sortByGroup(viewport.getAlignment());
3570 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3571 viewport.getAlignment()));
3573 alignPanel.paintAlignment(true, false);
3583 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3585 new RedundancyPanel(alignPanel, this);
3595 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3597 if ((viewport.getSelectionGroup() == null)
3598 || (viewport.getSelectionGroup().getSize() < 2))
3600 JvOptionPane.showInternalMessageDialog(this,
3601 MessageManager.getString(
3602 "label.you_must_select_least_two_sequences"),
3603 MessageManager.getString("label.invalid_selection"),
3604 JvOptionPane.WARNING_MESSAGE);
3608 JInternalFrame frame = new JInternalFrame();
3609 frame.setContentPane(new PairwiseAlignPanel(viewport));
3610 Desktop.addInternalFrame(frame,
3611 MessageManager.getString("action.pairwise_alignment"), 600,
3617 public void autoCalculate_actionPerformed(ActionEvent e)
3619 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3620 if (viewport.autoCalculateConsensus)
3622 viewport.firePropertyChange("alignment", null,
3623 viewport.getAlignment().getSequences());
3628 public void sortByTreeOption_actionPerformed(ActionEvent e)
3630 viewport.sortByTree = sortByTree.isSelected();
3634 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3636 viewport.followSelection = listenToViewSelections.isSelected();
3640 * Constructs a tree panel and adds it to the desktop
3643 * tree type (NJ or AV)
3645 * name of score model used to compute the tree
3647 * parameters for the distance or similarity calculation
3649 void newTreePanel(String type, String modelName,
3650 SimilarityParamsI options)
3652 String frameTitle = "";
3655 boolean onSelection = false;
3656 if (viewport.getSelectionGroup() != null
3657 && viewport.getSelectionGroup().getSize() > 0)
3659 SequenceGroup sg = viewport.getSelectionGroup();
3661 /* Decide if the selection is a column region */
3662 for (SequenceI _s : sg.getSequences())
3664 if (_s.getLength() < sg.getEndRes())
3666 JvOptionPane.showMessageDialog(Desktop.desktop,
3667 MessageManager.getString(
3668 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3669 MessageManager.getString(
3670 "label.sequences_selection_not_aligned"),
3671 JvOptionPane.WARNING_MESSAGE);
3680 if (viewport.getAlignment().getHeight() < 2)
3686 tp = new TreePanel(alignPanel, type, modelName, options);
3687 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3689 frameTitle += " from ";
3691 if (viewport.getViewName() != null)
3693 frameTitle += viewport.getViewName() + " of ";
3696 frameTitle += this.title;
3698 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3709 public void addSortByOrderMenuItem(String title,
3710 final AlignmentOrder order)
3712 final JMenuItem item = new JMenuItem(MessageManager
3713 .formatMessage("action.by_title_param", new Object[]
3716 item.addActionListener(new java.awt.event.ActionListener()
3719 public void actionPerformed(ActionEvent e)
3721 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3723 // TODO: JBPNote - have to map order entries to curent SequenceI
3725 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3727 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3728 viewport.getAlignment()));
3730 alignPanel.paintAlignment(true, false);
3736 * Add a new sort by annotation score menu item
3739 * the menu to add the option to
3741 * the label used to retrieve scores for each sequence on the
3744 public void addSortByAnnotScoreMenuItem(JMenu sort,
3745 final String scoreLabel)
3747 final JMenuItem item = new JMenuItem(scoreLabel);
3749 item.addActionListener(new java.awt.event.ActionListener()
3752 public void actionPerformed(ActionEvent e)
3754 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3755 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3756 viewport.getAlignment());// ,viewport.getSelectionGroup());
3757 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3758 viewport.getAlignment()));
3759 alignPanel.paintAlignment(true, false);
3765 * last hash for alignment's annotation array - used to minimise cost of
3768 protected int _annotationScoreVectorHash;
3771 * search the alignment and rebuild the sort by annotation score submenu the
3772 * last alignment annotation vector hash is stored to minimize cost of
3773 * rebuilding in subsequence calls.
3777 public void buildSortByAnnotationScoresMenu()
3779 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3784 if (viewport.getAlignment().getAlignmentAnnotation()
3785 .hashCode() != _annotationScoreVectorHash)
3787 sortByAnnotScore.removeAll();
3788 // almost certainly a quicker way to do this - but we keep it simple
3789 Hashtable scoreSorts = new Hashtable();
3790 AlignmentAnnotation aann[];
3791 for (SequenceI sqa : viewport.getAlignment().getSequences())
3793 aann = sqa.getAnnotation();
3794 for (int i = 0; aann != null && i < aann.length; i++)
3796 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3798 scoreSorts.put(aann[i].label, aann[i].label);
3802 Enumeration labels = scoreSorts.keys();
3803 while (labels.hasMoreElements())
3805 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3806 (String) labels.nextElement());
3808 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3811 _annotationScoreVectorHash = viewport.getAlignment()
3812 .getAlignmentAnnotation().hashCode();
3817 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3818 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3819 * call. Listeners are added to remove the menu item when the treePanel is
3820 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3824 public void buildTreeSortMenu()
3826 sortByTreeMenu.removeAll();
3828 List<Component> comps = PaintRefresher.components
3829 .get(viewport.getSequenceSetId());
3830 List<TreePanel> treePanels = new ArrayList<>();
3831 for (Component comp : comps)
3833 if (comp instanceof TreePanel)
3835 treePanels.add((TreePanel) comp);
3839 if (treePanels.size() < 1)
3841 sortByTreeMenu.setVisible(false);
3845 sortByTreeMenu.setVisible(true);
3847 for (final TreePanel tp : treePanels)
3849 final JMenuItem item = new JMenuItem(tp.getTitle());
3850 item.addActionListener(new java.awt.event.ActionListener()
3853 public void actionPerformed(ActionEvent e)
3855 tp.sortByTree_actionPerformed();
3856 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3861 sortByTreeMenu.add(item);
3865 public boolean sortBy(AlignmentOrder alorder, String undoname)
3867 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3868 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3869 if (undoname != null)
3871 addHistoryItem(new OrderCommand(undoname, oldOrder,
3872 viewport.getAlignment()));
3874 alignPanel.paintAlignment(true, false);
3879 * Work out whether the whole set of sequences or just the selected set will
3880 * be submitted for multiple alignment.
3883 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3885 // Now, check we have enough sequences
3886 AlignmentView msa = null;
3888 if ((viewport.getSelectionGroup() != null)
3889 && (viewport.getSelectionGroup().getSize() > 1))
3891 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3892 // some common interface!
3894 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3895 * SequenceI[sz = seqs.getSize(false)];
3897 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3898 * seqs.getSequenceAt(i); }
3900 msa = viewport.getAlignmentView(true);
3902 else if (viewport.getSelectionGroup() != null
3903 && viewport.getSelectionGroup().getSize() == 1)
3905 int option = JvOptionPane.showConfirmDialog(this,
3906 MessageManager.getString("warn.oneseq_msainput_selection"),
3907 MessageManager.getString("label.invalid_selection"),
3908 JvOptionPane.OK_CANCEL_OPTION);
3909 if (option == JvOptionPane.OK_OPTION)
3911 msa = viewport.getAlignmentView(false);
3916 msa = viewport.getAlignmentView(false);
3922 * Decides what is submitted to a secondary structure prediction service: the
3923 * first sequence in the alignment, or in the current selection, or, if the
3924 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3925 * region or the whole alignment. (where the first sequence in the set is the
3926 * one that the prediction will be for).
3928 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3930 AlignmentView seqs = null;
3932 if ((viewport.getSelectionGroup() != null)
3933 && (viewport.getSelectionGroup().getSize() > 0))
3935 seqs = viewport.getAlignmentView(true);
3939 seqs = viewport.getAlignmentView(false);
3941 // limit sequences - JBPNote in future - could spawn multiple prediction
3943 // TODO: viewport.getAlignment().isAligned is a global state - the local
3944 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3945 if (!viewport.getAlignment().isAligned(false))
3947 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3948 // TODO: if seqs.getSequences().length>1 then should really have warned
3962 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3964 // Pick the tree file
3965 JalviewFileChooser chooser = new JalviewFileChooser(
3966 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3967 chooser.setFileView(new JalviewFileView());
3968 chooser.setDialogTitle(
3969 MessageManager.getString("label.select_newick_like_tree_file"));
3970 chooser.setToolTipText(
3971 MessageManager.getString("label.load_tree_file"));
3973 chooser.setResponseHandler(0,new Runnable()
3978 String filePath = chooser.getSelectedFile().getPath();
3979 Cache.setProperty("LAST_DIRECTORY", filePath);
3980 NewickFile fin = null;
3983 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
3984 DataSourceType.FILE));
3985 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
3986 } catch (Exception ex)
3988 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
3990 .getString("label.problem_reading_tree_file"),
3991 JvOptionPane.WARNING_MESSAGE);
3992 ex.printStackTrace();
3994 if (fin != null && fin.hasWarningMessage())
3996 JvOptionPane.showMessageDialog(Desktop.desktop,
3997 fin.getWarningMessage(),
3998 MessageManager.getString(
3999 "label.possible_problem_with_tree_file"),
4000 JvOptionPane.WARNING_MESSAGE);
4004 chooser.showOpenDialog(this);
4007 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4009 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4012 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4013 int h, int x, int y)
4015 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4019 * Add a treeviewer for the tree extracted from a Newick file object to the
4020 * current alignment view
4027 * Associated alignment input data (or null)
4036 * @return TreePanel handle
4038 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4039 AlignmentView input, int w, int h, int x, int y)
4041 TreePanel tp = null;
4047 if (nf.getTree() != null)
4049 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4055 tp.setLocation(x, y);
4058 Desktop.addInternalFrame(tp, treeTitle, w, h);
4060 } catch (Exception ex)
4062 ex.printStackTrace();
4068 private boolean buildingMenu = false;
4071 * Generates menu items and listener event actions for web service clients
4074 public void BuildWebServiceMenu()
4076 while (buildingMenu)
4080 System.err.println("Waiting for building menu to finish.");
4082 } catch (Exception e)
4086 final AlignFrame me = this;
4087 buildingMenu = true;
4088 new Thread(new Runnable()
4093 final List<JMenuItem> legacyItems = new ArrayList<>();
4096 // System.err.println("Building ws menu again "
4097 // + Thread.currentThread());
4098 // TODO: add support for context dependent disabling of services based
4100 // alignment and current selection
4101 // TODO: add additional serviceHandle parameter to specify abstract
4103 // class independently of AbstractName
4104 // TODO: add in rediscovery GUI function to restart discoverer
4105 // TODO: group services by location as well as function and/or
4107 // object broker mechanism.
4108 final Vector<JMenu> wsmenu = new Vector<>();
4109 final IProgressIndicator af = me;
4112 * do not i18n these strings - they are hard-coded in class
4113 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4114 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4116 final JMenu msawsmenu = new JMenu("Alignment");
4117 final JMenu secstrmenu = new JMenu(
4118 "Secondary Structure Prediction");
4119 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4120 final JMenu analymenu = new JMenu("Analysis");
4121 final JMenu dismenu = new JMenu("Protein Disorder");
4122 // JAL-940 - only show secondary structure prediction services from
4123 // the legacy server
4124 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4126 Discoverer.services != null && (Discoverer.services.size() > 0))
4128 // TODO: refactor to allow list of AbstractName/Handler bindings to
4130 // stored or retrieved from elsewhere
4131 // No MSAWS used any more:
4132 // Vector msaws = null; // (Vector)
4133 // Discoverer.services.get("MsaWS");
4134 Vector secstrpr = (Vector) Discoverer.services
4136 if (secstrpr != null)
4138 // Add any secondary structure prediction services
4139 for (int i = 0, j = secstrpr.size(); i < j; i++)
4141 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4143 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4144 .getServiceClient(sh);
4145 int p = secstrmenu.getItemCount();
4146 impl.attachWSMenuEntry(secstrmenu, me);
4147 int q = secstrmenu.getItemCount();
4148 for (int litm = p; litm < q; litm++)
4150 legacyItems.add(secstrmenu.getItem(litm));
4156 // Add all submenus in the order they should appear on the web
4158 wsmenu.add(msawsmenu);
4159 wsmenu.add(secstrmenu);
4160 wsmenu.add(dismenu);
4161 wsmenu.add(analymenu);
4162 // No search services yet
4163 // wsmenu.add(seqsrchmenu);
4165 javax.swing.SwingUtilities.invokeLater(new Runnable()
4172 webService.removeAll();
4173 // first, add discovered services onto the webservices menu
4174 if (wsmenu.size() > 0)
4176 for (int i = 0, j = wsmenu.size(); i < j; i++)
4178 webService.add(wsmenu.get(i));
4183 webService.add(me.webServiceNoServices);
4185 // TODO: move into separate menu builder class.
4186 boolean new_sspred = false;
4187 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4189 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4190 if (jws2servs != null)
4192 if (jws2servs.hasServices())
4194 jws2servs.attachWSMenuEntry(webService, me);
4195 for (Jws2Instance sv : jws2servs.getServices())
4197 if (sv.description.toLowerCase().contains("jpred"))
4199 for (JMenuItem jmi : legacyItems)
4201 jmi.setVisible(false);
4207 if (jws2servs.isRunning())
4209 JMenuItem tm = new JMenuItem(
4210 "Still discovering JABA Services");
4211 tm.setEnabled(false);
4216 build_urlServiceMenu(me.webService);
4217 build_fetchdbmenu(webService);
4218 for (JMenu item : wsmenu)
4220 if (item.getItemCount() == 0)
4222 item.setEnabled(false);
4226 item.setEnabled(true);
4229 } catch (Exception e)
4232 "Exception during web service menu building process.",
4237 } catch (Exception e)
4240 buildingMenu = false;
4247 * construct any groupURL type service menu entries.
4251 private void build_urlServiceMenu(JMenu webService)
4253 // TODO: remove this code when 2.7 is released
4254 // DEBUG - alignmentView
4256 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4257 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4259 * @Override public void actionPerformed(ActionEvent e) {
4260 * jalview.datamodel.AlignmentView
4261 * .testSelectionViews(af.viewport.getAlignment(),
4262 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4264 * }); webService.add(testAlView);
4266 // TODO: refactor to RestClient discoverer and merge menu entries for
4267 // rest-style services with other types of analysis/calculation service
4268 // SHmmr test client - still being implemented.
4269 // DEBUG - alignmentView
4271 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4274 client.attachWSMenuEntry(
4275 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4281 * Searches the alignment sequences for xRefs and builds the Show
4282 * Cross-References menu (formerly called Show Products), with database
4283 * sources for which cross-references are found (protein sources for a
4284 * nucleotide alignment and vice versa)
4286 * @return true if Show Cross-references menu should be enabled
4288 public boolean canShowProducts()
4290 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4291 AlignmentI dataset = viewport.getAlignment().getDataset();
4293 showProducts.removeAll();
4294 final boolean dna = viewport.getAlignment().isNucleotide();
4296 if (seqs == null || seqs.length == 0)
4298 // nothing to see here.
4302 boolean showp = false;
4305 List<String> ptypes = new CrossRef(seqs, dataset)
4306 .findXrefSourcesForSequences(dna);
4308 for (final String source : ptypes)
4311 final AlignFrame af = this;
4312 JMenuItem xtype = new JMenuItem(source);
4313 xtype.addActionListener(new ActionListener()
4316 public void actionPerformed(ActionEvent e)
4318 showProductsFor(af.viewport.getSequenceSelection(), dna,
4322 showProducts.add(xtype);
4324 showProducts.setVisible(showp);
4325 showProducts.setEnabled(showp);
4326 } catch (Exception e)
4329 "canShowProducts threw an exception - please report to help@jalview.org",
4337 * Finds and displays cross-references for the selected sequences (protein
4338 * products for nucleotide sequences, dna coding sequences for peptides).
4341 * the sequences to show cross-references for
4343 * true if from a nucleotide alignment (so showing proteins)
4345 * the database to show cross-references for
4347 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4348 final String source)
4350 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4355 * Construct and display a new frame containing the translation of this
4356 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4359 public void showTranslation_actionPerformed(ActionEvent e)
4361 AlignmentI al = null;
4364 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4366 al = dna.translateCdna();
4367 } catch (Exception ex)
4369 jalview.bin.Cache.log.error(
4370 "Exception during translation. Please report this !", ex);
4371 final String msg = MessageManager.getString(
4372 "label.error_when_translating_sequences_submit_bug_report");
4373 final String errorTitle = MessageManager
4374 .getString("label.implementation_error")
4375 + MessageManager.getString("label.translation_failed");
4376 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4377 JvOptionPane.ERROR_MESSAGE);
4380 if (al == null || al.getHeight() == 0)
4382 final String msg = MessageManager.getString(
4383 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4384 final String errorTitle = MessageManager
4385 .getString("label.translation_failed");
4386 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4387 JvOptionPane.WARNING_MESSAGE);
4391 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4392 af.setFileFormat(this.currentFileFormat);
4393 final String newTitle = MessageManager
4394 .formatMessage("label.translation_of_params", new Object[]
4395 { this.getTitle() });
4396 af.setTitle(newTitle);
4397 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4399 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4400 viewport.openSplitFrame(af, new Alignment(seqs));
4404 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4411 * Set the file format
4415 public void setFileFormat(FileFormatI format)
4417 this.currentFileFormat = format;
4421 * Try to load a features file onto the alignment.
4424 * contents or path to retrieve file or a File object
4426 * access mode of file (see jalview.io.AlignFile)
4427 * @return true if features file was parsed correctly.
4429 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4432 return avc.parseFeaturesFile(file, sourceType,
4433 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4438 public void refreshFeatureUI(boolean enableIfNecessary)
4440 // note - currently this is only still here rather than in the controller
4441 // because of the featureSettings hard reference that is yet to be
4443 if (enableIfNecessary)
4445 viewport.setShowSequenceFeatures(true);
4446 showSeqFeatures.setSelected(true);
4452 public void dragEnter(DropTargetDragEvent evt)
4457 public void dragExit(DropTargetEvent evt)
4462 public void dragOver(DropTargetDragEvent evt)
4467 public void dropActionChanged(DropTargetDragEvent evt)
4472 public void drop(DropTargetDropEvent evt)
4474 // JAL-1552 - acceptDrop required before getTransferable call for
4475 // Java's Transferable for native dnd
4476 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4477 Transferable t = evt.getTransferable();
4479 final AlignFrame thisaf = this;
4480 final List<Object> files = new ArrayList<>();
4481 List<DataSourceType> protocols = new ArrayList<>();
4485 Desktop.transferFromDropTarget(files, protocols, evt, t);
4486 } catch (Exception e)
4488 e.printStackTrace();
4492 new Thread(new Runnable()
4499 // check to see if any of these files have names matching sequences
4502 SequenceIdMatcher idm = new SequenceIdMatcher(
4503 viewport.getAlignment().getSequencesArray());
4505 * Object[] { String,SequenceI}
4507 ArrayList<Object[]> filesmatched = new ArrayList<>();
4508 ArrayList<Object> filesnotmatched = new ArrayList<>();
4509 for (int i = 0; i < files.size(); i++)
4512 Object file = files.get(i);
4513 String fileName = file.toString();
4515 DataSourceType protocol = (file instanceof File
4516 ? DataSourceType.FILE
4517 : FormatAdapter.checkProtocol(fileName));
4518 if (protocol == DataSourceType.FILE)
4520 File fl = (file instanceof File ? (File) file
4521 : new File(fileName));
4522 pdbfn = fl.getName();
4524 else if (protocol == DataSourceType.URL)
4526 URL url = new URL(fileName);
4527 pdbfn = url.getFile();
4529 if (pdbfn.length() > 0)
4531 // attempt to find a match in the alignment
4532 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4533 int l = 0, c = pdbfn.indexOf(".");
4534 while (mtch == null && c != -1)
4539 } while ((c = pdbfn.indexOf(".", l)) > l);
4542 pdbfn = pdbfn.substring(0, l);
4544 mtch = idm.findAllIdMatches(pdbfn);
4551 type = new IdentifyFile().identify(file, protocol);
4552 } catch (Exception ex)
4556 if (type != null && type.isStructureFile())
4558 filesmatched.add(new Object[] { file, protocol, mtch });
4562 // File wasn't named like one of the sequences or wasn't a PDB
4564 filesnotmatched.add(file);
4568 if (filesmatched.size() > 0)
4570 boolean autoAssociate = Cache
4571 .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4574 String msg = MessageManager.formatMessage(
4575 "label.automatically_associate_structure_files_with_sequences_same_name",
4577 { Integer.valueOf(filesmatched.size())
4579 String ttl = MessageManager.getString(
4580 "label.automatically_associate_structure_files_by_name");
4581 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4582 ttl, JvOptionPane.YES_NO_OPTION);
4583 autoAssociate = choice == JvOptionPane.YES_OPTION;
4587 for (Object[] fm : filesmatched)
4589 // try and associate
4590 // TODO: may want to set a standard ID naming formalism for
4591 // associating PDB files which have no IDs.
4592 for (SequenceI toassoc : (SequenceI[]) fm[2])
4594 PDBEntry pe = new AssociatePdbFileWithSeq()
4595 .associatePdbWithSeq(fm[0].toString(),
4596 (DataSourceType) fm[1], toassoc, false,
4600 System.err.println("Associated file : "
4601 + (fm[0].toString()) + " with "
4602 + toassoc.getDisplayId(true));
4606 // TODO: do we need to update overview ? only if features are
4608 alignPanel.paintAlignment(true, false);
4614 * add declined structures as sequences
4616 for (Object[] o : filesmatched)
4618 filesnotmatched.add(o[0]);
4622 if (filesnotmatched.size() > 0)
4624 if (assocfiles > 0 && (Cache.getDefault(
4625 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4626 || JvOptionPane.showConfirmDialog(thisaf,
4627 "<html>" + MessageManager.formatMessage(
4628 "label.ignore_unmatched_dropped_files_info",
4631 filesnotmatched.size())
4634 MessageManager.getString(
4635 "label.ignore_unmatched_dropped_files"),
4636 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4640 for (Object fn : filesnotmatched)
4642 loadJalviewDataFile(fn, null, null, null);
4646 } catch (Exception ex)
4648 ex.printStackTrace();
4656 * Attempt to load a "dropped" file or URL string, by testing in turn for
4658 * <li>an Annotation file</li>
4659 * <li>a JNet file</li>
4660 * <li>a features file</li>
4661 * <li>else try to interpret as an alignment file</li>
4665 * either a filename or a URL string.
4667 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4668 FileFormatI format, SequenceI assocSeq)
4670 // BH 2018 was String file
4673 if (sourceType == null)
4675 sourceType = FormatAdapter.checkProtocol(file);
4677 // if the file isn't identified, or not positively identified as some
4678 // other filetype (PFAM is default unidentified alignment file type) then
4679 // try to parse as annotation.
4680 boolean isAnnotation = (format == null
4681 || FileFormat.Pfam.equals(format))
4682 ? new AnnotationFile().annotateAlignmentView(viewport,
4688 // first see if its a T-COFFEE score file
4689 TCoffeeScoreFile tcf = null;
4692 tcf = new TCoffeeScoreFile(file, sourceType);
4695 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4699 new TCoffeeColourScheme(viewport.getAlignment()));
4700 isAnnotation = true;
4701 setStatus(MessageManager.getString(
4702 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4706 // some problem - if no warning its probable that the ID matching
4707 // process didn't work
4708 JvOptionPane.showMessageDialog(Desktop.desktop,
4709 tcf.getWarningMessage() == null
4710 ? MessageManager.getString(
4711 "label.check_file_matches_sequence_ids_alignment")
4712 : tcf.getWarningMessage(),
4713 MessageManager.getString(
4714 "label.problem_reading_tcoffee_score_file"),
4715 JvOptionPane.WARNING_MESSAGE);
4722 } catch (Exception x)
4725 "Exception when processing data source as T-COFFEE score file",
4731 // try to see if its a JNet 'concise' style annotation file *before*
4733 // try to parse it as a features file
4736 format = new IdentifyFile().identify(file, sourceType);
4738 if (FileFormat.ScoreMatrix == format)
4740 ScoreMatrixFile sm = new ScoreMatrixFile(
4741 new FileParse(file, sourceType));
4743 // todo: i18n this message
4744 setStatus(MessageManager.formatMessage(
4745 "label.successfully_loaded_matrix",
4746 sm.getMatrixName()));
4748 else if (FileFormat.Jnet.equals(format))
4750 JPredFile predictions = new JPredFile(file, sourceType);
4751 new JnetAnnotationMaker();
4752 JnetAnnotationMaker.add_annotation(predictions,
4753 viewport.getAlignment(), 0, false);
4754 viewport.getAlignment().setupJPredAlignment();
4755 isAnnotation = true;
4757 // else if (IdentifyFile.FeaturesFile.equals(format))
4758 else if (FileFormat.Features.equals(format))
4760 if (parseFeaturesFile(file, sourceType))
4762 alignPanel.paintAlignment(true, true);
4767 new FileLoader().LoadFile(viewport, file, sourceType, format);
4774 alignPanel.adjustAnnotationHeight();
4775 viewport.updateSequenceIdColours();
4776 buildSortByAnnotationScoresMenu();
4777 alignPanel.paintAlignment(true, true);
4779 } catch (Exception ex)
4781 ex.printStackTrace();
4782 } catch (OutOfMemoryError oom)
4787 } catch (Exception x)
4792 + (sourceType != null
4793 ? (sourceType == DataSourceType.PASTE
4795 : "using " + sourceType + " from "
4799 ? "(parsing as '" + format + "' file)"
4801 oom, Desktop.desktop);
4806 * Method invoked by the ChangeListener on the tabbed pane, in other words
4807 * when a different tabbed pane is selected by the user or programmatically.
4810 public void tabSelectionChanged(int index)
4814 alignPanel = alignPanels.get(index);
4815 viewport = alignPanel.av;
4816 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4817 setMenusFromViewport(viewport);
4821 * 'focus' any colour slider that is open to the selected viewport
4823 if (viewport.getConservationSelected())
4825 SliderPanel.setConservationSlider(alignPanel,
4826 viewport.getResidueShading(), alignPanel.getViewName());
4830 SliderPanel.hideConservationSlider();
4832 if (viewport.getAbovePIDThreshold())
4834 SliderPanel.setPIDSliderSource(alignPanel,
4835 viewport.getResidueShading(), alignPanel.getViewName());
4839 SliderPanel.hidePIDSlider();
4843 * If there is a frame linked to this one in a SplitPane, switch it to the
4844 * same view tab index. No infinite recursion of calls should happen, since
4845 * tabSelectionChanged() should not get invoked on setting the selected
4846 * index to an unchanged value. Guard against setting an invalid index
4847 * before the new view peer tab has been created.
4849 final AlignViewportI peer = viewport.getCodingComplement();
4852 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4853 .getAlignPanel().alignFrame;
4854 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4856 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4862 * On right mouse click on view tab, prompt for and set new view name.
4865 public void tabbedPane_mousePressed(MouseEvent e)
4867 if (e.isPopupTrigger())
4869 String msg = MessageManager.getString("label.enter_view_name");
4870 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
4871 String reply = JvOptionPane.showInputDialog(msg, ttl);
4875 viewport.setViewName(reply);
4876 // TODO warn if reply is in getExistingViewNames()?
4877 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4882 public AlignViewport getCurrentView()
4888 * Open the dialog for regex description parsing.
4891 protected void extractScores_actionPerformed(ActionEvent e)
4893 ParseProperties pp = new jalview.analysis.ParseProperties(
4894 viewport.getAlignment());
4895 // TODO: verify regex and introduce GUI dialog for version 2.5
4896 // if (pp.getScoresFromDescription("col", "score column ",
4897 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4899 if (pp.getScoresFromDescription("description column",
4900 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4902 buildSortByAnnotationScoresMenu();
4910 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4914 protected void showDbRefs_actionPerformed(ActionEvent e)
4916 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4922 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4926 protected void showNpFeats_actionPerformed(ActionEvent e)
4928 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4932 * find the viewport amongst the tabs in this alignment frame and close that
4937 public boolean closeView(AlignViewportI av)
4941 this.closeMenuItem_actionPerformed(false);
4944 Component[] comp = tabbedPane.getComponents();
4945 for (int i = 0; comp != null && i < comp.length; i++)
4947 if (comp[i] instanceof AlignmentPanel)
4949 if (((AlignmentPanel) comp[i]).av == av)
4952 closeView((AlignmentPanel) comp[i]);
4960 protected void build_fetchdbmenu(JMenu webService)
4962 // Temporary hack - DBRef Fetcher always top level ws entry.
4963 // TODO We probably want to store a sequence database checklist in
4964 // preferences and have checkboxes.. rather than individual sources selected
4966 final JMenu rfetch = new JMenu(
4967 MessageManager.getString("action.fetch_db_references"));
4968 rfetch.setToolTipText(MessageManager.getString(
4969 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4970 webService.add(rfetch);
4972 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4973 MessageManager.getString("option.trim_retrieved_seqs"));
4974 trimrs.setToolTipText(
4975 MessageManager.getString("label.trim_retrieved_sequences"));
4977 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
4978 trimrs.addActionListener(new ActionListener()
4981 public void actionPerformed(ActionEvent e)
4983 trimrs.setSelected(trimrs.isSelected());
4984 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
4985 Boolean.valueOf(trimrs.isSelected()).toString());
4989 JMenuItem fetchr = new JMenuItem(
4990 MessageManager.getString("label.standard_databases"));
4991 fetchr.setToolTipText(
4992 MessageManager.getString("label.fetch_embl_uniprot"));
4993 fetchr.addActionListener(new ActionListener()
4997 public void actionPerformed(ActionEvent e)
4999 new Thread(new Runnable()
5004 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5005 .getAlignment().isNucleotide();
5006 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5007 alignPanel.av.getSequenceSelection(),
5008 alignPanel.alignFrame, null,
5009 alignPanel.alignFrame.featureSettings, isNucleotide);
5010 dbRefFetcher.addListener(new FetchFinishedListenerI()
5013 public void finished()
5015 AlignFrame.this.setMenusForViewport();
5018 dbRefFetcher.fetchDBRefs(false);
5026 new Thread(new Runnable()
5031 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5032 .getSequenceFetcherSingleton();
5033 javax.swing.SwingUtilities.invokeLater(new Runnable()
5038 String[] dbclasses = sf.getNonAlignmentSources();
5039 List<DbSourceProxy> otherdb;
5040 JMenu dfetch = new JMenu();
5041 JMenu ifetch = new JMenu();
5042 JMenuItem fetchr = null;
5043 int comp = 0, icomp = 0, mcomp = 15;
5044 String mname = null;
5046 for (String dbclass : dbclasses)
5048 otherdb = sf.getSourceProxy(dbclass);
5049 // add a single entry for this class, or submenu allowing 'fetch
5051 if (otherdb == null || otherdb.size() < 1)
5057 mname = "From " + dbclass;
5059 if (otherdb.size() == 1)
5061 final DbSourceProxy[] dassource = otherdb
5062 .toArray(new DbSourceProxy[0]);
5063 DbSourceProxy src = otherdb.get(0);
5064 fetchr = new JMenuItem(src.getDbSource());
5065 fetchr.addActionListener(new ActionListener()
5069 public void actionPerformed(ActionEvent e)
5071 new Thread(new Runnable()
5077 boolean isNucleotide = alignPanel.alignFrame
5078 .getViewport().getAlignment()
5080 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5081 alignPanel.av.getSequenceSelection(),
5082 alignPanel.alignFrame, dassource,
5083 alignPanel.alignFrame.featureSettings,
5086 .addListener(new FetchFinishedListenerI()
5089 public void finished()
5091 AlignFrame.this.setMenusForViewport();
5094 dbRefFetcher.fetchDBRefs(false);
5100 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5101 MessageManager.formatMessage(
5102 "label.fetch_retrieve_from", new Object[]
5103 { src.getDbName() })));
5109 final DbSourceProxy[] dassource = otherdb
5110 .toArray(new DbSourceProxy[0]);
5112 DbSourceProxy src = otherdb.get(0);
5113 fetchr = new JMenuItem(MessageManager
5114 .formatMessage("label.fetch_all_param", new Object[]
5115 { src.getDbSource() }));
5116 fetchr.addActionListener(new ActionListener()
5119 public void actionPerformed(ActionEvent e)
5121 new Thread(new Runnable()
5127 boolean isNucleotide = alignPanel.alignFrame
5128 .getViewport().getAlignment()
5130 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5131 alignPanel.av.getSequenceSelection(),
5132 alignPanel.alignFrame, dassource,
5133 alignPanel.alignFrame.featureSettings,
5136 .addListener(new FetchFinishedListenerI()
5139 public void finished()
5141 AlignFrame.this.setMenusForViewport();
5144 dbRefFetcher.fetchDBRefs(false);
5150 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5151 MessageManager.formatMessage(
5152 "label.fetch_retrieve_from_all_sources",
5154 { Integer.valueOf(otherdb.size())
5156 src.getDbSource(), src.getDbName() })));
5159 // and then build the rest of the individual menus
5160 ifetch = new JMenu(MessageManager.formatMessage(
5161 "label.source_from_db_source", new Object[]
5162 { src.getDbSource() }));
5164 String imname = null;
5166 for (DbSourceProxy sproxy : otherdb)
5168 String dbname = sproxy.getDbName();
5169 String sname = dbname.length() > 5
5170 ? dbname.substring(0, 5) + "..."
5172 String msname = dbname.length() > 10
5173 ? dbname.substring(0, 10) + "..."
5177 imname = MessageManager
5178 .formatMessage("label.from_msname", new Object[]
5181 fetchr = new JMenuItem(msname);
5182 final DbSourceProxy[] dassrc = { sproxy };
5183 fetchr.addActionListener(new ActionListener()
5187 public void actionPerformed(ActionEvent e)
5189 new Thread(new Runnable()
5195 boolean isNucleotide = alignPanel.alignFrame
5196 .getViewport().getAlignment()
5198 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5199 alignPanel.av.getSequenceSelection(),
5200 alignPanel.alignFrame, dassrc,
5201 alignPanel.alignFrame.featureSettings,
5204 .addListener(new FetchFinishedListenerI()
5207 public void finished()
5209 AlignFrame.this.setMenusForViewport();
5212 dbRefFetcher.fetchDBRefs(false);
5218 fetchr.setToolTipText(
5219 "<html>" + MessageManager.formatMessage(
5220 "label.fetch_retrieve_from", new Object[]
5224 if (++icomp >= mcomp || i == (otherdb.size()))
5226 ifetch.setText(MessageManager.formatMessage(
5227 "label.source_to_target", imname, sname));
5229 ifetch = new JMenu();
5237 if (comp >= mcomp || dbi >= (dbclasses.length))
5239 dfetch.setText(MessageManager.formatMessage(
5240 "label.source_to_target", mname, dbclass));
5242 dfetch = new JMenu();
5255 * Left justify the whole alignment.
5258 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5260 AlignmentI al = viewport.getAlignment();
5262 viewport.firePropertyChange("alignment", null, al);
5266 * Right justify the whole alignment.
5269 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5271 AlignmentI al = viewport.getAlignment();
5273 viewport.firePropertyChange("alignment", null, al);
5277 public void setShowSeqFeatures(boolean b)
5279 showSeqFeatures.setSelected(b);
5280 viewport.setShowSequenceFeatures(b);
5287 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5288 * awt.event.ActionEvent)
5291 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5293 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5294 alignPanel.paintAlignment(false, false);
5301 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5305 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5307 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5308 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5316 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5317 * .event.ActionEvent)
5320 protected void showGroupConservation_actionPerformed(ActionEvent e)
5322 viewport.setShowGroupConservation(showGroupConservation.getState());
5323 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5330 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5331 * .event.ActionEvent)
5334 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5336 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5337 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5344 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5345 * .event.ActionEvent)
5348 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5350 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5351 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5355 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5357 showSequenceLogo.setState(true);
5358 viewport.setShowSequenceLogo(true);
5359 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5360 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5364 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5366 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5373 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5374 * .event.ActionEvent)
5377 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5379 if (avc.makeGroupsFromSelection())
5381 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5382 alignPanel.updateAnnotation();
5383 alignPanel.paintAlignment(true, true);
5387 public void clearAlignmentSeqRep()
5389 // TODO refactor alignmentseqrep to controller
5390 if (viewport.getAlignment().hasSeqrep())
5392 viewport.getAlignment().setSeqrep(null);
5393 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5394 alignPanel.updateAnnotation();
5395 alignPanel.paintAlignment(true, true);
5400 protected void createGroup_actionPerformed(ActionEvent e)
5402 if (avc.createGroup())
5404 if (applyAutoAnnotationSettings.isSelected())
5406 alignPanel.updateAnnotation(true, false);
5408 alignPanel.alignmentChanged();
5413 protected void unGroup_actionPerformed(ActionEvent e)
5417 alignPanel.alignmentChanged();
5422 * make the given alignmentPanel the currently selected tab
5424 * @param alignmentPanel
5426 public void setDisplayedView(AlignmentPanel alignmentPanel)
5428 if (!viewport.getSequenceSetId()
5429 .equals(alignmentPanel.av.getSequenceSetId()))
5431 throw new Error(MessageManager.getString(
5432 "error.implementation_error_cannot_show_view_alignment_frame"));
5434 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5435 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5437 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5442 * Action on selection of menu options to Show or Hide annotations.
5445 * @param forSequences
5446 * update sequence-related annotations
5447 * @param forAlignment
5448 * update non-sequence-related annotations
5451 protected void setAnnotationsVisibility(boolean visible,
5452 boolean forSequences, boolean forAlignment)
5454 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5455 .getAlignmentAnnotation();
5460 for (AlignmentAnnotation aa : anns)
5463 * don't display non-positional annotations on an alignment
5465 if (aa.annotations == null)
5469 boolean apply = (aa.sequenceRef == null && forAlignment)
5470 || (aa.sequenceRef != null && forSequences);
5473 aa.visible = visible;
5476 alignPanel.validateAnnotationDimensions(true);
5477 alignPanel.alignmentChanged();
5481 * Store selected annotation sort order for the view and repaint.
5484 protected void sortAnnotations_actionPerformed()
5486 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5488 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5489 alignPanel.paintAlignment(false, false);
5494 * @return alignment panels in this alignment frame
5496 public List<? extends AlignmentViewPanel> getAlignPanels()
5498 // alignPanels is never null
5499 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5504 * Open a new alignment window, with the cDNA associated with this (protein)
5505 * alignment, aligned as is the protein.
5507 protected void viewAsCdna_actionPerformed()
5509 // TODO no longer a menu action - refactor as required
5510 final AlignmentI alignment = getViewport().getAlignment();
5511 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5512 if (mappings == null)
5516 List<SequenceI> cdnaSeqs = new ArrayList<>();
5517 for (SequenceI aaSeq : alignment.getSequences())
5519 for (AlignedCodonFrame acf : mappings)
5521 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5525 * There is a cDNA mapping for this protein sequence - add to new
5526 * alignment. It will share the same dataset sequence as other mapped
5527 * cDNA (no new mappings need to be created).
5529 final Sequence newSeq = new Sequence(dnaSeq);
5530 newSeq.setDatasetSequence(dnaSeq);
5531 cdnaSeqs.add(newSeq);
5535 if (cdnaSeqs.size() == 0)
5537 // show a warning dialog no mapped cDNA
5540 AlignmentI cdna = new Alignment(
5541 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5542 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5543 AlignFrame.DEFAULT_HEIGHT);
5544 cdna.alignAs(alignment);
5545 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5547 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5548 AlignFrame.DEFAULT_HEIGHT);
5552 * Set visibility of dna/protein complement view (available when shown in a
5558 protected void showComplement_actionPerformed(boolean show)
5560 SplitContainerI sf = getSplitViewContainer();
5563 sf.setComplementVisible(this, show);
5568 * Generate the reverse (optionally complemented) of the selected sequences,
5569 * and add them to the alignment
5572 protected void showReverse_actionPerformed(boolean complement)
5574 AlignmentI al = null;
5577 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5578 al = dna.reverseCdna(complement);
5579 viewport.addAlignment(al, "");
5580 addHistoryItem(new EditCommand(
5581 MessageManager.getString("label.add_sequences"), Action.PASTE,
5582 al.getSequencesArray(), 0, al.getWidth(),
5583 viewport.getAlignment()));
5584 } catch (Exception ex)
5586 System.err.println(ex.getMessage());
5592 * Try to run a script in the Groovy console, having first ensured that this
5593 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5594 * be targeted at this alignment.
5597 protected void runGroovy_actionPerformed()
5599 Jalview.setCurrentAlignFrame(this);
5600 groovy.ui.Console console = Desktop.getGroovyConsole();
5601 if (console != null)
5605 console.runScript();
5606 } catch (Exception ex)
5608 System.err.println((ex.toString()));
5609 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5610 MessageManager.getString("label.couldnt_run_groovy_script"),
5611 MessageManager.getString("label.groovy_support_failed"),
5612 JvOptionPane.ERROR_MESSAGE);
5617 System.err.println("Can't run Groovy script as console not found");
5622 * Hides columns containing (or not containing) a specified feature, provided
5623 * that would not leave all columns hidden
5625 * @param featureType
5626 * @param columnsContaining
5629 public boolean hideFeatureColumns(String featureType,
5630 boolean columnsContaining)
5632 boolean notForHiding = avc.markColumnsContainingFeatures(
5633 columnsContaining, false, false, featureType);
5636 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5637 false, featureType))
5639 getViewport().hideSelectedColumns();
5647 protected void selectHighlightedColumns_actionPerformed(
5648 ActionEvent actionEvent)
5650 // include key modifier check in case user selects from menu
5651 avc.markHighlightedColumns(
5652 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5653 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5654 | ActionEvent.CTRL_MASK)) != 0);
5658 * Rebuilds the Colour menu, including any user-defined colours which have
5659 * been loaded either on startup or during the session
5661 public void buildColourMenu()
5663 colourMenu.removeAll();
5665 colourMenu.add(applyToAllGroups);
5666 colourMenu.add(textColour);
5667 colourMenu.addSeparator();
5669 ColourMenuHelper.addMenuItems(colourMenu, this, viewport.getAlignment(),
5672 colourMenu.addSeparator();
5673 colourMenu.add(conservationMenuItem);
5674 colourMenu.add(modifyConservation);
5675 colourMenu.add(abovePIDThreshold);
5676 colourMenu.add(modifyPID);
5677 colourMenu.add(annotationColour);
5679 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5680 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5684 * Open a dialog (if not already open) that allows the user to select and
5685 * calculate PCA or Tree analysis
5687 protected void openTreePcaDialog()
5689 if (alignPanel.getCalculationDialog() == null)
5691 new CalculationChooser(AlignFrame.this);
5696 protected void loadVcf_actionPerformed()
5698 JalviewFileChooser chooser = new JalviewFileChooser(
5699 Cache.getProperty("LAST_DIRECTORY"));
5700 chooser.setFileView(new JalviewFileView());
5701 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5702 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5703 final AlignFrame us = this;
5704 chooser.setResponseHandler(0, new Runnable()
5709 String choice = chooser.getSelectedFile().getPath();
5710 Cache.setProperty("LAST_DIRECTORY", choice);
5711 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5712 new VCFLoader(choice).loadVCF(seqs, us);
5715 chooser.showOpenDialog(null);
5721 class PrintThread extends Thread
5725 public PrintThread(AlignmentPanel ap)
5730 static PageFormat pf;
5735 PrinterJob printJob = PrinterJob.getPrinterJob();
5739 printJob.setPrintable(ap, pf);
5743 printJob.setPrintable(ap);
5746 if (printJob.printDialog())
5751 } catch (Exception PrintException)
5753 PrintException.printStackTrace();