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.GeneticCodeI;
28 import jalview.analysis.ParseProperties;
29 import jalview.analysis.SequenceIdMatcher;
30 import jalview.api.AlignExportSettingI;
31 import jalview.api.AlignViewControllerGuiI;
32 import jalview.api.AlignViewControllerI;
33 import jalview.api.AlignViewportI;
34 import jalview.api.AlignmentViewPanel;
35 import jalview.api.FeatureSettingsControllerI;
36 import jalview.api.FeatureSettingsModelI;
37 import jalview.api.SplitContainerI;
38 import jalview.api.ViewStyleI;
39 import jalview.api.analysis.SimilarityParamsI;
40 import jalview.bin.Cache;
41 import jalview.bin.Jalview;
42 import jalview.commands.CommandI;
43 import jalview.commands.EditCommand;
44 import jalview.commands.EditCommand.Action;
45 import jalview.commands.OrderCommand;
46 import jalview.commands.RemoveGapColCommand;
47 import jalview.commands.RemoveGapsCommand;
48 import jalview.commands.SlideSequencesCommand;
49 import jalview.commands.TrimRegionCommand;
50 import jalview.datamodel.AlignedCodonFrame;
51 import jalview.datamodel.Alignment;
52 import jalview.datamodel.AlignmentAnnotation;
53 import jalview.datamodel.AlignmentExportData;
54 import jalview.datamodel.AlignmentI;
55 import jalview.datamodel.AlignmentOrder;
56 import jalview.datamodel.AlignmentView;
57 import jalview.datamodel.ColumnSelection;
58 import jalview.datamodel.HiddenColumns;
59 import jalview.datamodel.HiddenSequences;
60 import jalview.datamodel.PDBEntry;
61 import jalview.datamodel.SeqCigar;
62 import jalview.datamodel.Sequence;
63 import jalview.datamodel.SequenceGroup;
64 import jalview.datamodel.SequenceI;
65 import jalview.gui.ColourMenuHelper.ColourChangeListener;
66 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
67 import jalview.io.AlignmentProperties;
68 import jalview.io.AnnotationFile;
69 import jalview.io.BackupFiles;
70 import jalview.io.BioJsHTMLOutput;
71 import jalview.io.DataSourceType;
72 import jalview.io.FileFormat;
73 import jalview.io.FileFormatI;
74 import jalview.io.FileFormats;
75 import jalview.io.FileLoader;
76 import jalview.io.FileParse;
77 import jalview.io.FormatAdapter;
78 import jalview.io.HtmlSvgOutput;
79 import jalview.io.IdentifyFile;
80 import jalview.io.JPredFile;
81 import jalview.io.JalviewFileChooser;
82 import jalview.io.JalviewFileView;
83 import jalview.io.JnetAnnotationMaker;
84 import jalview.io.NewickFile;
85 import jalview.io.ScoreMatrixFile;
86 import jalview.io.TCoffeeScoreFile;
87 import jalview.io.vcf.VCFLoader;
88 import jalview.jbgui.GAlignFrame;
89 import jalview.schemes.ColourSchemeI;
90 import jalview.schemes.ColourSchemes;
91 import jalview.schemes.ResidueColourScheme;
92 import jalview.schemes.TCoffeeColourScheme;
93 import jalview.util.MessageManager;
94 import jalview.viewmodel.AlignmentViewport;
95 import jalview.viewmodel.ViewportRanges;
96 import jalview.ws.DBRefFetcher;
97 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
98 import jalview.ws.jws1.Discoverer;
99 import jalview.ws.jws2.Jws2Discoverer;
100 import jalview.ws.jws2.jabaws2.Jws2Instance;
101 import jalview.ws.seqfetcher.DbSourceProxy;
103 import java.awt.BorderLayout;
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.ButtonGroup;
141 import javax.swing.JCheckBoxMenuItem;
142 import javax.swing.JEditorPane;
143 import javax.swing.JInternalFrame;
144 import javax.swing.JLayeredPane;
145 import javax.swing.JMenu;
146 import javax.swing.JMenuItem;
147 import javax.swing.JScrollPane;
148 import javax.swing.SwingUtilities;
154 * @version $Revision$
156 public class AlignFrame extends GAlignFrame implements DropTargetListener,
157 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
160 public static final int DEFAULT_WIDTH = 700;
162 public static final int DEFAULT_HEIGHT = 500;
165 * The currently displayed panel (selected tabbed view if more than one)
167 public AlignmentPanel alignPanel;
169 AlignViewport viewport;
171 public AlignViewControllerI avc;
173 List<AlignmentPanel> alignPanels = new ArrayList<>();
176 * Last format used to load or save alignments in this window
178 FileFormatI currentFileFormat = null;
181 * Current filename for this alignment
183 String fileName = null;
186 * Creates a new AlignFrame object with specific width and height.
192 public AlignFrame(AlignmentI al, int width, int height)
194 this(al, null, width, height);
198 * Creates a new AlignFrame object with specific width, height and
204 * @param sequenceSetId
206 public AlignFrame(AlignmentI al, int width, int height,
207 String sequenceSetId)
209 this(al, null, width, height, sequenceSetId);
213 * Creates a new AlignFrame object with specific width, height and
219 * @param sequenceSetId
222 public AlignFrame(AlignmentI al, int width, int height,
223 String sequenceSetId, String viewId)
225 this(al, null, width, height, sequenceSetId, viewId);
229 * new alignment window with hidden columns
233 * @param hiddenColumns
234 * ColumnSelection or null
236 * Width of alignment frame
240 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
243 this(al, hiddenColumns, width, height, null);
247 * Create alignment frame for al with hiddenColumns, a specific width and
248 * height, and specific sequenceId
251 * @param hiddenColumns
254 * @param sequenceSetId
257 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
258 int height, String sequenceSetId)
260 this(al, hiddenColumns, width, height, sequenceSetId, null);
264 * Create alignment frame for al with hiddenColumns, a specific width and
265 * height, and specific sequenceId
268 * @param hiddenColumns
271 * @param sequenceSetId
276 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
277 int height, String sequenceSetId, String viewId)
279 setSize(width, height);
281 if (al.getDataset() == null)
286 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
288 alignPanel = new AlignmentPanel(this, viewport);
290 addAlignmentPanel(alignPanel, true);
294 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
295 HiddenColumns hiddenColumns, int width, int height)
297 setSize(width, height);
299 if (al.getDataset() == null)
304 viewport = new AlignViewport(al, hiddenColumns);
306 if (hiddenSeqs != null && hiddenSeqs.length > 0)
308 viewport.hideSequence(hiddenSeqs);
310 alignPanel = new AlignmentPanel(this, viewport);
311 addAlignmentPanel(alignPanel, true);
316 * Make a new AlignFrame from existing alignmentPanels
323 public AlignFrame(AlignmentPanel ap)
327 addAlignmentPanel(ap, false);
332 * initalise the alignframe from the underlying viewport data and the
337 if (!Jalview.isHeadlessMode())
339 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
342 avc = new jalview.controller.AlignViewController(this, viewport,
344 if (viewport.getAlignmentConservationAnnotation() == null)
346 // BLOSUM62Colour.setEnabled(false);
347 conservationMenuItem.setEnabled(false);
348 modifyConservation.setEnabled(false);
349 // PIDColour.setEnabled(false);
350 // abovePIDThreshold.setEnabled(false);
351 // modifyPID.setEnabled(false);
354 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
357 if (sortby.equals("Id"))
359 sortIDMenuItem_actionPerformed(null);
361 else if (sortby.equals("Pairwise Identity"))
363 sortPairwiseMenuItem_actionPerformed(null);
367 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
369 setMenusFromViewport(viewport);
370 buildSortByAnnotationScoresMenu();
371 calculateTree.addActionListener(new ActionListener()
375 public void actionPerformed(ActionEvent e)
382 if (Desktop.desktop != null)
384 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
385 addServiceListeners();
389 if (viewport.getWrapAlignment())
391 wrapMenuItem_actionPerformed(null);
394 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
396 this.overviewMenuItem_actionPerformed(null);
401 final List<AlignmentPanel> selviews = new ArrayList<>();
402 final List<AlignmentPanel> origview = new ArrayList<>();
403 final String menuLabel = MessageManager
404 .getString("label.copy_format_from");
405 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
406 new ViewSetProvider()
410 public AlignmentPanel[] getAllAlignmentPanels()
413 origview.add(alignPanel);
414 // make an array of all alignment panels except for this one
415 List<AlignmentPanel> aps = new ArrayList<>(
416 Arrays.asList(Desktop.getAlignmentPanels(null)));
417 aps.remove(AlignFrame.this.alignPanel);
418 return aps.toArray(new AlignmentPanel[aps.size()]);
420 }, selviews, new ItemListener()
424 public void itemStateChanged(ItemEvent e)
426 if (origview.size() > 0)
428 final AlignmentPanel ap = origview.get(0);
431 * Copy the ViewStyle of the selected panel to 'this one'.
432 * Don't change value of 'scaleProteinAsCdna' unless copying
435 ViewStyleI vs = selviews.get(0).getAlignViewport()
437 boolean fromSplitFrame = selviews.get(0)
438 .getAlignViewport().getCodingComplement() != null;
441 vs.setScaleProteinAsCdna(ap.getAlignViewport()
442 .getViewStyle().isScaleProteinAsCdna());
444 ap.getAlignViewport().setViewStyle(vs);
447 * Also rescale ViewStyle of SplitFrame complement if there is
448 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
449 * the whole ViewStyle (allow cDNA protein to have different
452 AlignViewportI complement = ap.getAlignViewport()
453 .getCodingComplement();
454 if (complement != null && vs.isScaleProteinAsCdna())
456 AlignFrame af = Desktop.getAlignFrameFor(complement);
457 ((SplitFrame) af.getSplitViewContainer())
459 af.setMenusForViewport();
463 ap.setSelected(true);
464 ap.alignFrame.setMenusForViewport();
469 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
470 .indexOf("devel") > -1
471 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
472 .indexOf("test") > -1)
474 formatMenu.add(vsel);
476 addFocusListener(new FocusAdapter()
479 public void focusGained(FocusEvent e)
481 Jalview.setCurrentAlignFrame(AlignFrame.this);
488 * Change the filename and format for the alignment, and enable the 'reload'
489 * button functionality.
496 public void setFileName(String file, FileFormatI format)
499 setFileFormat(format);
500 reload.setEnabled(true);
504 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
507 void addKeyListener()
509 addKeyListener(new KeyAdapter()
512 public void keyPressed(KeyEvent evt)
514 if (viewport.cursorMode
515 && ((evt.getKeyCode() >= KeyEvent.VK_0
516 && evt.getKeyCode() <= KeyEvent.VK_9)
517 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
518 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
519 && Character.isDigit(evt.getKeyChar()))
521 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
524 switch (evt.getKeyCode())
527 case 27: // escape key
528 deselectAllSequenceMenuItem_actionPerformed(null);
532 case KeyEvent.VK_DOWN:
533 if (evt.isAltDown() || !viewport.cursorMode)
535 moveSelectedSequences(false);
537 if (viewport.cursorMode)
539 alignPanel.getSeqPanel().moveCursor(0, 1);
544 if (evt.isAltDown() || !viewport.cursorMode)
546 moveSelectedSequences(true);
548 if (viewport.cursorMode)
550 alignPanel.getSeqPanel().moveCursor(0, -1);
555 case KeyEvent.VK_LEFT:
556 if (evt.isAltDown() || !viewport.cursorMode)
558 slideSequences(false,
559 alignPanel.getSeqPanel().getKeyboardNo1());
563 alignPanel.getSeqPanel().moveCursor(-1, 0);
568 case KeyEvent.VK_RIGHT:
569 if (evt.isAltDown() || !viewport.cursorMode)
571 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
575 alignPanel.getSeqPanel().moveCursor(1, 0);
579 case KeyEvent.VK_SPACE:
580 if (viewport.cursorMode)
582 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
583 || evt.isShiftDown() || evt.isAltDown());
587 // case KeyEvent.VK_A:
588 // if (viewport.cursorMode)
590 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
591 // //System.out.println("A");
595 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
596 * System.out.println("closing bracket"); } break;
598 case KeyEvent.VK_DELETE:
599 case KeyEvent.VK_BACK_SPACE:
600 if (!viewport.cursorMode)
602 cut_actionPerformed(null);
606 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
607 || evt.isShiftDown() || evt.isAltDown());
613 if (viewport.cursorMode)
615 alignPanel.getSeqPanel().setCursorRow();
619 if (viewport.cursorMode && !evt.isControlDown())
621 alignPanel.getSeqPanel().setCursorColumn();
625 if (viewport.cursorMode)
627 alignPanel.getSeqPanel().setCursorPosition();
631 case KeyEvent.VK_ENTER:
632 case KeyEvent.VK_COMMA:
633 if (viewport.cursorMode)
635 alignPanel.getSeqPanel().setCursorRowAndColumn();
640 if (viewport.cursorMode)
642 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
646 if (viewport.cursorMode)
648 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
653 viewport.cursorMode = !viewport.cursorMode;
654 statusBar.setText(MessageManager
655 .formatMessage("label.keyboard_editing_mode", new String[]
656 { (viewport.cursorMode ? "on" : "off") }));
657 if (viewport.cursorMode)
659 ViewportRanges ranges = viewport.getRanges();
660 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
662 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
665 alignPanel.getSeqPanel().seqCanvas.repaint();
671 Help.showHelpWindow();
672 } catch (Exception ex)
674 ex.printStackTrace();
679 boolean toggleSeqs = !evt.isControlDown();
680 boolean toggleCols = !evt.isShiftDown();
681 toggleHiddenRegions(toggleSeqs, toggleCols);
686 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
687 boolean modifyExisting = true; // always modify, don't clear
688 // evt.isShiftDown();
689 boolean invertHighlighted = evt.isAltDown();
690 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
694 case KeyEvent.VK_PAGE_UP:
695 viewport.getRanges().pageUp();
697 case KeyEvent.VK_PAGE_DOWN:
698 viewport.getRanges().pageDown();
704 public void keyReleased(KeyEvent evt)
706 switch (evt.getKeyCode())
708 case KeyEvent.VK_LEFT:
709 if (evt.isAltDown() || !viewport.cursorMode)
711 viewport.firePropertyChange("alignment", null,
712 viewport.getAlignment().getSequences());
716 case KeyEvent.VK_RIGHT:
717 if (evt.isAltDown() || !viewport.cursorMode)
719 viewport.firePropertyChange("alignment", null,
720 viewport.getAlignment().getSequences());
728 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
730 ap.alignFrame = this;
731 avc = new jalview.controller.AlignViewController(this, viewport,
736 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
738 int aSize = alignPanels.size();
740 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
742 if (aSize == 1 && ap.av.getViewName() == null)
744 this.getContentPane().add(ap, BorderLayout.CENTER);
750 setInitialTabVisible();
753 expandViews.setEnabled(true);
754 gatherViews.setEnabled(true);
755 tabbedPane.addTab(ap.av.getViewName(), ap);
757 ap.setVisible(false);
762 if (ap.av.isPadGaps())
764 ap.av.getAlignment().padGaps();
766 ap.av.updateConservation(ap);
767 ap.av.updateConsensus(ap);
768 ap.av.updateStrucConsensus(ap);
772 public void setInitialTabVisible()
774 expandViews.setEnabled(true);
775 gatherViews.setEnabled(true);
776 tabbedPane.setVisible(true);
777 AlignmentPanel first = alignPanels.get(0);
778 tabbedPane.addTab(first.av.getViewName(), first);
779 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
782 public AlignViewport getViewport()
787 /* Set up intrinsic listeners for dynamically generated GUI bits. */
788 private void addServiceListeners()
790 final java.beans.PropertyChangeListener thisListener;
791 Desktop.instance.addJalviewPropertyChangeListener("services",
792 thisListener = new java.beans.PropertyChangeListener()
795 public void propertyChange(PropertyChangeEvent evt)
797 // // System.out.println("Discoverer property change.");
798 // if (evt.getPropertyName().equals("services"))
800 SwingUtilities.invokeLater(new Runnable()
807 "Rebuild WS Menu for service change");
808 BuildWebServiceMenu();
815 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
818 public void internalFrameClosed(
819 javax.swing.event.InternalFrameEvent evt)
821 // System.out.println("deregistering discoverer listener");
822 Desktop.instance.removeJalviewPropertyChangeListener("services",
824 closeMenuItem_actionPerformed(true);
827 // Finally, build the menu once to get current service state
828 new Thread(new Runnable()
833 BuildWebServiceMenu();
839 * Configure menu items that vary according to whether the alignment is
840 * nucleotide or protein
842 public void setGUINucleotide()
844 AlignmentI al = getViewport().getAlignment();
845 boolean nucleotide = al.isNucleotide();
847 loadVcf.setVisible(nucleotide);
848 showTranslation.setVisible(nucleotide);
849 showReverse.setVisible(nucleotide);
850 showReverseComplement.setVisible(nucleotide);
851 conservationMenuItem.setEnabled(!nucleotide);
853 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
854 showGroupConservation.setEnabled(!nucleotide);
856 showComplementMenuItem
857 .setText(nucleotide ? MessageManager.getString("label.protein")
858 : MessageManager.getString("label.nucleotide"));
862 * set up menus for the current viewport. This may be called after any
863 * operation that affects the data in the current view (selection changed,
864 * etc) to update the menus to reflect the new state.
867 public void setMenusForViewport()
869 setMenusFromViewport(viewport);
873 * Need to call this method when tabs are selected for multiple views, or when
874 * loading from Jalview2XML.java
879 public void setMenusFromViewport(AlignViewport av)
881 padGapsMenuitem.setSelected(av.isPadGaps());
882 colourTextMenuItem.setSelected(av.isShowColourText());
883 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
884 modifyPID.setEnabled(abovePIDThreshold.isSelected());
885 conservationMenuItem.setSelected(av.getConservationSelected());
886 modifyConservation.setEnabled(conservationMenuItem.isSelected());
887 seqLimits.setSelected(av.getShowJVSuffix());
888 idRightAlign.setSelected(av.isRightAlignIds());
889 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
890 renderGapsMenuItem.setSelected(av.isRenderGaps());
891 wrapMenuItem.setSelected(av.getWrapAlignment());
892 scaleAbove.setVisible(av.getWrapAlignment());
893 scaleLeft.setVisible(av.getWrapAlignment());
894 scaleRight.setVisible(av.getWrapAlignment());
895 annotationPanelMenuItem.setState(av.isShowAnnotation());
898 * Show/hide annotations only enabled if annotation panel is shown
900 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
901 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
902 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
903 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
904 viewBoxesMenuItem.setSelected(av.getShowBoxes());
905 viewTextMenuItem.setSelected(av.getShowText());
906 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
907 showGroupConsensus.setSelected(av.isShowGroupConsensus());
908 showGroupConservation.setSelected(av.isShowGroupConservation());
909 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
910 showSequenceLogo.setSelected(av.isShowSequenceLogo());
911 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
912 buildAutoAnnotationMenu(av);
914 ColourMenuHelper.setColourSelected(colourMenu,
915 av.getGlobalColourScheme());
917 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
918 hiddenMarkers.setState(av.getShowHiddenMarkers());
919 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
920 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
921 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
922 autoCalculate.setSelected(av.autoCalculateConsensus);
923 sortByTree.setSelected(av.sortByTree);
924 listenToViewSelections.setSelected(av.followSelection);
926 showProducts.setEnabled(canShowProducts());
927 setGroovyEnabled(Desktop.getGroovyConsole() != null);
933 * Adds menu items for the Autocalculated Annotation sub-menu
937 void buildAutoAnnotationMenu(AlignViewport av)
939 autoAnnMenu.removeAll();
940 autoAnnMenu.add(showAutoFirst);
941 autoAnnMenu.add(showAutoLast);
942 autoAnnMenu.addSeparator();
943 autoAnnMenu.add(applyAutoAnnotationSettings);
944 autoAnnMenu.add(showConsensusHistogram);
945 autoAnnMenu.add(showSequenceLogo);
946 autoAnnMenu.add(normaliseSequenceLogo);
947 autoAnnMenu.addSeparator();
950 * add options to reinstate any deleted auto-calculated annotations
952 boolean hasConservation = false;
953 boolean hasQuality = false;
954 boolean hasConsensus = false;
955 boolean hasOccupancy = false;
956 boolean hasRnaStruct = false;
957 AlignmentAnnotation[] anns = av.getAlignment().getAlignmentAnnotation();
962 for (int i = 0; i < anns.length; i++)
964 if (anns[i].autoCalculated)
966 // TODO JAL-3485 should let these strings be constants instead
967 if ("Conservation".equals(anns[i].label))
969 hasConservation = true;
971 else if ("Quality".equals(anns[i].label))
975 else if ("Consensus".equals(anns[i].label))
979 else if ("Occupancy".equals(anns[i].label))
983 else if ("StrucConsensus".equals(anns[i].label))
989 boolean added = false;
992 * a shareable action to refresh stuff; NB action listeners
993 * get run in reverse order to that in which they are added!
995 ActionListener refresher = new ActionListener()
998 public void actionPerformed(ActionEvent e)
1000 alignPanel.adjustAnnotationHeight();
1001 av.alignmentChanged(alignPanel);
1002 buildAutoAnnotationMenu(av);
1006 if (!av.isNucleotide())
1008 if (!hasConservation)
1010 JMenuItem mi = new JMenuItem("Conservation");
1011 mi.addActionListener(refresher);
1012 mi.addActionListener(new ActionListener()
1015 public void actionPerformed(ActionEvent e)
1017 av.initConservation();
1020 autoAnnMenu.add(mi);
1025 JMenuItem mi = new JMenuItem("Quality");
1026 mi.addActionListener(refresher);
1027 mi.addActionListener(new ActionListener()
1030 public void actionPerformed(ActionEvent e)
1035 autoAnnMenu.add(mi);
1041 JMenuItem mi = new JMenuItem("Consensus");
1042 mi.addActionListener(refresher);
1043 mi.addActionListener(new ActionListener()
1046 public void actionPerformed(ActionEvent e)
1051 autoAnnMenu.add(mi);
1056 JMenuItem mi = new JMenuItem("Occupancy");
1057 mi.addActionListener(refresher);
1058 mi.addActionListener(new ActionListener()
1061 public void actionPerformed(ActionEvent e)
1066 autoAnnMenu.add(mi);
1069 if (!hasRnaStruct && av.isNucleotide()
1070 && av.getAlignment().hasRNAStructure())
1072 JMenuItem mi = new JMenuItem("Structure Consensus");
1073 mi.addActionListener(refresher);
1074 mi.addActionListener(new ActionListener()
1077 public void actionPerformed(ActionEvent e)
1079 av.initRNAStructure();
1082 autoAnnMenu.add(mi);
1088 autoAnnMenu.addSeparator();
1090 autoAnnMenu.add(showGroupConservation);
1091 autoAnnMenu.add(showGroupConsensus);
1095 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
1099 public void setGroovyEnabled(boolean b)
1101 runGroovy.setEnabled(b);
1104 private IProgressIndicator progressBar;
1109 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
1112 public void setProgressBar(String message, long id)
1114 progressBar.setProgressBar(message, id);
1118 public void registerHandler(final long id,
1119 final IProgressIndicatorHandler handler)
1121 progressBar.registerHandler(id, handler);
1126 * @return true if any progress bars are still active
1129 public boolean operationInProgress()
1131 return progressBar.operationInProgress();
1135 * Sets the text of the status bar. Note that setting a null or empty value
1136 * will cause the status bar to be hidden, with possibly undesirable flicker
1137 * of the screen layout.
1140 public void setStatus(String text)
1142 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1146 * Added so Castor Mapping file can obtain Jalview Version
1148 public String getVersion()
1150 return jalview.bin.Cache.getProperty("VERSION");
1153 public FeatureRenderer getFeatureRenderer()
1155 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1159 public void fetchSequence_actionPerformed(ActionEvent e)
1161 new jalview.gui.SequenceFetcher(this);
1165 public void addFromFile_actionPerformed(ActionEvent e)
1167 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1171 public void reload_actionPerformed(ActionEvent e)
1173 if (fileName != null)
1175 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1176 // originating file's format
1177 // TODO: work out how to recover feature settings for correct view(s) when
1178 // file is reloaded.
1179 if (FileFormat.Jalview.equals(currentFileFormat))
1181 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1182 for (int i = 0; i < frames.length; i++)
1184 if (frames[i] instanceof AlignFrame && frames[i] != this
1185 && ((AlignFrame) frames[i]).fileName != null
1186 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1190 frames[i].setSelected(true);
1191 Desktop.instance.closeAssociatedWindows();
1192 } catch (java.beans.PropertyVetoException ex)
1198 Desktop.instance.closeAssociatedWindows();
1200 FileLoader loader = new FileLoader();
1201 DataSourceType protocol = fileName.startsWith("http:")
1202 ? DataSourceType.URL
1203 : DataSourceType.FILE;
1204 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1208 Rectangle bounds = this.getBounds();
1210 FileLoader loader = new FileLoader();
1211 DataSourceType protocol = fileName.startsWith("http:")
1212 ? DataSourceType.URL
1213 : DataSourceType.FILE;
1214 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1215 protocol, currentFileFormat);
1217 newframe.setBounds(bounds);
1218 if (featureSettings != null && featureSettings.isShowing())
1220 final Rectangle fspos = featureSettings.frame.getBounds();
1221 // TODO: need a 'show feature settings' function that takes bounds -
1222 // need to refactor Desktop.addFrame
1223 newframe.featureSettings_actionPerformed(null);
1224 final FeatureSettings nfs = newframe.featureSettings;
1225 SwingUtilities.invokeLater(new Runnable()
1230 nfs.frame.setBounds(fspos);
1233 this.featureSettings.close();
1234 this.featureSettings = null;
1236 this.closeMenuItem_actionPerformed(true);
1242 public void addFromText_actionPerformed(ActionEvent e)
1245 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1249 public void addFromURL_actionPerformed(ActionEvent e)
1251 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1255 public void save_actionPerformed(ActionEvent e)
1257 if (fileName == null || (currentFileFormat == null)
1258 || fileName.startsWith("http"))
1260 saveAs_actionPerformed(null);
1264 saveAlignment(fileName, currentFileFormat);
1275 public void saveAs_actionPerformed(ActionEvent e)
1277 String format = currentFileFormat == null ? null
1278 : currentFileFormat.getName();
1279 JalviewFileChooser chooser = JalviewFileChooser
1280 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1282 chooser.setFileView(new JalviewFileView());
1283 chooser.setDialogTitle(
1284 MessageManager.getString("label.save_alignment_to_file"));
1285 chooser.setToolTipText(MessageManager.getString("action.save"));
1287 int value = chooser.showSaveDialog(this);
1289 if (value == JalviewFileChooser.APPROVE_OPTION)
1291 currentFileFormat = chooser.getSelectedFormat();
1292 while (currentFileFormat == null)
1294 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1295 MessageManager.getString(
1296 "label.select_file_format_before_saving"),
1297 MessageManager.getString("label.file_format_not_specified"),
1298 JvOptionPane.WARNING_MESSAGE);
1299 currentFileFormat = chooser.getSelectedFormat();
1300 value = chooser.showSaveDialog(this);
1301 if (value != JalviewFileChooser.APPROVE_OPTION)
1307 fileName = chooser.getSelectedFile().getPath();
1309 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1311 Cache.setProperty("LAST_DIRECTORY", fileName);
1312 saveAlignment(fileName, currentFileFormat);
1316 public boolean saveAlignment(String file, FileFormatI format)
1318 boolean success = true;
1320 if (FileFormat.Jalview.equals(format))
1322 String shortName = title;
1324 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1326 shortName = shortName.substring(
1327 shortName.lastIndexOf(java.io.File.separatorChar) + 1);
1330 success = new jalview.project.Jalview2XML().saveAlignment(this, file,
1333 statusBar.setText(MessageManager.formatMessage(
1334 "label.successfully_saved_to_file_in_format", new Object[]
1335 { fileName, format }));
1340 AlignmentExportData exportData = getAlignmentForExport(format,
1342 if (exportData.getSettings().isCancelled())
1346 FormatAdapter f = new FormatAdapter(alignPanel,
1347 exportData.getSettings());
1348 String output = f.formatSequences(format, exportData.getAlignment(), // class
1352 // occur in the distant future
1353 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1354 f.getCacheSuffixDefault(format),
1355 viewport.getAlignment().getHiddenColumns());
1363 // create backupfiles object and get new temp filename destination
1364 BackupFiles backupfiles = new BackupFiles(file);
1368 PrintWriter out = new PrintWriter(
1369 new FileWriter(backupfiles.getTempFilePath()));
1373 this.setTitle(file);
1374 statusBar.setText(MessageManager.formatMessage(
1375 "label.successfully_saved_to_file_in_format", new Object[]
1376 { fileName, format.getName() }));
1377 } catch (Exception ex)
1380 ex.printStackTrace();
1383 backupfiles.setWriteSuccess(success);
1384 // do the backup file roll and rename the temp file to actual file
1385 success = backupfiles.rollBackupsAndRenameTempFile();
1392 JvOptionPane.showInternalMessageDialog(this, MessageManager
1393 .formatMessage("label.couldnt_save_file", new Object[]
1395 MessageManager.getString("label.error_saving_file"),
1396 JvOptionPane.WARNING_MESSAGE);
1402 private void warningMessage(String warning, String title)
1404 if (new jalview.util.Platform().isHeadless())
1406 System.err.println("Warning: " + title + "\nWarning: " + warning);
1411 JvOptionPane.showInternalMessageDialog(this, warning, title,
1412 JvOptionPane.WARNING_MESSAGE);
1424 protected void outputText_actionPerformed(ActionEvent e)
1426 FileFormatI fileFormat = FileFormats.getInstance()
1427 .forName(e.getActionCommand());
1428 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1430 if (exportData.getSettings().isCancelled())
1434 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1435 cap.setForInput(null);
1438 FileFormatI format = fileFormat;
1439 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1440 .formatSequences(format, exportData.getAlignment(),
1441 exportData.getOmitHidden(),
1442 exportData.getStartEndPostions(),
1443 viewport.getAlignment().getHiddenColumns()));
1444 Desktop.addInternalFrame(cap, MessageManager
1445 .formatMessage("label.alignment_output_command", new Object[]
1446 { e.getActionCommand() }), 600, 500);
1447 } catch (OutOfMemoryError oom)
1449 new OOMWarning("Outputting alignment as " + e.getActionCommand(),
1456 public static AlignmentExportData getAlignmentForExport(
1457 FileFormatI format, AlignViewportI viewport,
1458 AlignExportSettingI exportSettings)
1460 AlignmentI alignmentToExport = null;
1461 AlignExportSettingI settings = exportSettings;
1462 String[] omitHidden = null;
1464 HiddenSequences hiddenSeqs = viewport.getAlignment()
1465 .getHiddenSequences();
1467 alignmentToExport = viewport.getAlignment();
1469 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1470 if (settings == null)
1472 settings = new AlignExportSettings(hasHiddenSeqs,
1473 viewport.hasHiddenColumns(), format);
1475 // settings.isExportAnnotations();
1477 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1479 omitHidden = viewport.getViewAsString(false,
1480 settings.isExportHiddenSequences());
1483 int[] alignmentStartEnd = new int[2];
1484 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1486 alignmentToExport = hiddenSeqs.getFullAlignment();
1490 alignmentToExport = viewport.getAlignment();
1492 alignmentStartEnd = viewport.getAlignment().getHiddenColumns()
1493 .getVisibleStartAndEndIndex(alignmentToExport.getWidth());
1494 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1495 omitHidden, alignmentStartEnd, settings);
1506 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1508 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1509 htmlSVG.exportHTML(null);
1513 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1515 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1516 bjs.exportHTML(null);
1519 public void createImageMap(File file, String image)
1521 alignPanel.makePNGImageMap(file, image);
1531 public void createPNG(File f)
1533 alignPanel.makePNG(f);
1543 public void createEPS(File f)
1545 alignPanel.makeEPS(f);
1549 public void createSVG(File f)
1551 alignPanel.makeSVG(f);
1555 public void pageSetup_actionPerformed(ActionEvent e)
1557 PrinterJob printJob = PrinterJob.getPrinterJob();
1558 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1568 public void printMenuItem_actionPerformed(ActionEvent e)
1570 // Putting in a thread avoids Swing painting problems
1571 PrintThread thread = new PrintThread(alignPanel);
1576 public void exportFeatures_actionPerformed(ActionEvent e)
1578 new AnnotationExporter(alignPanel).exportFeatures();
1582 public void exportAnnotations_actionPerformed(ActionEvent e)
1584 new AnnotationExporter(alignPanel).exportAnnotations();
1588 public void associatedData_actionPerformed(ActionEvent e)
1590 // Pick the tree file
1591 JalviewFileChooser chooser = new JalviewFileChooser(
1592 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1593 chooser.setFileView(new JalviewFileView());
1594 chooser.setDialogTitle(
1595 MessageManager.getString("label.load_jalview_annotations"));
1596 chooser.setToolTipText(
1597 MessageManager.getString("label.load_jalview_annotations"));
1599 int value = chooser.showOpenDialog(null);
1601 if (value == JalviewFileChooser.APPROVE_OPTION)
1603 String choice = chooser.getSelectedFile().getPath();
1604 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1605 loadJalviewDataFile(choice, null, null, null);
1611 * Close the current view or all views in the alignment frame. If the frame
1612 * only contains one view then the alignment will be removed from memory.
1614 * @param closeAllTabs
1617 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1619 if (alignPanels != null && alignPanels.size() < 2)
1621 closeAllTabs = true;
1626 if (alignPanels != null)
1630 if (this.isClosed())
1632 // really close all the windows - otherwise wait till
1633 // setClosed(true) is called
1634 for (int i = 0; i < alignPanels.size(); i++)
1636 AlignmentPanel ap = alignPanels.get(i);
1643 closeView(alignPanel);
1650 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1651 * be called recursively, with the frame now in 'closed' state
1653 this.setClosed(true);
1655 } catch (Exception ex)
1657 ex.printStackTrace();
1662 * Close the specified panel and close up tabs appropriately.
1664 * @param panelToClose
1666 public void closeView(AlignmentPanel panelToClose)
1668 int index = tabbedPane.getSelectedIndex();
1669 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1670 alignPanels.remove(panelToClose);
1671 panelToClose.closePanel();
1672 panelToClose = null;
1674 tabbedPane.removeTabAt(closedindex);
1675 tabbedPane.validate();
1677 if (index > closedindex || index == tabbedPane.getTabCount())
1679 // modify currently selected tab index if necessary.
1683 this.tabSelectionChanged(index);
1689 void updateEditMenuBar()
1692 if (viewport.getHistoryList().size() > 0)
1694 undoMenuItem.setEnabled(true);
1695 CommandI command = viewport.getHistoryList().peek();
1696 undoMenuItem.setText(MessageManager
1697 .formatMessage("label.undo_command", new Object[]
1698 { command.getDescription() }));
1702 undoMenuItem.setEnabled(false);
1703 undoMenuItem.setText(MessageManager.getString("action.undo"));
1706 if (viewport.getRedoList().size() > 0)
1708 redoMenuItem.setEnabled(true);
1710 CommandI command = viewport.getRedoList().peek();
1711 redoMenuItem.setText(MessageManager
1712 .formatMessage("label.redo_command", new Object[]
1713 { command.getDescription() }));
1717 redoMenuItem.setEnabled(false);
1718 redoMenuItem.setText(MessageManager.getString("action.redo"));
1723 public void addHistoryItem(CommandI command)
1725 if (command.getSize() > 0)
1727 viewport.addToHistoryList(command);
1728 viewport.clearRedoList();
1729 updateEditMenuBar();
1730 viewport.updateHiddenColumns();
1731 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1732 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1733 // viewport.getColumnSelection()
1734 // .getHiddenColumns().size() > 0);
1740 * @return alignment objects for all views
1742 AlignmentI[] getViewAlignments()
1744 if (alignPanels != null)
1746 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1748 for (AlignmentPanel ap : alignPanels)
1750 als[i++] = ap.av.getAlignment();
1754 if (viewport != null)
1756 return new AlignmentI[] { viewport.getAlignment() };
1768 protected void undoMenuItem_actionPerformed(ActionEvent e)
1770 if (viewport.getHistoryList().isEmpty())
1774 CommandI command = viewport.getHistoryList().pop();
1775 viewport.addToRedoList(command);
1776 command.undoCommand(getViewAlignments());
1778 AlignmentViewport originalSource = getOriginatingSource(command);
1779 updateEditMenuBar();
1781 if (originalSource != null)
1783 if (originalSource != viewport)
1786 "Implementation worry: mismatch of viewport origin for undo");
1788 originalSource.updateHiddenColumns();
1789 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1791 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1792 // viewport.getColumnSelection()
1793 // .getHiddenColumns().size() > 0);
1794 originalSource.firePropertyChange("alignment", null,
1795 originalSource.getAlignment().getSequences());
1806 protected void redoMenuItem_actionPerformed(ActionEvent e)
1808 if (viewport.getRedoList().size() < 1)
1813 CommandI command = viewport.getRedoList().pop();
1814 viewport.addToHistoryList(command);
1815 command.doCommand(getViewAlignments());
1817 AlignmentViewport originalSource = getOriginatingSource(command);
1818 updateEditMenuBar();
1820 if (originalSource != null)
1823 if (originalSource != viewport)
1826 "Implementation worry: mismatch of viewport origin for redo");
1828 originalSource.updateHiddenColumns();
1829 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1831 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1832 // viewport.getColumnSelection()
1833 // .getHiddenColumns().size() > 0);
1834 originalSource.firePropertyChange("alignment", null,
1835 originalSource.getAlignment().getSequences());
1839 AlignmentViewport getOriginatingSource(CommandI command)
1841 AlignmentViewport originalSource = null;
1842 // For sequence removal and addition, we need to fire
1843 // the property change event FROM the viewport where the
1844 // original alignment was altered
1845 AlignmentI al = null;
1846 if (command instanceof EditCommand)
1848 EditCommand editCommand = (EditCommand) command;
1849 al = editCommand.getAlignment();
1850 List<Component> comps = PaintRefresher.components
1851 .get(viewport.getSequenceSetId());
1853 for (Component comp : comps)
1855 if (comp instanceof AlignmentPanel)
1857 if (al == ((AlignmentPanel) comp).av.getAlignment())
1859 originalSource = ((AlignmentPanel) comp).av;
1866 if (originalSource == null)
1868 // The original view is closed, we must validate
1869 // the current view against the closed view first
1872 PaintRefresher.validateSequences(al, viewport.getAlignment());
1875 originalSource = viewport;
1878 return originalSource;
1887 public void moveSelectedSequences(boolean up)
1889 SequenceGroup sg = viewport.getSelectionGroup();
1895 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1896 viewport.getHiddenRepSequences(), up);
1897 alignPanel.paintAlignment(true, false);
1900 synchronized void slideSequences(boolean right, int size)
1902 List<SequenceI> sg = new ArrayList<>();
1903 if (viewport.cursorMode)
1905 sg.add(viewport.getAlignment()
1906 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1908 else if (viewport.getSelectionGroup() != null
1909 && viewport.getSelectionGroup().getSize() != viewport
1910 .getAlignment().getHeight())
1912 sg = viewport.getSelectionGroup()
1913 .getSequences(viewport.getHiddenRepSequences());
1921 List<SequenceI> invertGroup = new ArrayList<>();
1923 for (SequenceI seq : viewport.getAlignment().getSequences())
1925 if (!sg.contains(seq))
1927 invertGroup.add(seq);
1931 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1933 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1934 for (int i = 0; i < invertGroup.size(); i++)
1936 seqs2[i] = invertGroup.get(i);
1939 SlideSequencesCommand ssc;
1942 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1943 viewport.getGapCharacter());
1947 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1948 viewport.getGapCharacter());
1951 int groupAdjustment = 0;
1952 if (ssc.getGapsInsertedBegin() && right)
1954 if (viewport.cursorMode)
1956 alignPanel.getSeqPanel().moveCursor(size, 0);
1960 groupAdjustment = size;
1963 else if (!ssc.getGapsInsertedBegin() && !right)
1965 if (viewport.cursorMode)
1967 alignPanel.getSeqPanel().moveCursor(-size, 0);
1971 groupAdjustment = -size;
1975 if (groupAdjustment != 0)
1977 viewport.getSelectionGroup().setStartRes(
1978 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1979 viewport.getSelectionGroup().setEndRes(
1980 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1984 * just extend the last slide command if compatible; but not if in
1985 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1987 boolean appendHistoryItem = false;
1988 Deque<CommandI> historyList = viewport.getHistoryList();
1989 boolean inSplitFrame = getSplitViewContainer() != null;
1990 if (!inSplitFrame && historyList != null && historyList.size() > 0
1991 && historyList.peek() instanceof SlideSequencesCommand)
1993 appendHistoryItem = ssc.appendSlideCommand(
1994 (SlideSequencesCommand) historyList.peek());
1997 if (!appendHistoryItem)
1999 addHistoryItem(ssc);
2012 protected void copy_actionPerformed(ActionEvent e)
2014 if (viewport.getSelectionGroup() == null)
2018 // TODO: preserve the ordering of displayed alignment annotation in any
2019 // internal paste (particularly sequence associated annotation)
2020 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2021 String[] omitHidden = null;
2023 if (viewport.hasHiddenColumns())
2025 omitHidden = viewport.getViewAsString(true);
2028 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2029 seqs, omitHidden, null);
2031 StringSelection ss = new StringSelection(output);
2035 jalview.gui.Desktop.internalCopy = true;
2036 // Its really worth setting the clipboard contents
2037 // to empty before setting the large StringSelection!!
2038 Toolkit.getDefaultToolkit().getSystemClipboard()
2039 .setContents(new StringSelection(""), null);
2041 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2043 } catch (OutOfMemoryError er)
2045 new OOMWarning("copying region", er);
2049 HiddenColumns hiddenColumns = null;
2050 if (viewport.hasHiddenColumns())
2052 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2053 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2055 // create new HiddenColumns object with copy of hidden regions
2056 // between startRes and endRes, offset by startRes
2057 hiddenColumns = new HiddenColumns(
2058 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2059 hiddenCutoff, hiddenOffset);
2062 Desktop.jalviewClipboard = new Object[] { seqs,
2063 viewport.getAlignment().getDataset(), hiddenColumns };
2064 statusBar.setText(MessageManager.formatMessage(
2065 "label.copied_sequences_to_clipboard", new Object[]
2066 { Integer.valueOf(seqs.length).toString() }));
2076 protected void pasteNew_actionPerformed(ActionEvent e)
2088 protected void pasteThis_actionPerformed(ActionEvent e)
2094 * Paste contents of Jalview clipboard
2096 * @param newAlignment
2097 * true to paste to a new alignment, otherwise add to this.
2099 void paste(boolean newAlignment)
2101 boolean externalPaste = true;
2104 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2105 Transferable contents = c.getContents(this);
2107 if (contents == null)
2116 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2117 if (str.length() < 1)
2122 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2124 } catch (OutOfMemoryError er)
2126 new OOMWarning("Out of memory pasting sequences!!", er);
2130 SequenceI[] sequences;
2131 boolean annotationAdded = false;
2132 AlignmentI alignment = null;
2134 if (Desktop.jalviewClipboard != null)
2136 // The clipboard was filled from within Jalview, we must use the
2138 // And dataset from the copied alignment
2139 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2140 // be doubly sure that we create *new* sequence objects.
2141 sequences = new SequenceI[newseq.length];
2142 for (int i = 0; i < newseq.length; i++)
2144 sequences[i] = new Sequence(newseq[i]);
2146 alignment = new Alignment(sequences);
2147 externalPaste = false;
2151 // parse the clipboard as an alignment.
2152 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2154 sequences = alignment.getSequencesArray();
2158 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2164 if (Desktop.jalviewClipboard != null)
2166 // dataset is inherited
2167 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2171 // new dataset is constructed
2172 alignment.setDataset(null);
2174 alwidth = alignment.getWidth() + 1;
2178 AlignmentI pastedal = alignment; // preserve pasted alignment object
2179 // Add pasted sequences and dataset into existing alignment.
2180 alignment = viewport.getAlignment();
2181 alwidth = alignment.getWidth() + 1;
2182 // decide if we need to import sequences from an existing dataset
2183 boolean importDs = Desktop.jalviewClipboard != null
2184 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2185 // importDs==true instructs us to copy over new dataset sequences from
2186 // an existing alignment
2187 Vector newDs = (importDs) ? new Vector() : null; // used to create
2188 // minimum dataset set
2190 for (int i = 0; i < sequences.length; i++)
2194 newDs.addElement(null);
2196 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2198 if (importDs && ds != null)
2200 if (!newDs.contains(ds))
2202 newDs.setElementAt(ds, i);
2203 ds = new Sequence(ds);
2204 // update with new dataset sequence
2205 sequences[i].setDatasetSequence(ds);
2209 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2214 // copy and derive new dataset sequence
2215 sequences[i] = sequences[i].deriveSequence();
2216 alignment.getDataset()
2217 .addSequence(sequences[i].getDatasetSequence());
2218 // TODO: avoid creation of duplicate dataset sequences with a
2219 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2221 alignment.addSequence(sequences[i]); // merges dataset
2225 newDs.clear(); // tidy up
2227 if (alignment.getAlignmentAnnotation() != null)
2229 for (AlignmentAnnotation alan : alignment
2230 .getAlignmentAnnotation())
2232 if (alan.graphGroup > fgroup)
2234 fgroup = alan.graphGroup;
2238 if (pastedal.getAlignmentAnnotation() != null)
2240 // Add any annotation attached to alignment.
2241 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2242 for (int i = 0; i < alann.length; i++)
2244 annotationAdded = true;
2245 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2247 AlignmentAnnotation newann = new AlignmentAnnotation(
2249 if (newann.graphGroup > -1)
2251 if (newGraphGroups.size() <= newann.graphGroup
2252 || newGraphGroups.get(newann.graphGroup) == null)
2254 for (int q = newGraphGroups
2255 .size(); q <= newann.graphGroup; q++)
2257 newGraphGroups.add(q, null);
2259 newGraphGroups.set(newann.graphGroup,
2260 Integer.valueOf(++fgroup));
2262 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2266 newann.padAnnotation(alwidth);
2267 alignment.addAnnotation(newann);
2277 addHistoryItem(new EditCommand(
2278 MessageManager.getString("label.add_sequences"),
2279 Action.PASTE, sequences, 0, alignment.getWidth(),
2282 // Add any annotations attached to sequences
2283 for (int i = 0; i < sequences.length; i++)
2285 if (sequences[i].getAnnotation() != null)
2287 AlignmentAnnotation newann;
2288 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2290 annotationAdded = true;
2291 newann = sequences[i].getAnnotation()[a];
2292 newann.adjustForAlignment();
2293 newann.padAnnotation(alwidth);
2294 if (newann.graphGroup > -1)
2296 if (newann.graphGroup > -1)
2298 if (newGraphGroups.size() <= newann.graphGroup
2299 || newGraphGroups.get(newann.graphGroup) == null)
2301 for (int q = newGraphGroups
2302 .size(); q <= newann.graphGroup; q++)
2304 newGraphGroups.add(q, null);
2306 newGraphGroups.set(newann.graphGroup,
2307 Integer.valueOf(++fgroup));
2309 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2313 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2317 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2325 // propagate alignment changed.
2326 viewport.getRanges().setEndSeq(alignment.getHeight());
2327 if (annotationAdded)
2329 // Duplicate sequence annotation in all views.
2330 AlignmentI[] alview = this.getViewAlignments();
2331 for (int i = 0; i < sequences.length; i++)
2333 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2338 for (int avnum = 0; avnum < alview.length; avnum++)
2340 if (alview[avnum] != alignment)
2342 // duplicate in a view other than the one with input focus
2343 int avwidth = alview[avnum].getWidth() + 1;
2344 // this relies on sann being preserved after we
2345 // modify the sequence's annotation array for each duplication
2346 for (int a = 0; a < sann.length; a++)
2348 AlignmentAnnotation newann = new AlignmentAnnotation(
2350 sequences[i].addAlignmentAnnotation(newann);
2351 newann.padAnnotation(avwidth);
2352 alview[avnum].addAnnotation(newann); // annotation was
2353 // duplicated earlier
2354 // TODO JAL-1145 graphGroups are not updated for sequence
2355 // annotation added to several views. This may cause
2357 alview[avnum].setAnnotationIndex(newann, a);
2362 buildSortByAnnotationScoresMenu();
2364 viewport.firePropertyChange("alignment", null,
2365 alignment.getSequences());
2366 if (alignPanels != null)
2368 for (AlignmentPanel ap : alignPanels)
2370 ap.validateAnnotationDimensions(false);
2375 alignPanel.validateAnnotationDimensions(false);
2381 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2383 String newtitle = new String("Copied sequences");
2385 if (Desktop.jalviewClipboard != null
2386 && Desktop.jalviewClipboard[2] != null)
2388 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2389 af.viewport.setHiddenColumns(hc);
2392 // >>>This is a fix for the moment, until a better solution is
2394 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2395 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2396 .getFeatureRenderer());
2398 // TODO: maintain provenance of an alignment, rather than just make the
2399 // title a concatenation of operations.
2402 if (title.startsWith("Copied sequences"))
2408 newtitle = newtitle.concat("- from " + title);
2413 newtitle = new String("Pasted sequences");
2416 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2421 } catch (Exception ex)
2423 ex.printStackTrace();
2424 System.out.println("Exception whilst pasting: " + ex);
2425 // could be anything being pasted in here
2431 protected void expand_newalign(ActionEvent e)
2435 AlignmentI alignment = AlignmentUtils
2436 .expandContext(getViewport().getAlignment(), -1);
2437 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2439 String newtitle = new String("Flanking alignment");
2441 if (Desktop.jalviewClipboard != null
2442 && Desktop.jalviewClipboard[2] != null)
2444 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2445 af.viewport.setHiddenColumns(hc);
2448 // >>>This is a fix for the moment, until a better solution is
2450 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2451 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2452 .getFeatureRenderer());
2454 // TODO: maintain provenance of an alignment, rather than just make the
2455 // title a concatenation of operations.
2457 if (title.startsWith("Copied sequences"))
2463 newtitle = newtitle.concat("- from " + title);
2467 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2469 } catch (Exception ex)
2471 ex.printStackTrace();
2472 System.out.println("Exception whilst pasting: " + ex);
2473 // could be anything being pasted in here
2474 } catch (OutOfMemoryError oom)
2476 new OOMWarning("Viewing flanking region of alignment", oom);
2487 protected void cut_actionPerformed(ActionEvent e)
2489 copy_actionPerformed(null);
2490 delete_actionPerformed(null);
2500 protected void delete_actionPerformed(ActionEvent evt)
2503 SequenceGroup sg = viewport.getSelectionGroup();
2510 * If the cut affects all sequences, warn, remove highlighted columns
2512 if (sg.getSize() == viewport.getAlignment().getHeight())
2514 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2515 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2516 if (isEntireAlignWidth)
2518 int confirm = JvOptionPane.showConfirmDialog(this,
2519 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2520 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2521 JvOptionPane.OK_CANCEL_OPTION);
2523 if (confirm == JvOptionPane.CANCEL_OPTION
2524 || confirm == JvOptionPane.CLOSED_OPTION)
2529 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2530 sg.getEndRes() + 1);
2532 SequenceI[] cut = sg.getSequences()
2533 .toArray(new SequenceI[sg.getSize()]);
2535 addHistoryItem(new EditCommand(
2536 MessageManager.getString("label.cut_sequences"), Action.CUT,
2537 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2538 viewport.getAlignment()));
2540 viewport.setSelectionGroup(null);
2541 viewport.sendSelection();
2542 viewport.getAlignment().deleteGroup(sg);
2544 viewport.firePropertyChange("alignment", null,
2545 viewport.getAlignment().getSequences());
2546 if (viewport.getAlignment().getHeight() < 1)
2550 this.setClosed(true);
2551 } catch (Exception ex)
2564 protected void deleteGroups_actionPerformed(ActionEvent e)
2566 if (avc.deleteGroups())
2568 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2569 alignPanel.updateAnnotation();
2570 alignPanel.paintAlignment(true, true);
2581 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2583 SequenceGroup sg = new SequenceGroup(
2584 viewport.getAlignment().getSequences());
2586 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2587 viewport.setSelectionGroup(sg);
2588 viewport.isSelectionGroupChanged(true);
2589 viewport.sendSelection();
2590 // JAL-2034 - should delegate to
2591 // alignPanel to decide if overview needs
2593 alignPanel.paintAlignment(false, false);
2594 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2604 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2606 if (viewport.cursorMode)
2608 alignPanel.getSeqPanel().keyboardNo1 = null;
2609 alignPanel.getSeqPanel().keyboardNo2 = null;
2611 viewport.setSelectionGroup(null);
2612 viewport.getColumnSelection().clear();
2613 viewport.setSelectionGroup(null);
2614 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2615 // JAL-2034 - should delegate to
2616 // alignPanel to decide if overview needs
2618 alignPanel.paintAlignment(false, false);
2619 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2620 viewport.sendSelection();
2630 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2632 SequenceGroup sg = viewport.getSelectionGroup();
2636 selectAllSequenceMenuItem_actionPerformed(null);
2641 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2643 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2645 // JAL-2034 - should delegate to
2646 // alignPanel to decide if overview needs
2649 alignPanel.paintAlignment(true, false);
2650 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2651 viewport.sendSelection();
2655 public void invertColSel_actionPerformed(ActionEvent e)
2657 viewport.invertColumnSelection();
2658 alignPanel.paintAlignment(true, false);
2659 viewport.sendSelection();
2669 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2671 trimAlignment(true);
2681 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2683 trimAlignment(false);
2686 void trimAlignment(boolean trimLeft)
2688 ColumnSelection colSel = viewport.getColumnSelection();
2691 if (!colSel.isEmpty())
2695 column = colSel.getMin();
2699 column = colSel.getMax();
2703 if (viewport.getSelectionGroup() != null)
2705 seqs = viewport.getSelectionGroup()
2706 .getSequencesAsArray(viewport.getHiddenRepSequences());
2710 seqs = viewport.getAlignment().getSequencesArray();
2713 TrimRegionCommand trimRegion;
2716 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2717 column, viewport.getAlignment());
2718 viewport.getRanges().setStartRes(0);
2722 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2723 column, viewport.getAlignment());
2726 statusBar.setText(MessageManager
2727 .formatMessage("label.removed_columns", new String[]
2728 { Integer.valueOf(trimRegion.getSize()).toString() }));
2730 addHistoryItem(trimRegion);
2732 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2734 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2735 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2737 viewport.getAlignment().deleteGroup(sg);
2741 viewport.firePropertyChange("alignment", null,
2742 viewport.getAlignment().getSequences());
2753 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2755 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2758 if (viewport.getSelectionGroup() != null)
2760 seqs = viewport.getSelectionGroup()
2761 .getSequencesAsArray(viewport.getHiddenRepSequences());
2762 start = viewport.getSelectionGroup().getStartRes();
2763 end = viewport.getSelectionGroup().getEndRes();
2767 seqs = viewport.getAlignment().getSequencesArray();
2770 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2771 "Remove Gapped Columns", seqs, start, end,
2772 viewport.getAlignment());
2774 addHistoryItem(removeGapCols);
2776 statusBar.setText(MessageManager
2777 .formatMessage("label.removed_empty_columns", new Object[]
2778 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2780 // This is to maintain viewport position on first residue
2781 // of first sequence
2782 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2783 ViewportRanges ranges = viewport.getRanges();
2784 int startRes = seq.findPosition(ranges.getStartRes());
2785 // ShiftList shifts;
2786 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2787 // edit.alColumnChanges=shifts.getInverse();
2788 // if (viewport.hasHiddenColumns)
2789 // viewport.getColumnSelection().compensateForEdits(shifts);
2790 ranges.setStartRes(seq.findIndex(startRes) - 1);
2791 viewport.firePropertyChange("alignment", null,
2792 viewport.getAlignment().getSequences());
2803 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2805 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2808 if (viewport.getSelectionGroup() != null)
2810 seqs = viewport.getSelectionGroup()
2811 .getSequencesAsArray(viewport.getHiddenRepSequences());
2812 start = viewport.getSelectionGroup().getStartRes();
2813 end = viewport.getSelectionGroup().getEndRes();
2817 seqs = viewport.getAlignment().getSequencesArray();
2820 // This is to maintain viewport position on first residue
2821 // of first sequence
2822 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2823 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2825 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2826 viewport.getAlignment()));
2828 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2830 viewport.firePropertyChange("alignment", null,
2831 viewport.getAlignment().getSequences());
2842 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2844 viewport.setPadGaps(padGapsMenuitem.isSelected());
2845 viewport.firePropertyChange("alignment", null,
2846 viewport.getAlignment().getSequences());
2856 public void findMenuItem_actionPerformed(ActionEvent e)
2862 * Create a new view of the current alignment.
2865 public void newView_actionPerformed(ActionEvent e)
2867 newView(null, true);
2871 * Creates and shows a new view of the current alignment.
2874 * title of newly created view; if null, one will be generated
2875 * @param copyAnnotation
2876 * if true then duplicate all annnotation, groups and settings
2877 * @return new alignment panel, already displayed.
2879 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2882 * Create a new AlignmentPanel (with its own, new Viewport)
2884 AlignmentPanel newap = new jalview.project.Jalview2XML()
2885 .copyAlignPanel(alignPanel);
2886 if (!copyAnnotation)
2889 * remove all groups and annotation except for the automatic stuff
2891 newap.av.getAlignment().deleteAllGroups();
2892 newap.av.getAlignment().deleteAllAnnotations(false);
2895 newap.av.setGatherViewsHere(false);
2897 if (viewport.getViewName() == null)
2899 viewport.setViewName(MessageManager
2900 .getString("label.view_name_original"));
2904 * Views share the same edits undo and redo stacks
2906 newap.av.setHistoryList(viewport.getHistoryList());
2907 newap.av.setRedoList(viewport.getRedoList());
2910 * copy any visualisation settings that are not saved in the project
2912 newap.av.setColourAppliesToAllGroups(
2913 viewport.getColourAppliesToAllGroups());
2916 * Views share the same mappings; need to deregister any new mappings
2917 * created by copyAlignPanel, and register the new reference to the shared
2920 newap.av.replaceMappings(viewport.getAlignment());
2923 * start up cDNA consensus (if applicable) now mappings are in place
2925 if (newap.av.initComplementConsensus())
2927 newap.refresh(true); // adjust layout of annotations
2930 newap.av.setViewName(getNewViewName(viewTitle));
2932 addAlignmentPanel(newap, true);
2933 newap.alignmentChanged();
2935 if (alignPanels.size() == 2)
2937 viewport.setGatherViewsHere(true);
2939 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2944 * Make a new name for the view, ensuring it is unique within the current
2945 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2946 * these now use viewId. Unique view names are still desirable for usability.)
2951 protected String getNewViewName(String viewTitle)
2953 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2954 boolean addFirstIndex = false;
2955 if (viewTitle == null || viewTitle.trim().length() == 0)
2957 viewTitle = MessageManager.getString("action.view");
2958 addFirstIndex = true;
2962 index = 1;// we count from 1 if given a specific name
2964 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2966 List<Component> comps = PaintRefresher.components
2967 .get(viewport.getSequenceSetId());
2969 List<String> existingNames = getExistingViewNames(comps);
2971 while (existingNames.contains(newViewName))
2973 newViewName = viewTitle + " " + (++index);
2979 * Returns a list of distinct view names found in the given list of
2980 * components. View names are held on the viewport of an AlignmentPanel.
2985 protected List<String> getExistingViewNames(List<Component> comps)
2987 List<String> existingNames = new ArrayList<>();
2988 for (Component comp : comps)
2990 if (comp instanceof AlignmentPanel)
2992 AlignmentPanel ap = (AlignmentPanel) comp;
2993 if (!existingNames.contains(ap.av.getViewName()))
2995 existingNames.add(ap.av.getViewName());
2999 return existingNames;
3003 * Explode tabbed views into separate windows.
3006 public void expandViews_actionPerformed(ActionEvent e)
3008 Desktop.explodeViews(this);
3012 * Gather views in separate windows back into a tabbed presentation.
3015 public void gatherViews_actionPerformed(ActionEvent e)
3017 Desktop.instance.gatherViews(this);
3027 public void font_actionPerformed(ActionEvent e)
3029 new FontChooser(alignPanel);
3039 protected void seqLimit_actionPerformed(ActionEvent e)
3041 viewport.setShowJVSuffix(seqLimits.isSelected());
3043 alignPanel.getIdPanel().getIdCanvas()
3044 .setPreferredSize(alignPanel.calculateIdWidth());
3045 alignPanel.paintAlignment(true, false);
3049 public void idRightAlign_actionPerformed(ActionEvent e)
3051 viewport.setRightAlignIds(idRightAlign.isSelected());
3052 alignPanel.paintAlignment(false, false);
3056 public void centreColumnLabels_actionPerformed(ActionEvent e)
3058 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3059 alignPanel.paintAlignment(false, false);
3065 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3068 protected void followHighlight_actionPerformed()
3071 * Set the 'follow' flag on the Viewport (and scroll to position if now
3074 final boolean state = this.followHighlightMenuItem.getState();
3075 viewport.setFollowHighlight(state);
3078 alignPanel.scrollToPosition(viewport.getSearchResults());
3089 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3091 viewport.setColourText(colourTextMenuItem.isSelected());
3092 alignPanel.paintAlignment(false, false);
3102 public void wrapMenuItem_actionPerformed(ActionEvent e)
3104 scaleAbove.setVisible(wrapMenuItem.isSelected());
3105 scaleLeft.setVisible(wrapMenuItem.isSelected());
3106 scaleRight.setVisible(wrapMenuItem.isSelected());
3107 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3108 alignPanel.updateLayout();
3112 public void showAllSeqs_actionPerformed(ActionEvent e)
3114 viewport.showAllHiddenSeqs();
3118 public void showAllColumns_actionPerformed(ActionEvent e)
3120 viewport.showAllHiddenColumns();
3121 alignPanel.paintAlignment(true, true);
3122 viewport.sendSelection();
3126 public void hideSelSequences_actionPerformed(ActionEvent e)
3128 viewport.hideAllSelectedSeqs();
3132 * called by key handler and the hide all/show all menu items
3137 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3140 boolean hide = false;
3141 SequenceGroup sg = viewport.getSelectionGroup();
3142 if (!toggleSeqs && !toggleCols)
3144 // Hide everything by the current selection - this is a hack - we do the
3145 // invert and then hide
3146 // first check that there will be visible columns after the invert.
3147 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3148 && sg.getStartRes() <= sg.getEndRes()))
3150 // now invert the sequence set, if required - empty selection implies
3151 // that no hiding is required.
3154 invertSequenceMenuItem_actionPerformed(null);
3155 sg = viewport.getSelectionGroup();
3159 viewport.expandColSelection(sg, true);
3160 // finally invert the column selection and get the new sequence
3162 invertColSel_actionPerformed(null);
3169 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3171 hideSelSequences_actionPerformed(null);
3174 else if (!(toggleCols && viewport.hasSelectedColumns()))
3176 showAllSeqs_actionPerformed(null);
3182 if (viewport.hasSelectedColumns())
3184 hideSelColumns_actionPerformed(null);
3187 viewport.setSelectionGroup(sg);
3192 showAllColumns_actionPerformed(null);
3201 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3202 * event.ActionEvent)
3205 public void hideAllButSelection_actionPerformed(ActionEvent e)
3207 toggleHiddenRegions(false, false);
3208 viewport.sendSelection();
3215 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3219 public void hideAllSelection_actionPerformed(ActionEvent e)
3221 SequenceGroup sg = viewport.getSelectionGroup();
3222 viewport.expandColSelection(sg, false);
3223 viewport.hideAllSelectedSeqs();
3224 viewport.hideSelectedColumns();
3225 alignPanel.updateLayout();
3226 alignPanel.paintAlignment(true, true);
3227 viewport.sendSelection();
3234 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3238 public void showAllhidden_actionPerformed(ActionEvent e)
3240 viewport.showAllHiddenColumns();
3241 viewport.showAllHiddenSeqs();
3242 alignPanel.paintAlignment(true, true);
3243 viewport.sendSelection();
3247 public void hideSelColumns_actionPerformed(ActionEvent e)
3249 viewport.hideSelectedColumns();
3250 alignPanel.updateLayout();
3251 alignPanel.paintAlignment(true, true);
3252 viewport.sendSelection();
3256 public void hiddenMarkers_actionPerformed(ActionEvent e)
3258 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3269 protected void scaleAbove_actionPerformed(ActionEvent e)
3271 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3272 alignPanel.updateLayout();
3273 alignPanel.paintAlignment(true, false);
3283 protected void scaleLeft_actionPerformed(ActionEvent e)
3285 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3286 alignPanel.updateLayout();
3287 alignPanel.paintAlignment(true, false);
3297 protected void scaleRight_actionPerformed(ActionEvent e)
3299 viewport.setScaleRightWrapped(scaleRight.isSelected());
3300 alignPanel.updateLayout();
3301 alignPanel.paintAlignment(true, false);
3311 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3313 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3314 alignPanel.paintAlignment(false, false);
3324 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3326 viewport.setShowText(viewTextMenuItem.isSelected());
3327 alignPanel.paintAlignment(false, false);
3337 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3339 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3340 alignPanel.paintAlignment(false, false);
3343 public FeatureSettings featureSettings;
3346 public FeatureSettingsControllerI getFeatureSettingsUI()
3348 return featureSettings;
3352 public void featureSettings_actionPerformed(ActionEvent e)
3354 if (featureSettings != null)
3356 featureSettings.close();
3357 featureSettings = null;
3359 if (!showSeqFeatures.isSelected())
3361 // make sure features are actually displayed
3362 showSeqFeatures.setSelected(true);
3363 showSeqFeatures_actionPerformed(null);
3365 featureSettings = new FeatureSettings(this);
3369 * Set or clear 'Show Sequence Features'
3375 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3377 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3378 alignPanel.paintAlignment(true, true);
3382 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3383 * the annotations panel as a whole.
3385 * The options to show/hide all annotations should be enabled when the panel
3386 * is shown, and disabled when the panel is hidden.
3391 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3393 final boolean setVisible = annotationPanelMenuItem.isSelected();
3394 viewport.setShowAnnotation(setVisible);
3395 this.showAllSeqAnnotations.setEnabled(setVisible);
3396 this.hideAllSeqAnnotations.setEnabled(setVisible);
3397 this.showAllAlAnnotations.setEnabled(setVisible);
3398 this.hideAllAlAnnotations.setEnabled(setVisible);
3399 alignPanel.updateLayout();
3403 public void alignmentProperties()
3405 JEditorPane editPane = new JEditorPane("text/html", "");
3406 editPane.setEditable(false);
3407 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3410 MessageManager.formatMessage("label.html_content", new Object[]
3411 { contents.toString() }));
3412 JInternalFrame frame = new JInternalFrame();
3413 frame.getContentPane().add(new JScrollPane(editPane));
3415 Desktop.addInternalFrame(frame, MessageManager
3416 .formatMessage("label.alignment_properties", new Object[]
3417 { getTitle() }), 500, 400);
3427 public void overviewMenuItem_actionPerformed(ActionEvent e)
3429 if (alignPanel.overviewPanel != null)
3434 JInternalFrame frame = new JInternalFrame();
3435 final OverviewPanel overview = new OverviewPanel(alignPanel);
3436 frame.setContentPane(overview);
3437 Desktop.addInternalFrame(frame, MessageManager
3438 .formatMessage("label.overview_params", new Object[]
3439 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3442 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3443 frame.addInternalFrameListener(
3444 new javax.swing.event.InternalFrameAdapter()
3447 public void internalFrameClosed(
3448 javax.swing.event.InternalFrameEvent evt)
3451 alignPanel.setOverviewPanel(null);
3454 if (getKeyListeners().length > 0)
3456 frame.addKeyListener(getKeyListeners()[0]);
3459 alignPanel.setOverviewPanel(overview);
3463 public void textColour_actionPerformed()
3465 new TextColourChooser().chooseColour(alignPanel, null);
3469 * public void covariationColour_actionPerformed() {
3471 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3475 public void annotationColour_actionPerformed()
3477 new AnnotationColourChooser(viewport, alignPanel);
3481 public void annotationColumn_actionPerformed(ActionEvent e)
3483 new AnnotationColumnChooser(viewport, alignPanel);
3487 * Action on the user checking or unchecking the option to apply the selected
3488 * colour scheme to all groups. If unchecked, groups may have their own
3489 * independent colour schemes.
3494 public void applyToAllGroups_actionPerformed(boolean selected)
3496 viewport.setColourAppliesToAllGroups(selected);
3500 * Action on user selecting a colour from the colour menu
3503 * the name (not the menu item label!) of the colour scheme
3506 public void changeColour_actionPerformed(String name)
3509 * 'User Defined' opens a panel to configure or load a
3510 * user-defined colour scheme
3512 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3514 new UserDefinedColours(alignPanel);
3519 * otherwise set the chosen colour scheme (or null for 'None')
3521 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3523 viewport.getAlignment(), viewport.getHiddenRepSequences());
3528 * Actions on setting or changing the alignment colour scheme
3533 public void changeColour(ColourSchemeI cs)
3535 // TODO: pull up to controller method
3536 ColourMenuHelper.setColourSelected(colourMenu, cs);
3538 viewport.setGlobalColourScheme(cs);
3540 alignPanel.paintAlignment(true, true);
3544 * Show the PID threshold slider panel
3547 protected void modifyPID_actionPerformed()
3549 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3550 alignPanel.getViewName());
3551 SliderPanel.showPIDSlider();
3555 * Show the Conservation slider panel
3558 protected void modifyConservation_actionPerformed()
3560 SliderPanel.setConservationSlider(alignPanel,
3561 viewport.getResidueShading(), alignPanel.getViewName());
3562 SliderPanel.showConservationSlider();
3566 * Action on selecting or deselecting (Colour) By Conservation
3569 public void conservationMenuItem_actionPerformed(boolean selected)
3571 modifyConservation.setEnabled(selected);
3572 viewport.setConservationSelected(selected);
3573 viewport.getResidueShading().setConservationApplied(selected);
3575 changeColour(viewport.getGlobalColourScheme());
3578 modifyConservation_actionPerformed();
3582 SliderPanel.hideConservationSlider();
3587 * Action on selecting or deselecting (Colour) Above PID Threshold
3590 public void abovePIDThreshold_actionPerformed(boolean selected)
3592 modifyPID.setEnabled(selected);
3593 viewport.setAbovePIDThreshold(selected);
3596 viewport.getResidueShading().setThreshold(0,
3597 viewport.isIgnoreGapsConsensus());
3600 changeColour(viewport.getGlobalColourScheme());
3603 modifyPID_actionPerformed();
3607 SliderPanel.hidePIDSlider();
3618 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3620 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3621 AlignmentSorter.sortByPID(viewport.getAlignment(),
3622 viewport.getAlignment().getSequenceAt(0));
3623 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3624 viewport.getAlignment()));
3625 alignPanel.paintAlignment(true, false);
3635 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3637 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3638 AlignmentSorter.sortByID(viewport.getAlignment());
3640 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3641 alignPanel.paintAlignment(true, false);
3651 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3653 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3654 AlignmentSorter.sortByLength(viewport.getAlignment());
3655 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3656 viewport.getAlignment()));
3657 alignPanel.paintAlignment(true, false);
3667 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3669 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3670 AlignmentSorter.sortByGroup(viewport.getAlignment());
3671 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3672 viewport.getAlignment()));
3674 alignPanel.paintAlignment(true, false);
3684 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3686 new RedundancyPanel(alignPanel, this);
3696 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3698 if ((viewport.getSelectionGroup() == null)
3699 || (viewport.getSelectionGroup().getSize() < 2))
3701 JvOptionPane.showInternalMessageDialog(this,
3702 MessageManager.getString(
3703 "label.you_must_select_least_two_sequences"),
3704 MessageManager.getString("label.invalid_selection"),
3705 JvOptionPane.WARNING_MESSAGE);
3709 JInternalFrame frame = new JInternalFrame();
3710 frame.setContentPane(new PairwiseAlignPanel(viewport));
3711 Desktop.addInternalFrame(frame,
3712 MessageManager.getString("action.pairwise_alignment"), 600,
3718 public void autoCalculate_actionPerformed(ActionEvent e)
3720 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3721 if (viewport.autoCalculateConsensus)
3723 viewport.firePropertyChange("alignment", null,
3724 viewport.getAlignment().getSequences());
3729 public void sortByTreeOption_actionPerformed(ActionEvent e)
3731 viewport.sortByTree = sortByTree.isSelected();
3735 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3737 viewport.followSelection = listenToViewSelections.isSelected();
3741 * Constructs a tree panel and adds it to the desktop
3744 * tree type (NJ or AV)
3746 * name of score model used to compute the tree
3748 * parameters for the distance or similarity calculation
3750 void newTreePanel(String type, String modelName,
3751 SimilarityParamsI options)
3753 String frameTitle = "";
3756 boolean onSelection = false;
3757 if (viewport.getSelectionGroup() != null
3758 && viewport.getSelectionGroup().getSize() > 0)
3760 SequenceGroup sg = viewport.getSelectionGroup();
3762 /* Decide if the selection is a column region */
3763 for (SequenceI _s : sg.getSequences())
3765 if (_s.getLength() < sg.getEndRes())
3767 JvOptionPane.showMessageDialog(Desktop.desktop,
3768 MessageManager.getString(
3769 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3770 MessageManager.getString(
3771 "label.sequences_selection_not_aligned"),
3772 JvOptionPane.WARNING_MESSAGE);
3781 if (viewport.getAlignment().getHeight() < 2)
3787 tp = new TreePanel(alignPanel, type, modelName, options);
3788 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3790 frameTitle += " from ";
3792 if (viewport.getViewName() != null)
3794 frameTitle += viewport.getViewName() + " of ";
3797 frameTitle += this.title;
3799 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3810 public void addSortByOrderMenuItem(String title,
3811 final AlignmentOrder order)
3813 final JMenuItem item = new JMenuItem(MessageManager
3814 .formatMessage("action.by_title_param", new Object[]
3817 item.addActionListener(new java.awt.event.ActionListener()
3820 public void actionPerformed(ActionEvent e)
3822 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3824 // TODO: JBPNote - have to map order entries to curent SequenceI
3826 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3828 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3829 viewport.getAlignment()));
3831 alignPanel.paintAlignment(true, false);
3837 * Add a new sort by annotation score menu item
3840 * the menu to add the option to
3842 * the label used to retrieve scores for each sequence on the
3845 public void addSortByAnnotScoreMenuItem(JMenu sort,
3846 final String scoreLabel)
3848 final JMenuItem item = new JMenuItem(scoreLabel);
3850 item.addActionListener(new java.awt.event.ActionListener()
3853 public void actionPerformed(ActionEvent e)
3855 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3856 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3857 viewport.getAlignment());// ,viewport.getSelectionGroup());
3858 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3859 viewport.getAlignment()));
3860 alignPanel.paintAlignment(true, false);
3866 * last hash for alignment's annotation array - used to minimise cost of
3869 protected int _annotationScoreVectorHash;
3872 * search the alignment and rebuild the sort by annotation score submenu the
3873 * last alignment annotation vector hash is stored to minimize cost of
3874 * rebuilding in subsequence calls.
3878 public void buildSortByAnnotationScoresMenu()
3880 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3885 if (viewport.getAlignment().getAlignmentAnnotation()
3886 .hashCode() != _annotationScoreVectorHash)
3888 sortByAnnotScore.removeAll();
3889 // almost certainly a quicker way to do this - but we keep it simple
3890 Hashtable scoreSorts = new Hashtable();
3891 AlignmentAnnotation aann[];
3892 for (SequenceI sqa : viewport.getAlignment().getSequences())
3894 aann = sqa.getAnnotation();
3895 for (int i = 0; aann != null && i < aann.length; i++)
3897 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3899 scoreSorts.put(aann[i].label, aann[i].label);
3903 Enumeration labels = scoreSorts.keys();
3904 while (labels.hasMoreElements())
3906 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3907 (String) labels.nextElement());
3909 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3912 _annotationScoreVectorHash = viewport.getAlignment()
3913 .getAlignmentAnnotation().hashCode();
3918 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3919 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3920 * call. Listeners are added to remove the menu item when the treePanel is
3921 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3925 public void buildTreeSortMenu()
3927 sortByTreeMenu.removeAll();
3929 List<Component> comps = PaintRefresher.components
3930 .get(viewport.getSequenceSetId());
3931 List<TreePanel> treePanels = new ArrayList<>();
3932 for (Component comp : comps)
3934 if (comp instanceof TreePanel)
3936 treePanels.add((TreePanel) comp);
3940 if (treePanels.size() < 1)
3942 sortByTreeMenu.setVisible(false);
3946 sortByTreeMenu.setVisible(true);
3948 for (final TreePanel tp : treePanels)
3950 final JMenuItem item = new JMenuItem(tp.getTitle());
3951 item.addActionListener(new java.awt.event.ActionListener()
3954 public void actionPerformed(ActionEvent e)
3956 tp.sortByTree_actionPerformed();
3957 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3962 sortByTreeMenu.add(item);
3966 public boolean sortBy(AlignmentOrder alorder, String undoname)
3968 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3969 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3970 if (undoname != null)
3972 addHistoryItem(new OrderCommand(undoname, oldOrder,
3973 viewport.getAlignment()));
3975 alignPanel.paintAlignment(true, false);
3980 * Work out whether the whole set of sequences or just the selected set will
3981 * be submitted for multiple alignment.
3984 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3986 // Now, check we have enough sequences
3987 AlignmentView msa = null;
3989 if ((viewport.getSelectionGroup() != null)
3990 && (viewport.getSelectionGroup().getSize() > 1))
3992 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3993 // some common interface!
3995 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3996 * SequenceI[sz = seqs.getSize(false)];
3998 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3999 * seqs.getSequenceAt(i); }
4001 msa = viewport.getAlignmentView(true);
4003 else if (viewport.getSelectionGroup() != null
4004 && viewport.getSelectionGroup().getSize() == 1)
4006 int option = JvOptionPane.showConfirmDialog(this,
4007 MessageManager.getString("warn.oneseq_msainput_selection"),
4008 MessageManager.getString("label.invalid_selection"),
4009 JvOptionPane.OK_CANCEL_OPTION);
4010 if (option == JvOptionPane.OK_OPTION)
4012 msa = viewport.getAlignmentView(false);
4017 msa = viewport.getAlignmentView(false);
4023 * Decides what is submitted to a secondary structure prediction service: the
4024 * first sequence in the alignment, or in the current selection, or, if the
4025 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4026 * region or the whole alignment. (where the first sequence in the set is the
4027 * one that the prediction will be for).
4029 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4031 AlignmentView seqs = null;
4033 if ((viewport.getSelectionGroup() != null)
4034 && (viewport.getSelectionGroup().getSize() > 0))
4036 seqs = viewport.getAlignmentView(true);
4040 seqs = viewport.getAlignmentView(false);
4042 // limit sequences - JBPNote in future - could spawn multiple prediction
4044 // TODO: viewport.getAlignment().isAligned is a global state - the local
4045 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4046 if (!viewport.getAlignment().isAligned(false))
4048 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4049 // TODO: if seqs.getSequences().length>1 then should really have warned
4063 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4065 // Pick the tree file
4066 JalviewFileChooser chooser = new JalviewFileChooser(
4067 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4068 chooser.setFileView(new JalviewFileView());
4069 chooser.setDialogTitle(
4070 MessageManager.getString("label.select_newick_like_tree_file"));
4071 chooser.setToolTipText(
4072 MessageManager.getString("label.load_tree_file"));
4074 int value = chooser.showOpenDialog(null);
4076 if (value == JalviewFileChooser.APPROVE_OPTION)
4078 String filePath = chooser.getSelectedFile().getPath();
4079 Cache.setProperty("LAST_DIRECTORY", filePath);
4080 NewickFile fin = null;
4083 fin = new NewickFile(filePath, DataSourceType.FILE);
4084 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4085 } catch (Exception ex)
4087 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4088 MessageManager.getString("label.problem_reading_tree_file"),
4089 JvOptionPane.WARNING_MESSAGE);
4090 ex.printStackTrace();
4092 if (fin != null && fin.hasWarningMessage())
4094 JvOptionPane.showMessageDialog(Desktop.desktop,
4095 fin.getWarningMessage(),
4097 .getString("label.possible_problem_with_tree_file"),
4098 JvOptionPane.WARNING_MESSAGE);
4103 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4105 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4108 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4109 int h, int x, int y)
4111 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4115 * Add a treeviewer for the tree extracted from a Newick file object to the
4116 * current alignment view
4123 * Associated alignment input data (or null)
4132 * @return TreePanel handle
4134 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4135 AlignmentView input, int w, int h, int x, int y)
4137 TreePanel tp = null;
4143 if (nf.getTree() != null)
4145 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4151 tp.setLocation(x, y);
4154 Desktop.addInternalFrame(tp, treeTitle, w, h);
4156 } catch (Exception ex)
4158 ex.printStackTrace();
4164 private boolean buildingMenu = false;
4167 * Generates menu items and listener event actions for web service clients
4170 public void BuildWebServiceMenu()
4172 while (buildingMenu)
4176 System.err.println("Waiting for building menu to finish.");
4178 } catch (Exception e)
4182 final AlignFrame me = this;
4183 buildingMenu = true;
4184 new Thread(new Runnable()
4189 final List<JMenuItem> legacyItems = new ArrayList<>();
4192 // System.err.println("Building ws menu again "
4193 // + Thread.currentThread());
4194 // TODO: add support for context dependent disabling of services based
4196 // alignment and current selection
4197 // TODO: add additional serviceHandle parameter to specify abstract
4199 // class independently of AbstractName
4200 // TODO: add in rediscovery GUI function to restart discoverer
4201 // TODO: group services by location as well as function and/or
4203 // object broker mechanism.
4204 final Vector<JMenu> wsmenu = new Vector<>();
4205 final IProgressIndicator af = me;
4208 * do not i18n these strings - they are hard-coded in class
4209 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4210 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4212 final JMenu msawsmenu = new JMenu("Alignment");
4213 final JMenu secstrmenu = new JMenu(
4214 "Secondary Structure Prediction");
4215 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4216 final JMenu analymenu = new JMenu("Analysis");
4217 final JMenu dismenu = new JMenu("Protein Disorder");
4218 // JAL-940 - only show secondary structure prediction services from
4219 // the legacy server
4220 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4222 Discoverer.services != null && (Discoverer.services.size() > 0))
4224 // TODO: refactor to allow list of AbstractName/Handler bindings to
4226 // stored or retrieved from elsewhere
4227 // No MSAWS used any more:
4228 // Vector msaws = null; // (Vector)
4229 // Discoverer.services.get("MsaWS");
4230 Vector secstrpr = (Vector) Discoverer.services
4232 if (secstrpr != null)
4234 // Add any secondary structure prediction services
4235 for (int i = 0, j = secstrpr.size(); i < j; i++)
4237 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4239 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4240 .getServiceClient(sh);
4241 int p = secstrmenu.getItemCount();
4242 impl.attachWSMenuEntry(secstrmenu, me);
4243 int q = secstrmenu.getItemCount();
4244 for (int litm = p; litm < q; litm++)
4246 legacyItems.add(secstrmenu.getItem(litm));
4252 // Add all submenus in the order they should appear on the web
4254 wsmenu.add(msawsmenu);
4255 wsmenu.add(secstrmenu);
4256 wsmenu.add(dismenu);
4257 wsmenu.add(analymenu);
4258 // No search services yet
4259 // wsmenu.add(seqsrchmenu);
4261 javax.swing.SwingUtilities.invokeLater(new Runnable()
4268 webService.removeAll();
4269 // first, add discovered services onto the webservices menu
4270 if (wsmenu.size() > 0)
4272 for (int i = 0, j = wsmenu.size(); i < j; i++)
4274 webService.add(wsmenu.get(i));
4279 webService.add(me.webServiceNoServices);
4281 // TODO: move into separate menu builder class.
4282 boolean new_sspred = false;
4283 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4285 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4286 if (jws2servs != null)
4288 if (jws2servs.hasServices())
4290 jws2servs.attachWSMenuEntry(webService, me);
4291 for (Jws2Instance sv : jws2servs.getServices())
4293 if (sv.description.toLowerCase().contains("jpred"))
4295 for (JMenuItem jmi : legacyItems)
4297 jmi.setVisible(false);
4303 if (jws2servs.isRunning())
4305 JMenuItem tm = new JMenuItem(
4306 "Still discovering JABA Services");
4307 tm.setEnabled(false);
4312 build_urlServiceMenu(me.webService);
4313 build_fetchdbmenu(webService);
4314 for (JMenu item : wsmenu)
4316 if (item.getItemCount() == 0)
4318 item.setEnabled(false);
4322 item.setEnabled(true);
4325 } catch (Exception e)
4328 "Exception during web service menu building process.",
4333 } catch (Exception e)
4336 buildingMenu = false;
4343 * construct any groupURL type service menu entries.
4347 private void build_urlServiceMenu(JMenu webService)
4349 // TODO: remove this code when 2.7 is released
4350 // DEBUG - alignmentView
4352 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4353 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4355 * @Override public void actionPerformed(ActionEvent e) {
4356 * jalview.datamodel.AlignmentView
4357 * .testSelectionViews(af.viewport.getAlignment(),
4358 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4360 * }); webService.add(testAlView);
4362 // TODO: refactor to RestClient discoverer and merge menu entries for
4363 // rest-style services with other types of analysis/calculation service
4364 // SHmmr test client - still being implemented.
4365 // DEBUG - alignmentView
4367 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4370 client.attachWSMenuEntry(
4371 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4377 * Searches the alignment sequences for xRefs and builds the Show
4378 * Cross-References menu (formerly called Show Products), with database
4379 * sources for which cross-references are found (protein sources for a
4380 * nucleotide alignment and vice versa)
4382 * @return true if Show Cross-references menu should be enabled
4384 public boolean canShowProducts()
4386 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4387 AlignmentI dataset = viewport.getAlignment().getDataset();
4389 showProducts.removeAll();
4390 final boolean dna = viewport.getAlignment().isNucleotide();
4392 if (seqs == null || seqs.length == 0)
4394 // nothing to see here.
4398 boolean showp = false;
4401 List<String> ptypes = new CrossRef(seqs, dataset)
4402 .findXrefSourcesForSequences(dna);
4404 for (final String source : ptypes)
4407 final AlignFrame af = this;
4408 JMenuItem xtype = new JMenuItem(source);
4409 xtype.addActionListener(new ActionListener()
4412 public void actionPerformed(ActionEvent e)
4414 showProductsFor(af.viewport.getSequenceSelection(), dna,
4418 showProducts.add(xtype);
4420 showProducts.setVisible(showp);
4421 showProducts.setEnabled(showp);
4422 } catch (Exception e)
4425 "canShowProducts threw an exception - please report to help@jalview.org",
4433 * Finds and displays cross-references for the selected sequences (protein
4434 * products for nucleotide sequences, dna coding sequences for peptides).
4437 * the sequences to show cross-references for
4439 * true if from a nucleotide alignment (so showing proteins)
4441 * the database to show cross-references for
4443 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4444 final String source)
4446 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4451 * Construct and display a new frame containing the translation of this
4452 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4455 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4457 AlignmentI al = null;
4460 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4462 al = dna.translateCdna(codeTable);
4463 } catch (Exception ex)
4465 jalview.bin.Cache.log.error(
4466 "Exception during translation. Please report this !", ex);
4467 final String msg = MessageManager.getString(
4468 "label.error_when_translating_sequences_submit_bug_report");
4469 final String errorTitle = MessageManager
4470 .getString("label.implementation_error")
4471 + MessageManager.getString("label.translation_failed");
4472 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4473 JvOptionPane.ERROR_MESSAGE);
4476 if (al == null || al.getHeight() == 0)
4478 final String msg = MessageManager.getString(
4479 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4480 final String errorTitle = MessageManager
4481 .getString("label.translation_failed");
4482 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4483 JvOptionPane.WARNING_MESSAGE);
4487 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4488 af.setFileFormat(this.currentFileFormat);
4489 final String newTitle = MessageManager
4490 .formatMessage("label.translation_of_params", new Object[]
4491 { this.getTitle(), codeTable.getId() });
4492 af.setTitle(newTitle);
4493 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4495 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4496 viewport.openSplitFrame(af, new Alignment(seqs));
4500 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4507 * Set the file format
4511 public void setFileFormat(FileFormatI format)
4513 this.currentFileFormat = format;
4517 * Try to load a features file onto the alignment.
4520 * contents or path to retrieve file
4522 * access mode of file (see jalview.io.AlignFile)
4523 * @return true if features file was parsed correctly.
4525 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4527 return avc.parseFeaturesFile(file, sourceType,
4528 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4533 public void refreshFeatureUI(boolean enableIfNecessary)
4535 // note - currently this is only still here rather than in the controller
4536 // because of the featureSettings hard reference that is yet to be
4538 if (enableIfNecessary)
4540 viewport.setShowSequenceFeatures(true);
4541 showSeqFeatures.setSelected(true);
4547 public void dragEnter(DropTargetDragEvent evt)
4552 public void dragExit(DropTargetEvent evt)
4557 public void dragOver(DropTargetDragEvent evt)
4562 public void dropActionChanged(DropTargetDragEvent evt)
4567 public void drop(DropTargetDropEvent evt)
4569 // JAL-1552 - acceptDrop required before getTransferable call for
4570 // Java's Transferable for native dnd
4571 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4572 Transferable t = evt.getTransferable();
4573 final AlignFrame thisaf = this;
4574 final List<String> files = new ArrayList<>();
4575 List<DataSourceType> protocols = new ArrayList<>();
4579 Desktop.transferFromDropTarget(files, protocols, evt, t);
4580 } catch (Exception e)
4582 e.printStackTrace();
4586 new Thread(new Runnable()
4593 // check to see if any of these files have names matching sequences
4596 SequenceIdMatcher idm = new SequenceIdMatcher(
4597 viewport.getAlignment().getSequencesArray());
4599 * Object[] { String,SequenceI}
4601 ArrayList<Object[]> filesmatched = new ArrayList<>();
4602 ArrayList<String> filesnotmatched = new ArrayList<>();
4603 for (int i = 0; i < files.size(); i++)
4605 String file = files.get(i).toString();
4607 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4608 if (protocol == DataSourceType.FILE)
4610 File fl = new File(file);
4611 pdbfn = fl.getName();
4613 else if (protocol == DataSourceType.URL)
4615 URL url = new URL(file);
4616 pdbfn = url.getFile();
4618 if (pdbfn.length() > 0)
4620 // attempt to find a match in the alignment
4621 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4622 int l = 0, c = pdbfn.indexOf(".");
4623 while (mtch == null && c != -1)
4628 } while ((c = pdbfn.indexOf(".", l)) > l);
4631 pdbfn = pdbfn.substring(0, l);
4633 mtch = idm.findAllIdMatches(pdbfn);
4637 FileFormatI type = null;
4640 type = new IdentifyFile().identify(file, protocol);
4641 } catch (Exception ex)
4645 if (type != null && type.isStructureFile())
4647 filesmatched.add(new Object[] { file, protocol, mtch });
4651 // File wasn't named like one of the sequences or wasn't a PDB
4653 filesnotmatched.add(file);
4657 if (filesmatched.size() > 0)
4659 boolean autoAssociate = Cache
4660 .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4663 String msg = MessageManager.formatMessage(
4664 "label.automatically_associate_structure_files_with_sequences_same_name",
4666 { Integer.valueOf(filesmatched.size())
4668 String ttl = MessageManager.getString(
4669 "label.automatically_associate_structure_files_by_name");
4670 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4671 ttl, JvOptionPane.YES_NO_OPTION);
4672 autoAssociate = choice == JvOptionPane.YES_OPTION;
4676 for (Object[] fm : filesmatched)
4678 // try and associate
4679 // TODO: may want to set a standard ID naming formalism for
4680 // associating PDB files which have no IDs.
4681 for (SequenceI toassoc : (SequenceI[]) fm[2])
4683 PDBEntry pe = new AssociatePdbFileWithSeq()
4684 .associatePdbWithSeq((String) fm[0],
4685 (DataSourceType) fm[1], toassoc, false,
4689 System.err.println("Associated file : "
4690 + ((String) fm[0]) + " with "
4691 + toassoc.getDisplayId(true));
4695 // TODO: do we need to update overview ? only if features are
4697 alignPanel.paintAlignment(true, false);
4703 * add declined structures as sequences
4705 for (Object[] o : filesmatched)
4707 filesnotmatched.add((String) o[0]);
4711 if (filesnotmatched.size() > 0)
4713 if (assocfiles > 0 && (Cache.getDefault(
4714 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4715 || JvOptionPane.showConfirmDialog(thisaf,
4716 "<html>" + MessageManager.formatMessage(
4717 "label.ignore_unmatched_dropped_files_info",
4720 filesnotmatched.size())
4723 MessageManager.getString(
4724 "label.ignore_unmatched_dropped_files"),
4725 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4729 for (String fn : filesnotmatched)
4731 loadJalviewDataFile(fn, null, null, null);
4735 } catch (Exception ex)
4737 ex.printStackTrace();
4745 * Attempt to load a "dropped" file or URL string, by testing in turn for
4747 * <li>an Annotation file</li>
4748 * <li>a JNet file</li>
4749 * <li>a features file</li>
4750 * <li>else try to interpret as an alignment file</li>
4754 * either a filename or a URL string.
4756 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4757 FileFormatI format, SequenceI assocSeq)
4761 if (sourceType == null)
4763 sourceType = FormatAdapter.checkProtocol(file);
4765 // if the file isn't identified, or not positively identified as some
4766 // other filetype (PFAM is default unidentified alignment file type) then
4767 // try to parse as annotation.
4768 boolean isAnnotation = (format == null
4769 || FileFormat.Pfam.equals(format))
4770 ? new AnnotationFile().annotateAlignmentView(viewport,
4776 // first see if its a T-COFFEE score file
4777 TCoffeeScoreFile tcf = null;
4780 tcf = new TCoffeeScoreFile(file, sourceType);
4783 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4787 new TCoffeeColourScheme(viewport.getAlignment()));
4788 isAnnotation = true;
4789 statusBar.setText(MessageManager.getString(
4790 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4794 // some problem - if no warning its probable that the ID matching
4795 // process didn't work
4796 JvOptionPane.showMessageDialog(Desktop.desktop,
4797 tcf.getWarningMessage() == null
4798 ? MessageManager.getString(
4799 "label.check_file_matches_sequence_ids_alignment")
4800 : tcf.getWarningMessage(),
4801 MessageManager.getString(
4802 "label.problem_reading_tcoffee_score_file"),
4803 JvOptionPane.WARNING_MESSAGE);
4810 } catch (Exception x)
4813 "Exception when processing data source as T-COFFEE score file",
4819 // try to see if its a JNet 'concise' style annotation file *before*
4821 // try to parse it as a features file
4824 format = new IdentifyFile().identify(file, sourceType);
4826 if (FileFormat.ScoreMatrix == format)
4828 ScoreMatrixFile sm = new ScoreMatrixFile(
4829 new FileParse(file, sourceType));
4831 // todo: i18n this message
4832 statusBar.setText(MessageManager.formatMessage(
4833 "label.successfully_loaded_matrix",
4834 sm.getMatrixName()));
4836 else if (FileFormat.Jnet.equals(format))
4838 JPredFile predictions = new JPredFile(file, sourceType);
4839 new JnetAnnotationMaker();
4840 JnetAnnotationMaker.add_annotation(predictions,
4841 viewport.getAlignment(), 0, false);
4842 viewport.getAlignment().setupJPredAlignment();
4843 isAnnotation = true;
4845 // else if (IdentifyFile.FeaturesFile.equals(format))
4846 else if (FileFormat.Features.equals(format))
4848 if (parseFeaturesFile(file, sourceType))
4850 alignPanel.paintAlignment(true, true);
4855 new FileLoader().LoadFile(viewport, file, sourceType, format);
4862 alignPanel.adjustAnnotationHeight();
4863 viewport.updateSequenceIdColours();
4864 buildSortByAnnotationScoresMenu();
4865 alignPanel.paintAlignment(true, true);
4867 } catch (Exception ex)
4869 ex.printStackTrace();
4870 } catch (OutOfMemoryError oom)
4875 } catch (Exception x)
4880 + (sourceType != null
4881 ? (sourceType == DataSourceType.PASTE
4883 : "using " + sourceType + " from "
4887 ? "(parsing as '" + format + "' file)"
4889 oom, Desktop.desktop);
4894 * Method invoked by the ChangeListener on the tabbed pane, in other words
4895 * when a different tabbed pane is selected by the user or programmatically.
4898 public void tabSelectionChanged(int index)
4902 alignPanel = alignPanels.get(index);
4903 viewport = alignPanel.av;
4904 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4905 setMenusFromViewport(viewport);
4909 * 'focus' any colour slider that is open to the selected viewport
4911 if (viewport.getConservationSelected())
4913 SliderPanel.setConservationSlider(alignPanel,
4914 viewport.getResidueShading(), alignPanel.getViewName());
4918 SliderPanel.hideConservationSlider();
4920 if (viewport.getAbovePIDThreshold())
4922 SliderPanel.setPIDSliderSource(alignPanel,
4923 viewport.getResidueShading(), alignPanel.getViewName());
4927 SliderPanel.hidePIDSlider();
4931 * If there is a frame linked to this one in a SplitPane, switch it to the
4932 * same view tab index. No infinite recursion of calls should happen, since
4933 * tabSelectionChanged() should not get invoked on setting the selected
4934 * index to an unchanged value. Guard against setting an invalid index
4935 * before the new view peer tab has been created.
4937 final AlignViewportI peer = viewport.getCodingComplement();
4940 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4941 .getAlignPanel().alignFrame;
4942 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4944 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4950 * On right mouse click on view tab, prompt for and set new view name.
4953 public void tabbedPane_mousePressed(MouseEvent e)
4955 if (e.isPopupTrigger())
4957 String msg = MessageManager.getString("label.enter_view_name");
4958 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4959 JvOptionPane.QUESTION_MESSAGE);
4963 viewport.setViewName(reply);
4964 // TODO warn if reply is in getExistingViewNames()?
4965 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4970 public AlignViewport getCurrentView()
4976 * Open the dialog for regex description parsing.
4979 protected void extractScores_actionPerformed(ActionEvent e)
4981 ParseProperties pp = new jalview.analysis.ParseProperties(
4982 viewport.getAlignment());
4983 // TODO: verify regex and introduce GUI dialog for version 2.5
4984 // if (pp.getScoresFromDescription("col", "score column ",
4985 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4987 if (pp.getScoresFromDescription("description column",
4988 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4990 buildSortByAnnotationScoresMenu();
4998 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5002 protected void showDbRefs_actionPerformed(ActionEvent e)
5004 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5010 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5014 protected void showNpFeats_actionPerformed(ActionEvent e)
5016 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5020 * find the viewport amongst the tabs in this alignment frame and close that
5025 public boolean closeView(AlignViewportI av)
5029 this.closeMenuItem_actionPerformed(false);
5032 Component[] comp = tabbedPane.getComponents();
5033 for (int i = 0; comp != null && i < comp.length; i++)
5035 if (comp[i] instanceof AlignmentPanel)
5037 if (((AlignmentPanel) comp[i]).av == av)
5040 closeView((AlignmentPanel) comp[i]);
5048 protected void build_fetchdbmenu(JMenu webService)
5050 // Temporary hack - DBRef Fetcher always top level ws entry.
5051 // TODO We probably want to store a sequence database checklist in
5052 // preferences and have checkboxes.. rather than individual sources selected
5054 final JMenu rfetch = new JMenu(
5055 MessageManager.getString("action.fetch_db_references"));
5056 rfetch.setToolTipText(MessageManager.getString(
5057 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5058 webService.add(rfetch);
5060 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5061 MessageManager.getString("option.trim_retrieved_seqs"));
5062 trimrs.setToolTipText(
5063 MessageManager.getString("label.trim_retrieved_sequences"));
5065 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5066 trimrs.addActionListener(new ActionListener()
5069 public void actionPerformed(ActionEvent e)
5071 trimrs.setSelected(trimrs.isSelected());
5072 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5073 Boolean.valueOf(trimrs.isSelected()).toString());
5077 JMenuItem fetchr = new JMenuItem(
5078 MessageManager.getString("label.standard_databases"));
5079 fetchr.setToolTipText(
5080 MessageManager.getString("label.fetch_embl_uniprot"));
5081 fetchr.addActionListener(new ActionListener()
5085 public void actionPerformed(ActionEvent e)
5087 new Thread(new Runnable()
5092 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5093 .getAlignment().isNucleotide();
5094 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5095 alignPanel.av.getSequenceSelection(),
5096 alignPanel.alignFrame, null,
5097 alignPanel.alignFrame.featureSettings, isNucleotide);
5098 dbRefFetcher.addListener(new FetchFinishedListenerI()
5101 public void finished()
5104 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5105 .getFeatureSettingsModels())
5108 alignPanel.av.mergeFeaturesStyle(srcSettings);
5110 AlignFrame.this.setMenusForViewport();
5113 dbRefFetcher.fetchDBRefs(false);
5121 final AlignFrame me = this;
5122 new Thread(new Runnable()
5127 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5128 .getSequenceFetcherSingleton(me);
5129 javax.swing.SwingUtilities.invokeLater(new Runnable()
5134 String[] dbclasses = sf.getOrderedSupportedSources();
5135 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5136 // jalview.util.QuickSort.sort(otherdb, otherdb);
5137 List<DbSourceProxy> otherdb;
5138 JMenu dfetch = new JMenu();
5139 JMenu ifetch = new JMenu();
5140 JMenuItem fetchr = null;
5141 int comp = 0, icomp = 0, mcomp = 15;
5142 String mname = null;
5144 for (String dbclass : dbclasses)
5146 otherdb = sf.getSourceProxy(dbclass);
5147 // add a single entry for this class, or submenu allowing 'fetch
5149 if (otherdb == null || otherdb.size() < 1)
5153 // List<DbSourceProxy> dbs=otherdb;
5154 // otherdb=new ArrayList<DbSourceProxy>();
5155 // for (DbSourceProxy db:dbs)
5157 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5161 mname = "From " + dbclass;
5163 if (otherdb.size() == 1)
5165 final DbSourceProxy[] dassource = otherdb
5166 .toArray(new DbSourceProxy[0]);
5167 DbSourceProxy src = otherdb.get(0);
5168 fetchr = new JMenuItem(src.getDbSource());
5169 fetchr.addActionListener(new ActionListener()
5173 public void actionPerformed(ActionEvent e)
5175 new Thread(new Runnable()
5181 boolean isNucleotide = alignPanel.alignFrame
5182 .getViewport().getAlignment()
5184 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5185 alignPanel.av.getSequenceSelection(),
5186 alignPanel.alignFrame, dassource,
5187 alignPanel.alignFrame.featureSettings,
5190 .addListener(new FetchFinishedListenerI()
5193 public void finished()
5195 FeatureSettingsModelI srcSettings = dassource[0]
5196 .getFeatureColourScheme();
5197 alignPanel.av.mergeFeaturesStyle(
5199 AlignFrame.this.setMenusForViewport();
5202 dbRefFetcher.fetchDBRefs(false);
5208 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5209 MessageManager.formatMessage(
5210 "label.fetch_retrieve_from", new Object[]
5211 { src.getDbName() })));
5217 final DbSourceProxy[] dassource = otherdb
5218 .toArray(new DbSourceProxy[0]);
5220 DbSourceProxy src = otherdb.get(0);
5221 fetchr = new JMenuItem(MessageManager
5222 .formatMessage("label.fetch_all_param", new Object[]
5223 { src.getDbSource() }));
5224 fetchr.addActionListener(new ActionListener()
5227 public void actionPerformed(ActionEvent e)
5229 new Thread(new Runnable()
5235 boolean isNucleotide = alignPanel.alignFrame
5236 .getViewport().getAlignment()
5238 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5239 alignPanel.av.getSequenceSelection(),
5240 alignPanel.alignFrame, dassource,
5241 alignPanel.alignFrame.featureSettings,
5244 .addListener(new FetchFinishedListenerI()
5247 public void finished()
5249 AlignFrame.this.setMenusForViewport();
5252 dbRefFetcher.fetchDBRefs(false);
5258 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5259 MessageManager.formatMessage(
5260 "label.fetch_retrieve_from_all_sources",
5262 { Integer.valueOf(otherdb.size())
5264 src.getDbSource(), src.getDbName() })));
5267 // and then build the rest of the individual menus
5268 ifetch = new JMenu(MessageManager.formatMessage(
5269 "label.source_from_db_source", new Object[]
5270 { src.getDbSource() }));
5272 String imname = null;
5274 for (DbSourceProxy sproxy : otherdb)
5276 String dbname = sproxy.getDbName();
5277 String sname = dbname.length() > 5
5278 ? dbname.substring(0, 5) + "..."
5280 String msname = dbname.length() > 10
5281 ? dbname.substring(0, 10) + "..."
5285 imname = MessageManager
5286 .formatMessage("label.from_msname", new Object[]
5289 fetchr = new JMenuItem(msname);
5290 final DbSourceProxy[] dassrc = { sproxy };
5291 fetchr.addActionListener(new ActionListener()
5295 public void actionPerformed(ActionEvent e)
5297 new Thread(new Runnable()
5303 boolean isNucleotide = alignPanel.alignFrame
5304 .getViewport().getAlignment()
5306 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5307 alignPanel.av.getSequenceSelection(),
5308 alignPanel.alignFrame, dassrc,
5309 alignPanel.alignFrame.featureSettings,
5312 .addListener(new FetchFinishedListenerI()
5315 public void finished()
5317 AlignFrame.this.setMenusForViewport();
5320 dbRefFetcher.fetchDBRefs(false);
5326 fetchr.setToolTipText(
5327 "<html>" + MessageManager.formatMessage(
5328 "label.fetch_retrieve_from", new Object[]
5332 if (++icomp >= mcomp || i == (otherdb.size()))
5334 ifetch.setText(MessageManager.formatMessage(
5335 "label.source_to_target", imname, sname));
5337 ifetch = new JMenu();
5345 if (comp >= mcomp || dbi >= (dbclasses.length))
5347 dfetch.setText(MessageManager.formatMessage(
5348 "label.source_to_target", mname, dbclass));
5350 dfetch = new JMenu();
5363 * Left justify the whole alignment.
5366 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5368 AlignmentI al = viewport.getAlignment();
5370 viewport.firePropertyChange("alignment", null, al);
5374 * Right justify the whole alignment.
5377 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5379 AlignmentI al = viewport.getAlignment();
5381 viewport.firePropertyChange("alignment", null, al);
5385 public void setShowSeqFeatures(boolean b)
5387 showSeqFeatures.setSelected(b);
5388 viewport.setShowSequenceFeatures(b);
5395 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5396 * awt.event.ActionEvent)
5399 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5401 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5402 alignPanel.paintAlignment(false, false);
5409 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5413 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5415 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5416 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5424 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5425 * .event.ActionEvent)
5428 protected void showGroupConservation_actionPerformed(ActionEvent e)
5430 viewport.setShowGroupConservation(showGroupConservation.getState());
5431 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5438 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5439 * .event.ActionEvent)
5442 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5444 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5445 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5452 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5453 * .event.ActionEvent)
5456 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5458 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5459 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5463 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5465 showSequenceLogo.setState(true);
5466 viewport.setShowSequenceLogo(true);
5467 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5468 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5472 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5474 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5481 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5482 * .event.ActionEvent)
5485 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5487 if (avc.makeGroupsFromSelection())
5489 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5490 alignPanel.updateAnnotation();
5491 alignPanel.paintAlignment(true,
5492 viewport.needToUpdateStructureViews());
5496 public void clearAlignmentSeqRep()
5498 // TODO refactor alignmentseqrep to controller
5499 if (viewport.getAlignment().hasSeqrep())
5501 viewport.getAlignment().setSeqrep(null);
5502 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5503 alignPanel.updateAnnotation();
5504 alignPanel.paintAlignment(true, true);
5509 protected void createGroup_actionPerformed(ActionEvent e)
5511 if (avc.createGroup())
5513 if (applyAutoAnnotationSettings.isSelected())
5515 alignPanel.updateAnnotation(true, false);
5517 alignPanel.alignmentChanged();
5522 protected void unGroup_actionPerformed(ActionEvent e)
5526 alignPanel.alignmentChanged();
5531 * make the given alignmentPanel the currently selected tab
5533 * @param alignmentPanel
5535 public void setDisplayedView(AlignmentPanel alignmentPanel)
5537 if (!viewport.getSequenceSetId()
5538 .equals(alignmentPanel.av.getSequenceSetId()))
5540 throw new Error(MessageManager.getString(
5541 "error.implementation_error_cannot_show_view_alignment_frame"));
5543 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5544 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5546 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5551 * Action on selection of menu options to Show or Hide annotations.
5554 * @param forSequences
5555 * update sequence-related annotations
5556 * @param forAlignment
5557 * update non-sequence-related annotations
5560 protected void setAnnotationsVisibility(boolean visible,
5561 boolean forSequences, boolean forAlignment)
5563 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5564 .getAlignmentAnnotation();
5569 for (AlignmentAnnotation aa : anns)
5572 * don't display non-positional annotations on an alignment
5574 if (aa.annotations == null)
5578 boolean apply = (aa.sequenceRef == null && forAlignment)
5579 || (aa.sequenceRef != null && forSequences);
5582 aa.visible = visible;
5585 alignPanel.validateAnnotationDimensions(true);
5586 alignPanel.alignmentChanged();
5590 * Store selected annotation sort order for the view and repaint.
5593 protected void sortAnnotations_actionPerformed()
5595 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5597 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5598 alignPanel.paintAlignment(false, false);
5603 * @return alignment panels in this alignment frame
5605 public List<? extends AlignmentViewPanel> getAlignPanels()
5607 // alignPanels is never null
5608 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5613 * Open a new alignment window, with the cDNA associated with this (protein)
5614 * alignment, aligned as is the protein.
5616 protected void viewAsCdna_actionPerformed()
5618 // TODO no longer a menu action - refactor as required
5619 final AlignmentI alignment = getViewport().getAlignment();
5620 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5621 if (mappings == null)
5625 List<SequenceI> cdnaSeqs = new ArrayList<>();
5626 for (SequenceI aaSeq : alignment.getSequences())
5628 for (AlignedCodonFrame acf : mappings)
5630 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5634 * There is a cDNA mapping for this protein sequence - add to new
5635 * alignment. It will share the same dataset sequence as other mapped
5636 * cDNA (no new mappings need to be created).
5638 final Sequence newSeq = new Sequence(dnaSeq);
5639 newSeq.setDatasetSequence(dnaSeq);
5640 cdnaSeqs.add(newSeq);
5644 if (cdnaSeqs.size() == 0)
5646 // show a warning dialog no mapped cDNA
5649 AlignmentI cdna = new Alignment(
5650 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5651 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5652 AlignFrame.DEFAULT_HEIGHT);
5653 cdna.alignAs(alignment);
5654 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5656 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5657 AlignFrame.DEFAULT_HEIGHT);
5661 * Set visibility of dna/protein complement view (available when shown in a
5667 protected void showComplement_actionPerformed(boolean show)
5669 SplitContainerI sf = getSplitViewContainer();
5672 sf.setComplementVisible(this, show);
5677 * Generate the reverse (optionally complemented) of the selected sequences,
5678 * and add them to the alignment
5681 protected void showReverse_actionPerformed(boolean complement)
5683 AlignmentI al = null;
5686 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5687 al = dna.reverseCdna(complement);
5688 viewport.addAlignment(al, "");
5689 addHistoryItem(new EditCommand(
5690 MessageManager.getString("label.add_sequences"), Action.PASTE,
5691 al.getSequencesArray(), 0, al.getWidth(),
5692 viewport.getAlignment()));
5693 } catch (Exception ex)
5695 System.err.println(ex.getMessage());
5701 * Try to run a script in the Groovy console, having first ensured that this
5702 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5703 * be targeted at this alignment.
5706 protected void runGroovy_actionPerformed()
5708 Jalview.setCurrentAlignFrame(this);
5709 groovy.ui.Console console = Desktop.getGroovyConsole();
5710 if (console != null)
5714 console.runScript();
5715 } catch (Exception ex)
5717 System.err.println((ex.toString()));
5718 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5719 MessageManager.getString("label.couldnt_run_groovy_script"),
5720 MessageManager.getString("label.groovy_support_failed"),
5721 JvOptionPane.ERROR_MESSAGE);
5726 System.err.println("Can't run Groovy script as console not found");
5731 * Hides columns containing (or not containing) a specified feature, provided
5732 * that would not leave all columns hidden
5734 * @param featureType
5735 * @param columnsContaining
5738 public boolean hideFeatureColumns(String featureType,
5739 boolean columnsContaining)
5741 boolean notForHiding = avc.markColumnsContainingFeatures(
5742 columnsContaining, false, false, featureType);
5745 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5746 false, featureType))
5748 getViewport().hideSelectedColumns();
5756 protected void selectHighlightedColumns_actionPerformed(
5757 ActionEvent actionEvent)
5759 // include key modifier check in case user selects from menu
5760 avc.markHighlightedColumns(
5761 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5762 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5763 | ActionEvent.CTRL_MASK)) != 0);
5767 * Rebuilds the Colour menu, including any user-defined colours which have
5768 * been loaded either on startup or during the session
5770 public void buildColourMenu()
5772 colourMenu.removeAll();
5774 colourMenu.add(applyToAllGroups);
5775 colourMenu.add(textColour);
5776 colourMenu.addSeparator();
5778 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5779 viewport.getAlignment(), false);
5781 colourMenu.add(annotationColour);
5782 bg.add(annotationColour);
5783 colourMenu.addSeparator();
5784 colourMenu.add(conservationMenuItem);
5785 colourMenu.add(modifyConservation);
5786 colourMenu.add(abovePIDThreshold);
5787 colourMenu.add(modifyPID);
5789 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5790 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5794 * Open a dialog (if not already open) that allows the user to select and
5795 * calculate PCA or Tree analysis
5797 protected void openTreePcaDialog()
5799 if (alignPanel.getCalculationDialog() == null)
5801 new CalculationChooser(AlignFrame.this);
5806 protected void loadVcf_actionPerformed()
5808 JalviewFileChooser chooser = new JalviewFileChooser(
5809 Cache.getProperty("LAST_DIRECTORY"));
5810 chooser.setFileView(new JalviewFileView());
5811 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5812 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5814 int value = chooser.showOpenDialog(null);
5816 if (value == JalviewFileChooser.APPROVE_OPTION)
5818 String choice = chooser.getSelectedFile().getPath();
5819 Cache.setProperty("LAST_DIRECTORY", choice);
5820 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5821 new VCFLoader(choice).loadVCF(seqs, this);
5827 class PrintThread extends Thread
5831 public PrintThread(AlignmentPanel ap)
5836 static PageFormat pf;
5841 PrinterJob printJob = PrinterJob.getPrinterJob();
5845 printJob.setPrintable(ap, pf);
5849 printJob.setPrintable(ap);
5852 if (printJob.printDialog())
5857 } catch (Exception PrintException)
5859 PrintException.printStackTrace();