2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AlignmentSorter;
24 import jalview.analysis.AlignmentUtils;
25 import jalview.analysis.CrossRef;
26 import jalview.analysis.Dna;
27 import jalview.analysis.ParseProperties;
28 import jalview.analysis.SequenceIdMatcher;
29 import jalview.api.AlignExportSettingsI;
30 import jalview.api.AlignViewControllerGuiI;
31 import jalview.api.AlignViewControllerI;
32 import jalview.api.AlignViewportI;
33 import jalview.api.AlignmentViewPanel;
34 import jalview.api.FeatureSettingsControllerI;
35 import jalview.api.SplitContainerI;
36 import jalview.api.ViewStyleI;
37 import jalview.api.analysis.SimilarityParamsI;
38 import jalview.bin.Cache;
39 import jalview.bin.Jalview;
40 import jalview.commands.CommandI;
41 import jalview.commands.EditCommand;
42 import jalview.commands.EditCommand.Action;
43 import jalview.commands.OrderCommand;
44 import jalview.commands.RemoveGapColCommand;
45 import jalview.commands.RemoveGapsCommand;
46 import jalview.commands.SlideSequencesCommand;
47 import jalview.commands.TrimRegionCommand;
48 import jalview.datamodel.AlignExportSettingsAdapter;
49 import jalview.datamodel.AlignedCodonFrame;
50 import jalview.datamodel.Alignment;
51 import jalview.datamodel.AlignmentAnnotation;
52 import jalview.datamodel.AlignmentExportData;
53 import jalview.datamodel.AlignmentI;
54 import jalview.datamodel.AlignmentOrder;
55 import jalview.datamodel.AlignmentView;
56 import jalview.datamodel.ColumnSelection;
57 import jalview.datamodel.HiddenColumns;
58 import jalview.datamodel.PDBEntry;
59 import jalview.datamodel.SeqCigar;
60 import jalview.datamodel.Sequence;
61 import jalview.datamodel.SequenceGroup;
62 import jalview.datamodel.SequenceI;
63 import jalview.gui.ColourMenuHelper.ColourChangeListener;
64 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
65 import jalview.io.AlignmentProperties;
66 import jalview.io.AnnotationFile;
67 import jalview.io.BioJsHTMLOutput;
68 import jalview.io.DataSourceType;
69 import jalview.io.FileFormat;
70 import jalview.io.FileFormatI;
71 import jalview.io.FileFormats;
72 import jalview.io.FileLoader;
73 import jalview.io.FileParse;
74 import jalview.io.FormatAdapter;
75 import jalview.io.HtmlSvgOutput;
76 import jalview.io.IdentifyFile;
77 import jalview.io.JPredFile;
78 import jalview.io.JalviewFileChooser;
79 import jalview.io.JalviewFileView;
80 import jalview.io.JnetAnnotationMaker;
81 import jalview.io.NewickFile;
82 import jalview.io.ScoreMatrixFile;
83 import jalview.io.TCoffeeScoreFile;
84 import jalview.io.vcf.VCFLoader;
85 import jalview.jbgui.GAlignFrame;
86 import jalview.schemes.ColourSchemeI;
87 import jalview.schemes.ColourSchemes;
88 import jalview.schemes.ResidueColourScheme;
89 import jalview.schemes.TCoffeeColourScheme;
90 import jalview.util.ImageMaker.TYPE;
91 import jalview.util.MessageManager;
92 import jalview.util.dialogrunner.RunResponse;
93 import jalview.viewmodel.AlignmentViewport;
94 import jalview.viewmodel.ViewportRanges;
95 import jalview.ws.DBRefFetcher;
96 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
97 import jalview.ws.jws1.Discoverer;
98 import jalview.ws.jws2.Jws2Discoverer;
99 import jalview.ws.jws2.jabaws2.Jws2Instance;
100 import jalview.ws.seqfetcher.DbSourceProxy;
102 import java.awt.BorderLayout;
103 import java.awt.Color;
104 import java.awt.Component;
105 import java.awt.Rectangle;
106 import java.awt.Toolkit;
107 import java.awt.datatransfer.Clipboard;
108 import java.awt.datatransfer.DataFlavor;
109 import java.awt.datatransfer.StringSelection;
110 import java.awt.datatransfer.Transferable;
111 import java.awt.dnd.DnDConstants;
112 import java.awt.dnd.DropTargetDragEvent;
113 import java.awt.dnd.DropTargetDropEvent;
114 import java.awt.dnd.DropTargetEvent;
115 import java.awt.dnd.DropTargetListener;
116 import java.awt.event.ActionEvent;
117 import java.awt.event.ActionListener;
118 import java.awt.event.FocusAdapter;
119 import java.awt.event.FocusEvent;
120 import java.awt.event.ItemEvent;
121 import java.awt.event.ItemListener;
122 import java.awt.event.KeyAdapter;
123 import java.awt.event.KeyEvent;
124 import java.awt.event.MouseEvent;
125 import java.awt.print.PageFormat;
126 import java.awt.print.PrinterJob;
127 import java.beans.PropertyChangeEvent;
129 import java.io.FileWriter;
130 import java.io.PrintWriter;
132 import java.util.ArrayList;
133 import java.util.Arrays;
134 import java.util.Deque;
135 import java.util.Enumeration;
136 import java.util.Hashtable;
137 import java.util.List;
138 import java.util.Vector;
140 import javax.swing.JCheckBoxMenuItem;
141 import javax.swing.JComponent;
142 import javax.swing.JEditorPane;
143 import javax.swing.JInternalFrame;
144 import javax.swing.JLabel;
145 import javax.swing.JLayeredPane;
146 import javax.swing.JMenu;
147 import javax.swing.JMenuItem;
148 import javax.swing.JPanel;
149 import javax.swing.JScrollPane;
150 import javax.swing.SwingUtilities;
156 * @version $Revision$
158 public class AlignFrame extends GAlignFrame implements DropTargetListener,
159 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
162 public static final int DEFAULT_WIDTH = 700;
164 public static final int DEFAULT_HEIGHT = 500;
167 * The currently displayed panel (selected tabbed view if more than one)
169 public AlignmentPanel alignPanel;
171 AlignViewport viewport;
173 public AlignViewControllerI avc;
175 List<AlignmentPanel> alignPanels = new ArrayList<>();
178 * Last format used to load or save alignments in this window
180 FileFormatI currentFileFormat = null;
183 * Current filename for this alignment
185 String fileName = null;
190 * Creates a new AlignFrame object with specific width and height.
196 public AlignFrame(AlignmentI al, int width, int height)
198 this(al, null, width, height);
202 * Creates a new AlignFrame object with specific width, height and
208 * @param sequenceSetId
210 public AlignFrame(AlignmentI al, int width, int height,
211 String sequenceSetId)
213 this(al, null, width, height, sequenceSetId);
217 * Creates a new AlignFrame object with specific width, height and
223 * @param sequenceSetId
226 public AlignFrame(AlignmentI al, int width, int height,
227 String sequenceSetId, String viewId)
229 this(al, null, width, height, sequenceSetId, viewId);
233 * new alignment window with hidden columns
237 * @param hiddenColumns
238 * ColumnSelection or null
240 * Width of alignment frame
244 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
247 this(al, hiddenColumns, width, height, null);
251 * Create alignment frame for al with hiddenColumns, a specific width and
252 * height, and specific sequenceId
255 * @param hiddenColumns
258 * @param sequenceSetId
261 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
262 int height, String sequenceSetId)
264 this(al, hiddenColumns, width, height, sequenceSetId, null);
268 * Create alignment frame for al with hiddenColumns, a specific width and
269 * height, and specific sequenceId
272 * @param hiddenColumns
275 * @param sequenceSetId
280 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
281 int height, String sequenceSetId, String viewId)
283 setSize(width, height);
285 if (al.getDataset() == null)
290 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
292 alignPanel = new AlignmentPanel(this, viewport);
294 addAlignmentPanel(alignPanel, true);
298 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
299 HiddenColumns hiddenColumns, int width, int height)
301 setSize(width, height);
303 if (al.getDataset() == null)
308 viewport = new AlignViewport(al, hiddenColumns);
310 if (hiddenSeqs != null && hiddenSeqs.length > 0)
312 viewport.hideSequence(hiddenSeqs);
314 alignPanel = new AlignmentPanel(this, viewport);
315 addAlignmentPanel(alignPanel, true);
320 * Make a new AlignFrame from existing alignmentPanels
327 public AlignFrame(AlignmentPanel ap)
331 addAlignmentPanel(ap, false);
336 * initalise the alignframe from the underlying viewport data and the
341 if (!Jalview.isHeadlessMode())
343 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
346 avc = new jalview.controller.AlignViewController(this, viewport,
348 if (viewport.getAlignmentConservationAnnotation() == null)
350 // BLOSUM62Colour.setEnabled(false);
351 conservationMenuItem.setEnabled(false);
352 modifyConservation.setEnabled(false);
353 // PIDColour.setEnabled(false);
354 // abovePIDThreshold.setEnabled(false);
355 // modifyPID.setEnabled(false);
358 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
361 if (sortby.equals("Id"))
363 sortIDMenuItem_actionPerformed(null);
365 else if (sortby.equals("Pairwise Identity"))
367 sortPairwiseMenuItem_actionPerformed(null);
371 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
373 setMenusFromViewport(viewport);
374 buildSortByAnnotationScoresMenu();
375 calculateTree.addActionListener(new ActionListener()
379 public void actionPerformed(ActionEvent e)
386 if (Desktop.desktop != null)
388 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
390 * BH 2018 ignore service listeners
396 addServiceListeners();
401 if (viewport.getWrapAlignment())
403 wrapMenuItem_actionPerformed(null);
406 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
408 this.overviewMenuItem_actionPerformed(null);
413 final List<AlignmentPanel> selviews = new ArrayList<>();
414 final List<AlignmentPanel> origview = new ArrayList<>();
415 final String menuLabel = MessageManager
416 .getString("label.copy_format_from");
417 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
418 new ViewSetProvider()
422 public AlignmentPanel[] getAllAlignmentPanels()
425 origview.add(alignPanel);
426 // make an array of all alignment panels except for this one
427 List<AlignmentPanel> aps = new ArrayList<>(
428 Arrays.asList(Desktop.getAlignmentPanels(null)));
429 aps.remove(AlignFrame.this.alignPanel);
430 return aps.toArray(new AlignmentPanel[aps.size()]);
432 }, selviews, new ItemListener()
436 public void itemStateChanged(ItemEvent e)
438 if (origview.size() > 0)
440 final AlignmentPanel ap = origview.get(0);
443 * Copy the ViewStyle of the selected panel to 'this one'.
444 * Don't change value of 'scaleProteinAsCdna' unless copying
447 ViewStyleI vs = selviews.get(0).getAlignViewport()
449 boolean fromSplitFrame = selviews.get(0)
450 .getAlignViewport().getCodingComplement() != null;
453 vs.setScaleProteinAsCdna(ap.getAlignViewport()
454 .getViewStyle().isScaleProteinAsCdna());
456 ap.getAlignViewport().setViewStyle(vs);
459 * Also rescale ViewStyle of SplitFrame complement if there is
460 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
461 * the whole ViewStyle (allow cDNA protein to have different
464 AlignViewportI complement = ap.getAlignViewport()
465 .getCodingComplement();
466 if (complement != null && vs.isScaleProteinAsCdna())
468 AlignFrame af = Desktop.getAlignFrameFor(complement);
469 ((SplitFrame) af.getSplitViewContainer())
471 af.setMenusForViewport();
475 ap.setSelected(true);
476 ap.alignFrame.setMenusForViewport();
481 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
482 .indexOf("devel") > -1
483 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
484 .indexOf("test") > -1)
486 formatMenu.add(vsel);
488 addFocusListener(new FocusAdapter()
491 public void focusGained(FocusEvent e)
493 Jalview.setCurrentAlignFrame(AlignFrame.this);
500 * Change the filename and format for the alignment, and enable the 'reload'
501 * button functionality.
508 public void setFileName(String file, FileFormatI format)
511 setFileFormat(format);
512 reload.setEnabled(true);
516 * JavaScript will have this, maybe others. More dependable than a file name
517 * and maintains a reference to the actual bytes loaded.
521 public void setFileObject(File file)
523 this.fileObject = file;
527 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
530 void addKeyListener()
532 addKeyListener(new KeyAdapter()
535 public void keyPressed(KeyEvent evt)
537 if (viewport.cursorMode
538 && ((evt.getKeyCode() >= KeyEvent.VK_0
539 && evt.getKeyCode() <= KeyEvent.VK_9)
540 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
541 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
542 && Character.isDigit(evt.getKeyChar()))
544 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
547 switch (evt.getKeyCode())
550 case 27: // escape key
551 deselectAllSequenceMenuItem_actionPerformed(null);
555 case KeyEvent.VK_DOWN:
556 if (evt.isAltDown() || !viewport.cursorMode)
558 moveSelectedSequences(false);
560 if (viewport.cursorMode)
562 alignPanel.getSeqPanel().moveCursor(0, 1);
567 if (evt.isAltDown() || !viewport.cursorMode)
569 moveSelectedSequences(true);
571 if (viewport.cursorMode)
573 alignPanel.getSeqPanel().moveCursor(0, -1);
578 case KeyEvent.VK_LEFT:
579 if (evt.isAltDown() || !viewport.cursorMode)
581 slideSequences(false,
582 alignPanel.getSeqPanel().getKeyboardNo1());
586 alignPanel.getSeqPanel().moveCursor(-1, 0);
591 case KeyEvent.VK_RIGHT:
592 if (evt.isAltDown() || !viewport.cursorMode)
594 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
598 alignPanel.getSeqPanel().moveCursor(1, 0);
602 case KeyEvent.VK_SPACE:
603 if (viewport.cursorMode)
605 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
606 || evt.isShiftDown() || evt.isAltDown());
610 // case KeyEvent.VK_A:
611 // if (viewport.cursorMode)
613 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
614 // //System.out.println("A");
618 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
619 * System.out.println("closing bracket"); } break;
621 case KeyEvent.VK_DELETE:
622 case KeyEvent.VK_BACK_SPACE:
623 if (!viewport.cursorMode)
625 cut_actionPerformed(null);
629 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
630 || evt.isShiftDown() || evt.isAltDown());
636 if (viewport.cursorMode)
638 alignPanel.getSeqPanel().setCursorRow();
642 if (viewport.cursorMode && !evt.isControlDown())
644 alignPanel.getSeqPanel().setCursorColumn();
648 if (viewport.cursorMode)
650 alignPanel.getSeqPanel().setCursorPosition();
654 case KeyEvent.VK_ENTER:
655 case KeyEvent.VK_COMMA:
656 if (viewport.cursorMode)
658 alignPanel.getSeqPanel().setCursorRowAndColumn();
663 if (viewport.cursorMode)
665 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
669 if (viewport.cursorMode)
671 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
676 viewport.cursorMode = !viewport.cursorMode;
677 setStatus(MessageManager
678 .formatMessage("label.keyboard_editing_mode", new String[]
679 { (viewport.cursorMode ? "on" : "off") }));
680 if (viewport.cursorMode)
682 ViewportRanges ranges = viewport.getRanges();
683 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
685 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
688 alignPanel.getSeqPanel().seqCanvas.repaint();
694 Help.showHelpWindow();
695 } catch (Exception ex)
697 ex.printStackTrace();
702 boolean toggleSeqs = !evt.isControlDown();
703 boolean toggleCols = !evt.isShiftDown();
704 toggleHiddenRegions(toggleSeqs, toggleCols);
709 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
710 boolean modifyExisting = true; // always modify, don't clear
711 // evt.isShiftDown();
712 boolean invertHighlighted = evt.isAltDown();
713 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
717 case KeyEvent.VK_PAGE_UP:
718 viewport.getRanges().pageUp();
720 case KeyEvent.VK_PAGE_DOWN:
721 viewport.getRanges().pageDown();
727 public void keyReleased(KeyEvent evt)
729 switch (evt.getKeyCode())
731 case KeyEvent.VK_LEFT:
732 if (evt.isAltDown() || !viewport.cursorMode)
734 viewport.firePropertyChange("alignment", null,
735 viewport.getAlignment().getSequences());
739 case KeyEvent.VK_RIGHT:
740 if (evt.isAltDown() || !viewport.cursorMode)
742 viewport.firePropertyChange("alignment", null,
743 viewport.getAlignment().getSequences());
751 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
753 ap.alignFrame = this;
754 avc = new jalview.controller.AlignViewController(this, viewport,
759 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
761 int aSize = alignPanels.size();
763 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
765 if (aSize == 1 && ap.av.viewName == null)
767 this.getContentPane().add(ap, BorderLayout.CENTER);
773 setInitialTabVisible();
776 expandViews.setEnabled(true);
777 gatherViews.setEnabled(true);
778 tabbedPane.addTab(ap.av.viewName, ap);
780 ap.setVisible(false);
785 if (ap.av.isPadGaps())
787 ap.av.getAlignment().padGaps();
789 ap.av.updateConservation(ap);
790 ap.av.updateConsensus(ap);
791 ap.av.updateStrucConsensus(ap);
795 public void setInitialTabVisible()
797 expandViews.setEnabled(true);
798 gatherViews.setEnabled(true);
799 tabbedPane.setVisible(true);
800 AlignmentPanel first = alignPanels.get(0);
801 tabbedPane.addTab(first.av.viewName, first);
802 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
805 public AlignViewport getViewport()
810 /* Set up intrinsic listeners for dynamically generated GUI bits. */
811 private void addServiceListeners()
813 final java.beans.PropertyChangeListener thisListener;
814 Desktop.instance.addJalviewPropertyChangeListener("services",
815 thisListener = new java.beans.PropertyChangeListener()
818 public void propertyChange(PropertyChangeEvent evt)
820 // // System.out.println("Discoverer property change.");
821 // if (evt.getPropertyName().equals("services"))
823 SwingUtilities.invokeLater(new Runnable()
830 "Rebuild WS Menu for service change");
831 BuildWebServiceMenu();
838 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
841 public void internalFrameClosed(
842 javax.swing.event.InternalFrameEvent evt)
844 // System.out.println("deregistering discoverer listener");
845 Desktop.instance.removeJalviewPropertyChangeListener("services",
847 closeMenuItem_actionPerformed(true);
850 // Finally, build the menu once to get current service state
851 new Thread(new Runnable()
856 BuildWebServiceMenu();
862 * Configure menu items that vary according to whether the alignment is
863 * nucleotide or protein
865 public void setGUINucleotide()
867 AlignmentI al = getViewport().getAlignment();
868 boolean nucleotide = al.isNucleotide();
870 loadVcf.setVisible(nucleotide);
871 showTranslation.setVisible(nucleotide);
872 showReverse.setVisible(nucleotide);
873 showReverseComplement.setVisible(nucleotide);
874 conservationMenuItem.setEnabled(!nucleotide);
876 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
877 showGroupConservation.setEnabled(!nucleotide);
879 showComplementMenuItem
880 .setText(nucleotide ? MessageManager.getString("label.protein")
881 : MessageManager.getString("label.nucleotide"));
885 * set up menus for the current viewport. This may be called after any
886 * operation that affects the data in the current view (selection changed,
887 * etc) to update the menus to reflect the new state.
890 public void setMenusForViewport()
892 setMenusFromViewport(viewport);
896 * Need to call this method when tabs are selected for multiple views, or when
897 * loading from Jalview2XML.java
902 void setMenusFromViewport(AlignViewport av)
904 padGapsMenuitem.setSelected(av.isPadGaps());
905 colourTextMenuItem.setSelected(av.isShowColourText());
906 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
907 modifyPID.setEnabled(abovePIDThreshold.isSelected());
908 conservationMenuItem.setSelected(av.getConservationSelected());
909 modifyConservation.setEnabled(conservationMenuItem.isSelected());
910 seqLimits.setSelected(av.getShowJVSuffix());
911 idRightAlign.setSelected(av.isRightAlignIds());
912 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
913 renderGapsMenuItem.setSelected(av.isRenderGaps());
914 wrapMenuItem.setSelected(av.getWrapAlignment());
915 scaleAbove.setVisible(av.getWrapAlignment());
916 scaleLeft.setVisible(av.getWrapAlignment());
917 scaleRight.setVisible(av.getWrapAlignment());
918 annotationPanelMenuItem.setState(av.isShowAnnotation());
920 * Show/hide annotations only enabled if annotation panel is shown
922 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
923 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
924 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
925 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
926 viewBoxesMenuItem.setSelected(av.getShowBoxes());
927 viewTextMenuItem.setSelected(av.getShowText());
928 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
929 showGroupConsensus.setSelected(av.isShowGroupConsensus());
930 showGroupConservation.setSelected(av.isShowGroupConservation());
931 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
932 showSequenceLogo.setSelected(av.isShowSequenceLogo());
933 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
935 ColourMenuHelper.setColourSelected(colourMenu,
936 av.getGlobalColourScheme());
938 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
939 hiddenMarkers.setState(av.getShowHiddenMarkers());
940 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
941 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
942 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
943 autoCalculate.setSelected(av.autoCalculateConsensus);
944 sortByTree.setSelected(av.sortByTree);
945 listenToViewSelections.setSelected(av.followSelection);
947 showProducts.setEnabled(canShowProducts());
948 setGroovyEnabled(Desktop.getGroovyConsole() != null);
954 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
958 public void setGroovyEnabled(boolean b)
960 runGroovy.setEnabled(b);
963 private IProgressIndicator progressBar;
968 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
971 public void setProgressBar(String message, long id)
973 progressBar.setProgressBar(message, id);
977 public void registerHandler(final long id,
978 final IProgressIndicatorHandler handler)
980 progressBar.registerHandler(id, handler);
985 * @return true if any progress bars are still active
988 public boolean operationInProgress()
990 return progressBar.operationInProgress();
994 public void setStatus(String text)
996 statusBar.setText(text);
1000 * Added so Castor Mapping file can obtain Jalview Version
1002 public String getVersion()
1004 return jalview.bin.Cache.getProperty("VERSION");
1007 public FeatureRenderer getFeatureRenderer()
1009 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1013 public void fetchSequence_actionPerformed()
1015 new SequenceFetcher(this);
1019 public void addFromFile_actionPerformed(ActionEvent e)
1021 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1025 public void reload_actionPerformed(ActionEvent e)
1027 if (fileName != null)
1029 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1030 // originating file's format
1031 // TODO: work out how to recover feature settings for correct view(s) when
1032 // file is reloaded.
1033 if (FileFormat.Jalview.equals(currentFileFormat))
1035 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1036 for (int i = 0; i < frames.length; i++)
1038 if (frames[i] instanceof AlignFrame && frames[i] != this
1039 && ((AlignFrame) frames[i]).fileName != null
1040 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1044 frames[i].setSelected(true);
1045 Desktop.instance.closeAssociatedWindows();
1046 } catch (java.beans.PropertyVetoException ex)
1052 Desktop.instance.closeAssociatedWindows();
1054 FileLoader loader = new FileLoader();
1055 DataSourceType protocol = fileName.startsWith("http:")
1056 ? DataSourceType.URL
1057 : DataSourceType.FILE;
1058 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1062 Rectangle bounds = this.getBounds();
1064 FileLoader loader = new FileLoader();
1066 AlignFrame newframe = null;
1068 if (fileObject == null)
1071 DataSourceType protocol = (fileName.startsWith("http:")
1072 ? DataSourceType.URL
1073 : DataSourceType.FILE);
1074 newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1079 newframe = loader.LoadFileWaitTillLoaded(fileObject,
1080 DataSourceType.FILE, currentFileFormat);
1083 newframe.setBounds(bounds);
1084 if (featureSettings != null && featureSettings.isShowing())
1086 final Rectangle fspos = featureSettings.frame.getBounds();
1087 // TODO: need a 'show feature settings' function that takes bounds -
1088 // need to refactor Desktop.addFrame
1089 newframe.featureSettings_actionPerformed(null);
1090 final FeatureSettings nfs = newframe.featureSettings;
1091 SwingUtilities.invokeLater(new Runnable()
1096 nfs.frame.setBounds(fspos);
1099 this.featureSettings.close();
1100 this.featureSettings = null;
1102 this.closeMenuItem_actionPerformed(true);
1108 public void addFromText_actionPerformed(ActionEvent e)
1111 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1115 public void addFromURL_actionPerformed(ActionEvent e)
1117 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1121 public void save_actionPerformed(ActionEvent e)
1123 if (fileName == null || (currentFileFormat == null)
1124 || fileName.startsWith("http"))
1126 saveAs_actionPerformed();
1130 saveAlignment(fileName, currentFileFormat);
1135 * Saves the alignment to a file with a name chosen by the user, if necessary
1136 * warning if a file would be overwritten
1139 public void saveAs_actionPerformed()
1141 String format = currentFileFormat == null ? null
1142 : currentFileFormat.getName();
1143 JalviewFileChooser chooser = JalviewFileChooser
1144 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1146 chooser.setFileView(new JalviewFileView());
1147 chooser.setDialogTitle(
1148 MessageManager.getString("label.save_alignment_to_file"));
1149 chooser.setToolTipText(MessageManager.getString("action.save"));
1151 int value = chooser.showSaveDialog(this);
1153 if (value != JalviewFileChooser.APPROVE_OPTION)
1157 currentFileFormat = chooser.getSelectedFormat();
1158 // todo is this (2005) test now obsolete - value is never null?
1159 while (currentFileFormat == null)
1161 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1163 .getString("label.select_file_format_before_saving"),
1164 MessageManager.getString("label.file_format_not_specified"),
1165 JvOptionPane.WARNING_MESSAGE);
1166 currentFileFormat = chooser.getSelectedFormat();
1167 value = chooser.showSaveDialog(this);
1168 if (value != JalviewFileChooser.APPROVE_OPTION)
1174 fileName = chooser.getSelectedFile().getPath();
1176 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1177 Cache.setProperty("LAST_DIRECTORY", fileName);
1178 saveAlignment(fileName, currentFileFormat);
1181 boolean lastSaveSuccessful = false;
1183 FileFormatI lastFormatSaved;
1185 String lastFilenameSaved;
1188 * Raise a dialog or status message for the last call to saveAlignment.
1190 * @return true if last call to saveAlignment(file, format) was successful.
1192 public boolean isSaveAlignmentSuccessful()
1195 if (!lastSaveSuccessful)
1197 JvOptionPane.showInternalMessageDialog(this, MessageManager
1198 .formatMessage("label.couldnt_save_file", new Object[]
1199 { lastFilenameSaved }),
1200 MessageManager.getString("label.error_saving_file"),
1201 JvOptionPane.WARNING_MESSAGE);
1206 setStatus(MessageManager.formatMessage(
1207 "label.successfully_saved_to_file_in_format", new Object[]
1208 { lastFilenameSaved, lastFormatSaved }));
1211 return lastSaveSuccessful;
1215 * Saves the alignment to the specified file path, in the specified format,
1216 * which may be an alignment format, or Jalview project format. If the
1217 * alignment has hidden regions, or the format is one capable of including
1218 * non-sequence data (features, annotations, groups), then the user may be
1219 * prompted to specify what to include in the output.
1224 public void saveAlignment(String file, FileFormatI format)
1226 lastSaveSuccessful = false;
1227 lastFilenameSaved = file;
1228 lastFormatSaved = format;
1230 if (FileFormat.Jalview.equals(format))
1232 String shortName = title;
1233 if (shortName.indexOf(File.separatorChar) > -1)
1235 shortName = shortName.substring(
1236 shortName.lastIndexOf(File.separatorChar) + 1);
1238 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file,
1243 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1244 RunResponse cancelAction = new RunResponse(JvOptionPane.CANCEL_OPTION)
1249 lastSaveSuccessful = false;
1252 RunResponse outputAction = new RunResponse(JvOptionPane.OK_OPTION)
1257 // todo defer this to inside formatSequences (or later)
1258 AlignmentExportData exportData = viewport
1259 .getAlignExportData(options);
1260 String output = new FormatAdapter(alignPanel, options)
1261 .formatSequences(format, exportData.getAlignment(),
1262 exportData.getOmitHidden(),
1263 exportData.getStartEndPostions(),
1264 viewport.getAlignment().getHiddenColumns());
1267 lastSaveSuccessful = false;
1273 PrintWriter out = new PrintWriter(new FileWriter(file));
1276 AlignFrame.this.setTitle(file);
1277 setStatus(MessageManager.formatMessage(
1278 "label.successfully_saved_to_file_in_format",
1280 { fileName, format.getName() }));
1281 } catch (Exception ex)
1283 lastSaveSuccessful = false;
1284 ex.printStackTrace();
1291 * show dialog with export options if applicable; else just do it
1293 if (AlignExportOptions.isNeeded(viewport, format))
1295 AlignExportOptions choices = new AlignExportOptions(
1296 alignPanel.getAlignViewport(), format, options);
1297 choices.setResponseAction(outputAction);
1298 choices.setResponseAction(cancelAction);
1299 choices.showDialog();
1308 * Outputs the alignment to textbox in the requested format, if necessary
1309 * first prompting the user for whether to include hidden regions or
1312 * @param fileFormatName
1315 protected void outputText_actionPerformed(String fileFormatName)
1317 FileFormatI fileFormat = FileFormats.getInstance()
1318 .forName(fileFormatName);
1319 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1320 RunResponse outputAction = new RunResponse(JvOptionPane.OK_OPTION)
1325 // todo defer this to inside formatSequences (or later)
1326 AlignmentExportData exportData = viewport
1327 .getAlignExportData(options);
1328 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1329 cap.setForInput(null);
1332 FileFormatI format = fileFormat;
1333 cap.setText(new FormatAdapter(alignPanel, options)
1334 .formatSequences(format, exportData.getAlignment(),
1335 exportData.getOmitHidden(),
1336 exportData.getStartEndPostions(),
1337 viewport.getAlignment().getHiddenColumns()));
1338 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1339 "label.alignment_output_command", new Object[]
1340 { fileFormat.getName() }), 600, 500);
1341 } catch (OutOfMemoryError oom)
1343 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1351 * show dialog with export options if applicable; else just do it
1353 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1355 AlignExportOptions choices = new AlignExportOptions(
1356 alignPanel.getAlignViewport(), fileFormat, options);
1357 choices.setResponseAction(outputAction);
1358 choices.showDialog();
1373 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1375 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1376 htmlSVG.exportHTML(null);
1380 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1382 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1383 bjs.exportHTML(null);
1386 public void createImageMap(File file, String image)
1388 alignPanel.makePNGImageMap(file, image);
1392 * Creates a PNG image of the alignment and writes it to the given file. If
1393 * the file is null, the user is prompted to choose a file.
1398 public void createPNG(File f)
1400 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1404 * Creates an EPS image of the alignment and writes it to the given file. If
1405 * the file is null, the user is prompted to choose a file.
1410 public void createEPS(File f)
1412 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1416 * Creates an SVG image of the alignment and writes it to the given file. If
1417 * the file is null, the user is prompted to choose a file.
1422 public void createSVG(File f)
1424 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1428 public void pageSetup_actionPerformed(ActionEvent e)
1430 PrinterJob printJob = PrinterJob.getPrinterJob();
1431 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1441 public void printMenuItem_actionPerformed(ActionEvent e)
1443 // Putting in a thread avoids Swing painting problems
1444 PrintThread thread = new PrintThread(alignPanel);
1449 public void exportFeatures_actionPerformed(ActionEvent e)
1451 new AnnotationExporter(alignPanel).exportFeatures();
1455 public void exportAnnotations_actionPerformed(ActionEvent e)
1457 new AnnotationExporter(alignPanel).exportAnnotations();
1461 public void associatedData_actionPerformed(ActionEvent e)
1463 final JalviewFileChooser chooser = new JalviewFileChooser(
1464 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1465 chooser.setFileView(new JalviewFileView());
1466 chooser.setDialogTitle(
1467 MessageManager.getString("label.load_jalview_annotations"));
1468 chooser.setToolTipText(
1469 MessageManager.getString("label.load_jalview_annotations"));
1470 chooser.response(new RunResponse(JalviewFileChooser.APPROVE_OPTION)
1476 String choice = chooser.getSelectedFile().getPath();
1477 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1478 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1483 chooser.openDialog(this);
1487 * Close the current view or all views in the alignment frame. If the frame
1488 * only contains one view then the alignment will be removed from memory.
1490 * @param closeAllTabs
1493 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1495 if (alignPanels != null && alignPanels.size() < 2)
1497 closeAllTabs = true;
1502 if (alignPanels != null)
1506 if (this.isClosed())
1508 // really close all the windows - otherwise wait till
1509 // setClosed(true) is called
1510 for (int i = 0; i < alignPanels.size(); i++)
1512 AlignmentPanel ap = alignPanels.get(i);
1519 closeView(alignPanel);
1526 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1527 * be called recursively, with the frame now in 'closed' state
1529 this.setClosed(true);
1531 } catch (Exception ex)
1533 ex.printStackTrace();
1538 * Close the specified panel and close up tabs appropriately.
1540 * @param panelToClose
1542 public void closeView(AlignmentPanel panelToClose)
1544 int index = tabbedPane.getSelectedIndex();
1545 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1546 alignPanels.remove(panelToClose);
1547 panelToClose.closePanel();
1548 panelToClose = null;
1550 tabbedPane.removeTabAt(closedindex);
1551 tabbedPane.validate();
1553 if (index > closedindex || index == tabbedPane.getTabCount())
1555 // modify currently selected tab index if necessary.
1559 this.tabSelectionChanged(index);
1565 void updateEditMenuBar()
1568 if (viewport.getHistoryList().size() > 0)
1570 undoMenuItem.setEnabled(true);
1571 CommandI command = viewport.getHistoryList().peek();
1572 undoMenuItem.setText(MessageManager
1573 .formatMessage("label.undo_command", new Object[]
1574 { command.getDescription() }));
1578 undoMenuItem.setEnabled(false);
1579 undoMenuItem.setText(MessageManager.getString("action.undo"));
1582 if (viewport.getRedoList().size() > 0)
1584 redoMenuItem.setEnabled(true);
1586 CommandI command = viewport.getRedoList().peek();
1587 redoMenuItem.setText(MessageManager
1588 .formatMessage("label.redo_command", new Object[]
1589 { command.getDescription() }));
1593 redoMenuItem.setEnabled(false);
1594 redoMenuItem.setText(MessageManager.getString("action.redo"));
1599 public void addHistoryItem(CommandI command)
1601 if (command.getSize() > 0)
1603 viewport.addToHistoryList(command);
1604 viewport.clearRedoList();
1605 updateEditMenuBar();
1606 viewport.updateHiddenColumns();
1607 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1608 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1609 // viewport.getColumnSelection()
1610 // .getHiddenColumns().size() > 0);
1616 * @return alignment objects for all views
1618 AlignmentI[] getViewAlignments()
1620 if (alignPanels != null)
1622 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1624 for (AlignmentPanel ap : alignPanels)
1626 als[i++] = ap.av.getAlignment();
1630 if (viewport != null)
1632 return new AlignmentI[] { viewport.getAlignment() };
1644 protected void undoMenuItem_actionPerformed(ActionEvent e)
1646 if (viewport.getHistoryList().isEmpty())
1650 CommandI command = viewport.getHistoryList().pop();
1651 viewport.addToRedoList(command);
1652 command.undoCommand(getViewAlignments());
1654 AlignmentViewport originalSource = getOriginatingSource(command);
1655 updateEditMenuBar();
1657 if (originalSource != null)
1659 if (originalSource != viewport)
1662 "Implementation worry: mismatch of viewport origin for undo");
1664 originalSource.updateHiddenColumns();
1665 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1667 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1668 // viewport.getColumnSelection()
1669 // .getHiddenColumns().size() > 0);
1670 originalSource.firePropertyChange("alignment", null,
1671 originalSource.getAlignment().getSequences());
1682 protected void redoMenuItem_actionPerformed(ActionEvent e)
1684 if (viewport.getRedoList().size() < 1)
1689 CommandI command = viewport.getRedoList().pop();
1690 viewport.addToHistoryList(command);
1691 command.doCommand(getViewAlignments());
1693 AlignmentViewport originalSource = getOriginatingSource(command);
1694 updateEditMenuBar();
1696 if (originalSource != null)
1699 if (originalSource != viewport)
1702 "Implementation worry: mismatch of viewport origin for redo");
1704 originalSource.updateHiddenColumns();
1705 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1707 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1708 // viewport.getColumnSelection()
1709 // .getHiddenColumns().size() > 0);
1710 originalSource.firePropertyChange("alignment", null,
1711 originalSource.getAlignment().getSequences());
1715 AlignmentViewport getOriginatingSource(CommandI command)
1717 AlignmentViewport originalSource = null;
1718 // For sequence removal and addition, we need to fire
1719 // the property change event FROM the viewport where the
1720 // original alignment was altered
1721 AlignmentI al = null;
1722 if (command instanceof EditCommand)
1724 EditCommand editCommand = (EditCommand) command;
1725 al = editCommand.getAlignment();
1726 List<Component> comps = PaintRefresher.components
1727 .get(viewport.getSequenceSetId());
1729 for (Component comp : comps)
1731 if (comp instanceof AlignmentPanel)
1733 if (al == ((AlignmentPanel) comp).av.getAlignment())
1735 originalSource = ((AlignmentPanel) comp).av;
1742 if (originalSource == null)
1744 // The original view is closed, we must validate
1745 // the current view against the closed view first
1748 PaintRefresher.validateSequences(al, viewport.getAlignment());
1751 originalSource = viewport;
1754 return originalSource;
1763 public void moveSelectedSequences(boolean up)
1765 SequenceGroup sg = viewport.getSelectionGroup();
1771 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1772 viewport.getHiddenRepSequences(), up);
1773 alignPanel.paintAlignment(true, false);
1776 synchronized void slideSequences(boolean right, int size)
1778 List<SequenceI> sg = new ArrayList<>();
1779 if (viewport.cursorMode)
1781 sg.add(viewport.getAlignment()
1782 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1784 else if (viewport.getSelectionGroup() != null
1785 && viewport.getSelectionGroup().getSize() != viewport
1786 .getAlignment().getHeight())
1788 sg = viewport.getSelectionGroup()
1789 .getSequences(viewport.getHiddenRepSequences());
1797 List<SequenceI> invertGroup = new ArrayList<>();
1799 for (SequenceI seq : viewport.getAlignment().getSequences())
1801 if (!sg.contains(seq))
1803 invertGroup.add(seq);
1807 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1809 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1810 for (int i = 0; i < invertGroup.size(); i++)
1812 seqs2[i] = invertGroup.get(i);
1815 SlideSequencesCommand ssc;
1818 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1819 viewport.getGapCharacter());
1823 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1824 viewport.getGapCharacter());
1827 int groupAdjustment = 0;
1828 if (ssc.getGapsInsertedBegin() && right)
1830 if (viewport.cursorMode)
1832 alignPanel.getSeqPanel().moveCursor(size, 0);
1836 groupAdjustment = size;
1839 else if (!ssc.getGapsInsertedBegin() && !right)
1841 if (viewport.cursorMode)
1843 alignPanel.getSeqPanel().moveCursor(-size, 0);
1847 groupAdjustment = -size;
1851 if (groupAdjustment != 0)
1853 viewport.getSelectionGroup().setStartRes(
1854 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1855 viewport.getSelectionGroup().setEndRes(
1856 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1860 * just extend the last slide command if compatible; but not if in
1861 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1863 boolean appendHistoryItem = false;
1864 Deque<CommandI> historyList = viewport.getHistoryList();
1865 boolean inSplitFrame = getSplitViewContainer() != null;
1866 if (!inSplitFrame && historyList != null && historyList.size() > 0
1867 && historyList.peek() instanceof SlideSequencesCommand)
1869 appendHistoryItem = ssc.appendSlideCommand(
1870 (SlideSequencesCommand) historyList.peek());
1873 if (!appendHistoryItem)
1875 addHistoryItem(ssc);
1888 protected void copy_actionPerformed(ActionEvent e)
1890 if (viewport.getSelectionGroup() == null)
1894 // TODO: preserve the ordering of displayed alignment annotation in any
1895 // internal paste (particularly sequence associated annotation)
1896 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1897 String[] omitHidden = null;
1899 if (viewport.hasHiddenColumns())
1901 omitHidden = viewport.getViewAsString(true);
1904 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1905 seqs, omitHidden, null);
1907 StringSelection ss = new StringSelection(output);
1911 jalview.gui.Desktop.internalCopy = true;
1912 // Its really worth setting the clipboard contents
1913 // to empty before setting the large StringSelection!!
1914 Toolkit.getDefaultToolkit().getSystemClipboard()
1915 .setContents(new StringSelection(""), null);
1917 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1919 } catch (OutOfMemoryError er)
1921 new OOMWarning("copying region", er);
1925 HiddenColumns hiddenColumns = null;
1926 if (viewport.hasHiddenColumns())
1928 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1929 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1931 // create new HiddenColumns object with copy of hidden regions
1932 // between startRes and endRes, offset by startRes
1933 hiddenColumns = new HiddenColumns(
1934 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
1935 hiddenCutoff, hiddenOffset);
1938 Desktop.jalviewClipboard = new Object[] { seqs,
1939 viewport.getAlignment().getDataset(), hiddenColumns };
1940 setStatus(MessageManager.formatMessage(
1941 "label.copied_sequences_to_clipboard", new Object[]
1942 { Integer.valueOf(seqs.length).toString() }));
1952 protected void pasteNew_actionPerformed(ActionEvent e)
1964 protected void pasteThis_actionPerformed(ActionEvent e)
1970 * Paste contents of Jalview clipboard
1972 * @param newAlignment
1973 * true to paste to a new alignment, otherwise add to this.
1975 void paste(boolean newAlignment)
1977 boolean externalPaste = true;
1980 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1981 Transferable contents = c.getContents(this);
1983 if (contents == null)
1992 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1993 if (str.length() < 1)
1998 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2000 } catch (OutOfMemoryError er)
2002 new OOMWarning("Out of memory pasting sequences!!", er);
2006 SequenceI[] sequences;
2007 boolean annotationAdded = false;
2008 AlignmentI alignment = null;
2010 if (Desktop.jalviewClipboard != null)
2012 // The clipboard was filled from within Jalview, we must use the
2014 // And dataset from the copied alignment
2015 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2016 // be doubly sure that we create *new* sequence objects.
2017 sequences = new SequenceI[newseq.length];
2018 for (int i = 0; i < newseq.length; i++)
2020 sequences[i] = new Sequence(newseq[i]);
2022 alignment = new Alignment(sequences);
2023 externalPaste = false;
2027 // parse the clipboard as an alignment.
2028 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2030 sequences = alignment.getSequencesArray();
2034 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2040 if (Desktop.jalviewClipboard != null)
2042 // dataset is inherited
2043 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2047 // new dataset is constructed
2048 alignment.setDataset(null);
2050 alwidth = alignment.getWidth() + 1;
2054 AlignmentI pastedal = alignment; // preserve pasted alignment object
2055 // Add pasted sequences and dataset into existing alignment.
2056 alignment = viewport.getAlignment();
2057 alwidth = alignment.getWidth() + 1;
2058 // decide if we need to import sequences from an existing dataset
2059 boolean importDs = Desktop.jalviewClipboard != null
2060 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2061 // importDs==true instructs us to copy over new dataset sequences from
2062 // an existing alignment
2063 Vector newDs = (importDs) ? new Vector() : null; // used to create
2064 // minimum dataset set
2066 for (int i = 0; i < sequences.length; i++)
2070 newDs.addElement(null);
2072 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2074 if (importDs && ds != null)
2076 if (!newDs.contains(ds))
2078 newDs.setElementAt(ds, i);
2079 ds = new Sequence(ds);
2080 // update with new dataset sequence
2081 sequences[i].setDatasetSequence(ds);
2085 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2090 // copy and derive new dataset sequence
2091 sequences[i] = sequences[i].deriveSequence();
2092 alignment.getDataset()
2093 .addSequence(sequences[i].getDatasetSequence());
2094 // TODO: avoid creation of duplicate dataset sequences with a
2095 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2097 alignment.addSequence(sequences[i]); // merges dataset
2101 newDs.clear(); // tidy up
2103 if (alignment.getAlignmentAnnotation() != null)
2105 for (AlignmentAnnotation alan : alignment
2106 .getAlignmentAnnotation())
2108 if (alan.graphGroup > fgroup)
2110 fgroup = alan.graphGroup;
2114 if (pastedal.getAlignmentAnnotation() != null)
2116 // Add any annotation attached to alignment.
2117 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2118 for (int i = 0; i < alann.length; i++)
2120 annotationAdded = true;
2121 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2123 AlignmentAnnotation newann = new AlignmentAnnotation(
2125 if (newann.graphGroup > -1)
2127 if (newGraphGroups.size() <= newann.graphGroup
2128 || newGraphGroups.get(newann.graphGroup) == null)
2130 for (int q = newGraphGroups
2131 .size(); q <= newann.graphGroup; q++)
2133 newGraphGroups.add(q, null);
2135 newGraphGroups.set(newann.graphGroup,
2136 new Integer(++fgroup));
2138 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2142 newann.padAnnotation(alwidth);
2143 alignment.addAnnotation(newann);
2153 addHistoryItem(new EditCommand(
2154 MessageManager.getString("label.add_sequences"),
2155 Action.PASTE, sequences, 0, alignment.getWidth(),
2158 // Add any annotations attached to sequences
2159 for (int i = 0; i < sequences.length; i++)
2161 if (sequences[i].getAnnotation() != null)
2163 AlignmentAnnotation newann;
2164 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2166 annotationAdded = true;
2167 newann = sequences[i].getAnnotation()[a];
2168 newann.adjustForAlignment();
2169 newann.padAnnotation(alwidth);
2170 if (newann.graphGroup > -1)
2172 if (newann.graphGroup > -1)
2174 if (newGraphGroups.size() <= newann.graphGroup
2175 || newGraphGroups.get(newann.graphGroup) == null)
2177 for (int q = newGraphGroups
2178 .size(); q <= newann.graphGroup; q++)
2180 newGraphGroups.add(q, null);
2182 newGraphGroups.set(newann.graphGroup,
2183 new Integer(++fgroup));
2185 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2189 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2193 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2201 // propagate alignment changed.
2202 viewport.getRanges().setEndSeq(alignment.getHeight());
2203 if (annotationAdded)
2205 // Duplicate sequence annotation in all views.
2206 AlignmentI[] alview = this.getViewAlignments();
2207 for (int i = 0; i < sequences.length; i++)
2209 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2214 for (int avnum = 0; avnum < alview.length; avnum++)
2216 if (alview[avnum] != alignment)
2218 // duplicate in a view other than the one with input focus
2219 int avwidth = alview[avnum].getWidth() + 1;
2220 // this relies on sann being preserved after we
2221 // modify the sequence's annotation array for each duplication
2222 for (int a = 0; a < sann.length; a++)
2224 AlignmentAnnotation newann = new AlignmentAnnotation(
2226 sequences[i].addAlignmentAnnotation(newann);
2227 newann.padAnnotation(avwidth);
2228 alview[avnum].addAnnotation(newann); // annotation was
2229 // duplicated earlier
2230 // TODO JAL-1145 graphGroups are not updated for sequence
2231 // annotation added to several views. This may cause
2233 alview[avnum].setAnnotationIndex(newann, a);
2238 buildSortByAnnotationScoresMenu();
2240 viewport.firePropertyChange("alignment", null,
2241 alignment.getSequences());
2242 if (alignPanels != null)
2244 for (AlignmentPanel ap : alignPanels)
2246 ap.validateAnnotationDimensions(false);
2251 alignPanel.validateAnnotationDimensions(false);
2257 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2259 String newtitle = new String("Copied sequences");
2261 if (Desktop.jalviewClipboard != null
2262 && Desktop.jalviewClipboard[2] != null)
2264 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2265 af.viewport.setHiddenColumns(hc);
2268 // >>>This is a fix for the moment, until a better solution is
2270 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2271 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2272 .getFeatureRenderer());
2274 // TODO: maintain provenance of an alignment, rather than just make the
2275 // title a concatenation of operations.
2278 if (title.startsWith("Copied sequences"))
2284 newtitle = newtitle.concat("- from " + title);
2289 newtitle = new String("Pasted sequences");
2292 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2297 } catch (Exception ex)
2299 ex.printStackTrace();
2300 System.out.println("Exception whilst pasting: " + ex);
2301 // could be anything being pasted in here
2307 protected void expand_newalign(ActionEvent e)
2311 AlignmentI alignment = AlignmentUtils
2312 .expandContext(getViewport().getAlignment(), -1);
2313 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2315 String newtitle = new String("Flanking alignment");
2317 if (Desktop.jalviewClipboard != null
2318 && Desktop.jalviewClipboard[2] != null)
2320 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2321 af.viewport.setHiddenColumns(hc);
2324 // >>>This is a fix for the moment, until a better solution is
2326 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2327 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2328 .getFeatureRenderer());
2330 // TODO: maintain provenance of an alignment, rather than just make the
2331 // title a concatenation of operations.
2333 if (title.startsWith("Copied sequences"))
2339 newtitle = newtitle.concat("- from " + title);
2343 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2345 } catch (Exception ex)
2347 ex.printStackTrace();
2348 System.out.println("Exception whilst pasting: " + ex);
2349 // could be anything being pasted in here
2350 } catch (OutOfMemoryError oom)
2352 new OOMWarning("Viewing flanking region of alignment", oom);
2363 protected void cut_actionPerformed(ActionEvent e)
2365 copy_actionPerformed(null);
2366 delete_actionPerformed(null);
2376 protected void delete_actionPerformed(ActionEvent evt)
2379 SequenceGroup sg = viewport.getSelectionGroup();
2386 * If the cut affects all sequences, warn, remove highlighted columns
2388 if (sg.getSize() == viewport.getAlignment().getHeight())
2390 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2391 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2392 if (isEntireAlignWidth)
2394 int confirm = JvOptionPane.showConfirmDialog(this,
2395 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2396 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2397 JvOptionPane.OK_CANCEL_OPTION);
2399 if (confirm == JvOptionPane.CANCEL_OPTION
2400 || confirm == JvOptionPane.CLOSED_OPTION)
2405 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2406 sg.getEndRes() + 1);
2408 SequenceI[] cut = sg.getSequences()
2409 .toArray(new SequenceI[sg.getSize()]);
2411 addHistoryItem(new EditCommand(
2412 MessageManager.getString("label.cut_sequences"), Action.CUT,
2413 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2414 viewport.getAlignment()));
2416 viewport.setSelectionGroup(null);
2417 viewport.sendSelection();
2418 viewport.getAlignment().deleteGroup(sg);
2420 viewport.firePropertyChange("alignment", null,
2421 viewport.getAlignment().getSequences());
2422 if (viewport.getAlignment().getHeight() < 1)
2426 this.setClosed(true);
2427 } catch (Exception ex)
2440 protected void deleteGroups_actionPerformed(ActionEvent e)
2442 if (avc.deleteGroups())
2444 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2445 alignPanel.updateAnnotation();
2446 alignPanel.paintAlignment(true, true);
2457 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2459 SequenceGroup sg = new SequenceGroup();
2461 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2463 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2466 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2467 viewport.setSelectionGroup(sg);
2468 viewport.sendSelection();
2469 // JAL-2034 - should delegate to
2470 // alignPanel to decide if overview needs
2472 alignPanel.paintAlignment(false, false);
2473 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2483 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2485 if (viewport.cursorMode)
2487 alignPanel.getSeqPanel().keyboardNo1 = null;
2488 alignPanel.getSeqPanel().keyboardNo2 = null;
2490 viewport.setSelectionGroup(null);
2491 viewport.getColumnSelection().clear();
2492 viewport.setSelectionGroup(null);
2493 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2494 // JAL-2034 - should delegate to
2495 // alignPanel to decide if overview needs
2497 alignPanel.paintAlignment(false, false);
2498 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2499 viewport.sendSelection();
2509 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2511 SequenceGroup sg = viewport.getSelectionGroup();
2515 selectAllSequenceMenuItem_actionPerformed(null);
2520 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2522 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2524 // JAL-2034 - should delegate to
2525 // alignPanel to decide if overview needs
2528 alignPanel.paintAlignment(true, false);
2529 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2530 viewport.sendSelection();
2534 public void invertColSel_actionPerformed(ActionEvent e)
2536 viewport.invertColumnSelection();
2537 alignPanel.paintAlignment(true, false);
2538 viewport.sendSelection();
2548 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2550 trimAlignment(true);
2560 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2562 trimAlignment(false);
2565 void trimAlignment(boolean trimLeft)
2567 ColumnSelection colSel = viewport.getColumnSelection();
2570 if (!colSel.isEmpty())
2574 column = colSel.getMin();
2578 column = colSel.getMax();
2582 if (viewport.getSelectionGroup() != null)
2584 seqs = viewport.getSelectionGroup()
2585 .getSequencesAsArray(viewport.getHiddenRepSequences());
2589 seqs = viewport.getAlignment().getSequencesArray();
2592 TrimRegionCommand trimRegion;
2595 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2596 column, viewport.getAlignment());
2597 viewport.getRanges().setStartRes(0);
2601 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2602 column, viewport.getAlignment());
2605 setStatus(MessageManager
2606 .formatMessage("label.removed_columns", new String[]
2607 { Integer.valueOf(trimRegion.getSize()).toString() }));
2609 addHistoryItem(trimRegion);
2611 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2613 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2614 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2616 viewport.getAlignment().deleteGroup(sg);
2620 viewport.firePropertyChange("alignment", null,
2621 viewport.getAlignment().getSequences());
2632 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2634 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2637 if (viewport.getSelectionGroup() != null)
2639 seqs = viewport.getSelectionGroup()
2640 .getSequencesAsArray(viewport.getHiddenRepSequences());
2641 start = viewport.getSelectionGroup().getStartRes();
2642 end = viewport.getSelectionGroup().getEndRes();
2646 seqs = viewport.getAlignment().getSequencesArray();
2649 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2650 "Remove Gapped Columns", seqs, start, end,
2651 viewport.getAlignment());
2653 addHistoryItem(removeGapCols);
2655 setStatus(MessageManager
2656 .formatMessage("label.removed_empty_columns", new Object[]
2657 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2659 // This is to maintain viewport position on first residue
2660 // of first sequence
2661 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2662 ViewportRanges ranges = viewport.getRanges();
2663 int startRes = seq.findPosition(ranges.getStartRes());
2664 // ShiftList shifts;
2665 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2666 // edit.alColumnChanges=shifts.getInverse();
2667 // if (viewport.hasHiddenColumns)
2668 // viewport.getColumnSelection().compensateForEdits(shifts);
2669 ranges.setStartRes(seq.findIndex(startRes) - 1);
2670 viewport.firePropertyChange("alignment", null,
2671 viewport.getAlignment().getSequences());
2682 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2684 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2687 if (viewport.getSelectionGroup() != null)
2689 seqs = viewport.getSelectionGroup()
2690 .getSequencesAsArray(viewport.getHiddenRepSequences());
2691 start = viewport.getSelectionGroup().getStartRes();
2692 end = viewport.getSelectionGroup().getEndRes();
2696 seqs = viewport.getAlignment().getSequencesArray();
2699 // This is to maintain viewport position on first residue
2700 // of first sequence
2701 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2702 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2704 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2705 viewport.getAlignment()));
2707 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2709 viewport.firePropertyChange("alignment", null,
2710 viewport.getAlignment().getSequences());
2721 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2723 viewport.setPadGaps(padGapsMenuitem.isSelected());
2724 viewport.firePropertyChange("alignment", null,
2725 viewport.getAlignment().getSequences());
2735 public void findMenuItem_actionPerformed(ActionEvent e)
2741 * Create a new view of the current alignment.
2744 public void newView_actionPerformed(ActionEvent e)
2746 newView(null, true);
2750 * Creates and shows a new view of the current alignment.
2753 * title of newly created view; if null, one will be generated
2754 * @param copyAnnotation
2755 * if true then duplicate all annnotation, groups and settings
2756 * @return new alignment panel, already displayed.
2758 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2761 * Create a new AlignmentPanel (with its own, new Viewport)
2763 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel);
2764 if (!copyAnnotation)
2767 * remove all groups and annotation except for the automatic stuff
2769 newap.av.getAlignment().deleteAllGroups();
2770 newap.av.getAlignment().deleteAllAnnotations(false);
2773 newap.av.setGatherViewsHere(false);
2775 if (viewport.viewName == null)
2777 viewport.viewName = MessageManager
2778 .getString("label.view_name_original");
2782 * Views share the same edits undo and redo stacks
2784 newap.av.setHistoryList(viewport.getHistoryList());
2785 newap.av.setRedoList(viewport.getRedoList());
2788 * Views share the same mappings; need to deregister any new mappings
2789 * created by copyAlignPanel, and register the new reference to the shared
2792 newap.av.replaceMappings(viewport.getAlignment());
2795 * start up cDNA consensus (if applicable) now mappings are in place
2797 if (newap.av.initComplementConsensus())
2799 newap.refresh(true); // adjust layout of annotations
2802 newap.av.viewName = getNewViewName(viewTitle);
2804 addAlignmentPanel(newap, true);
2805 newap.alignmentChanged();
2807 if (alignPanels.size() == 2)
2809 viewport.setGatherViewsHere(true);
2811 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2816 * Make a new name for the view, ensuring it is unique within the current
2817 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2818 * these now use viewId. Unique view names are still desirable for usability.)
2823 protected String getNewViewName(String viewTitle)
2825 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2826 boolean addFirstIndex = false;
2827 if (viewTitle == null || viewTitle.trim().length() == 0)
2829 viewTitle = MessageManager.getString("action.view");
2830 addFirstIndex = true;
2834 index = 1;// we count from 1 if given a specific name
2836 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2838 List<Component> comps = PaintRefresher.components
2839 .get(viewport.getSequenceSetId());
2841 List<String> existingNames = getExistingViewNames(comps);
2843 while (existingNames.contains(newViewName))
2845 newViewName = viewTitle + " " + (++index);
2851 * Returns a list of distinct view names found in the given list of
2852 * components. View names are held on the viewport of an AlignmentPanel.
2857 protected List<String> getExistingViewNames(List<Component> comps)
2859 List<String> existingNames = new ArrayList<>();
2860 for (Component comp : comps)
2862 if (comp instanceof AlignmentPanel)
2864 AlignmentPanel ap = (AlignmentPanel) comp;
2865 if (!existingNames.contains(ap.av.viewName))
2867 existingNames.add(ap.av.viewName);
2871 return existingNames;
2875 * Explode tabbed views into separate windows.
2878 public void expandViews_actionPerformed(ActionEvent e)
2880 Desktop.explodeViews(this);
2884 * Gather views in separate windows back into a tabbed presentation.
2887 public void gatherViews_actionPerformed(ActionEvent e)
2889 Desktop.instance.gatherViews(this);
2899 public void font_actionPerformed(ActionEvent e)
2901 new FontChooser(alignPanel);
2911 protected void seqLimit_actionPerformed(ActionEvent e)
2913 viewport.setShowJVSuffix(seqLimits.isSelected());
2915 alignPanel.getIdPanel().getIdCanvas()
2916 .setPreferredSize(alignPanel.calculateIdWidth());
2917 alignPanel.paintAlignment(true, false);
2921 public void idRightAlign_actionPerformed(ActionEvent e)
2923 viewport.setRightAlignIds(idRightAlign.isSelected());
2924 alignPanel.paintAlignment(false, false);
2928 public void centreColumnLabels_actionPerformed(ActionEvent e)
2930 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2931 alignPanel.paintAlignment(false, false);
2937 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2940 protected void followHighlight_actionPerformed()
2943 * Set the 'follow' flag on the Viewport (and scroll to position if now
2946 final boolean state = this.followHighlightMenuItem.getState();
2947 viewport.setFollowHighlight(state);
2950 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2961 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2963 viewport.setColourText(colourTextMenuItem.isSelected());
2964 alignPanel.paintAlignment(false, false);
2974 public void wrapMenuItem_actionPerformed(ActionEvent e)
2976 scaleAbove.setVisible(wrapMenuItem.isSelected());
2977 scaleLeft.setVisible(wrapMenuItem.isSelected());
2978 scaleRight.setVisible(wrapMenuItem.isSelected());
2979 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2980 alignPanel.updateLayout();
2984 public void showAllSeqs_actionPerformed(ActionEvent e)
2986 viewport.showAllHiddenSeqs();
2990 public void showAllColumns_actionPerformed(ActionEvent e)
2992 viewport.showAllHiddenColumns();
2993 alignPanel.paintAlignment(true, true);
2994 viewport.sendSelection();
2998 public void hideSelSequences_actionPerformed(ActionEvent e)
3000 viewport.hideAllSelectedSeqs();
3004 * called by key handler and the hide all/show all menu items
3009 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3012 boolean hide = false;
3013 SequenceGroup sg = viewport.getSelectionGroup();
3014 if (!toggleSeqs && !toggleCols)
3016 // Hide everything by the current selection - this is a hack - we do the
3017 // invert and then hide
3018 // first check that there will be visible columns after the invert.
3019 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3020 && sg.getStartRes() <= sg.getEndRes()))
3022 // now invert the sequence set, if required - empty selection implies
3023 // that no hiding is required.
3026 invertSequenceMenuItem_actionPerformed(null);
3027 sg = viewport.getSelectionGroup();
3031 viewport.expandColSelection(sg, true);
3032 // finally invert the column selection and get the new sequence
3034 invertColSel_actionPerformed(null);
3041 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3043 hideSelSequences_actionPerformed(null);
3046 else if (!(toggleCols && viewport.hasSelectedColumns()))
3048 showAllSeqs_actionPerformed(null);
3054 if (viewport.hasSelectedColumns())
3056 hideSelColumns_actionPerformed(null);
3059 viewport.setSelectionGroup(sg);
3064 showAllColumns_actionPerformed(null);
3073 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3074 * event.ActionEvent)
3077 public void hideAllButSelection_actionPerformed(ActionEvent e)
3079 toggleHiddenRegions(false, false);
3080 viewport.sendSelection();
3087 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3091 public void hideAllSelection_actionPerformed(ActionEvent e)
3093 SequenceGroup sg = viewport.getSelectionGroup();
3094 viewport.expandColSelection(sg, false);
3095 viewport.hideAllSelectedSeqs();
3096 viewport.hideSelectedColumns();
3097 alignPanel.paintAlignment(true, true);
3098 viewport.sendSelection();
3105 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3109 public void showAllhidden_actionPerformed(ActionEvent e)
3111 viewport.showAllHiddenColumns();
3112 viewport.showAllHiddenSeqs();
3113 alignPanel.paintAlignment(true, true);
3114 viewport.sendSelection();
3118 public void hideSelColumns_actionPerformed(ActionEvent e)
3120 viewport.hideSelectedColumns();
3121 alignPanel.paintAlignment(true, true);
3122 viewport.sendSelection();
3126 public void hiddenMarkers_actionPerformed(ActionEvent e)
3128 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3139 protected void scaleAbove_actionPerformed(ActionEvent e)
3141 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3142 // TODO: do we actually need to update overview for scale above change ?
3143 alignPanel.paintAlignment(true, false);
3153 protected void scaleLeft_actionPerformed(ActionEvent e)
3155 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3156 alignPanel.paintAlignment(true, false);
3166 protected void scaleRight_actionPerformed(ActionEvent e)
3168 viewport.setScaleRightWrapped(scaleRight.isSelected());
3169 alignPanel.paintAlignment(true, false);
3179 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3181 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3182 alignPanel.paintAlignment(false, false);
3192 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3194 viewport.setShowText(viewTextMenuItem.isSelected());
3195 alignPanel.paintAlignment(false, false);
3205 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3207 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3208 alignPanel.paintAlignment(false, false);
3211 public FeatureSettings featureSettings;
3214 public FeatureSettingsControllerI getFeatureSettingsUI()
3216 return featureSettings;
3220 public void featureSettings_actionPerformed(ActionEvent e)
3222 if (featureSettings != null)
3224 featureSettings.close();
3225 featureSettings = null;
3227 if (!showSeqFeatures.isSelected())
3229 // make sure features are actually displayed
3230 showSeqFeatures.setSelected(true);
3231 showSeqFeatures_actionPerformed(null);
3233 featureSettings = new FeatureSettings(this);
3237 * Set or clear 'Show Sequence Features'
3243 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3245 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3246 alignPanel.paintAlignment(true, true);
3250 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3251 * the annotations panel as a whole.
3253 * The options to show/hide all annotations should be enabled when the panel
3254 * is shown, and disabled when the panel is hidden.
3259 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3261 final boolean setVisible = annotationPanelMenuItem.isSelected();
3262 viewport.setShowAnnotation(setVisible);
3263 this.showAllSeqAnnotations.setEnabled(setVisible);
3264 this.hideAllSeqAnnotations.setEnabled(setVisible);
3265 this.showAllAlAnnotations.setEnabled(setVisible);
3266 this.hideAllAlAnnotations.setEnabled(setVisible);
3267 alignPanel.updateLayout();
3271 public void alignmentProperties()
3274 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3277 String content = MessageManager.formatMessage("label.html_content",
3279 { contents.toString() });
3284 JLabel textLabel = new JLabel();
3285 textLabel.setText(content);
3286 textLabel.setBackground(Color.WHITE);
3288 pane = new JPanel(new BorderLayout());
3289 ((JPanel) pane).setOpaque(true);
3290 pane.setBackground(Color.WHITE);
3291 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3295 JEditorPane editPane = new JEditorPane("text/html", "");
3296 editPane.setEditable(false);
3297 editPane.setText(content);
3301 JInternalFrame frame = new JInternalFrame();
3303 frame.getContentPane().add(new JScrollPane(pane));
3305 Desktop.addInternalFrame(frame, MessageManager
3306 .formatMessage("label.alignment_properties", new Object[]
3307 { getTitle() }), 500, 400);
3317 public void overviewMenuItem_actionPerformed(ActionEvent e)
3319 if (alignPanel.overviewPanel != null)
3324 JInternalFrame frame = new JInternalFrame();
3325 final OverviewPanel overview = new OverviewPanel(alignPanel);
3326 frame.setContentPane(overview);
3327 Desktop.addInternalFrame(frame, MessageManager
3328 .formatMessage("label.overview_params", new Object[]
3329 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3332 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3333 frame.addInternalFrameListener(
3334 new javax.swing.event.InternalFrameAdapter()
3337 public void internalFrameClosed(
3338 javax.swing.event.InternalFrameEvent evt)
3341 alignPanel.setOverviewPanel(null);
3344 if (getKeyListeners().length > 0)
3346 frame.addKeyListener(getKeyListeners()[0]);
3349 alignPanel.setOverviewPanel(overview);
3353 public void textColour_actionPerformed()
3355 new TextColourChooser().chooseColour(alignPanel, null);
3359 * public void covariationColour_actionPerformed() {
3361 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3365 public void annotationColour_actionPerformed()
3367 new AnnotationColourChooser(viewport, alignPanel);
3371 public void annotationColumn_actionPerformed(ActionEvent e)
3373 new AnnotationColumnChooser(viewport, alignPanel);
3377 * Action on the user checking or unchecking the option to apply the selected
3378 * colour scheme to all groups. If unchecked, groups may have their own
3379 * independent colour schemes.
3384 public void applyToAllGroups_actionPerformed(boolean selected)
3386 viewport.setColourAppliesToAllGroups(selected);
3390 * Action on user selecting a colour from the colour menu
3393 * the name (not the menu item label!) of the colour scheme
3396 public void changeColour_actionPerformed(String name)
3399 * 'User Defined' opens a panel to configure or load a
3400 * user-defined colour scheme
3402 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3404 new UserDefinedColours(alignPanel);
3409 * otherwise set the chosen colour scheme (or null for 'None')
3411 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3412 viewport.getAlignment(), viewport.getHiddenRepSequences());
3417 * Actions on setting or changing the alignment colour scheme
3422 public void changeColour(ColourSchemeI cs)
3424 // TODO: pull up to controller method
3425 ColourMenuHelper.setColourSelected(colourMenu, cs);
3427 viewport.setGlobalColourScheme(cs);
3429 alignPanel.paintAlignment(true, true);
3433 * Show the PID threshold slider panel
3436 protected void modifyPID_actionPerformed()
3438 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3439 alignPanel.getViewName());
3440 SliderPanel.showPIDSlider();
3444 * Show the Conservation slider panel
3447 protected void modifyConservation_actionPerformed()
3449 SliderPanel.setConservationSlider(alignPanel,
3450 viewport.getResidueShading(), alignPanel.getViewName());
3451 SliderPanel.showConservationSlider();
3455 * Action on selecting or deselecting (Colour) By Conservation
3458 public void conservationMenuItem_actionPerformed(boolean selected)
3460 modifyConservation.setEnabled(selected);
3461 viewport.setConservationSelected(selected);
3462 viewport.getResidueShading().setConservationApplied(selected);
3464 changeColour(viewport.getGlobalColourScheme());
3467 modifyConservation_actionPerformed();
3471 SliderPanel.hideConservationSlider();
3476 * Action on selecting or deselecting (Colour) Above PID Threshold
3479 public void abovePIDThreshold_actionPerformed(boolean selected)
3481 modifyPID.setEnabled(selected);
3482 viewport.setAbovePIDThreshold(selected);
3485 viewport.getResidueShading().setThreshold(0,
3486 viewport.isIgnoreGapsConsensus());
3489 changeColour(viewport.getGlobalColourScheme());
3492 modifyPID_actionPerformed();
3496 SliderPanel.hidePIDSlider();
3507 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3509 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3510 AlignmentSorter.sortByPID(viewport.getAlignment(),
3511 viewport.getAlignment().getSequenceAt(0));
3512 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3513 viewport.getAlignment()));
3514 alignPanel.paintAlignment(true, false);
3524 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3526 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3527 AlignmentSorter.sortByID(viewport.getAlignment());
3529 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3530 alignPanel.paintAlignment(true, false);
3540 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3542 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3543 AlignmentSorter.sortByLength(viewport.getAlignment());
3544 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3545 viewport.getAlignment()));
3546 alignPanel.paintAlignment(true, false);
3556 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3558 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3559 AlignmentSorter.sortByGroup(viewport.getAlignment());
3560 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3561 viewport.getAlignment()));
3563 alignPanel.paintAlignment(true, false);
3573 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3575 new RedundancyPanel(alignPanel, this);
3585 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3587 if ((viewport.getSelectionGroup() == null)
3588 || (viewport.getSelectionGroup().getSize() < 2))
3590 JvOptionPane.showInternalMessageDialog(this,
3591 MessageManager.getString(
3592 "label.you_must_select_least_two_sequences"),
3593 MessageManager.getString("label.invalid_selection"),
3594 JvOptionPane.WARNING_MESSAGE);
3598 JInternalFrame frame = new JInternalFrame();
3599 frame.setContentPane(new PairwiseAlignPanel(viewport));
3600 Desktop.addInternalFrame(frame,
3601 MessageManager.getString("action.pairwise_alignment"), 600,
3607 public void autoCalculate_actionPerformed(ActionEvent e)
3609 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3610 if (viewport.autoCalculateConsensus)
3612 viewport.firePropertyChange("alignment", null,
3613 viewport.getAlignment().getSequences());
3618 public void sortByTreeOption_actionPerformed(ActionEvent e)
3620 viewport.sortByTree = sortByTree.isSelected();
3624 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3626 viewport.followSelection = listenToViewSelections.isSelected();
3630 * Constructs a tree panel and adds it to the desktop
3633 * tree type (NJ or AV)
3635 * name of score model used to compute the tree
3637 * parameters for the distance or similarity calculation
3639 void newTreePanel(String type, String modelName,
3640 SimilarityParamsI options)
3642 String frameTitle = "";
3645 boolean onSelection = false;
3646 if (viewport.getSelectionGroup() != null
3647 && viewport.getSelectionGroup().getSize() > 0)
3649 SequenceGroup sg = viewport.getSelectionGroup();
3651 /* Decide if the selection is a column region */
3652 for (SequenceI _s : sg.getSequences())
3654 if (_s.getLength() < sg.getEndRes())
3656 JvOptionPane.showMessageDialog(Desktop.desktop,
3657 MessageManager.getString(
3658 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3659 MessageManager.getString(
3660 "label.sequences_selection_not_aligned"),
3661 JvOptionPane.WARNING_MESSAGE);
3670 if (viewport.getAlignment().getHeight() < 2)
3676 tp = new TreePanel(alignPanel, type, modelName, options);
3677 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3679 frameTitle += " from ";
3681 if (viewport.viewName != null)
3683 frameTitle += viewport.viewName + " of ";
3686 frameTitle += this.title;
3688 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3699 public void addSortByOrderMenuItem(String title,
3700 final AlignmentOrder order)
3702 final JMenuItem item = new JMenuItem(MessageManager
3703 .formatMessage("action.by_title_param", new Object[]
3706 item.addActionListener(new java.awt.event.ActionListener()
3709 public void actionPerformed(ActionEvent e)
3711 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3713 // TODO: JBPNote - have to map order entries to curent SequenceI
3715 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3717 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3718 viewport.getAlignment()));
3720 alignPanel.paintAlignment(true, false);
3726 * Add a new sort by annotation score menu item
3729 * the menu to add the option to
3731 * the label used to retrieve scores for each sequence on the
3734 public void addSortByAnnotScoreMenuItem(JMenu sort,
3735 final String scoreLabel)
3737 final JMenuItem item = new JMenuItem(scoreLabel);
3739 item.addActionListener(new java.awt.event.ActionListener()
3742 public void actionPerformed(ActionEvent e)
3744 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3745 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3746 viewport.getAlignment());// ,viewport.getSelectionGroup());
3747 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3748 viewport.getAlignment()));
3749 alignPanel.paintAlignment(true, false);
3755 * last hash for alignment's annotation array - used to minimise cost of
3758 protected int _annotationScoreVectorHash;
3761 * search the alignment and rebuild the sort by annotation score submenu the
3762 * last alignment annotation vector hash is stored to minimize cost of
3763 * rebuilding in subsequence calls.
3767 public void buildSortByAnnotationScoresMenu()
3769 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3774 if (viewport.getAlignment().getAlignmentAnnotation()
3775 .hashCode() != _annotationScoreVectorHash)
3777 sortByAnnotScore.removeAll();
3778 // almost certainly a quicker way to do this - but we keep it simple
3779 Hashtable scoreSorts = new Hashtable();
3780 AlignmentAnnotation aann[];
3781 for (SequenceI sqa : viewport.getAlignment().getSequences())
3783 aann = sqa.getAnnotation();
3784 for (int i = 0; aann != null && i < aann.length; i++)
3786 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3788 scoreSorts.put(aann[i].label, aann[i].label);
3792 Enumeration labels = scoreSorts.keys();
3793 while (labels.hasMoreElements())
3795 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3796 (String) labels.nextElement());
3798 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3801 _annotationScoreVectorHash = viewport.getAlignment()
3802 .getAlignmentAnnotation().hashCode();
3807 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3808 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3809 * call. Listeners are added to remove the menu item when the treePanel is
3810 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3814 public void buildTreeSortMenu()
3816 sortByTreeMenu.removeAll();
3818 List<Component> comps = PaintRefresher.components
3819 .get(viewport.getSequenceSetId());
3820 List<TreePanel> treePanels = new ArrayList<>();
3821 for (Component comp : comps)
3823 if (comp instanceof TreePanel)
3825 treePanels.add((TreePanel) comp);
3829 if (treePanels.size() < 1)
3831 sortByTreeMenu.setVisible(false);
3835 sortByTreeMenu.setVisible(true);
3837 for (final TreePanel tp : treePanels)
3839 final JMenuItem item = new JMenuItem(tp.getTitle());
3840 item.addActionListener(new java.awt.event.ActionListener()
3843 public void actionPerformed(ActionEvent e)
3845 tp.sortByTree_actionPerformed();
3846 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3851 sortByTreeMenu.add(item);
3855 public boolean sortBy(AlignmentOrder alorder, String undoname)
3857 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3858 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3859 if (undoname != null)
3861 addHistoryItem(new OrderCommand(undoname, oldOrder,
3862 viewport.getAlignment()));
3864 alignPanel.paintAlignment(true, false);
3869 * Work out whether the whole set of sequences or just the selected set will
3870 * be submitted for multiple alignment.
3873 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3875 // Now, check we have enough sequences
3876 AlignmentView msa = null;
3878 if ((viewport.getSelectionGroup() != null)
3879 && (viewport.getSelectionGroup().getSize() > 1))
3881 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3882 // some common interface!
3884 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3885 * SequenceI[sz = seqs.getSize(false)];
3887 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3888 * seqs.getSequenceAt(i); }
3890 msa = viewport.getAlignmentView(true);
3892 else if (viewport.getSelectionGroup() != null
3893 && viewport.getSelectionGroup().getSize() == 1)
3895 int option = JvOptionPane.showConfirmDialog(this,
3896 MessageManager.getString("warn.oneseq_msainput_selection"),
3897 MessageManager.getString("label.invalid_selection"),
3898 JvOptionPane.OK_CANCEL_OPTION);
3899 if (option == JvOptionPane.OK_OPTION)
3901 msa = viewport.getAlignmentView(false);
3906 msa = viewport.getAlignmentView(false);
3912 * Decides what is submitted to a secondary structure prediction service: the
3913 * first sequence in the alignment, or in the current selection, or, if the
3914 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3915 * region or the whole alignment. (where the first sequence in the set is the
3916 * one that the prediction will be for).
3918 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3920 AlignmentView seqs = null;
3922 if ((viewport.getSelectionGroup() != null)
3923 && (viewport.getSelectionGroup().getSize() > 0))
3925 seqs = viewport.getAlignmentView(true);
3929 seqs = viewport.getAlignmentView(false);
3931 // limit sequences - JBPNote in future - could spawn multiple prediction
3933 // TODO: viewport.getAlignment().isAligned is a global state - the local
3934 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3935 if (!viewport.getAlignment().isAligned(false))
3937 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3938 // TODO: if seqs.getSequences().length>1 then should really have warned
3952 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3954 // Pick the tree file
3955 JalviewFileChooser chooser = new JalviewFileChooser(
3956 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3957 chooser.setFileView(new JalviewFileView());
3958 chooser.setDialogTitle(
3959 MessageManager.getString("label.select_newick_like_tree_file"));
3960 chooser.setToolTipText(
3961 MessageManager.getString("label.load_tree_file"));
3963 chooser.response(new jalview.util.dialogrunner.RunResponse(
3964 JalviewFileChooser.APPROVE_OPTION)
3969 String filePath = chooser.getSelectedFile().getPath();
3970 Cache.setProperty("LAST_DIRECTORY", filePath);
3971 NewickFile fin = null;
3974 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
3975 DataSourceType.FILE));
3976 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
3977 } catch (Exception ex)
3979 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
3981 .getString("label.problem_reading_tree_file"),
3982 JvOptionPane.WARNING_MESSAGE);
3983 ex.printStackTrace();
3985 if (fin != null && fin.hasWarningMessage())
3987 JvOptionPane.showMessageDialog(Desktop.desktop,
3988 fin.getWarningMessage(),
3989 MessageManager.getString(
3990 "label.possible_problem_with_tree_file"),
3991 JvOptionPane.WARNING_MESSAGE);
3994 }).openDialog(this);
3997 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
3999 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4002 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4003 int h, int x, int y)
4005 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4009 * Add a treeviewer for the tree extracted from a Newick file object to the
4010 * current alignment view
4017 * Associated alignment input data (or null)
4026 * @return TreePanel handle
4028 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4029 AlignmentView input, int w, int h, int x, int y)
4031 TreePanel tp = null;
4037 if (nf.getTree() != null)
4039 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4045 tp.setLocation(x, y);
4048 Desktop.addInternalFrame(tp, treeTitle, w, h);
4050 } catch (Exception ex)
4052 ex.printStackTrace();
4058 private boolean buildingMenu = false;
4061 * Generates menu items and listener event actions for web service clients
4064 public void BuildWebServiceMenu()
4066 while (buildingMenu)
4070 System.err.println("Waiting for building menu to finish.");
4072 } catch (Exception e)
4076 final AlignFrame me = this;
4077 buildingMenu = true;
4078 new Thread(new Runnable()
4083 final List<JMenuItem> legacyItems = new ArrayList<>();
4086 // System.err.println("Building ws menu again "
4087 // + Thread.currentThread());
4088 // TODO: add support for context dependent disabling of services based
4090 // alignment and current selection
4091 // TODO: add additional serviceHandle parameter to specify abstract
4093 // class independently of AbstractName
4094 // TODO: add in rediscovery GUI function to restart discoverer
4095 // TODO: group services by location as well as function and/or
4097 // object broker mechanism.
4098 final Vector<JMenu> wsmenu = new Vector<>();
4099 final IProgressIndicator af = me;
4102 * do not i18n these strings - they are hard-coded in class
4103 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4104 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4106 final JMenu msawsmenu = new JMenu("Alignment");
4107 final JMenu secstrmenu = new JMenu(
4108 "Secondary Structure Prediction");
4109 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4110 final JMenu analymenu = new JMenu("Analysis");
4111 final JMenu dismenu = new JMenu("Protein Disorder");
4112 // JAL-940 - only show secondary structure prediction services from
4113 // the legacy server
4114 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4116 Discoverer.services != null && (Discoverer.services.size() > 0))
4118 // TODO: refactor to allow list of AbstractName/Handler bindings to
4120 // stored or retrieved from elsewhere
4121 // No MSAWS used any more:
4122 // Vector msaws = null; // (Vector)
4123 // Discoverer.services.get("MsaWS");
4124 Vector secstrpr = (Vector) Discoverer.services
4126 if (secstrpr != null)
4128 // Add any secondary structure prediction services
4129 for (int i = 0, j = secstrpr.size(); i < j; i++)
4131 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4133 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4134 .getServiceClient(sh);
4135 int p = secstrmenu.getItemCount();
4136 impl.attachWSMenuEntry(secstrmenu, me);
4137 int q = secstrmenu.getItemCount();
4138 for (int litm = p; litm < q; litm++)
4140 legacyItems.add(secstrmenu.getItem(litm));
4146 // Add all submenus in the order they should appear on the web
4148 wsmenu.add(msawsmenu);
4149 wsmenu.add(secstrmenu);
4150 wsmenu.add(dismenu);
4151 wsmenu.add(analymenu);
4152 // No search services yet
4153 // wsmenu.add(seqsrchmenu);
4155 javax.swing.SwingUtilities.invokeLater(new Runnable()
4162 webService.removeAll();
4163 // first, add discovered services onto the webservices menu
4164 if (wsmenu.size() > 0)
4166 for (int i = 0, j = wsmenu.size(); i < j; i++)
4168 webService.add(wsmenu.get(i));
4173 webService.add(me.webServiceNoServices);
4175 // TODO: move into separate menu builder class.
4176 boolean new_sspred = false;
4177 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4179 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4180 if (jws2servs != null)
4182 if (jws2servs.hasServices())
4184 jws2servs.attachWSMenuEntry(webService, me);
4185 for (Jws2Instance sv : jws2servs.getServices())
4187 if (sv.description.toLowerCase().contains("jpred"))
4189 for (JMenuItem jmi : legacyItems)
4191 jmi.setVisible(false);
4197 if (jws2servs.isRunning())
4199 JMenuItem tm = new JMenuItem(
4200 "Still discovering JABA Services");
4201 tm.setEnabled(false);
4206 build_urlServiceMenu(me.webService);
4207 build_fetchdbmenu(webService);
4208 for (JMenu item : wsmenu)
4210 if (item.getItemCount() == 0)
4212 item.setEnabled(false);
4216 item.setEnabled(true);
4219 } catch (Exception e)
4222 "Exception during web service menu building process.",
4227 } catch (Exception e)
4230 buildingMenu = false;
4237 * construct any groupURL type service menu entries.
4241 private void build_urlServiceMenu(JMenu webService)
4243 // TODO: remove this code when 2.7 is released
4244 // DEBUG - alignmentView
4246 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4247 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4249 * @Override public void actionPerformed(ActionEvent e) {
4250 * jalview.datamodel.AlignmentView
4251 * .testSelectionViews(af.viewport.getAlignment(),
4252 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4254 * }); webService.add(testAlView);
4256 // TODO: refactor to RestClient discoverer and merge menu entries for
4257 // rest-style services with other types of analysis/calculation service
4258 // SHmmr test client - still being implemented.
4259 // DEBUG - alignmentView
4261 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4264 client.attachWSMenuEntry(
4265 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4271 * Searches the alignment sequences for xRefs and builds the Show
4272 * Cross-References menu (formerly called Show Products), with database
4273 * sources for which cross-references are found (protein sources for a
4274 * nucleotide alignment and vice versa)
4276 * @return true if Show Cross-references menu should be enabled
4278 public boolean canShowProducts()
4280 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4281 AlignmentI dataset = viewport.getAlignment().getDataset();
4283 showProducts.removeAll();
4284 final boolean dna = viewport.getAlignment().isNucleotide();
4286 if (seqs == null || seqs.length == 0)
4288 // nothing to see here.
4292 boolean showp = false;
4295 List<String> ptypes = new CrossRef(seqs, dataset)
4296 .findXrefSourcesForSequences(dna);
4298 for (final String source : ptypes)
4301 final AlignFrame af = this;
4302 JMenuItem xtype = new JMenuItem(source);
4303 xtype.addActionListener(new ActionListener()
4306 public void actionPerformed(ActionEvent e)
4308 showProductsFor(af.viewport.getSequenceSelection(), dna,
4312 showProducts.add(xtype);
4314 showProducts.setVisible(showp);
4315 showProducts.setEnabled(showp);
4316 } catch (Exception e)
4319 "canShowProducts threw an exception - please report to help@jalview.org",
4327 * Finds and displays cross-references for the selected sequences (protein
4328 * products for nucleotide sequences, dna coding sequences for peptides).
4331 * the sequences to show cross-references for
4333 * true if from a nucleotide alignment (so showing proteins)
4335 * the database to show cross-references for
4337 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4338 final String source)
4340 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4345 * Construct and display a new frame containing the translation of this
4346 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4349 public void showTranslation_actionPerformed(ActionEvent e)
4351 AlignmentI al = null;
4354 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4356 al = dna.translateCdna();
4357 } catch (Exception ex)
4359 jalview.bin.Cache.log.error(
4360 "Exception during translation. Please report this !", ex);
4361 final String msg = MessageManager.getString(
4362 "label.error_when_translating_sequences_submit_bug_report");
4363 final String errorTitle = MessageManager
4364 .getString("label.implementation_error")
4365 + MessageManager.getString("label.translation_failed");
4366 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4367 JvOptionPane.ERROR_MESSAGE);
4370 if (al == null || al.getHeight() == 0)
4372 final String msg = MessageManager.getString(
4373 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4374 final String errorTitle = MessageManager
4375 .getString("label.translation_failed");
4376 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4377 JvOptionPane.WARNING_MESSAGE);
4381 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4382 af.setFileFormat(this.currentFileFormat);
4383 final String newTitle = MessageManager
4384 .formatMessage("label.translation_of_params", new Object[]
4385 { this.getTitle() });
4386 af.setTitle(newTitle);
4387 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4389 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4390 viewport.openSplitFrame(af, new Alignment(seqs));
4394 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4401 * Set the file format
4405 public void setFileFormat(FileFormatI format)
4407 this.currentFileFormat = format;
4411 * Try to load a features file onto the alignment.
4414 * contents or path to retrieve file or a File object
4416 * access mode of file (see jalview.io.AlignFile)
4417 * @return true if features file was parsed correctly.
4419 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4422 return avc.parseFeaturesFile(file, sourceType,
4423 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4428 public void refreshFeatureUI(boolean enableIfNecessary)
4430 // note - currently this is only still here rather than in the controller
4431 // because of the featureSettings hard reference that is yet to be
4433 if (enableIfNecessary)
4435 viewport.setShowSequenceFeatures(true);
4436 showSeqFeatures.setSelected(true);
4442 public void dragEnter(DropTargetDragEvent evt)
4447 public void dragExit(DropTargetEvent evt)
4452 public void dragOver(DropTargetDragEvent evt)
4457 public void dropActionChanged(DropTargetDragEvent evt)
4462 public void drop(DropTargetDropEvent evt)
4464 // JAL-1552 - acceptDrop required before getTransferable call for
4465 // Java's Transferable for native dnd
4466 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4467 Transferable t = evt.getTransferable();
4469 final AlignFrame thisaf = this;
4470 final List<Object> files = new ArrayList<>();
4471 List<DataSourceType> protocols = new ArrayList<>();
4475 Desktop.transferFromDropTarget(files, protocols, evt, t);
4476 } catch (Exception e)
4478 e.printStackTrace();
4482 new Thread(new Runnable()
4489 // check to see if any of these files have names matching sequences
4492 SequenceIdMatcher idm = new SequenceIdMatcher(
4493 viewport.getAlignment().getSequencesArray());
4495 * Object[] { String,SequenceI}
4497 ArrayList<Object[]> filesmatched = new ArrayList<>();
4498 ArrayList<Object> filesnotmatched = new ArrayList<>();
4499 for (int i = 0; i < files.size(); i++)
4502 Object file = files.get(i);
4503 String fileName = file.toString();
4505 DataSourceType protocol = (file instanceof File
4506 ? DataSourceType.FILE
4507 : FormatAdapter.checkProtocol(fileName));
4508 if (protocol == DataSourceType.FILE)
4510 File fl = (file instanceof File ? (File) file
4511 : new File(fileName));
4512 pdbfn = fl.getName();
4514 else if (protocol == DataSourceType.URL)
4516 URL url = new URL(fileName);
4517 pdbfn = url.getFile();
4519 if (pdbfn.length() > 0)
4521 // attempt to find a match in the alignment
4522 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4523 int l = 0, c = pdbfn.indexOf(".");
4524 while (mtch == null && c != -1)
4529 } while ((c = pdbfn.indexOf(".", l)) > l);
4532 pdbfn = pdbfn.substring(0, l);
4534 mtch = idm.findAllIdMatches(pdbfn);
4541 type = new IdentifyFile().identify(file, protocol);
4542 } catch (Exception ex)
4546 if (type != null && type.isStructureFile())
4548 filesmatched.add(new Object[] { file, protocol, mtch });
4552 // File wasn't named like one of the sequences or wasn't a PDB
4554 filesnotmatched.add(file);
4558 if (filesmatched.size() > 0)
4560 boolean autoAssociate = Cache
4561 .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4564 String msg = MessageManager.formatMessage(
4565 "label.automatically_associate_structure_files_with_sequences_same_name",
4567 { Integer.valueOf(filesmatched.size())
4569 String ttl = MessageManager.getString(
4570 "label.automatically_associate_structure_files_by_name");
4571 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4572 ttl, JvOptionPane.YES_NO_OPTION);
4573 autoAssociate = choice == JvOptionPane.YES_OPTION;
4577 for (Object[] fm : filesmatched)
4579 // try and associate
4580 // TODO: may want to set a standard ID naming formalism for
4581 // associating PDB files which have no IDs.
4582 for (SequenceI toassoc : (SequenceI[]) fm[2])
4584 PDBEntry pe = new AssociatePdbFileWithSeq()
4585 .associatePdbWithSeq(fm[0].toString(),
4586 (DataSourceType) fm[1], toassoc, false,
4590 System.err.println("Associated file : "
4591 + (fm[0].toString()) + " with "
4592 + toassoc.getDisplayId(true));
4596 // TODO: do we need to update overview ? only if features are
4598 alignPanel.paintAlignment(true, false);
4604 * add declined structures as sequences
4606 for (Object[] o : filesmatched)
4608 filesnotmatched.add(o[0]);
4612 if (filesnotmatched.size() > 0)
4614 if (assocfiles > 0 && (Cache.getDefault(
4615 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4616 || JvOptionPane.showConfirmDialog(thisaf,
4617 "<html>" + MessageManager.formatMessage(
4618 "label.ignore_unmatched_dropped_files_info",
4621 filesnotmatched.size())
4624 MessageManager.getString(
4625 "label.ignore_unmatched_dropped_files"),
4626 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4630 for (Object fn : filesnotmatched)
4632 loadJalviewDataFile(fn, null, null, null);
4636 } catch (Exception ex)
4638 ex.printStackTrace();
4646 * Attempt to load a "dropped" file or URL string, by testing in turn for
4648 * <li>an Annotation file</li>
4649 * <li>a JNet file</li>
4650 * <li>a features file</li>
4651 * <li>else try to interpret as an alignment file</li>
4655 * either a filename or a URL string.
4657 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4658 FileFormatI format, SequenceI assocSeq)
4660 // BH 2018 was String file
4663 if (sourceType == null)
4665 sourceType = FormatAdapter.checkProtocol(file);
4667 // if the file isn't identified, or not positively identified as some
4668 // other filetype (PFAM is default unidentified alignment file type) then
4669 // try to parse as annotation.
4670 boolean isAnnotation = (format == null
4671 || FileFormat.Pfam.equals(format))
4672 ? new AnnotationFile().annotateAlignmentView(viewport,
4678 // first see if its a T-COFFEE score file
4679 TCoffeeScoreFile tcf = null;
4682 tcf = new TCoffeeScoreFile(file, sourceType);
4685 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4689 new TCoffeeColourScheme(viewport.getAlignment()));
4690 isAnnotation = true;
4691 setStatus(MessageManager.getString(
4692 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4696 // some problem - if no warning its probable that the ID matching
4697 // process didn't work
4698 JvOptionPane.showMessageDialog(Desktop.desktop,
4699 tcf.getWarningMessage() == null
4700 ? MessageManager.getString(
4701 "label.check_file_matches_sequence_ids_alignment")
4702 : tcf.getWarningMessage(),
4703 MessageManager.getString(
4704 "label.problem_reading_tcoffee_score_file"),
4705 JvOptionPane.WARNING_MESSAGE);
4712 } catch (Exception x)
4715 "Exception when processing data source as T-COFFEE score file",
4721 // try to see if its a JNet 'concise' style annotation file *before*
4723 // try to parse it as a features file
4726 format = new IdentifyFile().identify(file, sourceType);
4728 if (FileFormat.ScoreMatrix == format)
4730 ScoreMatrixFile sm = new ScoreMatrixFile(
4731 new FileParse(file, sourceType));
4733 // todo: i18n this message
4734 setStatus(MessageManager.formatMessage(
4735 "label.successfully_loaded_matrix",
4736 sm.getMatrixName()));
4738 else if (FileFormat.Jnet.equals(format))
4740 JPredFile predictions = new JPredFile(file, sourceType);
4741 new JnetAnnotationMaker();
4742 JnetAnnotationMaker.add_annotation(predictions,
4743 viewport.getAlignment(), 0, false);
4744 viewport.getAlignment().setupJPredAlignment();
4745 isAnnotation = true;
4747 // else if (IdentifyFile.FeaturesFile.equals(format))
4748 else if (FileFormat.Features.equals(format))
4750 if (parseFeaturesFile(file, sourceType))
4752 alignPanel.paintAlignment(true, true);
4757 new FileLoader().LoadFile(viewport, file, sourceType, format);
4764 alignPanel.adjustAnnotationHeight();
4765 viewport.updateSequenceIdColours();
4766 buildSortByAnnotationScoresMenu();
4767 alignPanel.paintAlignment(true, true);
4769 } catch (Exception ex)
4771 ex.printStackTrace();
4772 } catch (OutOfMemoryError oom)
4777 } catch (Exception x)
4782 + (sourceType != null
4783 ? (sourceType == DataSourceType.PASTE
4785 : "using " + sourceType + " from "
4789 ? "(parsing as '" + format + "' file)"
4791 oom, Desktop.desktop);
4796 * Method invoked by the ChangeListener on the tabbed pane, in other words
4797 * when a different tabbed pane is selected by the user or programmatically.
4800 public void tabSelectionChanged(int index)
4804 alignPanel = alignPanels.get(index);
4805 viewport = alignPanel.av;
4806 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4807 setMenusFromViewport(viewport);
4811 * 'focus' any colour slider that is open to the selected viewport
4813 if (viewport.getConservationSelected())
4815 SliderPanel.setConservationSlider(alignPanel,
4816 viewport.getResidueShading(), alignPanel.getViewName());
4820 SliderPanel.hideConservationSlider();
4822 if (viewport.getAbovePIDThreshold())
4824 SliderPanel.setPIDSliderSource(alignPanel,
4825 viewport.getResidueShading(), alignPanel.getViewName());
4829 SliderPanel.hidePIDSlider();
4833 * If there is a frame linked to this one in a SplitPane, switch it to the
4834 * same view tab index. No infinite recursion of calls should happen, since
4835 * tabSelectionChanged() should not get invoked on setting the selected
4836 * index to an unchanged value. Guard against setting an invalid index
4837 * before the new view peer tab has been created.
4839 final AlignViewportI peer = viewport.getCodingComplement();
4842 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4843 .getAlignPanel().alignFrame;
4844 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4846 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4852 * On right mouse click on view tab, prompt for and set new view name.
4855 public void tabbedPane_mousePressed(MouseEvent e)
4857 if (e.isPopupTrigger())
4859 String msg = MessageManager.getString("label.enter_view_name");
4860 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
4861 String reply = JvOptionPane.showInputDialog(msg, ttl);
4865 viewport.viewName = reply;
4866 // TODO warn if reply is in getExistingViewNames()?
4867 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4872 public AlignViewport getCurrentView()
4878 * Open the dialog for regex description parsing.
4881 protected void extractScores_actionPerformed(ActionEvent e)
4883 ParseProperties pp = new jalview.analysis.ParseProperties(
4884 viewport.getAlignment());
4885 // TODO: verify regex and introduce GUI dialog for version 2.5
4886 // if (pp.getScoresFromDescription("col", "score column ",
4887 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4889 if (pp.getScoresFromDescription("description column",
4890 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4892 buildSortByAnnotationScoresMenu();
4900 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4904 protected void showDbRefs_actionPerformed(ActionEvent e)
4906 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4912 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4916 protected void showNpFeats_actionPerformed(ActionEvent e)
4918 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4922 * find the viewport amongst the tabs in this alignment frame and close that
4927 public boolean closeView(AlignViewportI av)
4931 this.closeMenuItem_actionPerformed(false);
4934 Component[] comp = tabbedPane.getComponents();
4935 for (int i = 0; comp != null && i < comp.length; i++)
4937 if (comp[i] instanceof AlignmentPanel)
4939 if (((AlignmentPanel) comp[i]).av == av)
4942 closeView((AlignmentPanel) comp[i]);
4950 protected void build_fetchdbmenu(JMenu webService)
4952 // Temporary hack - DBRef Fetcher always top level ws entry.
4953 // TODO We probably want to store a sequence database checklist in
4954 // preferences and have checkboxes.. rather than individual sources selected
4956 final JMenu rfetch = new JMenu(
4957 MessageManager.getString("action.fetch_db_references"));
4958 rfetch.setToolTipText(MessageManager.getString(
4959 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4960 webService.add(rfetch);
4962 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4963 MessageManager.getString("option.trim_retrieved_seqs"));
4964 trimrs.setToolTipText(
4965 MessageManager.getString("label.trim_retrieved_sequences"));
4967 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
4968 trimrs.addActionListener(new ActionListener()
4971 public void actionPerformed(ActionEvent e)
4973 trimrs.setSelected(trimrs.isSelected());
4974 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
4975 Boolean.valueOf(trimrs.isSelected()).toString());
4979 JMenuItem fetchr = new JMenuItem(
4980 MessageManager.getString("label.standard_databases"));
4981 fetchr.setToolTipText(
4982 MessageManager.getString("label.fetch_embl_uniprot"));
4983 fetchr.addActionListener(new ActionListener()
4987 public void actionPerformed(ActionEvent e)
4989 new Thread(new Runnable()
4994 boolean isNucleotide = alignPanel.alignFrame.getViewport()
4995 .getAlignment().isNucleotide();
4996 DBRefFetcher dbRefFetcher = new DBRefFetcher(
4997 alignPanel.av.getSequenceSelection(),
4998 alignPanel.alignFrame, null,
4999 alignPanel.alignFrame.featureSettings, isNucleotide);
5000 dbRefFetcher.addListener(new FetchFinishedListenerI()
5003 public void finished()
5005 AlignFrame.this.setMenusForViewport();
5008 dbRefFetcher.fetchDBRefs(false);
5016 new Thread(new Runnable()
5021 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5022 .getSequenceFetcherSingleton();
5023 javax.swing.SwingUtilities.invokeLater(new Runnable()
5028 String[] dbclasses = sf.getNonAlignmentSources();
5029 List<DbSourceProxy> otherdb;
5030 JMenu dfetch = new JMenu();
5031 JMenu ifetch = new JMenu();
5032 JMenuItem fetchr = null;
5033 int comp = 0, icomp = 0, mcomp = 15;
5034 String mname = null;
5036 for (String dbclass : dbclasses)
5038 otherdb = sf.getSourceProxy(dbclass);
5039 // add a single entry for this class, or submenu allowing 'fetch
5041 if (otherdb == null || otherdb.size() < 1)
5047 mname = "From " + dbclass;
5049 if (otherdb.size() == 1)
5051 final DbSourceProxy[] dassource = otherdb
5052 .toArray(new DbSourceProxy[0]);
5053 DbSourceProxy src = otherdb.get(0);
5054 fetchr = new JMenuItem(src.getDbSource());
5055 fetchr.addActionListener(new ActionListener()
5059 public void actionPerformed(ActionEvent e)
5061 new Thread(new Runnable()
5067 boolean isNucleotide = alignPanel.alignFrame
5068 .getViewport().getAlignment()
5070 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5071 alignPanel.av.getSequenceSelection(),
5072 alignPanel.alignFrame, dassource,
5073 alignPanel.alignFrame.featureSettings,
5076 .addListener(new FetchFinishedListenerI()
5079 public void finished()
5081 AlignFrame.this.setMenusForViewport();
5084 dbRefFetcher.fetchDBRefs(false);
5090 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5091 MessageManager.formatMessage(
5092 "label.fetch_retrieve_from", new Object[]
5093 { src.getDbName() })));
5099 final DbSourceProxy[] dassource = otherdb
5100 .toArray(new DbSourceProxy[0]);
5102 DbSourceProxy src = otherdb.get(0);
5103 fetchr = new JMenuItem(MessageManager
5104 .formatMessage("label.fetch_all_param", new Object[]
5105 { src.getDbSource() }));
5106 fetchr.addActionListener(new ActionListener()
5109 public void actionPerformed(ActionEvent e)
5111 new Thread(new Runnable()
5117 boolean isNucleotide = alignPanel.alignFrame
5118 .getViewport().getAlignment()
5120 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5121 alignPanel.av.getSequenceSelection(),
5122 alignPanel.alignFrame, dassource,
5123 alignPanel.alignFrame.featureSettings,
5126 .addListener(new FetchFinishedListenerI()
5129 public void finished()
5131 AlignFrame.this.setMenusForViewport();
5134 dbRefFetcher.fetchDBRefs(false);
5140 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5141 MessageManager.formatMessage(
5142 "label.fetch_retrieve_from_all_sources",
5144 { Integer.valueOf(otherdb.size())
5146 src.getDbSource(), src.getDbName() })));
5149 // and then build the rest of the individual menus
5150 ifetch = new JMenu(MessageManager.formatMessage(
5151 "label.source_from_db_source", new Object[]
5152 { src.getDbSource() }));
5154 String imname = null;
5156 for (DbSourceProxy sproxy : otherdb)
5158 String dbname = sproxy.getDbName();
5159 String sname = dbname.length() > 5
5160 ? dbname.substring(0, 5) + "..."
5162 String msname = dbname.length() > 10
5163 ? dbname.substring(0, 10) + "..."
5167 imname = MessageManager
5168 .formatMessage("label.from_msname", new Object[]
5171 fetchr = new JMenuItem(msname);
5172 final DbSourceProxy[] dassrc = { sproxy };
5173 fetchr.addActionListener(new ActionListener()
5177 public void actionPerformed(ActionEvent e)
5179 new Thread(new Runnable()
5185 boolean isNucleotide = alignPanel.alignFrame
5186 .getViewport().getAlignment()
5188 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5189 alignPanel.av.getSequenceSelection(),
5190 alignPanel.alignFrame, dassrc,
5191 alignPanel.alignFrame.featureSettings,
5194 .addListener(new FetchFinishedListenerI()
5197 public void finished()
5199 AlignFrame.this.setMenusForViewport();
5202 dbRefFetcher.fetchDBRefs(false);
5208 fetchr.setToolTipText(
5209 "<html>" + MessageManager.formatMessage(
5210 "label.fetch_retrieve_from", new Object[]
5214 if (++icomp >= mcomp || i == (otherdb.size()))
5216 ifetch.setText(MessageManager.formatMessage(
5217 "label.source_to_target", imname, sname));
5219 ifetch = new JMenu();
5227 if (comp >= mcomp || dbi >= (dbclasses.length))
5229 dfetch.setText(MessageManager.formatMessage(
5230 "label.source_to_target", mname, dbclass));
5232 dfetch = new JMenu();
5245 * Left justify the whole alignment.
5248 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5250 AlignmentI al = viewport.getAlignment();
5252 viewport.firePropertyChange("alignment", null, al);
5256 * Right justify the whole alignment.
5259 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5261 AlignmentI al = viewport.getAlignment();
5263 viewport.firePropertyChange("alignment", null, al);
5267 public void setShowSeqFeatures(boolean b)
5269 showSeqFeatures.setSelected(b);
5270 viewport.setShowSequenceFeatures(b);
5277 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5278 * awt.event.ActionEvent)
5281 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5283 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5284 alignPanel.paintAlignment(false, false);
5291 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5295 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5297 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5298 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5306 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5307 * .event.ActionEvent)
5310 protected void showGroupConservation_actionPerformed(ActionEvent e)
5312 viewport.setShowGroupConservation(showGroupConservation.getState());
5313 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5320 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5321 * .event.ActionEvent)
5324 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5326 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5327 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5334 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5335 * .event.ActionEvent)
5338 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5340 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5341 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5345 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5347 showSequenceLogo.setState(true);
5348 viewport.setShowSequenceLogo(true);
5349 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5350 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5354 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5356 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5363 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5364 * .event.ActionEvent)
5367 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5369 if (avc.makeGroupsFromSelection())
5371 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5372 alignPanel.updateAnnotation();
5373 alignPanel.paintAlignment(true, true);
5377 public void clearAlignmentSeqRep()
5379 // TODO refactor alignmentseqrep to controller
5380 if (viewport.getAlignment().hasSeqrep())
5382 viewport.getAlignment().setSeqrep(null);
5383 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5384 alignPanel.updateAnnotation();
5385 alignPanel.paintAlignment(true, true);
5390 protected void createGroup_actionPerformed(ActionEvent e)
5392 if (avc.createGroup())
5394 alignPanel.alignmentChanged();
5399 protected void unGroup_actionPerformed(ActionEvent e)
5403 alignPanel.alignmentChanged();
5408 * make the given alignmentPanel the currently selected tab
5410 * @param alignmentPanel
5412 public void setDisplayedView(AlignmentPanel alignmentPanel)
5414 if (!viewport.getSequenceSetId()
5415 .equals(alignmentPanel.av.getSequenceSetId()))
5417 throw new Error(MessageManager.getString(
5418 "error.implementation_error_cannot_show_view_alignment_frame"));
5420 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5421 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5423 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5428 * Action on selection of menu options to Show or Hide annotations.
5431 * @param forSequences
5432 * update sequence-related annotations
5433 * @param forAlignment
5434 * update non-sequence-related annotations
5437 protected void setAnnotationsVisibility(boolean visible,
5438 boolean forSequences, boolean forAlignment)
5440 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5441 .getAlignmentAnnotation();
5446 for (AlignmentAnnotation aa : anns)
5449 * don't display non-positional annotations on an alignment
5451 if (aa.annotations == null)
5455 boolean apply = (aa.sequenceRef == null && forAlignment)
5456 || (aa.sequenceRef != null && forSequences);
5459 aa.visible = visible;
5462 alignPanel.validateAnnotationDimensions(true);
5463 alignPanel.alignmentChanged();
5467 * Store selected annotation sort order for the view and repaint.
5470 protected void sortAnnotations_actionPerformed()
5472 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5474 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5475 alignPanel.paintAlignment(false, false);
5480 * @return alignment panels in this alignment frame
5482 public List<? extends AlignmentViewPanel> getAlignPanels()
5484 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5488 * Open a new alignment window, with the cDNA associated with this (protein)
5489 * alignment, aligned as is the protein.
5491 protected void viewAsCdna_actionPerformed()
5493 // TODO no longer a menu action - refactor as required
5494 final AlignmentI alignment = getViewport().getAlignment();
5495 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5496 if (mappings == null)
5500 List<SequenceI> cdnaSeqs = new ArrayList<>();
5501 for (SequenceI aaSeq : alignment.getSequences())
5503 for (AlignedCodonFrame acf : mappings)
5505 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5509 * There is a cDNA mapping for this protein sequence - add to new
5510 * alignment. It will share the same dataset sequence as other mapped
5511 * cDNA (no new mappings need to be created).
5513 final Sequence newSeq = new Sequence(dnaSeq);
5514 newSeq.setDatasetSequence(dnaSeq);
5515 cdnaSeqs.add(newSeq);
5519 if (cdnaSeqs.size() == 0)
5521 // show a warning dialog no mapped cDNA
5524 AlignmentI cdna = new Alignment(
5525 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5526 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5527 AlignFrame.DEFAULT_HEIGHT);
5528 cdna.alignAs(alignment);
5529 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5531 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5532 AlignFrame.DEFAULT_HEIGHT);
5536 * Set visibility of dna/protein complement view (available when shown in a
5542 protected void showComplement_actionPerformed(boolean show)
5544 SplitContainerI sf = getSplitViewContainer();
5547 sf.setComplementVisible(this, show);
5552 * Generate the reverse (optionally complemented) of the selected sequences,
5553 * and add them to the alignment
5556 protected void showReverse_actionPerformed(boolean complement)
5558 AlignmentI al = null;
5561 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5562 al = dna.reverseCdna(complement);
5563 viewport.addAlignment(al, "");
5564 addHistoryItem(new EditCommand(
5565 MessageManager.getString("label.add_sequences"), Action.PASTE,
5566 al.getSequencesArray(), 0, al.getWidth(),
5567 viewport.getAlignment()));
5568 } catch (Exception ex)
5570 System.err.println(ex.getMessage());
5576 * Try to run a script in the Groovy console, having first ensured that this
5577 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5578 * be targeted at this alignment.
5581 protected void runGroovy_actionPerformed()
5583 Jalview.setCurrentAlignFrame(this);
5584 groovy.ui.Console console = Desktop.getGroovyConsole();
5585 if (console != null)
5589 console.runScript();
5590 } catch (Exception ex)
5592 System.err.println((ex.toString()));
5593 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5594 MessageManager.getString("label.couldnt_run_groovy_script"),
5595 MessageManager.getString("label.groovy_support_failed"),
5596 JvOptionPane.ERROR_MESSAGE);
5601 System.err.println("Can't run Groovy script as console not found");
5606 * Hides columns containing (or not containing) a specified feature, provided
5607 * that would not leave all columns hidden
5609 * @param featureType
5610 * @param columnsContaining
5613 public boolean hideFeatureColumns(String featureType,
5614 boolean columnsContaining)
5616 boolean notForHiding = avc.markColumnsContainingFeatures(
5617 columnsContaining, false, false, featureType);
5620 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5621 false, featureType))
5623 getViewport().hideSelectedColumns();
5631 protected void selectHighlightedColumns_actionPerformed(
5632 ActionEvent actionEvent)
5634 // include key modifier check in case user selects from menu
5635 avc.markHighlightedColumns(
5636 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5637 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5638 | ActionEvent.CTRL_MASK)) != 0);
5642 * Rebuilds the Colour menu, including any user-defined colours which have
5643 * been loaded either on startup or during the session
5645 public void buildColourMenu()
5647 colourMenu.removeAll();
5649 colourMenu.add(applyToAllGroups);
5650 colourMenu.add(textColour);
5651 colourMenu.addSeparator();
5653 ColourMenuHelper.addMenuItems(colourMenu, this, viewport.getAlignment(),
5656 colourMenu.addSeparator();
5657 colourMenu.add(conservationMenuItem);
5658 colourMenu.add(modifyConservation);
5659 colourMenu.add(abovePIDThreshold);
5660 colourMenu.add(modifyPID);
5661 colourMenu.add(annotationColour);
5663 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5664 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5668 * Open a dialog (if not already open) that allows the user to select and
5669 * calculate PCA or Tree analysis
5671 protected void openTreePcaDialog()
5673 if (alignPanel.getCalculationDialog() == null)
5675 new CalculationChooser(AlignFrame.this);
5680 protected void loadVcf_actionPerformed()
5682 JalviewFileChooser chooser = new JalviewFileChooser(
5683 Cache.getProperty("LAST_DIRECTORY"));
5684 chooser.setFileView(new JalviewFileView());
5685 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5686 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5687 final AlignFrame us = this;
5688 chooser.response(new RunResponse(JalviewFileChooser.APPROVE_OPTION)
5695 String choice = chooser.getSelectedFile().getPath();
5696 Cache.setProperty("LAST_DIRECTORY", choice);
5697 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5698 new VCFLoader(choice).loadVCF(seqs, us);
5702 }).openDialog(null);
5708 class PrintThread extends Thread
5712 public PrintThread(AlignmentPanel ap)
5717 static PageFormat pf;
5722 PrinterJob printJob = PrinterJob.getPrinterJob();
5726 printJob.setPrintable(ap, pf);
5730 printJob.setPrintable(ap);
5733 if (printJob.printDialog())
5738 } catch (Exception PrintException)
5740 PrintException.printStackTrace();