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.util.Platform;
93 import jalview.viewmodel.AlignmentViewport;
94 import jalview.viewmodel.ViewportRanges;
95 import jalview.ws.DBRefFetcher;
96 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
97 import jalview.ws.jws1.Discoverer;
98 import jalview.ws.jws2.Jws2Discoverer;
99 import jalview.ws.jws2.jabaws2.Jws2Instance;
100 import jalview.ws.seqfetcher.DbSourceProxy;
102 import java.awt.BorderLayout;
103 import java.awt.Color;
104 import java.awt.Component;
105 import java.awt.Rectangle;
106 import java.awt.Toolkit;
107 import java.awt.datatransfer.Clipboard;
108 import java.awt.datatransfer.DataFlavor;
109 import java.awt.datatransfer.StringSelection;
110 import java.awt.datatransfer.Transferable;
111 import java.awt.dnd.DnDConstants;
112 import java.awt.dnd.DropTargetDragEvent;
113 import java.awt.dnd.DropTargetDropEvent;
114 import java.awt.dnd.DropTargetEvent;
115 import java.awt.dnd.DropTargetListener;
116 import java.awt.event.ActionEvent;
117 import java.awt.event.ActionListener;
118 import java.awt.event.FocusAdapter;
119 import java.awt.event.FocusEvent;
120 import java.awt.event.ItemEvent;
121 import java.awt.event.ItemListener;
122 import java.awt.event.KeyAdapter;
123 import java.awt.event.KeyEvent;
124 import java.awt.event.MouseEvent;
125 import java.awt.print.PageFormat;
126 import java.awt.print.PrinterJob;
127 import java.beans.PropertyChangeEvent;
129 import java.io.FileWriter;
130 import java.io.PrintWriter;
132 import java.util.ArrayList;
133 import java.util.Arrays;
134 import java.util.Deque;
135 import java.util.Enumeration;
136 import java.util.Hashtable;
137 import java.util.List;
138 import java.util.Vector;
140 import javax.swing.JCheckBoxMenuItem;
141 import javax.swing.JComponent;
142 import javax.swing.JEditorPane;
143 import javax.swing.JInternalFrame;
144 import javax.swing.JLabel;
145 import javax.swing.JLayeredPane;
146 import javax.swing.JMenu;
147 import javax.swing.JMenuItem;
148 import javax.swing.JPanel;
149 import javax.swing.JScrollPane;
150 import javax.swing.SwingUtilities;
156 * @version $Revision$
158 public class AlignFrame extends GAlignFrame implements DropTargetListener,
159 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
162 public static final int DEFAULT_WIDTH = 700;
164 public static final int DEFAULT_HEIGHT = 500;
167 * The currently displayed panel (selected tabbed view if more than one)
169 public AlignmentPanel alignPanel;
171 AlignViewport viewport;
173 public AlignViewControllerI avc;
175 List<AlignmentPanel> alignPanels = new ArrayList<>();
178 * Last format used to load or save alignments in this window
180 FileFormatI currentFileFormat = null;
183 * Current filename for this alignment
185 String fileName = null;
190 * Creates a new AlignFrame object with specific width and height.
196 public AlignFrame(AlignmentI al, int width, int height)
198 this(al, null, width, height);
202 * Creates a new AlignFrame object with specific width, height and
208 * @param sequenceSetId
210 public AlignFrame(AlignmentI al, int width, int height,
211 String sequenceSetId)
213 this(al, null, width, height, sequenceSetId);
217 * Creates a new AlignFrame object with specific width, height and
223 * @param sequenceSetId
226 public AlignFrame(AlignmentI al, int width, int height,
227 String sequenceSetId, String viewId)
229 this(al, null, width, height, sequenceSetId, viewId);
233 * new alignment window with hidden columns
237 * @param hiddenColumns
238 * ColumnSelection or null
240 * Width of alignment frame
244 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
247 this(al, hiddenColumns, width, height, null);
251 * Create alignment frame for al with hiddenColumns, a specific width and
252 * height, and specific sequenceId
255 * @param hiddenColumns
258 * @param sequenceSetId
261 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
262 int height, String sequenceSetId)
264 this(al, hiddenColumns, width, height, sequenceSetId, null);
268 * Create alignment frame for al with hiddenColumns, a specific width and
269 * height, and specific sequenceId
272 * @param hiddenColumns
275 * @param sequenceSetId
280 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
281 int height, String sequenceSetId, String viewId)
283 setSize(width, height);
285 if (al.getDataset() == null)
290 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
292 alignPanel = new AlignmentPanel(this, viewport);
294 addAlignmentPanel(alignPanel, true);
298 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
299 HiddenColumns hiddenColumns, int width, int height)
301 setSize(width, height);
303 if (al.getDataset() == null)
308 viewport = new AlignViewport(al, hiddenColumns);
310 if (hiddenSeqs != null && hiddenSeqs.length > 0)
312 viewport.hideSequence(hiddenSeqs);
314 alignPanel = new AlignmentPanel(this, viewport);
315 addAlignmentPanel(alignPanel, true);
320 * Make a new AlignFrame from existing alignmentPanels
327 public AlignFrame(AlignmentPanel ap)
331 addAlignmentPanel(ap, false);
336 * initalise the alignframe from the underlying viewport data and the
341 // setBackground(Color.white); // BH 2019
343 if (!Jalview.isHeadlessMode())
345 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
348 avc = new jalview.controller.AlignViewController(this, viewport,
350 if (viewport.getAlignmentConservationAnnotation() == null)
352 // BLOSUM62Colour.setEnabled(false);
353 conservationMenuItem.setEnabled(false);
354 modifyConservation.setEnabled(false);
355 // PIDColour.setEnabled(false);
356 // abovePIDThreshold.setEnabled(false);
357 // modifyPID.setEnabled(false);
360 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
363 if (sortby.equals("Id"))
365 sortIDMenuItem_actionPerformed(null);
367 else if (sortby.equals("Pairwise Identity"))
369 sortPairwiseMenuItem_actionPerformed(null);
373 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
375 setMenusFromViewport(viewport);
376 buildSortByAnnotationScoresMenu();
377 calculateTree.addActionListener(new ActionListener()
381 public void actionPerformed(ActionEvent e)
388 if (Desktop.desktop != null)
390 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
392 * BH 2018 ignore service listeners
398 addServiceListeners();
403 if (viewport.getWrapAlignment())
405 wrapMenuItem_actionPerformed(null);
408 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
410 this.overviewMenuItem_actionPerformed(null);
415 final List<AlignmentPanel> selviews = new ArrayList<>();
416 final List<AlignmentPanel> origview = new ArrayList<>();
417 final String menuLabel = MessageManager
418 .getString("label.copy_format_from");
419 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
420 new ViewSetProvider()
424 public AlignmentPanel[] getAllAlignmentPanels()
427 origview.add(alignPanel);
428 // make an array of all alignment panels except for this one
429 List<AlignmentPanel> aps = new ArrayList<>(
430 Arrays.asList(Desktop.getAlignmentPanels(null)));
431 aps.remove(AlignFrame.this.alignPanel);
432 return aps.toArray(new AlignmentPanel[aps.size()]);
434 }, selviews, new ItemListener()
438 public void itemStateChanged(ItemEvent e)
440 if (origview.size() > 0)
442 final AlignmentPanel ap = origview.get(0);
445 * Copy the ViewStyle of the selected panel to 'this one'.
446 * Don't change value of 'scaleProteinAsCdna' unless copying
449 ViewStyleI vs = selviews.get(0).getAlignViewport()
451 boolean fromSplitFrame = selviews.get(0)
452 .getAlignViewport().getCodingComplement() != null;
455 vs.setScaleProteinAsCdna(ap.getAlignViewport()
456 .getViewStyle().isScaleProteinAsCdna());
458 ap.getAlignViewport().setViewStyle(vs);
461 * Also rescale ViewStyle of SplitFrame complement if there is
462 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
463 * the whole ViewStyle (allow cDNA protein to have different
466 AlignViewportI complement = ap.getAlignViewport()
467 .getCodingComplement();
468 if (complement != null && vs.isScaleProteinAsCdna())
470 AlignFrame af = Desktop.getAlignFrameFor(complement);
471 ((SplitFrame) af.getSplitViewContainer())
473 af.setMenusForViewport();
477 ap.setSelected(true);
478 ap.alignFrame.setMenusForViewport();
483 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
484 .indexOf("devel") > -1
485 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
486 .indexOf("test") > -1)
488 formatMenu.add(vsel);
490 addFocusListener(new FocusAdapter()
493 public void focusGained(FocusEvent e)
495 Jalview.setCurrentAlignFrame(AlignFrame.this);
502 * Change the filename and format for the alignment, and enable the 'reload'
503 * button functionality.
510 public void setFileName(String file, FileFormatI format)
513 setFileFormat(format);
514 reload.setEnabled(true);
518 * JavaScript will have this, maybe others. More dependable than a file name
519 * and maintains a reference to the actual bytes loaded.
523 public void setFileObject(File file)
525 this.fileObject = file;
529 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
532 void addKeyListener()
534 addKeyListener(new KeyAdapter()
537 public void keyPressed(KeyEvent evt)
539 if (viewport.cursorMode
540 && ((evt.getKeyCode() >= KeyEvent.VK_0
541 && evt.getKeyCode() <= KeyEvent.VK_9)
542 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
543 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
544 && Character.isDigit(evt.getKeyChar()))
546 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
549 switch (evt.getKeyCode())
552 case 27: // escape key
553 deselectAllSequenceMenuItem_actionPerformed(null);
557 case KeyEvent.VK_DOWN:
558 if (evt.isAltDown() || !viewport.cursorMode)
560 moveSelectedSequences(false);
562 if (viewport.cursorMode)
564 alignPanel.getSeqPanel().moveCursor(0, 1);
569 if (evt.isAltDown() || !viewport.cursorMode)
571 moveSelectedSequences(true);
573 if (viewport.cursorMode)
575 alignPanel.getSeqPanel().moveCursor(0, -1);
580 case KeyEvent.VK_LEFT:
581 if (evt.isAltDown() || !viewport.cursorMode)
583 slideSequences(false,
584 alignPanel.getSeqPanel().getKeyboardNo1());
588 alignPanel.getSeqPanel().moveCursor(-1, 0);
593 case KeyEvent.VK_RIGHT:
594 if (evt.isAltDown() || !viewport.cursorMode)
596 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
600 alignPanel.getSeqPanel().moveCursor(1, 0);
604 case KeyEvent.VK_SPACE:
605 if (viewport.cursorMode)
607 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
608 || evt.isShiftDown() || evt.isAltDown());
612 // case KeyEvent.VK_A:
613 // if (viewport.cursorMode)
615 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
616 // //System.out.println("A");
620 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
621 * System.out.println("closing bracket"); } break;
623 case KeyEvent.VK_DELETE:
624 case KeyEvent.VK_BACK_SPACE:
625 if (!viewport.cursorMode)
627 cut_actionPerformed();
631 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
632 || evt.isShiftDown() || evt.isAltDown());
638 if (viewport.cursorMode)
640 alignPanel.getSeqPanel().setCursorRow();
644 if (viewport.cursorMode && !evt.isControlDown())
646 alignPanel.getSeqPanel().setCursorColumn();
650 if (viewport.cursorMode)
652 alignPanel.getSeqPanel().setCursorPosition();
656 case KeyEvent.VK_ENTER:
657 case KeyEvent.VK_COMMA:
658 if (viewport.cursorMode)
660 alignPanel.getSeqPanel().setCursorRowAndColumn();
665 if (viewport.cursorMode)
667 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
671 if (viewport.cursorMode)
673 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
678 viewport.cursorMode = !viewport.cursorMode;
679 setStatus(MessageManager
680 .formatMessage("label.keyboard_editing_mode", new String[]
681 { (viewport.cursorMode ? "on" : "off") }));
682 if (viewport.cursorMode)
684 ViewportRanges ranges = viewport.getRanges();
685 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
687 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
690 alignPanel.getSeqPanel().seqCanvas.repaint();
696 Help.showHelpWindow();
697 } catch (Exception ex)
699 ex.printStackTrace();
704 boolean toggleSeqs = !evt.isControlDown();
705 boolean toggleCols = !evt.isShiftDown();
706 toggleHiddenRegions(toggleSeqs, toggleCols);
711 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
712 boolean modifyExisting = true; // always modify, don't clear
713 // evt.isShiftDown();
714 boolean invertHighlighted = evt.isAltDown();
715 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
719 case KeyEvent.VK_PAGE_UP:
720 viewport.getRanges().pageUp();
722 case KeyEvent.VK_PAGE_DOWN:
723 viewport.getRanges().pageDown();
729 public void keyReleased(KeyEvent evt)
731 switch (evt.getKeyCode())
733 case KeyEvent.VK_LEFT:
734 if (evt.isAltDown() || !viewport.cursorMode)
736 viewport.firePropertyChange("alignment", null,
737 viewport.getAlignment().getSequences());
741 case KeyEvent.VK_RIGHT:
742 if (evt.isAltDown() || !viewport.cursorMode)
744 viewport.firePropertyChange("alignment", null,
745 viewport.getAlignment().getSequences());
753 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
755 ap.alignFrame = this;
756 avc = new jalview.controller.AlignViewController(this, viewport,
761 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
763 int aSize = alignPanels.size();
765 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
767 if (aSize == 1 && ap.av.getViewName() == null)
769 this.getContentPane().add(ap, BorderLayout.CENTER);
775 setInitialTabVisible();
778 expandViews.setEnabled(true);
779 gatherViews.setEnabled(true);
780 tabbedPane.addTab(ap.av.getViewName(), ap);
782 ap.setVisible(false);
787 if (ap.av.isPadGaps())
789 ap.av.getAlignment().padGaps();
791 ap.av.updateConservation(ap);
792 ap.av.updateConsensus(ap);
793 ap.av.updateStrucConsensus(ap);
797 public void setInitialTabVisible()
799 expandViews.setEnabled(true);
800 gatherViews.setEnabled(true);
801 tabbedPane.setVisible(true);
802 AlignmentPanel first = alignPanels.get(0);
803 tabbedPane.addTab(first.av.getViewName(), first);
804 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
807 public AlignViewport getViewport()
812 /* Set up intrinsic listeners for dynamically generated GUI bits. */
813 private void addServiceListeners()
815 final java.beans.PropertyChangeListener thisListener;
816 Desktop.instance.addJalviewPropertyChangeListener("services",
817 thisListener = new java.beans.PropertyChangeListener()
820 public void propertyChange(PropertyChangeEvent evt)
822 // // System.out.println("Discoverer property change.");
823 // if (evt.getPropertyName().equals("services"))
825 SwingUtilities.invokeLater(new Runnable()
832 "Rebuild WS Menu for service change");
833 BuildWebServiceMenu();
840 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
843 public void internalFrameClosed(
844 javax.swing.event.InternalFrameEvent evt)
846 // System.out.println("deregistering discoverer listener");
847 Desktop.instance.removeJalviewPropertyChangeListener("services",
849 closeMenuItem_actionPerformed(true);
852 // Finally, build the menu once to get current service state
853 new Thread(new Runnable()
858 BuildWebServiceMenu();
864 * Configure menu items that vary according to whether the alignment is
865 * nucleotide or protein
867 public void setGUINucleotide()
869 AlignmentI al = getViewport().getAlignment();
870 boolean nucleotide = al.isNucleotide();
872 loadVcf.setVisible(nucleotide);
873 showTranslation.setVisible(nucleotide);
874 showReverse.setVisible(nucleotide);
875 showReverseComplement.setVisible(nucleotide);
876 conservationMenuItem.setEnabled(!nucleotide);
878 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
879 showGroupConservation.setEnabled(!nucleotide);
881 showComplementMenuItem
882 .setText(nucleotide ? MessageManager.getString("label.protein")
883 : MessageManager.getString("label.nucleotide"));
887 * set up menus for the current viewport. This may be called after any
888 * operation that affects the data in the current view (selection changed,
889 * etc) to update the menus to reflect the new state.
892 public void setMenusForViewport()
894 setMenusFromViewport(viewport);
898 * Need to call this method when tabs are selected for multiple views, or when
899 * loading from Jalview2XML.java
904 public void setMenusFromViewport(AlignViewport av)
906 padGapsMenuitem.setSelected(av.isPadGaps());
907 colourTextMenuItem.setSelected(av.isShowColourText());
908 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
909 modifyPID.setEnabled(abovePIDThreshold.isSelected());
910 conservationMenuItem.setSelected(av.getConservationSelected());
911 modifyConservation.setEnabled(conservationMenuItem.isSelected());
912 seqLimits.setSelected(av.getShowJVSuffix());
913 idRightAlign.setSelected(av.isRightAlignIds());
914 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
915 renderGapsMenuItem.setSelected(av.isRenderGaps());
916 wrapMenuItem.setSelected(av.getWrapAlignment());
917 scaleAbove.setVisible(av.getWrapAlignment());
918 scaleLeft.setVisible(av.getWrapAlignment());
919 scaleRight.setVisible(av.getWrapAlignment());
920 annotationPanelMenuItem.setState(av.isShowAnnotation());
922 * Show/hide annotations only enabled if annotation panel is shown
924 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
925 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
926 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
927 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
928 viewBoxesMenuItem.setSelected(av.getShowBoxes());
929 viewTextMenuItem.setSelected(av.getShowText());
930 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
931 showGroupConsensus.setSelected(av.isShowGroupConsensus());
932 showGroupConservation.setSelected(av.isShowGroupConservation());
933 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
934 showSequenceLogo.setSelected(av.isShowSequenceLogo());
935 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
937 ColourMenuHelper.setColourSelected(colourMenu,
938 av.getGlobalColourScheme());
940 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
941 hiddenMarkers.setState(av.getShowHiddenMarkers());
942 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
943 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
944 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
945 autoCalculate.setSelected(av.autoCalculateConsensus);
946 sortByTree.setSelected(av.sortByTree);
947 listenToViewSelections.setSelected(av.followSelection);
949 showProducts.setEnabled(canShowProducts());
950 setGroovyEnabled(Desktop.getGroovyConsole() != null);
956 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
960 public void setGroovyEnabled(boolean b)
962 runGroovy.setEnabled(b);
965 private IProgressIndicator progressBar;
970 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
973 public void setProgressBar(String message, long id)
975 progressBar.setProgressBar(message, id);
979 public void registerHandler(final long id,
980 final IProgressIndicatorHandler handler)
982 progressBar.registerHandler(id, handler);
987 * @return true if any progress bars are still active
990 public boolean operationInProgress()
992 return progressBar.operationInProgress();
996 public void setStatus(String text)
998 // BH note: If text width and height are 0, then the layout manager
999 // will dispense of it and change the frame height.
1000 // In JavaScript, we use \u00A0 -- unicode "non-breaking space"
1001 // which is the unicode encoding of
1003 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1007 * Added so Castor Mapping file can obtain Jalview Version
1009 public String getVersion()
1011 return jalview.bin.Cache.getProperty("VERSION");
1014 public FeatureRenderer getFeatureRenderer()
1016 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1020 public void fetchSequence_actionPerformed()
1022 new SequenceFetcher(this);
1026 public void addFromFile_actionPerformed(ActionEvent e)
1028 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1032 public void reload_actionPerformed(ActionEvent e)
1034 if (fileName != null)
1036 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1037 // originating file's format
1038 // TODO: work out how to recover feature settings for correct view(s) when
1039 // file is reloaded.
1040 if (FileFormat.Jalview.equals(currentFileFormat))
1042 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1043 for (int i = 0; i < frames.length; i++)
1045 if (frames[i] instanceof AlignFrame && frames[i] != this
1046 && ((AlignFrame) frames[i]).fileName != null
1047 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1051 frames[i].setSelected(true);
1052 Desktop.instance.closeAssociatedWindows();
1053 } catch (java.beans.PropertyVetoException ex)
1059 Desktop.instance.closeAssociatedWindows();
1061 FileLoader loader = new FileLoader();
1062 DataSourceType protocol = fileName.startsWith("http:")
1063 ? DataSourceType.URL
1064 : DataSourceType.FILE;
1065 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1069 Rectangle bounds = this.getBounds();
1071 FileLoader loader = new FileLoader();
1073 AlignFrame newframe = null;
1075 if (fileObject == null)
1078 DataSourceType protocol = (fileName.startsWith("http:")
1079 ? DataSourceType.URL
1080 : DataSourceType.FILE);
1081 newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1086 newframe = loader.LoadFileWaitTillLoaded(fileObject,
1087 DataSourceType.FILE, currentFileFormat);
1090 newframe.setBounds(bounds);
1091 if (featureSettings != null && featureSettings.isShowing())
1093 final Rectangle fspos = featureSettings.frame.getBounds();
1094 // TODO: need a 'show feature settings' function that takes bounds -
1095 // need to refactor Desktop.addFrame
1096 newframe.featureSettings_actionPerformed(null);
1097 final FeatureSettings nfs = newframe.featureSettings;
1098 SwingUtilities.invokeLater(new Runnable()
1103 nfs.frame.setBounds(fspos);
1106 this.featureSettings.close();
1107 this.featureSettings = null;
1109 this.closeMenuItem_actionPerformed(true);
1115 public void addFromText_actionPerformed(ActionEvent e)
1118 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1122 public void addFromURL_actionPerformed(ActionEvent e)
1124 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1128 public void save_actionPerformed(ActionEvent e)
1130 if (fileName == null || (currentFileFormat == null)
1131 || fileName.startsWith("http"))
1133 saveAs_actionPerformed();
1137 saveAlignment(fileName, currentFileFormat);
1142 * Saves the alignment to a file with a name chosen by the user, if necessary
1143 * warning if a file would be overwritten
1146 public void saveAs_actionPerformed()
1148 String format = currentFileFormat == null ? null
1149 : currentFileFormat.getName();
1150 JalviewFileChooser chooser = JalviewFileChooser
1151 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1153 chooser.setFileView(new JalviewFileView());
1154 chooser.setDialogTitle(
1155 MessageManager.getString("label.save_alignment_to_file"));
1156 chooser.setToolTipText(MessageManager.getString("action.save"));
1158 int value = chooser.showSaveDialog(this);
1160 if (value != JalviewFileChooser.APPROVE_OPTION)
1164 currentFileFormat = chooser.getSelectedFormat();
1165 // todo is this (2005) test now obsolete - value is never null?
1166 while (currentFileFormat == null)
1168 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1170 .getString("label.select_file_format_before_saving"),
1171 MessageManager.getString("label.file_format_not_specified"),
1172 JvOptionPane.WARNING_MESSAGE);
1173 currentFileFormat = chooser.getSelectedFormat();
1174 value = chooser.showSaveDialog(this);
1175 if (value != JalviewFileChooser.APPROVE_OPTION)
1181 fileName = chooser.getSelectedFile().getPath();
1183 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1184 Cache.setProperty("LAST_DIRECTORY", fileName);
1185 saveAlignment(fileName, currentFileFormat);
1188 boolean lastSaveSuccessful = false;
1190 FileFormatI lastFormatSaved;
1192 String lastFilenameSaved;
1195 * Raise a dialog or status message for the last call to saveAlignment.
1197 * @return true if last call to saveAlignment(file, format) was successful.
1199 public boolean isSaveAlignmentSuccessful()
1202 if (!lastSaveSuccessful)
1204 JvOptionPane.showInternalMessageDialog(this, MessageManager
1205 .formatMessage("label.couldnt_save_file", new Object[]
1206 { lastFilenameSaved }),
1207 MessageManager.getString("label.error_saving_file"),
1208 JvOptionPane.WARNING_MESSAGE);
1213 setStatus(MessageManager.formatMessage(
1214 "label.successfully_saved_to_file_in_format", new Object[]
1215 { lastFilenameSaved, lastFormatSaved }));
1218 return lastSaveSuccessful;
1222 * Saves the alignment to the specified file path, in the specified format,
1223 * which may be an alignment format, or Jalview project format. If the
1224 * alignment has hidden regions, or the format is one capable of including
1225 * non-sequence data (features, annotations, groups), then the user may be
1226 * prompted to specify what to include in the output.
1231 public void saveAlignment(String file, FileFormatI format)
1233 lastSaveSuccessful = false;
1234 lastFilenameSaved = file;
1235 lastFormatSaved = format;
1237 if (FileFormat.Jalview.equals(format))
1239 String shortName = title;
1240 if (shortName.indexOf(File.separatorChar) > -1)
1242 shortName = shortName.substring(
1243 shortName.lastIndexOf(File.separatorChar) + 1);
1245 lastSaveSuccessful = new jalview.project.Jalview2XML().saveAlignment(this, file,
1248 statusBar.setText(MessageManager.formatMessage(
1249 "label.successfully_saved_to_file_in_format", new Object[]
1250 { fileName, format }));
1255 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1256 Runnable cancelAction = new Runnable()
1261 lastSaveSuccessful = false;
1264 Runnable outputAction = new Runnable()
1269 // todo defer this to inside formatSequences (or later)
1270 AlignmentExportData exportData = viewport
1271 .getAlignExportData(options);
1272 String output = new FormatAdapter(alignPanel, options)
1273 .formatSequences(format, exportData.getAlignment(),
1274 exportData.getOmitHidden(),
1275 exportData.getStartEndPostions(),
1276 viewport.getAlignment().getHiddenColumns());
1279 lastSaveSuccessful = false;
1285 PrintWriter out = new PrintWriter(new FileWriter(file));
1288 AlignFrame.this.setTitle(file);
1289 setStatus(MessageManager.formatMessage(
1290 "label.successfully_saved_to_file_in_format",
1292 { fileName, format.getName() }));
1293 } catch (Exception ex)
1295 lastSaveSuccessful = false;
1296 ex.printStackTrace();
1303 * show dialog with export options if applicable; else just do it
1305 if (AlignExportOptions.isNeeded(viewport, format))
1307 AlignExportOptions choices = new AlignExportOptions(
1308 alignPanel.getAlignViewport(), format, options);
1309 choices.setResponseAction(0, outputAction);
1310 choices.setResponseAction(1, cancelAction);
1311 choices.showDialog();
1320 * Outputs the alignment to textbox in the requested format, if necessary
1321 * first prompting the user for whether to include hidden regions or
1324 * @param fileFormatName
1327 protected void outputText_actionPerformed(String fileFormatName)
1329 FileFormatI fileFormat = FileFormats.getInstance()
1330 .forName(fileFormatName);
1331 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1332 Runnable outputAction = new Runnable()
1337 // todo defer this to inside formatSequences (or later)
1338 AlignmentExportData exportData = viewport
1339 .getAlignExportData(options);
1340 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1341 cap.setForInput(null);
1344 FileFormatI format = fileFormat;
1345 cap.setText(new FormatAdapter(alignPanel, options)
1346 .formatSequences(format, exportData.getAlignment(),
1347 exportData.getOmitHidden(),
1348 exportData.getStartEndPostions(),
1349 viewport.getAlignment().getHiddenColumns()));
1350 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1351 "label.alignment_output_command", new Object[]
1352 { fileFormat.getName() }), 600, 500);
1353 } catch (OutOfMemoryError oom)
1355 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1363 * show dialog with export options if applicable; else just do it
1365 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1367 AlignExportOptions choices = new AlignExportOptions(
1368 alignPanel.getAlignViewport(), fileFormat, options);
1369 choices.setResponseAction(0, outputAction);
1370 choices.showDialog();
1385 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1387 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1388 htmlSVG.exportHTML(null);
1392 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1394 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1395 bjs.exportHTML(null);
1398 public void createImageMap(File file, String image)
1400 alignPanel.makePNGImageMap(file, image);
1404 * Creates a PNG image of the alignment and writes it to the given file. If
1405 * the file is null, the user is prompted to choose a file.
1410 public void createPNG(File f)
1412 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1416 * Creates an EPS image of the alignment and writes it to the given file. If
1417 * the file is null, the user is prompted to choose a file.
1422 public void createEPS(File f)
1424 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1428 * Creates an SVG image of the alignment and writes it to the given file. If
1429 * the file is null, the user is prompted to choose a file.
1434 public void createSVG(File f)
1436 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1440 public void pageSetup_actionPerformed(ActionEvent e)
1442 PrinterJob printJob = PrinterJob.getPrinterJob();
1443 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1453 public void printMenuItem_actionPerformed(ActionEvent e)
1455 // Putting in a thread avoids Swing painting problems
1456 PrintThread thread = new PrintThread(alignPanel);
1461 public void exportFeatures_actionPerformed(ActionEvent e)
1463 new AnnotationExporter(alignPanel).exportFeatures();
1467 public void exportAnnotations_actionPerformed(ActionEvent e)
1469 new AnnotationExporter(alignPanel).exportAnnotations();
1473 public void associatedData_actionPerformed(ActionEvent e)
1475 final JalviewFileChooser chooser = new JalviewFileChooser(
1476 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1477 chooser.setFileView(new JalviewFileView());
1478 chooser.setDialogTitle(
1479 MessageManager.getString("label.load_jalview_annotations"));
1480 chooser.setToolTipText(
1481 MessageManager.getString("label.load_jalview_annotations"));
1482 chooser.setResponseHandler(0, new Runnable()
1487 String choice = chooser.getSelectedFile().getPath();
1488 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1489 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1493 chooser.showOpenDialog(this);
1497 * Close the current view or all views in the alignment frame. If the frame
1498 * only contains one view then the alignment will be removed from memory.
1500 * @param closeAllTabs
1503 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1505 if (alignPanels != null && alignPanels.size() < 2)
1507 closeAllTabs = true;
1512 if (alignPanels != null)
1516 if (this.isClosed())
1518 // really close all the windows - otherwise wait till
1519 // setClosed(true) is called
1520 for (int i = 0; i < alignPanels.size(); i++)
1522 AlignmentPanel ap = alignPanels.get(i);
1529 closeView(alignPanel);
1536 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1537 * be called recursively, with the frame now in 'closed' state
1539 this.setClosed(true);
1541 } catch (Exception ex)
1543 ex.printStackTrace();
1548 * Close the specified panel and close up tabs appropriately.
1550 * @param panelToClose
1552 public void closeView(AlignmentPanel panelToClose)
1554 int index = tabbedPane.getSelectedIndex();
1555 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1556 alignPanels.remove(panelToClose);
1557 panelToClose.closePanel();
1558 panelToClose = null;
1560 tabbedPane.removeTabAt(closedindex);
1561 tabbedPane.validate();
1563 if (index > closedindex || index == tabbedPane.getTabCount())
1565 // modify currently selected tab index if necessary.
1569 this.tabSelectionChanged(index);
1575 void updateEditMenuBar()
1578 if (viewport.getHistoryList().size() > 0)
1580 undoMenuItem.setEnabled(true);
1581 CommandI command = viewport.getHistoryList().peek();
1582 undoMenuItem.setText(MessageManager
1583 .formatMessage("label.undo_command", new Object[]
1584 { command.getDescription() }));
1588 undoMenuItem.setEnabled(false);
1589 undoMenuItem.setText(MessageManager.getString("action.undo"));
1592 if (viewport.getRedoList().size() > 0)
1594 redoMenuItem.setEnabled(true);
1596 CommandI command = viewport.getRedoList().peek();
1597 redoMenuItem.setText(MessageManager
1598 .formatMessage("label.redo_command", new Object[]
1599 { command.getDescription() }));
1603 redoMenuItem.setEnabled(false);
1604 redoMenuItem.setText(MessageManager.getString("action.redo"));
1609 public void addHistoryItem(CommandI command)
1611 if (command.getSize() > 0)
1613 viewport.addToHistoryList(command);
1614 viewport.clearRedoList();
1615 updateEditMenuBar();
1616 viewport.updateHiddenColumns();
1617 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1618 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1619 // viewport.getColumnSelection()
1620 // .getHiddenColumns().size() > 0);
1626 * @return alignment objects for all views
1628 AlignmentI[] getViewAlignments()
1630 if (alignPanels != null)
1632 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1634 for (AlignmentPanel ap : alignPanels)
1636 als[i++] = ap.av.getAlignment();
1640 if (viewport != null)
1642 return new AlignmentI[] { viewport.getAlignment() };
1654 protected void undoMenuItem_actionPerformed(ActionEvent e)
1656 if (viewport.getHistoryList().isEmpty())
1660 CommandI command = viewport.getHistoryList().pop();
1661 viewport.addToRedoList(command);
1662 command.undoCommand(getViewAlignments());
1664 AlignmentViewport originalSource = getOriginatingSource(command);
1665 updateEditMenuBar();
1667 if (originalSource != null)
1669 if (originalSource != viewport)
1672 "Implementation worry: mismatch of viewport origin for undo");
1674 originalSource.updateHiddenColumns();
1675 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1677 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1678 // viewport.getColumnSelection()
1679 // .getHiddenColumns().size() > 0);
1680 originalSource.firePropertyChange("alignment", null,
1681 originalSource.getAlignment().getSequences());
1692 protected void redoMenuItem_actionPerformed(ActionEvent e)
1694 if (viewport.getRedoList().size() < 1)
1699 CommandI command = viewport.getRedoList().pop();
1700 viewport.addToHistoryList(command);
1701 command.doCommand(getViewAlignments());
1703 AlignmentViewport originalSource = getOriginatingSource(command);
1704 updateEditMenuBar();
1706 if (originalSource != null)
1709 if (originalSource != viewport)
1712 "Implementation worry: mismatch of viewport origin for redo");
1714 originalSource.updateHiddenColumns();
1715 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1717 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1718 // viewport.getColumnSelection()
1719 // .getHiddenColumns().size() > 0);
1720 originalSource.firePropertyChange("alignment", null,
1721 originalSource.getAlignment().getSequences());
1725 AlignmentViewport getOriginatingSource(CommandI command)
1727 AlignmentViewport originalSource = null;
1728 // For sequence removal and addition, we need to fire
1729 // the property change event FROM the viewport where the
1730 // original alignment was altered
1731 AlignmentI al = null;
1732 if (command instanceof EditCommand)
1734 EditCommand editCommand = (EditCommand) command;
1735 al = editCommand.getAlignment();
1736 List<Component> comps = PaintRefresher.components
1737 .get(viewport.getSequenceSetId());
1739 for (Component comp : comps)
1741 if (comp instanceof AlignmentPanel)
1743 if (al == ((AlignmentPanel) comp).av.getAlignment())
1745 originalSource = ((AlignmentPanel) comp).av;
1752 if (originalSource == null)
1754 // The original view is closed, we must validate
1755 // the current view against the closed view first
1758 PaintRefresher.validateSequences(al, viewport.getAlignment());
1761 originalSource = viewport;
1764 return originalSource;
1773 public void moveSelectedSequences(boolean up)
1775 SequenceGroup sg = viewport.getSelectionGroup();
1781 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1782 viewport.getHiddenRepSequences(), up);
1783 alignPanel.paintAlignment(true, false);
1786 synchronized void slideSequences(boolean right, int size)
1788 List<SequenceI> sg = new ArrayList<>();
1789 if (viewport.cursorMode)
1791 sg.add(viewport.getAlignment()
1792 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1794 else if (viewport.getSelectionGroup() != null
1795 && viewport.getSelectionGroup().getSize() != viewport
1796 .getAlignment().getHeight())
1798 sg = viewport.getSelectionGroup()
1799 .getSequences(viewport.getHiddenRepSequences());
1807 List<SequenceI> invertGroup = new ArrayList<>();
1809 for (SequenceI seq : viewport.getAlignment().getSequences())
1811 if (!sg.contains(seq))
1813 invertGroup.add(seq);
1817 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1819 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1820 for (int i = 0; i < invertGroup.size(); i++)
1822 seqs2[i] = invertGroup.get(i);
1825 SlideSequencesCommand ssc;
1828 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1829 viewport.getGapCharacter());
1833 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1834 viewport.getGapCharacter());
1837 int groupAdjustment = 0;
1838 if (ssc.getGapsInsertedBegin() && right)
1840 if (viewport.cursorMode)
1842 alignPanel.getSeqPanel().moveCursor(size, 0);
1846 groupAdjustment = size;
1849 else if (!ssc.getGapsInsertedBegin() && !right)
1851 if (viewport.cursorMode)
1853 alignPanel.getSeqPanel().moveCursor(-size, 0);
1857 groupAdjustment = -size;
1861 if (groupAdjustment != 0)
1863 viewport.getSelectionGroup().setStartRes(
1864 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1865 viewport.getSelectionGroup().setEndRes(
1866 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1870 * just extend the last slide command if compatible; but not if in
1871 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1873 boolean appendHistoryItem = false;
1874 Deque<CommandI> historyList = viewport.getHistoryList();
1875 boolean inSplitFrame = getSplitViewContainer() != null;
1876 if (!inSplitFrame && historyList != null && historyList.size() > 0
1877 && historyList.peek() instanceof SlideSequencesCommand)
1879 appendHistoryItem = ssc.appendSlideCommand(
1880 (SlideSequencesCommand) historyList.peek());
1883 if (!appendHistoryItem)
1885 addHistoryItem(ssc);
1898 protected void copy_actionPerformed()
1900 if (viewport.getSelectionGroup() == null)
1904 // TODO: preserve the ordering of displayed alignment annotation in any
1905 // internal paste (particularly sequence associated annotation)
1906 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1907 String[] omitHidden = null;
1909 if (viewport.hasHiddenColumns())
1911 omitHidden = viewport.getViewAsString(true);
1914 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1915 seqs, omitHidden, null);
1917 StringSelection ss = new StringSelection(output);
1921 jalview.gui.Desktop.internalCopy = true;
1922 // Its really worth setting the clipboard contents
1923 // to empty before setting the large StringSelection!!
1924 Toolkit.getDefaultToolkit().getSystemClipboard()
1925 .setContents(new StringSelection(""), null);
1927 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1929 } catch (OutOfMemoryError er)
1931 new OOMWarning("copying region", er);
1935 HiddenColumns hiddenColumns = null;
1936 if (viewport.hasHiddenColumns())
1938 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1939 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1941 // create new HiddenColumns object with copy of hidden regions
1942 // between startRes and endRes, offset by startRes
1943 hiddenColumns = new HiddenColumns(
1944 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
1945 hiddenCutoff, hiddenOffset);
1948 Desktop.jalviewClipboard = new Object[] { seqs,
1949 viewport.getAlignment().getDataset(), hiddenColumns };
1950 setStatus(MessageManager.formatMessage(
1951 "label.copied_sequences_to_clipboard", new Object[]
1952 { Integer.valueOf(seqs.length).toString() }));
1962 protected void pasteNew_actionPerformed(ActionEvent e)
1974 protected void pasteThis_actionPerformed(ActionEvent e)
1980 * Paste contents of Jalview clipboard
1982 * @param newAlignment
1983 * true to paste to a new alignment, otherwise add to this.
1985 void paste(boolean newAlignment)
1987 boolean externalPaste = true;
1990 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1991 Transferable contents = c.getContents(this);
1993 if (contents == null)
2002 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2003 if (str.length() < 1)
2008 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2010 } catch (OutOfMemoryError er)
2012 new OOMWarning("Out of memory pasting sequences!!", er);
2016 SequenceI[] sequences;
2017 boolean annotationAdded = false;
2018 AlignmentI alignment = null;
2020 if (Desktop.jalviewClipboard != null)
2022 // The clipboard was filled from within Jalview, we must use the
2024 // And dataset from the copied alignment
2025 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2026 // be doubly sure that we create *new* sequence objects.
2027 sequences = new SequenceI[newseq.length];
2028 for (int i = 0; i < newseq.length; i++)
2030 sequences[i] = new Sequence(newseq[i]);
2032 alignment = new Alignment(sequences);
2033 externalPaste = false;
2037 // parse the clipboard as an alignment.
2038 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2040 sequences = alignment.getSequencesArray();
2044 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2050 if (Desktop.jalviewClipboard != null)
2052 // dataset is inherited
2053 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2057 // new dataset is constructed
2058 alignment.setDataset(null);
2060 alwidth = alignment.getWidth() + 1;
2064 AlignmentI pastedal = alignment; // preserve pasted alignment object
2065 // Add pasted sequences and dataset into existing alignment.
2066 alignment = viewport.getAlignment();
2067 alwidth = alignment.getWidth() + 1;
2068 // decide if we need to import sequences from an existing dataset
2069 boolean importDs = Desktop.jalviewClipboard != null
2070 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2071 // importDs==true instructs us to copy over new dataset sequences from
2072 // an existing alignment
2073 Vector newDs = (importDs) ? new Vector() : null; // used to create
2074 // minimum dataset set
2076 for (int i = 0; i < sequences.length; i++)
2080 newDs.addElement(null);
2082 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2084 if (importDs && ds != null)
2086 if (!newDs.contains(ds))
2088 newDs.setElementAt(ds, i);
2089 ds = new Sequence(ds);
2090 // update with new dataset sequence
2091 sequences[i].setDatasetSequence(ds);
2095 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2100 // copy and derive new dataset sequence
2101 sequences[i] = sequences[i].deriveSequence();
2102 alignment.getDataset()
2103 .addSequence(sequences[i].getDatasetSequence());
2104 // TODO: avoid creation of duplicate dataset sequences with a
2105 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2107 alignment.addSequence(sequences[i]); // merges dataset
2111 newDs.clear(); // tidy up
2113 if (alignment.getAlignmentAnnotation() != null)
2115 for (AlignmentAnnotation alan : alignment
2116 .getAlignmentAnnotation())
2118 if (alan.graphGroup > fgroup)
2120 fgroup = alan.graphGroup;
2124 if (pastedal.getAlignmentAnnotation() != null)
2126 // Add any annotation attached to alignment.
2127 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2128 for (int i = 0; i < alann.length; i++)
2130 annotationAdded = true;
2131 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2133 AlignmentAnnotation newann = new AlignmentAnnotation(
2135 if (newann.graphGroup > -1)
2137 if (newGraphGroups.size() <= newann.graphGroup
2138 || newGraphGroups.get(newann.graphGroup) == null)
2140 for (int q = newGraphGroups
2141 .size(); q <= newann.graphGroup; q++)
2143 newGraphGroups.add(q, null);
2145 newGraphGroups.set(newann.graphGroup,
2146 new Integer(++fgroup));
2148 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2152 newann.padAnnotation(alwidth);
2153 alignment.addAnnotation(newann);
2163 addHistoryItem(new EditCommand(
2164 MessageManager.getString("label.add_sequences"),
2165 Action.PASTE, sequences, 0, alignment.getWidth(),
2168 // Add any annotations attached to sequences
2169 for (int i = 0; i < sequences.length; i++)
2171 if (sequences[i].getAnnotation() != null)
2173 AlignmentAnnotation newann;
2174 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2176 annotationAdded = true;
2177 newann = sequences[i].getAnnotation()[a];
2178 newann.adjustForAlignment();
2179 newann.padAnnotation(alwidth);
2180 if (newann.graphGroup > -1)
2182 if (newann.graphGroup > -1)
2184 if (newGraphGroups.size() <= newann.graphGroup
2185 || newGraphGroups.get(newann.graphGroup) == null)
2187 for (int q = newGraphGroups
2188 .size(); q <= newann.graphGroup; q++)
2190 newGraphGroups.add(q, null);
2192 newGraphGroups.set(newann.graphGroup,
2193 new Integer(++fgroup));
2195 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2199 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2203 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2211 // propagate alignment changed.
2212 viewport.getRanges().setEndSeq(alignment.getHeight());
2213 if (annotationAdded)
2215 // Duplicate sequence annotation in all views.
2216 AlignmentI[] alview = this.getViewAlignments();
2217 for (int i = 0; i < sequences.length; i++)
2219 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2224 for (int avnum = 0; avnum < alview.length; avnum++)
2226 if (alview[avnum] != alignment)
2228 // duplicate in a view other than the one with input focus
2229 int avwidth = alview[avnum].getWidth() + 1;
2230 // this relies on sann being preserved after we
2231 // modify the sequence's annotation array for each duplication
2232 for (int a = 0; a < sann.length; a++)
2234 AlignmentAnnotation newann = new AlignmentAnnotation(
2236 sequences[i].addAlignmentAnnotation(newann);
2237 newann.padAnnotation(avwidth);
2238 alview[avnum].addAnnotation(newann); // annotation was
2239 // duplicated earlier
2240 // TODO JAL-1145 graphGroups are not updated for sequence
2241 // annotation added to several views. This may cause
2243 alview[avnum].setAnnotationIndex(newann, a);
2248 buildSortByAnnotationScoresMenu();
2250 viewport.firePropertyChange("alignment", null,
2251 alignment.getSequences());
2252 if (alignPanels != null)
2254 for (AlignmentPanel ap : alignPanels)
2256 ap.validateAnnotationDimensions(false);
2261 alignPanel.validateAnnotationDimensions(false);
2267 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2269 String newtitle = new String("Copied sequences");
2271 if (Desktop.jalviewClipboard != null
2272 && Desktop.jalviewClipboard[2] != null)
2274 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2275 af.viewport.setHiddenColumns(hc);
2278 // >>>This is a fix for the moment, until a better solution is
2280 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2281 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2282 .getFeatureRenderer());
2284 // TODO: maintain provenance of an alignment, rather than just make the
2285 // title a concatenation of operations.
2288 if (title.startsWith("Copied sequences"))
2294 newtitle = newtitle.concat("- from " + title);
2299 newtitle = new String("Pasted sequences");
2302 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2307 } catch (Exception ex)
2309 ex.printStackTrace();
2310 System.out.println("Exception whilst pasting: " + ex);
2311 // could be anything being pasted in here
2317 protected void expand_newalign(ActionEvent e)
2321 AlignmentI alignment = AlignmentUtils
2322 .expandContext(getViewport().getAlignment(), -1);
2323 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2325 String newtitle = new String("Flanking alignment");
2327 if (Desktop.jalviewClipboard != null
2328 && Desktop.jalviewClipboard[2] != null)
2330 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2331 af.viewport.setHiddenColumns(hc);
2334 // >>>This is a fix for the moment, until a better solution is
2336 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2337 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2338 .getFeatureRenderer());
2340 // TODO: maintain provenance of an alignment, rather than just make the
2341 // title a concatenation of operations.
2343 if (title.startsWith("Copied sequences"))
2349 newtitle = newtitle.concat("- from " + title);
2353 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2355 } catch (Exception ex)
2357 ex.printStackTrace();
2358 System.out.println("Exception whilst pasting: " + ex);
2359 // could be anything being pasted in here
2360 } catch (OutOfMemoryError oom)
2362 new OOMWarning("Viewing flanking region of alignment", oom);
2367 * Action Cut (delete and copy) the selected region
2370 protected void cut_actionPerformed()
2372 copy_actionPerformed();
2373 delete_actionPerformed();
2377 * Performs menu option to Delete the currently selected region
2380 protected void delete_actionPerformed()
2383 SequenceGroup sg = viewport.getSelectionGroup();
2389 Runnable okAction = new Runnable()
2394 SequenceI[] cut = sg.getSequences()
2395 .toArray(new SequenceI[sg.getSize()]);
2397 addHistoryItem(new EditCommand(
2398 MessageManager.getString("label.cut_sequences"), Action.CUT,
2399 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2400 viewport.getAlignment()));
2402 viewport.setSelectionGroup(null);
2403 viewport.sendSelection();
2404 viewport.getAlignment().deleteGroup(sg);
2406 viewport.firePropertyChange("alignment", null,
2407 viewport.getAlignment().getSequences());
2408 if (viewport.getAlignment().getHeight() < 1)
2412 AlignFrame.this.setClosed(true);
2413 } catch (Exception ex)
2420 * If the cut affects all sequences, prompt for confirmation
2422 boolean wholeHeight = sg.getSize() == viewport.getAlignment().getHeight();
2423 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2424 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2425 if (wholeHeight && wholeWidth)
2427 JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.desktop);
2428 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2429 Object[] options = new Object[] { MessageManager.getString("action.ok"),
2430 MessageManager.getString("action.cancel") };
2431 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2432 MessageManager.getString("label.delete_all"),
2433 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2434 options, options[0]);
2448 protected void deleteGroups_actionPerformed(ActionEvent e)
2450 if (avc.deleteGroups())
2452 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2453 alignPanel.updateAnnotation();
2454 alignPanel.paintAlignment(true, true);
2465 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2467 SequenceGroup sg = new SequenceGroup();
2469 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2471 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2474 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2475 viewport.setSelectionGroup(sg);
2476 viewport.sendSelection();
2477 // JAL-2034 - should delegate to
2478 // alignPanel to decide if overview needs
2480 alignPanel.paintAlignment(false, false);
2481 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2491 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2493 if (viewport.cursorMode)
2495 alignPanel.getSeqPanel().keyboardNo1 = null;
2496 alignPanel.getSeqPanel().keyboardNo2 = null;
2498 viewport.setSelectionGroup(null);
2499 viewport.getColumnSelection().clear();
2500 viewport.setSelectionGroup(null);
2501 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2502 // JAL-2034 - should delegate to
2503 // alignPanel to decide if overview needs
2505 alignPanel.paintAlignment(false, false);
2506 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2507 viewport.sendSelection();
2517 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2519 SequenceGroup sg = viewport.getSelectionGroup();
2523 selectAllSequenceMenuItem_actionPerformed(null);
2528 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2530 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2532 // JAL-2034 - should delegate to
2533 // alignPanel to decide if overview needs
2536 alignPanel.paintAlignment(true, false);
2537 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2538 viewport.sendSelection();
2542 public void invertColSel_actionPerformed(ActionEvent e)
2544 viewport.invertColumnSelection();
2545 alignPanel.paintAlignment(true, false);
2546 viewport.sendSelection();
2556 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2558 trimAlignment(true);
2568 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2570 trimAlignment(false);
2573 void trimAlignment(boolean trimLeft)
2575 ColumnSelection colSel = viewport.getColumnSelection();
2578 if (!colSel.isEmpty())
2582 column = colSel.getMin();
2586 column = colSel.getMax();
2590 if (viewport.getSelectionGroup() != null)
2592 seqs = viewport.getSelectionGroup()
2593 .getSequencesAsArray(viewport.getHiddenRepSequences());
2597 seqs = viewport.getAlignment().getSequencesArray();
2600 TrimRegionCommand trimRegion;
2603 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2604 column, viewport.getAlignment());
2605 viewport.getRanges().setStartRes(0);
2609 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2610 column, viewport.getAlignment());
2613 setStatus(MessageManager
2614 .formatMessage("label.removed_columns", new String[]
2615 { Integer.valueOf(trimRegion.getSize()).toString() }));
2617 addHistoryItem(trimRegion);
2619 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2621 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2622 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2624 viewport.getAlignment().deleteGroup(sg);
2628 viewport.firePropertyChange("alignment", null,
2629 viewport.getAlignment().getSequences());
2640 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2642 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2645 if (viewport.getSelectionGroup() != null)
2647 seqs = viewport.getSelectionGroup()
2648 .getSequencesAsArray(viewport.getHiddenRepSequences());
2649 start = viewport.getSelectionGroup().getStartRes();
2650 end = viewport.getSelectionGroup().getEndRes();
2654 seqs = viewport.getAlignment().getSequencesArray();
2657 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2658 "Remove Gapped Columns", seqs, start, end,
2659 viewport.getAlignment());
2661 addHistoryItem(removeGapCols);
2663 setStatus(MessageManager
2664 .formatMessage("label.removed_empty_columns", new Object[]
2665 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2667 // This is to maintain viewport position on first residue
2668 // of first sequence
2669 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2670 ViewportRanges ranges = viewport.getRanges();
2671 int startRes = seq.findPosition(ranges.getStartRes());
2672 // ShiftList shifts;
2673 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2674 // edit.alColumnChanges=shifts.getInverse();
2675 // if (viewport.hasHiddenColumns)
2676 // viewport.getColumnSelection().compensateForEdits(shifts);
2677 ranges.setStartRes(seq.findIndex(startRes) - 1);
2678 viewport.firePropertyChange("alignment", null,
2679 viewport.getAlignment().getSequences());
2690 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2692 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2695 if (viewport.getSelectionGroup() != null)
2697 seqs = viewport.getSelectionGroup()
2698 .getSequencesAsArray(viewport.getHiddenRepSequences());
2699 start = viewport.getSelectionGroup().getStartRes();
2700 end = viewport.getSelectionGroup().getEndRes();
2704 seqs = viewport.getAlignment().getSequencesArray();
2707 // This is to maintain viewport position on first residue
2708 // of first sequence
2709 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2710 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2712 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2713 viewport.getAlignment()));
2715 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2717 viewport.firePropertyChange("alignment", null,
2718 viewport.getAlignment().getSequences());
2729 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2731 viewport.setPadGaps(padGapsMenuitem.isSelected());
2732 viewport.firePropertyChange("alignment", null,
2733 viewport.getAlignment().getSequences());
2743 public void findMenuItem_actionPerformed(ActionEvent e)
2749 * Create a new view of the current alignment.
2752 public void newView_actionPerformed(ActionEvent e)
2754 newView(null, true);
2758 * Creates and shows a new view of the current alignment.
2761 * title of newly created view; if null, one will be generated
2762 * @param copyAnnotation
2763 * if true then duplicate all annnotation, groups and settings
2764 * @return new alignment panel, already displayed.
2766 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2769 * Create a new AlignmentPanel (with its own, new Viewport)
2771 AlignmentPanel newap = new jalview.project.Jalview2XML()
2772 .copyAlignPanel(alignPanel);
2773 if (!copyAnnotation)
2776 * remove all groups and annotation except for the automatic stuff
2778 newap.av.getAlignment().deleteAllGroups();
2779 newap.av.getAlignment().deleteAllAnnotations(false);
2782 newap.av.setGatherViewsHere(false);
2784 if (viewport.getViewName() == null)
2786 viewport.setViewName(MessageManager
2787 .getString("label.view_name_original"));
2791 * Views share the same edits undo and redo stacks
2793 newap.av.setHistoryList(viewport.getHistoryList());
2794 newap.av.setRedoList(viewport.getRedoList());
2797 * Views share the same mappings; need to deregister any new mappings
2798 * created by copyAlignPanel, and register the new reference to the shared
2801 newap.av.replaceMappings(viewport.getAlignment());
2804 * start up cDNA consensus (if applicable) now mappings are in place
2806 if (newap.av.initComplementConsensus())
2808 newap.refresh(true); // adjust layout of annotations
2811 newap.av.setViewName(getNewViewName(viewTitle));
2813 addAlignmentPanel(newap, true);
2814 newap.alignmentChanged();
2816 if (alignPanels.size() == 2)
2818 viewport.setGatherViewsHere(true);
2820 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2825 * Make a new name for the view, ensuring it is unique within the current
2826 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2827 * these now use viewId. Unique view names are still desirable for usability.)
2832 protected String getNewViewName(String viewTitle)
2834 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2835 boolean addFirstIndex = false;
2836 if (viewTitle == null || viewTitle.trim().length() == 0)
2838 viewTitle = MessageManager.getString("action.view");
2839 addFirstIndex = true;
2843 index = 1;// we count from 1 if given a specific name
2845 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2847 List<Component> comps = PaintRefresher.components
2848 .get(viewport.getSequenceSetId());
2850 List<String> existingNames = getExistingViewNames(comps);
2852 while (existingNames.contains(newViewName))
2854 newViewName = viewTitle + " " + (++index);
2860 * Returns a list of distinct view names found in the given list of
2861 * components. View names are held on the viewport of an AlignmentPanel.
2866 protected List<String> getExistingViewNames(List<Component> comps)
2868 List<String> existingNames = new ArrayList<>();
2869 for (Component comp : comps)
2871 if (comp instanceof AlignmentPanel)
2873 AlignmentPanel ap = (AlignmentPanel) comp;
2874 if (!existingNames.contains(ap.av.getViewName()))
2876 existingNames.add(ap.av.getViewName());
2880 return existingNames;
2884 * Explode tabbed views into separate windows.
2887 public void expandViews_actionPerformed(ActionEvent e)
2889 Desktop.explodeViews(this);
2893 * Gather views in separate windows back into a tabbed presentation.
2896 public void gatherViews_actionPerformed(ActionEvent e)
2898 Desktop.instance.gatherViews(this);
2908 public void font_actionPerformed(ActionEvent e)
2910 new FontChooser(alignPanel);
2920 protected void seqLimit_actionPerformed(ActionEvent e)
2922 viewport.setShowJVSuffix(seqLimits.isSelected());
2924 alignPanel.getIdPanel().getIdCanvas()
2925 .setPreferredSize(alignPanel.calculateIdWidth());
2926 alignPanel.paintAlignment(true, false);
2930 public void idRightAlign_actionPerformed(ActionEvent e)
2932 viewport.setRightAlignIds(idRightAlign.isSelected());
2933 alignPanel.paintAlignment(false, false);
2937 public void centreColumnLabels_actionPerformed(ActionEvent e)
2939 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2940 alignPanel.paintAlignment(false, false);
2946 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2949 protected void followHighlight_actionPerformed()
2952 * Set the 'follow' flag on the Viewport (and scroll to position if now
2955 final boolean state = this.followHighlightMenuItem.getState();
2956 viewport.setFollowHighlight(state);
2959 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2970 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2972 viewport.setColourText(colourTextMenuItem.isSelected());
2973 alignPanel.paintAlignment(false, false);
2983 public void wrapMenuItem_actionPerformed(ActionEvent e)
2985 scaleAbove.setVisible(wrapMenuItem.isSelected());
2986 scaleLeft.setVisible(wrapMenuItem.isSelected());
2987 scaleRight.setVisible(wrapMenuItem.isSelected());
2988 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2989 alignPanel.updateLayout();
2993 public void showAllSeqs_actionPerformed(ActionEvent e)
2995 viewport.showAllHiddenSeqs();
2999 public void showAllColumns_actionPerformed(ActionEvent e)
3001 viewport.showAllHiddenColumns();
3002 alignPanel.paintAlignment(true, true);
3003 viewport.sendSelection();
3007 public void hideSelSequences_actionPerformed(ActionEvent e)
3009 viewport.hideAllSelectedSeqs();
3013 * called by key handler and the hide all/show all menu items
3018 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3021 boolean hide = false;
3022 SequenceGroup sg = viewport.getSelectionGroup();
3023 if (!toggleSeqs && !toggleCols)
3025 // Hide everything by the current selection - this is a hack - we do the
3026 // invert and then hide
3027 // first check that there will be visible columns after the invert.
3028 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3029 && sg.getStartRes() <= sg.getEndRes()))
3031 // now invert the sequence set, if required - empty selection implies
3032 // that no hiding is required.
3035 invertSequenceMenuItem_actionPerformed(null);
3036 sg = viewport.getSelectionGroup();
3040 viewport.expandColSelection(sg, true);
3041 // finally invert the column selection and get the new sequence
3043 invertColSel_actionPerformed(null);
3050 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3052 hideSelSequences_actionPerformed(null);
3055 else if (!(toggleCols && viewport.hasSelectedColumns()))
3057 showAllSeqs_actionPerformed(null);
3063 if (viewport.hasSelectedColumns())
3065 hideSelColumns_actionPerformed(null);
3068 viewport.setSelectionGroup(sg);
3073 showAllColumns_actionPerformed(null);
3082 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3083 * event.ActionEvent)
3086 public void hideAllButSelection_actionPerformed(ActionEvent e)
3088 toggleHiddenRegions(false, false);
3089 viewport.sendSelection();
3096 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3100 public void hideAllSelection_actionPerformed(ActionEvent e)
3102 SequenceGroup sg = viewport.getSelectionGroup();
3103 viewport.expandColSelection(sg, false);
3104 viewport.hideAllSelectedSeqs();
3105 viewport.hideSelectedColumns();
3106 alignPanel.paintAlignment(true, true);
3107 viewport.sendSelection();
3114 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3118 public void showAllhidden_actionPerformed(ActionEvent e)
3120 viewport.showAllHiddenColumns();
3121 viewport.showAllHiddenSeqs();
3122 alignPanel.paintAlignment(true, true);
3123 viewport.sendSelection();
3127 public void hideSelColumns_actionPerformed(ActionEvent e)
3129 viewport.hideSelectedColumns();
3130 alignPanel.paintAlignment(true, true);
3131 viewport.sendSelection();
3135 public void hiddenMarkers_actionPerformed(ActionEvent e)
3137 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3148 protected void scaleAbove_actionPerformed(ActionEvent e)
3150 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3151 // TODO: do we actually need to update overview for scale above change ?
3152 alignPanel.paintAlignment(true, false);
3162 protected void scaleLeft_actionPerformed(ActionEvent e)
3164 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3165 alignPanel.paintAlignment(true, false);
3175 protected void scaleRight_actionPerformed(ActionEvent e)
3177 viewport.setScaleRightWrapped(scaleRight.isSelected());
3178 alignPanel.paintAlignment(true, false);
3188 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3190 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3191 alignPanel.paintAlignment(false, false);
3201 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3203 viewport.setShowText(viewTextMenuItem.isSelected());
3204 alignPanel.paintAlignment(false, false);
3214 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3216 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3217 alignPanel.paintAlignment(false, false);
3220 public FeatureSettings featureSettings;
3223 public FeatureSettingsControllerI getFeatureSettingsUI()
3225 return featureSettings;
3229 public void featureSettings_actionPerformed(ActionEvent e)
3231 if (featureSettings != null)
3233 featureSettings.close();
3234 featureSettings = null;
3236 if (!showSeqFeatures.isSelected())
3238 // make sure features are actually displayed
3239 showSeqFeatures.setSelected(true);
3240 showSeqFeatures_actionPerformed(null);
3242 featureSettings = new FeatureSettings(this);
3246 * Set or clear 'Show Sequence Features'
3252 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3254 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3255 alignPanel.paintAlignment(true, true);
3259 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3260 * the annotations panel as a whole.
3262 * The options to show/hide all annotations should be enabled when the panel
3263 * is shown, and disabled when the panel is hidden.
3268 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3270 final boolean setVisible = annotationPanelMenuItem.isSelected();
3271 viewport.setShowAnnotation(setVisible);
3272 this.showAllSeqAnnotations.setEnabled(setVisible);
3273 this.hideAllSeqAnnotations.setEnabled(setVisible);
3274 this.showAllAlAnnotations.setEnabled(setVisible);
3275 this.hideAllAlAnnotations.setEnabled(setVisible);
3276 alignPanel.updateLayout();
3280 public void alignmentProperties()
3283 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3286 String content = MessageManager.formatMessage("label.html_content",
3288 { contents.toString() });
3291 if (Platform.isJS())
3293 JLabel textLabel = new JLabel();
3294 textLabel.setText(content);
3295 textLabel.setBackground(Color.WHITE);
3297 pane = new JPanel(new BorderLayout());
3298 ((JPanel) pane).setOpaque(true);
3299 pane.setBackground(Color.WHITE);
3300 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3304 JEditorPane editPane = new JEditorPane("text/html", "");
3305 editPane.setEditable(false);
3306 editPane.setText(content);
3310 JInternalFrame frame = new JInternalFrame();
3312 frame.getContentPane().add(new JScrollPane(pane));
3314 Desktop.addInternalFrame(frame, MessageManager
3315 .formatMessage("label.alignment_properties", new Object[]
3316 { getTitle() }), 500, 400);
3326 public void overviewMenuItem_actionPerformed(ActionEvent e)
3328 if (alignPanel.overviewPanel != null)
3333 JInternalFrame frame = new JInternalFrame();
3334 final OverviewPanel overview = new OverviewPanel(alignPanel);
3335 frame.setContentPane(overview);
3336 Desktop.addInternalFrame(frame, MessageManager
3337 .formatMessage("label.overview_params", new Object[]
3338 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3341 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3342 frame.addInternalFrameListener(
3343 new javax.swing.event.InternalFrameAdapter()
3346 public void internalFrameClosed(
3347 javax.swing.event.InternalFrameEvent evt)
3350 alignPanel.setOverviewPanel(null);
3353 if (getKeyListeners().length > 0)
3355 frame.addKeyListener(getKeyListeners()[0]);
3358 alignPanel.setOverviewPanel(overview);
3362 public void textColour_actionPerformed()
3364 new TextColourChooser().chooseColour(alignPanel, null);
3368 * public void covariationColour_actionPerformed() {
3370 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3374 public void annotationColour_actionPerformed()
3376 new AnnotationColourChooser(viewport, alignPanel);
3380 public void annotationColumn_actionPerformed(ActionEvent e)
3382 new AnnotationColumnChooser(viewport, alignPanel);
3386 * Action on the user checking or unchecking the option to apply the selected
3387 * colour scheme to all groups. If unchecked, groups may have their own
3388 * independent colour schemes.
3393 public void applyToAllGroups_actionPerformed(boolean selected)
3395 viewport.setColourAppliesToAllGroups(selected);
3399 * Action on user selecting a colour from the colour menu
3402 * the name (not the menu item label!) of the colour scheme
3405 public void changeColour_actionPerformed(String name)
3408 * 'User Defined' opens a panel to configure or load a
3409 * user-defined colour scheme
3411 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3413 new UserDefinedColours(alignPanel);
3418 * otherwise set the chosen colour scheme (or null for 'None')
3420 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3421 viewport.getAlignment(), viewport.getHiddenRepSequences());
3426 * Actions on setting or changing the alignment colour scheme
3431 public void changeColour(ColourSchemeI cs)
3433 // TODO: pull up to controller method
3434 ColourMenuHelper.setColourSelected(colourMenu, cs);
3436 viewport.setGlobalColourScheme(cs);
3438 alignPanel.paintAlignment(true, true);
3442 * Show the PID threshold slider panel
3445 protected void modifyPID_actionPerformed()
3447 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3448 alignPanel.getViewName());
3449 SliderPanel.showPIDSlider();
3453 * Show the Conservation slider panel
3456 protected void modifyConservation_actionPerformed()
3458 SliderPanel.setConservationSlider(alignPanel,
3459 viewport.getResidueShading(), alignPanel.getViewName());
3460 SliderPanel.showConservationSlider();
3464 * Action on selecting or deselecting (Colour) By Conservation
3467 public void conservationMenuItem_actionPerformed(boolean selected)
3469 modifyConservation.setEnabled(selected);
3470 viewport.setConservationSelected(selected);
3471 viewport.getResidueShading().setConservationApplied(selected);
3473 changeColour(viewport.getGlobalColourScheme());
3476 modifyConservation_actionPerformed();
3480 SliderPanel.hideConservationSlider();
3485 * Action on selecting or deselecting (Colour) Above PID Threshold
3488 public void abovePIDThreshold_actionPerformed(boolean selected)
3490 modifyPID.setEnabled(selected);
3491 viewport.setAbovePIDThreshold(selected);
3494 viewport.getResidueShading().setThreshold(0,
3495 viewport.isIgnoreGapsConsensus());
3498 changeColour(viewport.getGlobalColourScheme());
3501 modifyPID_actionPerformed();
3505 SliderPanel.hidePIDSlider();
3516 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3518 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3519 AlignmentSorter.sortByPID(viewport.getAlignment(),
3520 viewport.getAlignment().getSequenceAt(0));
3521 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3522 viewport.getAlignment()));
3523 alignPanel.paintAlignment(true, false);
3533 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3535 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3536 AlignmentSorter.sortByID(viewport.getAlignment());
3538 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3539 alignPanel.paintAlignment(true, false);
3549 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3551 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3552 AlignmentSorter.sortByLength(viewport.getAlignment());
3553 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3554 viewport.getAlignment()));
3555 alignPanel.paintAlignment(true, false);
3565 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3567 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3568 AlignmentSorter.sortByGroup(viewport.getAlignment());
3569 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3570 viewport.getAlignment()));
3572 alignPanel.paintAlignment(true, false);
3582 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3584 new RedundancyPanel(alignPanel, this);
3594 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3596 if ((viewport.getSelectionGroup() == null)
3597 || (viewport.getSelectionGroup().getSize() < 2))
3599 JvOptionPane.showInternalMessageDialog(this,
3600 MessageManager.getString(
3601 "label.you_must_select_least_two_sequences"),
3602 MessageManager.getString("label.invalid_selection"),
3603 JvOptionPane.WARNING_MESSAGE);
3607 JInternalFrame frame = new JInternalFrame();
3608 frame.setContentPane(new PairwiseAlignPanel(viewport));
3609 Desktop.addInternalFrame(frame,
3610 MessageManager.getString("action.pairwise_alignment"), 600,
3616 public void autoCalculate_actionPerformed(ActionEvent e)
3618 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3619 if (viewport.autoCalculateConsensus)
3621 viewport.firePropertyChange("alignment", null,
3622 viewport.getAlignment().getSequences());
3627 public void sortByTreeOption_actionPerformed(ActionEvent e)
3629 viewport.sortByTree = sortByTree.isSelected();
3633 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3635 viewport.followSelection = listenToViewSelections.isSelected();
3639 * Constructs a tree panel and adds it to the desktop
3642 * tree type (NJ or AV)
3644 * name of score model used to compute the tree
3646 * parameters for the distance or similarity calculation
3648 void newTreePanel(String type, String modelName,
3649 SimilarityParamsI options)
3651 String frameTitle = "";
3654 boolean onSelection = false;
3655 if (viewport.getSelectionGroup() != null
3656 && viewport.getSelectionGroup().getSize() > 0)
3658 SequenceGroup sg = viewport.getSelectionGroup();
3660 /* Decide if the selection is a column region */
3661 for (SequenceI _s : sg.getSequences())
3663 if (_s.getLength() < sg.getEndRes())
3665 JvOptionPane.showMessageDialog(Desktop.desktop,
3666 MessageManager.getString(
3667 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3668 MessageManager.getString(
3669 "label.sequences_selection_not_aligned"),
3670 JvOptionPane.WARNING_MESSAGE);
3679 if (viewport.getAlignment().getHeight() < 2)
3685 tp = new TreePanel(alignPanel, type, modelName, options);
3686 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3688 frameTitle += " from ";
3690 if (viewport.getViewName() != null)
3692 frameTitle += viewport.getViewName() + " of ";
3695 frameTitle += this.title;
3697 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3708 public void addSortByOrderMenuItem(String title,
3709 final AlignmentOrder order)
3711 final JMenuItem item = new JMenuItem(MessageManager
3712 .formatMessage("action.by_title_param", new Object[]
3715 item.addActionListener(new java.awt.event.ActionListener()
3718 public void actionPerformed(ActionEvent e)
3720 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3722 // TODO: JBPNote - have to map order entries to curent SequenceI
3724 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3726 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3727 viewport.getAlignment()));
3729 alignPanel.paintAlignment(true, false);
3735 * Add a new sort by annotation score menu item
3738 * the menu to add the option to
3740 * the label used to retrieve scores for each sequence on the
3743 public void addSortByAnnotScoreMenuItem(JMenu sort,
3744 final String scoreLabel)
3746 final JMenuItem item = new JMenuItem(scoreLabel);
3748 item.addActionListener(new java.awt.event.ActionListener()
3751 public void actionPerformed(ActionEvent e)
3753 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3754 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3755 viewport.getAlignment());// ,viewport.getSelectionGroup());
3756 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3757 viewport.getAlignment()));
3758 alignPanel.paintAlignment(true, false);
3764 * last hash for alignment's annotation array - used to minimise cost of
3767 protected int _annotationScoreVectorHash;
3770 * search the alignment and rebuild the sort by annotation score submenu the
3771 * last alignment annotation vector hash is stored to minimize cost of
3772 * rebuilding in subsequence calls.
3776 public void buildSortByAnnotationScoresMenu()
3778 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3783 if (viewport.getAlignment().getAlignmentAnnotation()
3784 .hashCode() != _annotationScoreVectorHash)
3786 sortByAnnotScore.removeAll();
3787 // almost certainly a quicker way to do this - but we keep it simple
3788 Hashtable scoreSorts = new Hashtable();
3789 AlignmentAnnotation aann[];
3790 for (SequenceI sqa : viewport.getAlignment().getSequences())
3792 aann = sqa.getAnnotation();
3793 for (int i = 0; aann != null && i < aann.length; i++)
3795 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3797 scoreSorts.put(aann[i].label, aann[i].label);
3801 Enumeration labels = scoreSorts.keys();
3802 while (labels.hasMoreElements())
3804 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3805 (String) labels.nextElement());
3807 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3810 _annotationScoreVectorHash = viewport.getAlignment()
3811 .getAlignmentAnnotation().hashCode();
3816 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3817 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3818 * call. Listeners are added to remove the menu item when the treePanel is
3819 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3823 public void buildTreeSortMenu()
3825 sortByTreeMenu.removeAll();
3827 List<Component> comps = PaintRefresher.components
3828 .get(viewport.getSequenceSetId());
3829 List<TreePanel> treePanels = new ArrayList<>();
3830 for (Component comp : comps)
3832 if (comp instanceof TreePanel)
3834 treePanels.add((TreePanel) comp);
3838 if (treePanels.size() < 1)
3840 sortByTreeMenu.setVisible(false);
3844 sortByTreeMenu.setVisible(true);
3846 for (final TreePanel tp : treePanels)
3848 final JMenuItem item = new JMenuItem(tp.getTitle());
3849 item.addActionListener(new java.awt.event.ActionListener()
3852 public void actionPerformed(ActionEvent e)
3854 tp.sortByTree_actionPerformed();
3855 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3860 sortByTreeMenu.add(item);
3864 public boolean sortBy(AlignmentOrder alorder, String undoname)
3866 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3867 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3868 if (undoname != null)
3870 addHistoryItem(new OrderCommand(undoname, oldOrder,
3871 viewport.getAlignment()));
3873 alignPanel.paintAlignment(true, false);
3878 * Work out whether the whole set of sequences or just the selected set will
3879 * be submitted for multiple alignment.
3882 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3884 // Now, check we have enough sequences
3885 AlignmentView msa = null;
3887 if ((viewport.getSelectionGroup() != null)
3888 && (viewport.getSelectionGroup().getSize() > 1))
3890 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3891 // some common interface!
3893 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3894 * SequenceI[sz = seqs.getSize(false)];
3896 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3897 * seqs.getSequenceAt(i); }
3899 msa = viewport.getAlignmentView(true);
3901 else if (viewport.getSelectionGroup() != null
3902 && viewport.getSelectionGroup().getSize() == 1)
3904 int option = JvOptionPane.showConfirmDialog(this,
3905 MessageManager.getString("warn.oneseq_msainput_selection"),
3906 MessageManager.getString("label.invalid_selection"),
3907 JvOptionPane.OK_CANCEL_OPTION);
3908 if (option == JvOptionPane.OK_OPTION)
3910 msa = viewport.getAlignmentView(false);
3915 msa = viewport.getAlignmentView(false);
3921 * Decides what is submitted to a secondary structure prediction service: the
3922 * first sequence in the alignment, or in the current selection, or, if the
3923 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3924 * region or the whole alignment. (where the first sequence in the set is the
3925 * one that the prediction will be for).
3927 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3929 AlignmentView seqs = null;
3931 if ((viewport.getSelectionGroup() != null)
3932 && (viewport.getSelectionGroup().getSize() > 0))
3934 seqs = viewport.getAlignmentView(true);
3938 seqs = viewport.getAlignmentView(false);
3940 // limit sequences - JBPNote in future - could spawn multiple prediction
3942 // TODO: viewport.getAlignment().isAligned is a global state - the local
3943 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3944 if (!viewport.getAlignment().isAligned(false))
3946 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3947 // TODO: if seqs.getSequences().length>1 then should really have warned
3961 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3963 // Pick the tree file
3964 JalviewFileChooser chooser = new JalviewFileChooser(
3965 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3966 chooser.setFileView(new JalviewFileView());
3967 chooser.setDialogTitle(
3968 MessageManager.getString("label.select_newick_like_tree_file"));
3969 chooser.setToolTipText(
3970 MessageManager.getString("label.load_tree_file"));
3972 chooser.setResponseHandler(0,new Runnable()
3977 String filePath = chooser.getSelectedFile().getPath();
3978 Cache.setProperty("LAST_DIRECTORY", filePath);
3979 NewickFile fin = null;
3982 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
3983 DataSourceType.FILE));
3984 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
3985 } catch (Exception ex)
3987 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
3989 .getString("label.problem_reading_tree_file"),
3990 JvOptionPane.WARNING_MESSAGE);
3991 ex.printStackTrace();
3993 if (fin != null && fin.hasWarningMessage())
3995 JvOptionPane.showMessageDialog(Desktop.desktop,
3996 fin.getWarningMessage(),
3997 MessageManager.getString(
3998 "label.possible_problem_with_tree_file"),
3999 JvOptionPane.WARNING_MESSAGE);
4003 chooser.showOpenDialog(this);
4006 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4008 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4011 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4012 int h, int x, int y)
4014 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4018 * Add a treeviewer for the tree extracted from a Newick file object to the
4019 * current alignment view
4026 * Associated alignment input data (or null)
4035 * @return TreePanel handle
4037 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4038 AlignmentView input, int w, int h, int x, int y)
4040 TreePanel tp = null;
4046 if (nf.getTree() != null)
4048 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4054 tp.setLocation(x, y);
4057 Desktop.addInternalFrame(tp, treeTitle, w, h);
4059 } catch (Exception ex)
4061 ex.printStackTrace();
4067 private boolean buildingMenu = false;
4070 * Generates menu items and listener event actions for web service clients
4073 public void BuildWebServiceMenu()
4075 while (buildingMenu)
4079 System.err.println("Waiting for building menu to finish.");
4081 } catch (Exception e)
4085 final AlignFrame me = this;
4086 buildingMenu = true;
4087 new Thread(new Runnable()
4092 final List<JMenuItem> legacyItems = new ArrayList<>();
4095 // System.err.println("Building ws menu again "
4096 // + Thread.currentThread());
4097 // TODO: add support for context dependent disabling of services based
4099 // alignment and current selection
4100 // TODO: add additional serviceHandle parameter to specify abstract
4102 // class independently of AbstractName
4103 // TODO: add in rediscovery GUI function to restart discoverer
4104 // TODO: group services by location as well as function and/or
4106 // object broker mechanism.
4107 final Vector<JMenu> wsmenu = new Vector<>();
4108 final IProgressIndicator af = me;
4111 * do not i18n these strings - they are hard-coded in class
4112 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4113 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4115 final JMenu msawsmenu = new JMenu("Alignment");
4116 final JMenu secstrmenu = new JMenu(
4117 "Secondary Structure Prediction");
4118 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4119 final JMenu analymenu = new JMenu("Analysis");
4120 final JMenu dismenu = new JMenu("Protein Disorder");
4121 // JAL-940 - only show secondary structure prediction services from
4122 // the legacy server
4123 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4125 Discoverer.services != null && (Discoverer.services.size() > 0))
4127 // TODO: refactor to allow list of AbstractName/Handler bindings to
4129 // stored or retrieved from elsewhere
4130 // No MSAWS used any more:
4131 // Vector msaws = null; // (Vector)
4132 // Discoverer.services.get("MsaWS");
4133 Vector secstrpr = (Vector) Discoverer.services
4135 if (secstrpr != null)
4137 // Add any secondary structure prediction services
4138 for (int i = 0, j = secstrpr.size(); i < j; i++)
4140 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4142 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4143 .getServiceClient(sh);
4144 int p = secstrmenu.getItemCount();
4145 impl.attachWSMenuEntry(secstrmenu, me);
4146 int q = secstrmenu.getItemCount();
4147 for (int litm = p; litm < q; litm++)
4149 legacyItems.add(secstrmenu.getItem(litm));
4155 // Add all submenus in the order they should appear on the web
4157 wsmenu.add(msawsmenu);
4158 wsmenu.add(secstrmenu);
4159 wsmenu.add(dismenu);
4160 wsmenu.add(analymenu);
4161 // No search services yet
4162 // wsmenu.add(seqsrchmenu);
4164 javax.swing.SwingUtilities.invokeLater(new Runnable()
4171 webService.removeAll();
4172 // first, add discovered services onto the webservices menu
4173 if (wsmenu.size() > 0)
4175 for (int i = 0, j = wsmenu.size(); i < j; i++)
4177 webService.add(wsmenu.get(i));
4182 webService.add(me.webServiceNoServices);
4184 // TODO: move into separate menu builder class.
4185 boolean new_sspred = false;
4186 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4188 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4189 if (jws2servs != null)
4191 if (jws2servs.hasServices())
4193 jws2servs.attachWSMenuEntry(webService, me);
4194 for (Jws2Instance sv : jws2servs.getServices())
4196 if (sv.description.toLowerCase().contains("jpred"))
4198 for (JMenuItem jmi : legacyItems)
4200 jmi.setVisible(false);
4206 if (jws2servs.isRunning())
4208 JMenuItem tm = new JMenuItem(
4209 "Still discovering JABA Services");
4210 tm.setEnabled(false);
4215 build_urlServiceMenu(me.webService);
4216 build_fetchdbmenu(webService);
4217 for (JMenu item : wsmenu)
4219 if (item.getItemCount() == 0)
4221 item.setEnabled(false);
4225 item.setEnabled(true);
4228 } catch (Exception e)
4231 "Exception during web service menu building process.",
4236 } catch (Exception e)
4239 buildingMenu = false;
4246 * construct any groupURL type service menu entries.
4250 private void build_urlServiceMenu(JMenu webService)
4252 // TODO: remove this code when 2.7 is released
4253 // DEBUG - alignmentView
4255 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4256 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4258 * @Override public void actionPerformed(ActionEvent e) {
4259 * jalview.datamodel.AlignmentView
4260 * .testSelectionViews(af.viewport.getAlignment(),
4261 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4263 * }); webService.add(testAlView);
4265 // TODO: refactor to RestClient discoverer and merge menu entries for
4266 // rest-style services with other types of analysis/calculation service
4267 // SHmmr test client - still being implemented.
4268 // DEBUG - alignmentView
4270 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4273 client.attachWSMenuEntry(
4274 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4280 * Searches the alignment sequences for xRefs and builds the Show
4281 * Cross-References menu (formerly called Show Products), with database
4282 * sources for which cross-references are found (protein sources for a
4283 * nucleotide alignment and vice versa)
4285 * @return true if Show Cross-references menu should be enabled
4287 public boolean canShowProducts()
4289 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4290 AlignmentI dataset = viewport.getAlignment().getDataset();
4292 showProducts.removeAll();
4293 final boolean dna = viewport.getAlignment().isNucleotide();
4295 if (seqs == null || seqs.length == 0)
4297 // nothing to see here.
4301 boolean showp = false;
4304 List<String> ptypes = new CrossRef(seqs, dataset)
4305 .findXrefSourcesForSequences(dna);
4307 for (final String source : ptypes)
4310 final AlignFrame af = this;
4311 JMenuItem xtype = new JMenuItem(source);
4312 xtype.addActionListener(new ActionListener()
4315 public void actionPerformed(ActionEvent e)
4317 showProductsFor(af.viewport.getSequenceSelection(), dna,
4321 showProducts.add(xtype);
4323 showProducts.setVisible(showp);
4324 showProducts.setEnabled(showp);
4325 } catch (Exception e)
4328 "canShowProducts threw an exception - please report to help@jalview.org",
4336 * Finds and displays cross-references for the selected sequences (protein
4337 * products for nucleotide sequences, dna coding sequences for peptides).
4340 * the sequences to show cross-references for
4342 * true if from a nucleotide alignment (so showing proteins)
4344 * the database to show cross-references for
4346 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4347 final String source)
4349 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4354 * Construct and display a new frame containing the translation of this
4355 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4358 public void showTranslation_actionPerformed(ActionEvent e)
4360 AlignmentI al = null;
4363 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4365 al = dna.translateCdna();
4366 } catch (Exception ex)
4368 jalview.bin.Cache.log.error(
4369 "Exception during translation. Please report this !", ex);
4370 final String msg = MessageManager.getString(
4371 "label.error_when_translating_sequences_submit_bug_report");
4372 final String errorTitle = MessageManager
4373 .getString("label.implementation_error")
4374 + MessageManager.getString("label.translation_failed");
4375 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4376 JvOptionPane.ERROR_MESSAGE);
4379 if (al == null || al.getHeight() == 0)
4381 final String msg = MessageManager.getString(
4382 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4383 final String errorTitle = MessageManager
4384 .getString("label.translation_failed");
4385 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4386 JvOptionPane.WARNING_MESSAGE);
4390 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4391 af.setFileFormat(this.currentFileFormat);
4392 final String newTitle = MessageManager
4393 .formatMessage("label.translation_of_params", new Object[]
4394 { this.getTitle() });
4395 af.setTitle(newTitle);
4396 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4398 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4399 viewport.openSplitFrame(af, new Alignment(seqs));
4403 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4410 * Set the file format
4414 public void setFileFormat(FileFormatI format)
4416 this.currentFileFormat = format;
4420 * Try to load a features file onto the alignment.
4423 * contents or path to retrieve file or a File object
4425 * access mode of file (see jalview.io.AlignFile)
4426 * @return true if features file was parsed correctly.
4428 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4431 return avc.parseFeaturesFile(file, sourceType,
4432 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4437 public void refreshFeatureUI(boolean enableIfNecessary)
4439 // note - currently this is only still here rather than in the controller
4440 // because of the featureSettings hard reference that is yet to be
4442 if (enableIfNecessary)
4444 viewport.setShowSequenceFeatures(true);
4445 showSeqFeatures.setSelected(true);
4451 public void dragEnter(DropTargetDragEvent evt)
4456 public void dragExit(DropTargetEvent evt)
4461 public void dragOver(DropTargetDragEvent evt)
4466 public void dropActionChanged(DropTargetDragEvent evt)
4471 public void drop(DropTargetDropEvent evt)
4473 // JAL-1552 - acceptDrop required before getTransferable call for
4474 // Java's Transferable for native dnd
4475 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4476 Transferable t = evt.getTransferable();
4478 final AlignFrame thisaf = this;
4479 final List<Object> files = new ArrayList<>();
4480 List<DataSourceType> protocols = new ArrayList<>();
4484 Desktop.transferFromDropTarget(files, protocols, evt, t);
4485 } catch (Exception e)
4487 e.printStackTrace();
4491 new Thread(new Runnable()
4498 // check to see if any of these files have names matching sequences
4501 SequenceIdMatcher idm = new SequenceIdMatcher(
4502 viewport.getAlignment().getSequencesArray());
4504 * Object[] { String,SequenceI}
4506 ArrayList<Object[]> filesmatched = new ArrayList<>();
4507 ArrayList<Object> filesnotmatched = new ArrayList<>();
4508 for (int i = 0; i < files.size(); i++)
4511 Object file = files.get(i);
4512 String fileName = file.toString();
4514 DataSourceType protocol = (file instanceof File
4515 ? DataSourceType.FILE
4516 : FormatAdapter.checkProtocol(fileName));
4517 if (protocol == DataSourceType.FILE)
4519 File fl = (file instanceof File ? (File) file
4520 : new File(fileName));
4521 pdbfn = fl.getName();
4523 else if (protocol == DataSourceType.URL)
4525 URL url = new URL(fileName);
4526 pdbfn = url.getFile();
4528 if (pdbfn.length() > 0)
4530 // attempt to find a match in the alignment
4531 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4532 int l = 0, c = pdbfn.indexOf(".");
4533 while (mtch == null && c != -1)
4538 } while ((c = pdbfn.indexOf(".", l)) > l);
4541 pdbfn = pdbfn.substring(0, l);
4543 mtch = idm.findAllIdMatches(pdbfn);
4550 type = new IdentifyFile().identify(file, protocol);
4551 } catch (Exception ex)
4555 if (type != null && type.isStructureFile())
4557 filesmatched.add(new Object[] { file, protocol, mtch });
4561 // File wasn't named like one of the sequences or wasn't a PDB
4563 filesnotmatched.add(file);
4567 if (filesmatched.size() > 0)
4569 boolean autoAssociate = Cache
4570 .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4573 String msg = MessageManager.formatMessage(
4574 "label.automatically_associate_structure_files_with_sequences_same_name",
4576 { Integer.valueOf(filesmatched.size())
4578 String ttl = MessageManager.getString(
4579 "label.automatically_associate_structure_files_by_name");
4580 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4581 ttl, JvOptionPane.YES_NO_OPTION);
4582 autoAssociate = choice == JvOptionPane.YES_OPTION;
4586 for (Object[] fm : filesmatched)
4588 // try and associate
4589 // TODO: may want to set a standard ID naming formalism for
4590 // associating PDB files which have no IDs.
4591 for (SequenceI toassoc : (SequenceI[]) fm[2])
4593 PDBEntry pe = new AssociatePdbFileWithSeq()
4594 .associatePdbWithSeq(fm[0].toString(),
4595 (DataSourceType) fm[1], toassoc, false,
4599 System.err.println("Associated file : "
4600 + (fm[0].toString()) + " with "
4601 + toassoc.getDisplayId(true));
4605 // TODO: do we need to update overview ? only if features are
4607 alignPanel.paintAlignment(true, false);
4613 * add declined structures as sequences
4615 for (Object[] o : filesmatched)
4617 filesnotmatched.add(o[0]);
4621 if (filesnotmatched.size() > 0)
4623 if (assocfiles > 0 && (Cache.getDefault(
4624 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4625 || JvOptionPane.showConfirmDialog(thisaf,
4626 "<html>" + MessageManager.formatMessage(
4627 "label.ignore_unmatched_dropped_files_info",
4630 filesnotmatched.size())
4633 MessageManager.getString(
4634 "label.ignore_unmatched_dropped_files"),
4635 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4639 for (Object fn : filesnotmatched)
4641 loadJalviewDataFile(fn, null, null, null);
4645 } catch (Exception ex)
4647 ex.printStackTrace();
4655 * Attempt to load a "dropped" file or URL string, by testing in turn for
4657 * <li>an Annotation file</li>
4658 * <li>a JNet file</li>
4659 * <li>a features file</li>
4660 * <li>else try to interpret as an alignment file</li>
4664 * either a filename or a URL string.
4666 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4667 FileFormatI format, SequenceI assocSeq)
4669 // BH 2018 was String file
4672 if (sourceType == null)
4674 sourceType = FormatAdapter.checkProtocol(file);
4676 // if the file isn't identified, or not positively identified as some
4677 // other filetype (PFAM is default unidentified alignment file type) then
4678 // try to parse as annotation.
4679 boolean isAnnotation = (format == null
4680 || FileFormat.Pfam.equals(format))
4681 ? new AnnotationFile().annotateAlignmentView(viewport,
4687 // first see if its a T-COFFEE score file
4688 TCoffeeScoreFile tcf = null;
4691 tcf = new TCoffeeScoreFile(file, sourceType);
4694 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4698 new TCoffeeColourScheme(viewport.getAlignment()));
4699 isAnnotation = true;
4700 setStatus(MessageManager.getString(
4701 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4705 // some problem - if no warning its probable that the ID matching
4706 // process didn't work
4707 JvOptionPane.showMessageDialog(Desktop.desktop,
4708 tcf.getWarningMessage() == null
4709 ? MessageManager.getString(
4710 "label.check_file_matches_sequence_ids_alignment")
4711 : tcf.getWarningMessage(),
4712 MessageManager.getString(
4713 "label.problem_reading_tcoffee_score_file"),
4714 JvOptionPane.WARNING_MESSAGE);
4721 } catch (Exception x)
4724 "Exception when processing data source as T-COFFEE score file",
4730 // try to see if its a JNet 'concise' style annotation file *before*
4732 // try to parse it as a features file
4735 format = new IdentifyFile().identify(file, sourceType);
4737 if (FileFormat.ScoreMatrix == format)
4739 ScoreMatrixFile sm = new ScoreMatrixFile(
4740 new FileParse(file, sourceType));
4742 // todo: i18n this message
4743 setStatus(MessageManager.formatMessage(
4744 "label.successfully_loaded_matrix",
4745 sm.getMatrixName()));
4747 else if (FileFormat.Jnet.equals(format))
4749 JPredFile predictions = new JPredFile(file, sourceType);
4750 new JnetAnnotationMaker();
4751 JnetAnnotationMaker.add_annotation(predictions,
4752 viewport.getAlignment(), 0, false);
4753 viewport.getAlignment().setupJPredAlignment();
4754 isAnnotation = true;
4756 // else if (IdentifyFile.FeaturesFile.equals(format))
4757 else if (FileFormat.Features.equals(format))
4759 if (parseFeaturesFile(file, sourceType))
4761 alignPanel.paintAlignment(true, true);
4766 new FileLoader().LoadFile(viewport, file, sourceType, format);
4773 alignPanel.adjustAnnotationHeight();
4774 viewport.updateSequenceIdColours();
4775 buildSortByAnnotationScoresMenu();
4776 alignPanel.paintAlignment(true, true);
4778 } catch (Exception ex)
4780 ex.printStackTrace();
4781 } catch (OutOfMemoryError oom)
4786 } catch (Exception x)
4791 + (sourceType != null
4792 ? (sourceType == DataSourceType.PASTE
4794 : "using " + sourceType + " from "
4798 ? "(parsing as '" + format + "' file)"
4800 oom, Desktop.desktop);
4805 * Method invoked by the ChangeListener on the tabbed pane, in other words
4806 * when a different tabbed pane is selected by the user or programmatically.
4809 public void tabSelectionChanged(int index)
4813 alignPanel = alignPanels.get(index);
4814 viewport = alignPanel.av;
4815 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4816 setMenusFromViewport(viewport);
4820 * 'focus' any colour slider that is open to the selected viewport
4822 if (viewport.getConservationSelected())
4824 SliderPanel.setConservationSlider(alignPanel,
4825 viewport.getResidueShading(), alignPanel.getViewName());
4829 SliderPanel.hideConservationSlider();
4831 if (viewport.getAbovePIDThreshold())
4833 SliderPanel.setPIDSliderSource(alignPanel,
4834 viewport.getResidueShading(), alignPanel.getViewName());
4838 SliderPanel.hidePIDSlider();
4842 * If there is a frame linked to this one in a SplitPane, switch it to the
4843 * same view tab index. No infinite recursion of calls should happen, since
4844 * tabSelectionChanged() should not get invoked on setting the selected
4845 * index to an unchanged value. Guard against setting an invalid index
4846 * before the new view peer tab has been created.
4848 final AlignViewportI peer = viewport.getCodingComplement();
4851 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4852 .getAlignPanel().alignFrame;
4853 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4855 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4861 * On right mouse click on view tab, prompt for and set new view name.
4864 public void tabbedPane_mousePressed(MouseEvent e)
4866 if (e.isPopupTrigger())
4868 String msg = MessageManager.getString("label.enter_view_name");
4869 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
4870 String reply = JvOptionPane.showInputDialog(msg, ttl);
4874 viewport.setViewName(reply);
4875 // TODO warn if reply is in getExistingViewNames()?
4876 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4881 public AlignViewport getCurrentView()
4887 * Open the dialog for regex description parsing.
4890 protected void extractScores_actionPerformed(ActionEvent e)
4892 ParseProperties pp = new jalview.analysis.ParseProperties(
4893 viewport.getAlignment());
4894 // TODO: verify regex and introduce GUI dialog for version 2.5
4895 // if (pp.getScoresFromDescription("col", "score column ",
4896 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4898 if (pp.getScoresFromDescription("description column",
4899 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4901 buildSortByAnnotationScoresMenu();
4909 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4913 protected void showDbRefs_actionPerformed(ActionEvent e)
4915 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4921 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4925 protected void showNpFeats_actionPerformed(ActionEvent e)
4927 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4931 * find the viewport amongst the tabs in this alignment frame and close that
4936 public boolean closeView(AlignViewportI av)
4940 this.closeMenuItem_actionPerformed(false);
4943 Component[] comp = tabbedPane.getComponents();
4944 for (int i = 0; comp != null && i < comp.length; i++)
4946 if (comp[i] instanceof AlignmentPanel)
4948 if (((AlignmentPanel) comp[i]).av == av)
4951 closeView((AlignmentPanel) comp[i]);
4959 protected void build_fetchdbmenu(JMenu webService)
4961 // Temporary hack - DBRef Fetcher always top level ws entry.
4962 // TODO We probably want to store a sequence database checklist in
4963 // preferences and have checkboxes.. rather than individual sources selected
4965 final JMenu rfetch = new JMenu(
4966 MessageManager.getString("action.fetch_db_references"));
4967 rfetch.setToolTipText(MessageManager.getString(
4968 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4969 webService.add(rfetch);
4971 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4972 MessageManager.getString("option.trim_retrieved_seqs"));
4973 trimrs.setToolTipText(
4974 MessageManager.getString("label.trim_retrieved_sequences"));
4976 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
4977 trimrs.addActionListener(new ActionListener()
4980 public void actionPerformed(ActionEvent e)
4982 trimrs.setSelected(trimrs.isSelected());
4983 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
4984 Boolean.valueOf(trimrs.isSelected()).toString());
4988 JMenuItem fetchr = new JMenuItem(
4989 MessageManager.getString("label.standard_databases"));
4990 fetchr.setToolTipText(
4991 MessageManager.getString("label.fetch_embl_uniprot"));
4992 fetchr.addActionListener(new ActionListener()
4996 public void actionPerformed(ActionEvent e)
4998 new Thread(new Runnable()
5003 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5004 .getAlignment().isNucleotide();
5005 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5006 alignPanel.av.getSequenceSelection(),
5007 alignPanel.alignFrame, null,
5008 alignPanel.alignFrame.featureSettings, isNucleotide);
5009 dbRefFetcher.addListener(new FetchFinishedListenerI()
5012 public void finished()
5014 AlignFrame.this.setMenusForViewport();
5017 dbRefFetcher.fetchDBRefs(false);
5025 new Thread(new Runnable()
5030 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5031 .getSequenceFetcherSingleton();
5032 javax.swing.SwingUtilities.invokeLater(new Runnable()
5037 String[] dbclasses = sf.getNonAlignmentSources();
5038 List<DbSourceProxy> otherdb;
5039 JMenu dfetch = new JMenu();
5040 JMenu ifetch = new JMenu();
5041 JMenuItem fetchr = null;
5042 int comp = 0, icomp = 0, mcomp = 15;
5043 String mname = null;
5045 for (String dbclass : dbclasses)
5047 otherdb = sf.getSourceProxy(dbclass);
5048 // add a single entry for this class, or submenu allowing 'fetch
5050 if (otherdb == null || otherdb.size() < 1)
5056 mname = "From " + dbclass;
5058 if (otherdb.size() == 1)
5060 final DbSourceProxy[] dassource = otherdb
5061 .toArray(new DbSourceProxy[0]);
5062 DbSourceProxy src = otherdb.get(0);
5063 fetchr = new JMenuItem(src.getDbSource());
5064 fetchr.addActionListener(new ActionListener()
5068 public void actionPerformed(ActionEvent e)
5070 new Thread(new Runnable()
5076 boolean isNucleotide = alignPanel.alignFrame
5077 .getViewport().getAlignment()
5079 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5080 alignPanel.av.getSequenceSelection(),
5081 alignPanel.alignFrame, dassource,
5082 alignPanel.alignFrame.featureSettings,
5085 .addListener(new FetchFinishedListenerI()
5088 public void finished()
5090 AlignFrame.this.setMenusForViewport();
5093 dbRefFetcher.fetchDBRefs(false);
5099 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5100 MessageManager.formatMessage(
5101 "label.fetch_retrieve_from", new Object[]
5102 { src.getDbName() })));
5108 final DbSourceProxy[] dassource = otherdb
5109 .toArray(new DbSourceProxy[0]);
5111 DbSourceProxy src = otherdb.get(0);
5112 fetchr = new JMenuItem(MessageManager
5113 .formatMessage("label.fetch_all_param", new Object[]
5114 { src.getDbSource() }));
5115 fetchr.addActionListener(new ActionListener()
5118 public void actionPerformed(ActionEvent e)
5120 new Thread(new Runnable()
5126 boolean isNucleotide = alignPanel.alignFrame
5127 .getViewport().getAlignment()
5129 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5130 alignPanel.av.getSequenceSelection(),
5131 alignPanel.alignFrame, dassource,
5132 alignPanel.alignFrame.featureSettings,
5135 .addListener(new FetchFinishedListenerI()
5138 public void finished()
5140 AlignFrame.this.setMenusForViewport();
5143 dbRefFetcher.fetchDBRefs(false);
5149 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5150 MessageManager.formatMessage(
5151 "label.fetch_retrieve_from_all_sources",
5153 { Integer.valueOf(otherdb.size())
5155 src.getDbSource(), src.getDbName() })));
5158 // and then build the rest of the individual menus
5159 ifetch = new JMenu(MessageManager.formatMessage(
5160 "label.source_from_db_source", new Object[]
5161 { src.getDbSource() }));
5163 String imname = null;
5165 for (DbSourceProxy sproxy : otherdb)
5167 String dbname = sproxy.getDbName();
5168 String sname = dbname.length() > 5
5169 ? dbname.substring(0, 5) + "..."
5171 String msname = dbname.length() > 10
5172 ? dbname.substring(0, 10) + "..."
5176 imname = MessageManager
5177 .formatMessage("label.from_msname", new Object[]
5180 fetchr = new JMenuItem(msname);
5181 final DbSourceProxy[] dassrc = { sproxy };
5182 fetchr.addActionListener(new ActionListener()
5186 public void actionPerformed(ActionEvent e)
5188 new Thread(new Runnable()
5194 boolean isNucleotide = alignPanel.alignFrame
5195 .getViewport().getAlignment()
5197 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5198 alignPanel.av.getSequenceSelection(),
5199 alignPanel.alignFrame, dassrc,
5200 alignPanel.alignFrame.featureSettings,
5203 .addListener(new FetchFinishedListenerI()
5206 public void finished()
5208 AlignFrame.this.setMenusForViewport();
5211 dbRefFetcher.fetchDBRefs(false);
5217 fetchr.setToolTipText(
5218 "<html>" + MessageManager.formatMessage(
5219 "label.fetch_retrieve_from", new Object[]
5223 if (++icomp >= mcomp || i == (otherdb.size()))
5225 ifetch.setText(MessageManager.formatMessage(
5226 "label.source_to_target", imname, sname));
5228 ifetch = new JMenu();
5236 if (comp >= mcomp || dbi >= (dbclasses.length))
5238 dfetch.setText(MessageManager.formatMessage(
5239 "label.source_to_target", mname, dbclass));
5241 dfetch = new JMenu();
5254 * Left justify the whole alignment.
5257 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5259 AlignmentI al = viewport.getAlignment();
5261 viewport.firePropertyChange("alignment", null, al);
5265 * Right justify the whole alignment.
5268 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5270 AlignmentI al = viewport.getAlignment();
5272 viewport.firePropertyChange("alignment", null, al);
5276 public void setShowSeqFeatures(boolean b)
5278 showSeqFeatures.setSelected(b);
5279 viewport.setShowSequenceFeatures(b);
5286 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5287 * awt.event.ActionEvent)
5290 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5292 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5293 alignPanel.paintAlignment(false, false);
5300 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5304 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5306 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5307 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5315 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5316 * .event.ActionEvent)
5319 protected void showGroupConservation_actionPerformed(ActionEvent e)
5321 viewport.setShowGroupConservation(showGroupConservation.getState());
5322 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5329 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5330 * .event.ActionEvent)
5333 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5335 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5336 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5343 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5344 * .event.ActionEvent)
5347 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5349 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5350 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5354 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5356 showSequenceLogo.setState(true);
5357 viewport.setShowSequenceLogo(true);
5358 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5359 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5363 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5365 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5372 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5373 * .event.ActionEvent)
5376 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5378 if (avc.makeGroupsFromSelection())
5380 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5381 alignPanel.updateAnnotation();
5382 alignPanel.paintAlignment(true, true);
5386 public void clearAlignmentSeqRep()
5388 // TODO refactor alignmentseqrep to controller
5389 if (viewport.getAlignment().hasSeqrep())
5391 viewport.getAlignment().setSeqrep(null);
5392 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5393 alignPanel.updateAnnotation();
5394 alignPanel.paintAlignment(true, true);
5399 protected void createGroup_actionPerformed(ActionEvent e)
5401 if (avc.createGroup())
5403 if (applyAutoAnnotationSettings.isSelected())
5405 alignPanel.updateAnnotation(true, false);
5407 alignPanel.alignmentChanged();
5412 protected void unGroup_actionPerformed(ActionEvent e)
5416 alignPanel.alignmentChanged();
5421 * make the given alignmentPanel the currently selected tab
5423 * @param alignmentPanel
5425 public void setDisplayedView(AlignmentPanel alignmentPanel)
5427 if (!viewport.getSequenceSetId()
5428 .equals(alignmentPanel.av.getSequenceSetId()))
5430 throw new Error(MessageManager.getString(
5431 "error.implementation_error_cannot_show_view_alignment_frame"));
5433 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5434 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5436 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5441 * Action on selection of menu options to Show or Hide annotations.
5444 * @param forSequences
5445 * update sequence-related annotations
5446 * @param forAlignment
5447 * update non-sequence-related annotations
5450 protected void setAnnotationsVisibility(boolean visible,
5451 boolean forSequences, boolean forAlignment)
5453 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5454 .getAlignmentAnnotation();
5459 for (AlignmentAnnotation aa : anns)
5462 * don't display non-positional annotations on an alignment
5464 if (aa.annotations == null)
5468 boolean apply = (aa.sequenceRef == null && forAlignment)
5469 || (aa.sequenceRef != null && forSequences);
5472 aa.visible = visible;
5475 alignPanel.validateAnnotationDimensions(true);
5476 alignPanel.alignmentChanged();
5480 * Store selected annotation sort order for the view and repaint.
5483 protected void sortAnnotations_actionPerformed()
5485 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5487 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5488 alignPanel.paintAlignment(false, false);
5493 * @return alignment panels in this alignment frame
5495 public List<? extends AlignmentViewPanel> getAlignPanels()
5497 // alignPanels is never null
5498 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5503 * Open a new alignment window, with the cDNA associated with this (protein)
5504 * alignment, aligned as is the protein.
5506 protected void viewAsCdna_actionPerformed()
5508 // TODO no longer a menu action - refactor as required
5509 final AlignmentI alignment = getViewport().getAlignment();
5510 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5511 if (mappings == null)
5515 List<SequenceI> cdnaSeqs = new ArrayList<>();
5516 for (SequenceI aaSeq : alignment.getSequences())
5518 for (AlignedCodonFrame acf : mappings)
5520 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5524 * There is a cDNA mapping for this protein sequence - add to new
5525 * alignment. It will share the same dataset sequence as other mapped
5526 * cDNA (no new mappings need to be created).
5528 final Sequence newSeq = new Sequence(dnaSeq);
5529 newSeq.setDatasetSequence(dnaSeq);
5530 cdnaSeqs.add(newSeq);
5534 if (cdnaSeqs.size() == 0)
5536 // show a warning dialog no mapped cDNA
5539 AlignmentI cdna = new Alignment(
5540 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5541 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5542 AlignFrame.DEFAULT_HEIGHT);
5543 cdna.alignAs(alignment);
5544 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5546 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5547 AlignFrame.DEFAULT_HEIGHT);
5551 * Set visibility of dna/protein complement view (available when shown in a
5557 protected void showComplement_actionPerformed(boolean show)
5559 SplitContainerI sf = getSplitViewContainer();
5562 sf.setComplementVisible(this, show);
5567 * Generate the reverse (optionally complemented) of the selected sequences,
5568 * and add them to the alignment
5571 protected void showReverse_actionPerformed(boolean complement)
5573 AlignmentI al = null;
5576 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5577 al = dna.reverseCdna(complement);
5578 viewport.addAlignment(al, "");
5579 addHistoryItem(new EditCommand(
5580 MessageManager.getString("label.add_sequences"), Action.PASTE,
5581 al.getSequencesArray(), 0, al.getWidth(),
5582 viewport.getAlignment()));
5583 } catch (Exception ex)
5585 System.err.println(ex.getMessage());
5591 * Try to run a script in the Groovy console, having first ensured that this
5592 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5593 * be targeted at this alignment.
5596 protected void runGroovy_actionPerformed()
5598 Jalview.setCurrentAlignFrame(this);
5599 groovy.ui.Console console = Desktop.getGroovyConsole();
5600 if (console != null)
5604 console.runScript();
5605 } catch (Exception ex)
5607 System.err.println((ex.toString()));
5608 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5609 MessageManager.getString("label.couldnt_run_groovy_script"),
5610 MessageManager.getString("label.groovy_support_failed"),
5611 JvOptionPane.ERROR_MESSAGE);
5616 System.err.println("Can't run Groovy script as console not found");
5621 * Hides columns containing (or not containing) a specified feature, provided
5622 * that would not leave all columns hidden
5624 * @param featureType
5625 * @param columnsContaining
5628 public boolean hideFeatureColumns(String featureType,
5629 boolean columnsContaining)
5631 boolean notForHiding = avc.markColumnsContainingFeatures(
5632 columnsContaining, false, false, featureType);
5635 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5636 false, featureType))
5638 getViewport().hideSelectedColumns();
5646 protected void selectHighlightedColumns_actionPerformed(
5647 ActionEvent actionEvent)
5649 // include key modifier check in case user selects from menu
5650 avc.markHighlightedColumns(
5651 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5652 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5653 | ActionEvent.CTRL_MASK)) != 0);
5657 * Rebuilds the Colour menu, including any user-defined colours which have
5658 * been loaded either on startup or during the session
5660 public void buildColourMenu()
5662 colourMenu.removeAll();
5664 colourMenu.add(applyToAllGroups);
5665 colourMenu.add(textColour);
5666 colourMenu.addSeparator();
5668 ColourMenuHelper.addMenuItems(colourMenu, this, viewport.getAlignment(),
5671 colourMenu.addSeparator();
5672 colourMenu.add(conservationMenuItem);
5673 colourMenu.add(modifyConservation);
5674 colourMenu.add(abovePIDThreshold);
5675 colourMenu.add(modifyPID);
5676 colourMenu.add(annotationColour);
5678 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5679 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5683 * Open a dialog (if not already open) that allows the user to select and
5684 * calculate PCA or Tree analysis
5686 protected void openTreePcaDialog()
5688 if (alignPanel.getCalculationDialog() == null)
5690 new CalculationChooser(AlignFrame.this);
5695 protected void loadVcf_actionPerformed()
5697 JalviewFileChooser chooser = new JalviewFileChooser(
5698 Cache.getProperty("LAST_DIRECTORY"));
5699 chooser.setFileView(new JalviewFileView());
5700 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5701 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5702 final AlignFrame us = this;
5703 chooser.setResponseHandler(0, new Runnable()
5708 String choice = chooser.getSelectedFile().getPath();
5709 Cache.setProperty("LAST_DIRECTORY", choice);
5710 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5711 new VCFLoader(choice).loadVCF(seqs, us);
5714 chooser.showOpenDialog(null);
5720 class PrintThread extends Thread
5724 public PrintThread(AlignmentPanel ap)
5729 static PageFormat pf;
5734 PrinterJob printJob = PrinterJob.getPrinterJob();
5738 printJob.setPrintable(ap, pf);
5742 printJob.setPrintable(ap);
5745 if (printJob.printDialog())
5750 } catch (Exception PrintException)
5752 PrintException.printStackTrace();