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.getViewName() != null);
765 if (aSize == 1 && ap.av.getViewName() == null)
767 this.getContentPane().add(ap, BorderLayout.CENTER);
773 setInitialTabVisible();
776 expandViews.setEnabled(true);
777 gatherViews.setEnabled(true);
778 tabbedPane.addTab(ap.av.getViewName(), 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.getViewName(), 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 public 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(ActionEvent e)
1015 new jalview.gui.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 jalview.project.Jalview2XML().saveAlignment(this, file,
1241 statusBar.setText(MessageManager.formatMessage(
1242 "label.successfully_saved_to_file_in_format", new Object[]
1243 { fileName, format }));
1248 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1249 RunResponse cancelAction = new RunResponse(JvOptionPane.CANCEL_OPTION)
1254 lastSaveSuccessful = false;
1257 RunResponse outputAction = new RunResponse(JvOptionPane.OK_OPTION)
1262 // todo defer this to inside formatSequences (or later)
1263 AlignmentExportData exportData = viewport
1264 .getAlignExportData(options);
1265 String output = new FormatAdapter(alignPanel, options)
1266 .formatSequences(format, exportData.getAlignment(),
1267 exportData.getOmitHidden(),
1268 exportData.getStartEndPostions(),
1269 viewport.getAlignment().getHiddenColumns());
1272 lastSaveSuccessful = false;
1278 PrintWriter out = new PrintWriter(new FileWriter(file));
1281 AlignFrame.this.setTitle(file);
1282 setStatus(MessageManager.formatMessage(
1283 "label.successfully_saved_to_file_in_format",
1285 { fileName, format.getName() }));
1286 } catch (Exception ex)
1288 lastSaveSuccessful = false;
1289 ex.printStackTrace();
1296 * show dialog with export options if applicable; else just do it
1298 if (AlignExportOptions.isNeeded(viewport, format))
1300 AlignExportOptions choices = new AlignExportOptions(
1301 alignPanel.getAlignViewport(), format, options);
1302 choices.setResponseAction(outputAction);
1303 choices.setResponseAction(cancelAction);
1304 choices.showDialog();
1313 * Outputs the alignment to textbox in the requested format, if necessary
1314 * first prompting the user for whether to include hidden regions or
1317 * @param fileFormatName
1320 protected void outputText_actionPerformed(String fileFormatName)
1322 FileFormatI fileFormat = FileFormats.getInstance()
1323 .forName(fileFormatName);
1324 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1325 RunResponse outputAction = new RunResponse(JvOptionPane.OK_OPTION)
1330 // todo defer this to inside formatSequences (or later)
1331 AlignmentExportData exportData = viewport
1332 .getAlignExportData(options);
1333 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1334 cap.setForInput(null);
1337 FileFormatI format = fileFormat;
1338 cap.setText(new FormatAdapter(alignPanel, options)
1339 .formatSequences(format, exportData.getAlignment(),
1340 exportData.getOmitHidden(),
1341 exportData.getStartEndPostions(),
1342 viewport.getAlignment().getHiddenColumns()));
1343 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1344 "label.alignment_output_command", new Object[]
1345 { fileFormat.getName() }), 600, 500);
1346 } catch (OutOfMemoryError oom)
1348 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1356 * show dialog with export options if applicable; else just do it
1358 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1360 AlignExportOptions choices = new AlignExportOptions(
1361 alignPanel.getAlignViewport(), fileFormat, options);
1362 choices.setResponseAction(outputAction);
1363 choices.showDialog();
1378 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1380 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1381 htmlSVG.exportHTML(null);
1385 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1387 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1388 bjs.exportHTML(null);
1391 public void createImageMap(File file, String image)
1393 alignPanel.makePNGImageMap(file, image);
1397 * Creates a PNG image of the alignment and writes it to the given file. If
1398 * the file is null, the user is prompted to choose a file.
1403 public void createPNG(File f)
1405 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1409 * Creates an EPS image of the alignment and writes it to the given file. If
1410 * the file is null, the user is prompted to choose a file.
1415 public void createEPS(File f)
1417 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1421 * Creates an SVG image of the alignment and writes it to the given file. If
1422 * the file is null, the user is prompted to choose a file.
1427 public void createSVG(File f)
1429 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1433 public void pageSetup_actionPerformed(ActionEvent e)
1435 PrinterJob printJob = PrinterJob.getPrinterJob();
1436 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1446 public void printMenuItem_actionPerformed(ActionEvent e)
1448 // Putting in a thread avoids Swing painting problems
1449 PrintThread thread = new PrintThread(alignPanel);
1454 public void exportFeatures_actionPerformed(ActionEvent e)
1456 new AnnotationExporter(alignPanel).exportFeatures();
1460 public void exportAnnotations_actionPerformed(ActionEvent e)
1462 new AnnotationExporter(alignPanel).exportAnnotations();
1466 public void associatedData_actionPerformed(ActionEvent e)
1468 final JalviewFileChooser chooser = new JalviewFileChooser(
1469 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1470 chooser.setFileView(new JalviewFileView());
1471 chooser.setDialogTitle(
1472 MessageManager.getString("label.load_jalview_annotations"));
1473 chooser.setToolTipText(
1474 MessageManager.getString("label.load_jalview_annotations"));
1475 chooser.response(new RunResponse(JalviewFileChooser.APPROVE_OPTION)
1481 String choice = chooser.getSelectedFile().getPath();
1482 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1483 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1488 chooser.openDialog(this);
1492 * Close the current view or all views in the alignment frame. If the frame
1493 * only contains one view then the alignment will be removed from memory.
1495 * @param closeAllTabs
1498 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1500 if (alignPanels != null && alignPanels.size() < 2)
1502 closeAllTabs = true;
1507 if (alignPanels != null)
1511 if (this.isClosed())
1513 // really close all the windows - otherwise wait till
1514 // setClosed(true) is called
1515 for (int i = 0; i < alignPanels.size(); i++)
1517 AlignmentPanel ap = alignPanels.get(i);
1524 closeView(alignPanel);
1531 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1532 * be called recursively, with the frame now in 'closed' state
1534 this.setClosed(true);
1536 } catch (Exception ex)
1538 ex.printStackTrace();
1543 * Close the specified panel and close up tabs appropriately.
1545 * @param panelToClose
1547 public void closeView(AlignmentPanel panelToClose)
1549 int index = tabbedPane.getSelectedIndex();
1550 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1551 alignPanels.remove(panelToClose);
1552 panelToClose.closePanel();
1553 panelToClose = null;
1555 tabbedPane.removeTabAt(closedindex);
1556 tabbedPane.validate();
1558 if (index > closedindex || index == tabbedPane.getTabCount())
1560 // modify currently selected tab index if necessary.
1564 this.tabSelectionChanged(index);
1570 void updateEditMenuBar()
1573 if (viewport.getHistoryList().size() > 0)
1575 undoMenuItem.setEnabled(true);
1576 CommandI command = viewport.getHistoryList().peek();
1577 undoMenuItem.setText(MessageManager
1578 .formatMessage("label.undo_command", new Object[]
1579 { command.getDescription() }));
1583 undoMenuItem.setEnabled(false);
1584 undoMenuItem.setText(MessageManager.getString("action.undo"));
1587 if (viewport.getRedoList().size() > 0)
1589 redoMenuItem.setEnabled(true);
1591 CommandI command = viewport.getRedoList().peek();
1592 redoMenuItem.setText(MessageManager
1593 .formatMessage("label.redo_command", new Object[]
1594 { command.getDescription() }));
1598 redoMenuItem.setEnabled(false);
1599 redoMenuItem.setText(MessageManager.getString("action.redo"));
1604 public void addHistoryItem(CommandI command)
1606 if (command.getSize() > 0)
1608 viewport.addToHistoryList(command);
1609 viewport.clearRedoList();
1610 updateEditMenuBar();
1611 viewport.updateHiddenColumns();
1612 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1613 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1614 // viewport.getColumnSelection()
1615 // .getHiddenColumns().size() > 0);
1621 * @return alignment objects for all views
1623 AlignmentI[] getViewAlignments()
1625 if (alignPanels != null)
1627 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1629 for (AlignmentPanel ap : alignPanels)
1631 als[i++] = ap.av.getAlignment();
1635 if (viewport != null)
1637 return new AlignmentI[] { viewport.getAlignment() };
1649 protected void undoMenuItem_actionPerformed(ActionEvent e)
1651 if (viewport.getHistoryList().isEmpty())
1655 CommandI command = viewport.getHistoryList().pop();
1656 viewport.addToRedoList(command);
1657 command.undoCommand(getViewAlignments());
1659 AlignmentViewport originalSource = getOriginatingSource(command);
1660 updateEditMenuBar();
1662 if (originalSource != null)
1664 if (originalSource != viewport)
1667 "Implementation worry: mismatch of viewport origin for undo");
1669 originalSource.updateHiddenColumns();
1670 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1672 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1673 // viewport.getColumnSelection()
1674 // .getHiddenColumns().size() > 0);
1675 originalSource.firePropertyChange("alignment", null,
1676 originalSource.getAlignment().getSequences());
1687 protected void redoMenuItem_actionPerformed(ActionEvent e)
1689 if (viewport.getRedoList().size() < 1)
1694 CommandI command = viewport.getRedoList().pop();
1695 viewport.addToHistoryList(command);
1696 command.doCommand(getViewAlignments());
1698 AlignmentViewport originalSource = getOriginatingSource(command);
1699 updateEditMenuBar();
1701 if (originalSource != null)
1704 if (originalSource != viewport)
1707 "Implementation worry: mismatch of viewport origin for redo");
1709 originalSource.updateHiddenColumns();
1710 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1712 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1713 // viewport.getColumnSelection()
1714 // .getHiddenColumns().size() > 0);
1715 originalSource.firePropertyChange("alignment", null,
1716 originalSource.getAlignment().getSequences());
1720 AlignmentViewport getOriginatingSource(CommandI command)
1722 AlignmentViewport originalSource = null;
1723 // For sequence removal and addition, we need to fire
1724 // the property change event FROM the viewport where the
1725 // original alignment was altered
1726 AlignmentI al = null;
1727 if (command instanceof EditCommand)
1729 EditCommand editCommand = (EditCommand) command;
1730 al = editCommand.getAlignment();
1731 List<Component> comps = PaintRefresher.components
1732 .get(viewport.getSequenceSetId());
1734 for (Component comp : comps)
1736 if (comp instanceof AlignmentPanel)
1738 if (al == ((AlignmentPanel) comp).av.getAlignment())
1740 originalSource = ((AlignmentPanel) comp).av;
1747 if (originalSource == null)
1749 // The original view is closed, we must validate
1750 // the current view against the closed view first
1753 PaintRefresher.validateSequences(al, viewport.getAlignment());
1756 originalSource = viewport;
1759 return originalSource;
1768 public void moveSelectedSequences(boolean up)
1770 SequenceGroup sg = viewport.getSelectionGroup();
1776 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1777 viewport.getHiddenRepSequences(), up);
1778 alignPanel.paintAlignment(true, false);
1781 synchronized void slideSequences(boolean right, int size)
1783 List<SequenceI> sg = new ArrayList<>();
1784 if (viewport.cursorMode)
1786 sg.add(viewport.getAlignment()
1787 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1789 else if (viewport.getSelectionGroup() != null
1790 && viewport.getSelectionGroup().getSize() != viewport
1791 .getAlignment().getHeight())
1793 sg = viewport.getSelectionGroup()
1794 .getSequences(viewport.getHiddenRepSequences());
1802 List<SequenceI> invertGroup = new ArrayList<>();
1804 for (SequenceI seq : viewport.getAlignment().getSequences())
1806 if (!sg.contains(seq))
1808 invertGroup.add(seq);
1812 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1814 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1815 for (int i = 0; i < invertGroup.size(); i++)
1817 seqs2[i] = invertGroup.get(i);
1820 SlideSequencesCommand ssc;
1823 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1824 viewport.getGapCharacter());
1828 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1829 viewport.getGapCharacter());
1832 int groupAdjustment = 0;
1833 if (ssc.getGapsInsertedBegin() && right)
1835 if (viewport.cursorMode)
1837 alignPanel.getSeqPanel().moveCursor(size, 0);
1841 groupAdjustment = size;
1844 else if (!ssc.getGapsInsertedBegin() && !right)
1846 if (viewport.cursorMode)
1848 alignPanel.getSeqPanel().moveCursor(-size, 0);
1852 groupAdjustment = -size;
1856 if (groupAdjustment != 0)
1858 viewport.getSelectionGroup().setStartRes(
1859 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1860 viewport.getSelectionGroup().setEndRes(
1861 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1865 * just extend the last slide command if compatible; but not if in
1866 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1868 boolean appendHistoryItem = false;
1869 Deque<CommandI> historyList = viewport.getHistoryList();
1870 boolean inSplitFrame = getSplitViewContainer() != null;
1871 if (!inSplitFrame && historyList != null && historyList.size() > 0
1872 && historyList.peek() instanceof SlideSequencesCommand)
1874 appendHistoryItem = ssc.appendSlideCommand(
1875 (SlideSequencesCommand) historyList.peek());
1878 if (!appendHistoryItem)
1880 addHistoryItem(ssc);
1893 protected void copy_actionPerformed(ActionEvent e)
1895 if (viewport.getSelectionGroup() == null)
1899 // TODO: preserve the ordering of displayed alignment annotation in any
1900 // internal paste (particularly sequence associated annotation)
1901 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1902 String[] omitHidden = null;
1904 if (viewport.hasHiddenColumns())
1906 omitHidden = viewport.getViewAsString(true);
1909 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1910 seqs, omitHidden, null);
1912 StringSelection ss = new StringSelection(output);
1916 jalview.gui.Desktop.internalCopy = true;
1917 // Its really worth setting the clipboard contents
1918 // to empty before setting the large StringSelection!!
1919 Toolkit.getDefaultToolkit().getSystemClipboard()
1920 .setContents(new StringSelection(""), null);
1922 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1924 } catch (OutOfMemoryError er)
1926 new OOMWarning("copying region", er);
1930 HiddenColumns hiddenColumns = null;
1931 if (viewport.hasHiddenColumns())
1933 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1934 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1936 // create new HiddenColumns object with copy of hidden regions
1937 // between startRes and endRes, offset by startRes
1938 hiddenColumns = new HiddenColumns(
1939 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
1940 hiddenCutoff, hiddenOffset);
1943 Desktop.jalviewClipboard = new Object[] { seqs,
1944 viewport.getAlignment().getDataset(), hiddenColumns };
1945 setStatus(MessageManager.formatMessage(
1946 "label.copied_sequences_to_clipboard", new Object[]
1947 { Integer.valueOf(seqs.length).toString() }));
1957 protected void pasteNew_actionPerformed(ActionEvent e)
1969 protected void pasteThis_actionPerformed(ActionEvent e)
1975 * Paste contents of Jalview clipboard
1977 * @param newAlignment
1978 * true to paste to a new alignment, otherwise add to this.
1980 void paste(boolean newAlignment)
1982 boolean externalPaste = true;
1985 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1986 Transferable contents = c.getContents(this);
1988 if (contents == null)
1997 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1998 if (str.length() < 1)
2003 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2005 } catch (OutOfMemoryError er)
2007 new OOMWarning("Out of memory pasting sequences!!", er);
2011 SequenceI[] sequences;
2012 boolean annotationAdded = false;
2013 AlignmentI alignment = null;
2015 if (Desktop.jalviewClipboard != null)
2017 // The clipboard was filled from within Jalview, we must use the
2019 // And dataset from the copied alignment
2020 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2021 // be doubly sure that we create *new* sequence objects.
2022 sequences = new SequenceI[newseq.length];
2023 for (int i = 0; i < newseq.length; i++)
2025 sequences[i] = new Sequence(newseq[i]);
2027 alignment = new Alignment(sequences);
2028 externalPaste = false;
2032 // parse the clipboard as an alignment.
2033 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2035 sequences = alignment.getSequencesArray();
2039 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2045 if (Desktop.jalviewClipboard != null)
2047 // dataset is inherited
2048 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2052 // new dataset is constructed
2053 alignment.setDataset(null);
2055 alwidth = alignment.getWidth() + 1;
2059 AlignmentI pastedal = alignment; // preserve pasted alignment object
2060 // Add pasted sequences and dataset into existing alignment.
2061 alignment = viewport.getAlignment();
2062 alwidth = alignment.getWidth() + 1;
2063 // decide if we need to import sequences from an existing dataset
2064 boolean importDs = Desktop.jalviewClipboard != null
2065 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2066 // importDs==true instructs us to copy over new dataset sequences from
2067 // an existing alignment
2068 Vector newDs = (importDs) ? new Vector() : null; // used to create
2069 // minimum dataset set
2071 for (int i = 0; i < sequences.length; i++)
2075 newDs.addElement(null);
2077 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2079 if (importDs && ds != null)
2081 if (!newDs.contains(ds))
2083 newDs.setElementAt(ds, i);
2084 ds = new Sequence(ds);
2085 // update with new dataset sequence
2086 sequences[i].setDatasetSequence(ds);
2090 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2095 // copy and derive new dataset sequence
2096 sequences[i] = sequences[i].deriveSequence();
2097 alignment.getDataset()
2098 .addSequence(sequences[i].getDatasetSequence());
2099 // TODO: avoid creation of duplicate dataset sequences with a
2100 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2102 alignment.addSequence(sequences[i]); // merges dataset
2106 newDs.clear(); // tidy up
2108 if (alignment.getAlignmentAnnotation() != null)
2110 for (AlignmentAnnotation alan : alignment
2111 .getAlignmentAnnotation())
2113 if (alan.graphGroup > fgroup)
2115 fgroup = alan.graphGroup;
2119 if (pastedal.getAlignmentAnnotation() != null)
2121 // Add any annotation attached to alignment.
2122 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2123 for (int i = 0; i < alann.length; i++)
2125 annotationAdded = true;
2126 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2128 AlignmentAnnotation newann = new AlignmentAnnotation(
2130 if (newann.graphGroup > -1)
2132 if (newGraphGroups.size() <= newann.graphGroup
2133 || newGraphGroups.get(newann.graphGroup) == null)
2135 for (int q = newGraphGroups
2136 .size(); q <= newann.graphGroup; q++)
2138 newGraphGroups.add(q, null);
2140 newGraphGroups.set(newann.graphGroup,
2141 new Integer(++fgroup));
2143 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2147 newann.padAnnotation(alwidth);
2148 alignment.addAnnotation(newann);
2158 addHistoryItem(new EditCommand(
2159 MessageManager.getString("label.add_sequences"),
2160 Action.PASTE, sequences, 0, alignment.getWidth(),
2163 // Add any annotations attached to sequences
2164 for (int i = 0; i < sequences.length; i++)
2166 if (sequences[i].getAnnotation() != null)
2168 AlignmentAnnotation newann;
2169 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2171 annotationAdded = true;
2172 newann = sequences[i].getAnnotation()[a];
2173 newann.adjustForAlignment();
2174 newann.padAnnotation(alwidth);
2175 if (newann.graphGroup > -1)
2177 if (newann.graphGroup > -1)
2179 if (newGraphGroups.size() <= newann.graphGroup
2180 || newGraphGroups.get(newann.graphGroup) == null)
2182 for (int q = newGraphGroups
2183 .size(); q <= newann.graphGroup; q++)
2185 newGraphGroups.add(q, null);
2187 newGraphGroups.set(newann.graphGroup,
2188 new Integer(++fgroup));
2190 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2194 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2198 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2206 // propagate alignment changed.
2207 viewport.getRanges().setEndSeq(alignment.getHeight());
2208 if (annotationAdded)
2210 // Duplicate sequence annotation in all views.
2211 AlignmentI[] alview = this.getViewAlignments();
2212 for (int i = 0; i < sequences.length; i++)
2214 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2219 for (int avnum = 0; avnum < alview.length; avnum++)
2221 if (alview[avnum] != alignment)
2223 // duplicate in a view other than the one with input focus
2224 int avwidth = alview[avnum].getWidth() + 1;
2225 // this relies on sann being preserved after we
2226 // modify the sequence's annotation array for each duplication
2227 for (int a = 0; a < sann.length; a++)
2229 AlignmentAnnotation newann = new AlignmentAnnotation(
2231 sequences[i].addAlignmentAnnotation(newann);
2232 newann.padAnnotation(avwidth);
2233 alview[avnum].addAnnotation(newann); // annotation was
2234 // duplicated earlier
2235 // TODO JAL-1145 graphGroups are not updated for sequence
2236 // annotation added to several views. This may cause
2238 alview[avnum].setAnnotationIndex(newann, a);
2243 buildSortByAnnotationScoresMenu();
2245 viewport.firePropertyChange("alignment", null,
2246 alignment.getSequences());
2247 if (alignPanels != null)
2249 for (AlignmentPanel ap : alignPanels)
2251 ap.validateAnnotationDimensions(false);
2256 alignPanel.validateAnnotationDimensions(false);
2262 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2264 String newtitle = new String("Copied sequences");
2266 if (Desktop.jalviewClipboard != null
2267 && Desktop.jalviewClipboard[2] != null)
2269 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2270 af.viewport.setHiddenColumns(hc);
2273 // >>>This is a fix for the moment, until a better solution is
2275 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2276 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2277 .getFeatureRenderer());
2279 // TODO: maintain provenance of an alignment, rather than just make the
2280 // title a concatenation of operations.
2283 if (title.startsWith("Copied sequences"))
2289 newtitle = newtitle.concat("- from " + title);
2294 newtitle = new String("Pasted sequences");
2297 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2302 } catch (Exception ex)
2304 ex.printStackTrace();
2305 System.out.println("Exception whilst pasting: " + ex);
2306 // could be anything being pasted in here
2312 protected void expand_newalign(ActionEvent e)
2316 AlignmentI alignment = AlignmentUtils
2317 .expandContext(getViewport().getAlignment(), -1);
2318 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2320 String newtitle = new String("Flanking alignment");
2322 if (Desktop.jalviewClipboard != null
2323 && Desktop.jalviewClipboard[2] != null)
2325 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2326 af.viewport.setHiddenColumns(hc);
2329 // >>>This is a fix for the moment, until a better solution is
2331 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2332 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2333 .getFeatureRenderer());
2335 // TODO: maintain provenance of an alignment, rather than just make the
2336 // title a concatenation of operations.
2338 if (title.startsWith("Copied sequences"))
2344 newtitle = newtitle.concat("- from " + title);
2348 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2350 } catch (Exception ex)
2352 ex.printStackTrace();
2353 System.out.println("Exception whilst pasting: " + ex);
2354 // could be anything being pasted in here
2355 } catch (OutOfMemoryError oom)
2357 new OOMWarning("Viewing flanking region of alignment", oom);
2368 protected void cut_actionPerformed(ActionEvent e)
2370 copy_actionPerformed(null);
2371 delete_actionPerformed(null);
2381 protected void delete_actionPerformed(ActionEvent evt)
2384 SequenceGroup sg = viewport.getSelectionGroup();
2391 * If the cut affects all sequences, warn, remove highlighted columns
2393 if (sg.getSize() == viewport.getAlignment().getHeight())
2395 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2396 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2397 if (isEntireAlignWidth)
2399 int confirm = JvOptionPane.showConfirmDialog(this,
2400 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2401 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2402 JvOptionPane.OK_CANCEL_OPTION);
2404 if (confirm == JvOptionPane.CANCEL_OPTION
2405 || confirm == JvOptionPane.CLOSED_OPTION)
2410 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2411 sg.getEndRes() + 1);
2413 SequenceI[] cut = sg.getSequences()
2414 .toArray(new SequenceI[sg.getSize()]);
2416 addHistoryItem(new EditCommand(
2417 MessageManager.getString("label.cut_sequences"), Action.CUT,
2418 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2419 viewport.getAlignment()));
2421 viewport.setSelectionGroup(null);
2422 viewport.sendSelection();
2423 viewport.getAlignment().deleteGroup(sg);
2425 viewport.firePropertyChange("alignment", null,
2426 viewport.getAlignment().getSequences());
2427 if (viewport.getAlignment().getHeight() < 1)
2431 this.setClosed(true);
2432 } catch (Exception ex)
2445 protected void deleteGroups_actionPerformed(ActionEvent e)
2447 if (avc.deleteGroups())
2449 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2450 alignPanel.updateAnnotation();
2451 alignPanel.paintAlignment(true, true);
2462 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2464 SequenceGroup sg = new SequenceGroup();
2466 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2468 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2471 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2472 viewport.setSelectionGroup(sg);
2473 viewport.sendSelection();
2474 // JAL-2034 - should delegate to
2475 // alignPanel to decide if overview needs
2477 alignPanel.paintAlignment(false, false);
2478 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2488 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2490 if (viewport.cursorMode)
2492 alignPanel.getSeqPanel().keyboardNo1 = null;
2493 alignPanel.getSeqPanel().keyboardNo2 = null;
2495 viewport.setSelectionGroup(null);
2496 viewport.getColumnSelection().clear();
2497 viewport.setSelectionGroup(null);
2498 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2499 // JAL-2034 - should delegate to
2500 // alignPanel to decide if overview needs
2502 alignPanel.paintAlignment(false, false);
2503 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2504 viewport.sendSelection();
2514 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2516 SequenceGroup sg = viewport.getSelectionGroup();
2520 selectAllSequenceMenuItem_actionPerformed(null);
2525 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2527 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2529 // JAL-2034 - should delegate to
2530 // alignPanel to decide if overview needs
2533 alignPanel.paintAlignment(true, false);
2534 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2535 viewport.sendSelection();
2539 public void invertColSel_actionPerformed(ActionEvent e)
2541 viewport.invertColumnSelection();
2542 alignPanel.paintAlignment(true, false);
2543 viewport.sendSelection();
2553 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2555 trimAlignment(true);
2565 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2567 trimAlignment(false);
2570 void trimAlignment(boolean trimLeft)
2572 ColumnSelection colSel = viewport.getColumnSelection();
2575 if (!colSel.isEmpty())
2579 column = colSel.getMin();
2583 column = colSel.getMax();
2587 if (viewport.getSelectionGroup() != null)
2589 seqs = viewport.getSelectionGroup()
2590 .getSequencesAsArray(viewport.getHiddenRepSequences());
2594 seqs = viewport.getAlignment().getSequencesArray();
2597 TrimRegionCommand trimRegion;
2600 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2601 column, viewport.getAlignment());
2602 viewport.getRanges().setStartRes(0);
2606 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2607 column, viewport.getAlignment());
2610 setStatus(MessageManager
2611 .formatMessage("label.removed_columns", new String[]
2612 { Integer.valueOf(trimRegion.getSize()).toString() }));
2614 addHistoryItem(trimRegion);
2616 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2618 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2619 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2621 viewport.getAlignment().deleteGroup(sg);
2625 viewport.firePropertyChange("alignment", null,
2626 viewport.getAlignment().getSequences());
2637 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2639 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2642 if (viewport.getSelectionGroup() != null)
2644 seqs = viewport.getSelectionGroup()
2645 .getSequencesAsArray(viewport.getHiddenRepSequences());
2646 start = viewport.getSelectionGroup().getStartRes();
2647 end = viewport.getSelectionGroup().getEndRes();
2651 seqs = viewport.getAlignment().getSequencesArray();
2654 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2655 "Remove Gapped Columns", seqs, start, end,
2656 viewport.getAlignment());
2658 addHistoryItem(removeGapCols);
2660 setStatus(MessageManager
2661 .formatMessage("label.removed_empty_columns", new Object[]
2662 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2664 // This is to maintain viewport position on first residue
2665 // of first sequence
2666 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2667 ViewportRanges ranges = viewport.getRanges();
2668 int startRes = seq.findPosition(ranges.getStartRes());
2669 // ShiftList shifts;
2670 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2671 // edit.alColumnChanges=shifts.getInverse();
2672 // if (viewport.hasHiddenColumns)
2673 // viewport.getColumnSelection().compensateForEdits(shifts);
2674 ranges.setStartRes(seq.findIndex(startRes) - 1);
2675 viewport.firePropertyChange("alignment", null,
2676 viewport.getAlignment().getSequences());
2687 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2689 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2692 if (viewport.getSelectionGroup() != null)
2694 seqs = viewport.getSelectionGroup()
2695 .getSequencesAsArray(viewport.getHiddenRepSequences());
2696 start = viewport.getSelectionGroup().getStartRes();
2697 end = viewport.getSelectionGroup().getEndRes();
2701 seqs = viewport.getAlignment().getSequencesArray();
2704 // This is to maintain viewport position on first residue
2705 // of first sequence
2706 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2707 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2709 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2710 viewport.getAlignment()));
2712 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2714 viewport.firePropertyChange("alignment", null,
2715 viewport.getAlignment().getSequences());
2726 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2728 viewport.setPadGaps(padGapsMenuitem.isSelected());
2729 viewport.firePropertyChange("alignment", null,
2730 viewport.getAlignment().getSequences());
2740 public void findMenuItem_actionPerformed(ActionEvent e)
2746 * Create a new view of the current alignment.
2749 public void newView_actionPerformed(ActionEvent e)
2751 newView(null, true);
2755 * Creates and shows a new view of the current alignment.
2758 * title of newly created view; if null, one will be generated
2759 * @param copyAnnotation
2760 * if true then duplicate all annnotation, groups and settings
2761 * @return new alignment panel, already displayed.
2763 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2766 * Create a new AlignmentPanel (with its own, new Viewport)
2768 AlignmentPanel newap = new jalview.project.Jalview2XML()
2769 .copyAlignPanel(alignPanel);
2770 if (!copyAnnotation)
2773 * remove all groups and annotation except for the automatic stuff
2775 newap.av.getAlignment().deleteAllGroups();
2776 newap.av.getAlignment().deleteAllAnnotations(false);
2779 newap.av.setGatherViewsHere(false);
2781 if (viewport.getViewName() == null)
2783 viewport.setViewName(MessageManager
2784 .getString("label.view_name_original"));
2788 * Views share the same edits undo and redo stacks
2790 newap.av.setHistoryList(viewport.getHistoryList());
2791 newap.av.setRedoList(viewport.getRedoList());
2794 * Views share the same mappings; need to deregister any new mappings
2795 * created by copyAlignPanel, and register the new reference to the shared
2798 newap.av.replaceMappings(viewport.getAlignment());
2801 * start up cDNA consensus (if applicable) now mappings are in place
2803 if (newap.av.initComplementConsensus())
2805 newap.refresh(true); // adjust layout of annotations
2808 newap.av.setViewName(getNewViewName(viewTitle));
2810 addAlignmentPanel(newap, true);
2811 newap.alignmentChanged();
2813 if (alignPanels.size() == 2)
2815 viewport.setGatherViewsHere(true);
2817 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2822 * Make a new name for the view, ensuring it is unique within the current
2823 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2824 * these now use viewId. Unique view names are still desirable for usability.)
2829 protected String getNewViewName(String viewTitle)
2831 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2832 boolean addFirstIndex = false;
2833 if (viewTitle == null || viewTitle.trim().length() == 0)
2835 viewTitle = MessageManager.getString("action.view");
2836 addFirstIndex = true;
2840 index = 1;// we count from 1 if given a specific name
2842 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2844 List<Component> comps = PaintRefresher.components
2845 .get(viewport.getSequenceSetId());
2847 List<String> existingNames = getExistingViewNames(comps);
2849 while (existingNames.contains(newViewName))
2851 newViewName = viewTitle + " " + (++index);
2857 * Returns a list of distinct view names found in the given list of
2858 * components. View names are held on the viewport of an AlignmentPanel.
2863 protected List<String> getExistingViewNames(List<Component> comps)
2865 List<String> existingNames = new ArrayList<>();
2866 for (Component comp : comps)
2868 if (comp instanceof AlignmentPanel)
2870 AlignmentPanel ap = (AlignmentPanel) comp;
2871 if (!existingNames.contains(ap.av.getViewName()))
2873 existingNames.add(ap.av.getViewName());
2877 return existingNames;
2881 * Explode tabbed views into separate windows.
2884 public void expandViews_actionPerformed(ActionEvent e)
2886 Desktop.explodeViews(this);
2890 * Gather views in separate windows back into a tabbed presentation.
2893 public void gatherViews_actionPerformed(ActionEvent e)
2895 Desktop.instance.gatherViews(this);
2905 public void font_actionPerformed(ActionEvent e)
2907 new FontChooser(alignPanel);
2917 protected void seqLimit_actionPerformed(ActionEvent e)
2919 viewport.setShowJVSuffix(seqLimits.isSelected());
2921 alignPanel.getIdPanel().getIdCanvas()
2922 .setPreferredSize(alignPanel.calculateIdWidth());
2923 alignPanel.paintAlignment(true, false);
2927 public void idRightAlign_actionPerformed(ActionEvent e)
2929 viewport.setRightAlignIds(idRightAlign.isSelected());
2930 alignPanel.paintAlignment(false, false);
2934 public void centreColumnLabels_actionPerformed(ActionEvent e)
2936 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2937 alignPanel.paintAlignment(false, false);
2943 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2946 protected void followHighlight_actionPerformed()
2949 * Set the 'follow' flag on the Viewport (and scroll to position if now
2952 final boolean state = this.followHighlightMenuItem.getState();
2953 viewport.setFollowHighlight(state);
2956 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2967 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2969 viewport.setColourText(colourTextMenuItem.isSelected());
2970 alignPanel.paintAlignment(false, false);
2980 public void wrapMenuItem_actionPerformed(ActionEvent e)
2982 scaleAbove.setVisible(wrapMenuItem.isSelected());
2983 scaleLeft.setVisible(wrapMenuItem.isSelected());
2984 scaleRight.setVisible(wrapMenuItem.isSelected());
2985 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2986 alignPanel.updateLayout();
2990 public void showAllSeqs_actionPerformed(ActionEvent e)
2992 viewport.showAllHiddenSeqs();
2996 public void showAllColumns_actionPerformed(ActionEvent e)
2998 viewport.showAllHiddenColumns();
2999 alignPanel.paintAlignment(true, true);
3000 viewport.sendSelection();
3004 public void hideSelSequences_actionPerformed(ActionEvent e)
3006 viewport.hideAllSelectedSeqs();
3010 * called by key handler and the hide all/show all menu items
3015 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3018 boolean hide = false;
3019 SequenceGroup sg = viewport.getSelectionGroup();
3020 if (!toggleSeqs && !toggleCols)
3022 // Hide everything by the current selection - this is a hack - we do the
3023 // invert and then hide
3024 // first check that there will be visible columns after the invert.
3025 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3026 && sg.getStartRes() <= sg.getEndRes()))
3028 // now invert the sequence set, if required - empty selection implies
3029 // that no hiding is required.
3032 invertSequenceMenuItem_actionPerformed(null);
3033 sg = viewport.getSelectionGroup();
3037 viewport.expandColSelection(sg, true);
3038 // finally invert the column selection and get the new sequence
3040 invertColSel_actionPerformed(null);
3047 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3049 hideSelSequences_actionPerformed(null);
3052 else if (!(toggleCols && viewport.hasSelectedColumns()))
3054 showAllSeqs_actionPerformed(null);
3060 if (viewport.hasSelectedColumns())
3062 hideSelColumns_actionPerformed(null);
3065 viewport.setSelectionGroup(sg);
3070 showAllColumns_actionPerformed(null);
3079 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3080 * event.ActionEvent)
3083 public void hideAllButSelection_actionPerformed(ActionEvent e)
3085 toggleHiddenRegions(false, false);
3086 viewport.sendSelection();
3093 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3097 public void hideAllSelection_actionPerformed(ActionEvent e)
3099 SequenceGroup sg = viewport.getSelectionGroup();
3100 viewport.expandColSelection(sg, false);
3101 viewport.hideAllSelectedSeqs();
3102 viewport.hideSelectedColumns();
3103 alignPanel.paintAlignment(true, true);
3104 viewport.sendSelection();
3111 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3115 public void showAllhidden_actionPerformed(ActionEvent e)
3117 viewport.showAllHiddenColumns();
3118 viewport.showAllHiddenSeqs();
3119 alignPanel.paintAlignment(true, true);
3120 viewport.sendSelection();
3124 public void hideSelColumns_actionPerformed(ActionEvent e)
3126 viewport.hideSelectedColumns();
3127 alignPanel.paintAlignment(true, true);
3128 viewport.sendSelection();
3132 public void hiddenMarkers_actionPerformed(ActionEvent e)
3134 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3145 protected void scaleAbove_actionPerformed(ActionEvent e)
3147 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3148 // TODO: do we actually need to update overview for scale above change ?
3149 alignPanel.paintAlignment(true, false);
3159 protected void scaleLeft_actionPerformed(ActionEvent e)
3161 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3162 alignPanel.paintAlignment(true, false);
3172 protected void scaleRight_actionPerformed(ActionEvent e)
3174 viewport.setScaleRightWrapped(scaleRight.isSelected());
3175 alignPanel.paintAlignment(true, false);
3185 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3187 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3188 alignPanel.paintAlignment(false, false);
3198 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3200 viewport.setShowText(viewTextMenuItem.isSelected());
3201 alignPanel.paintAlignment(false, false);
3211 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3213 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3214 alignPanel.paintAlignment(false, false);
3217 public FeatureSettings featureSettings;
3220 public FeatureSettingsControllerI getFeatureSettingsUI()
3222 return featureSettings;
3226 public void featureSettings_actionPerformed(ActionEvent e)
3228 if (featureSettings != null)
3230 featureSettings.close();
3231 featureSettings = null;
3233 if (!showSeqFeatures.isSelected())
3235 // make sure features are actually displayed
3236 showSeqFeatures.setSelected(true);
3237 showSeqFeatures_actionPerformed(null);
3239 featureSettings = new FeatureSettings(this);
3243 * Set or clear 'Show Sequence Features'
3249 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3251 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3252 alignPanel.paintAlignment(true, true);
3256 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3257 * the annotations panel as a whole.
3259 * The options to show/hide all annotations should be enabled when the panel
3260 * is shown, and disabled when the panel is hidden.
3265 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3267 final boolean setVisible = annotationPanelMenuItem.isSelected();
3268 viewport.setShowAnnotation(setVisible);
3269 this.showAllSeqAnnotations.setEnabled(setVisible);
3270 this.hideAllSeqAnnotations.setEnabled(setVisible);
3271 this.showAllAlAnnotations.setEnabled(setVisible);
3272 this.hideAllAlAnnotations.setEnabled(setVisible);
3273 alignPanel.updateLayout();
3277 public void alignmentProperties()
3280 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3283 String content = MessageManager.formatMessage("label.html_content",
3285 { contents.toString() });
3290 JLabel textLabel = new JLabel();
3291 textLabel.setText(content);
3292 textLabel.setBackground(Color.WHITE);
3294 pane = new JPanel(new BorderLayout());
3295 ((JPanel) pane).setOpaque(true);
3296 pane.setBackground(Color.WHITE);
3297 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3301 JEditorPane editPane = new JEditorPane("text/html", "");
3302 editPane.setEditable(false);
3303 editPane.setText(content);
3307 JInternalFrame frame = new JInternalFrame();
3309 frame.getContentPane().add(new JScrollPane(pane));
3311 Desktop.addInternalFrame(frame, MessageManager
3312 .formatMessage("label.alignment_properties", new Object[]
3313 { getTitle() }), 500, 400);
3323 public void overviewMenuItem_actionPerformed(ActionEvent e)
3325 if (alignPanel.overviewPanel != null)
3330 JInternalFrame frame = new JInternalFrame();
3331 final OverviewPanel overview = new OverviewPanel(alignPanel);
3332 frame.setContentPane(overview);
3333 Desktop.addInternalFrame(frame, MessageManager
3334 .formatMessage("label.overview_params", new Object[]
3335 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3338 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3339 frame.addInternalFrameListener(
3340 new javax.swing.event.InternalFrameAdapter()
3343 public void internalFrameClosed(
3344 javax.swing.event.InternalFrameEvent evt)
3347 alignPanel.setOverviewPanel(null);
3350 if (getKeyListeners().length > 0)
3352 frame.addKeyListener(getKeyListeners()[0]);
3355 alignPanel.setOverviewPanel(overview);
3359 public void textColour_actionPerformed()
3361 new TextColourChooser().chooseColour(alignPanel, null);
3365 * public void covariationColour_actionPerformed() {
3367 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3371 public void annotationColour_actionPerformed()
3373 new AnnotationColourChooser(viewport, alignPanel);
3377 public void annotationColumn_actionPerformed(ActionEvent e)
3379 new AnnotationColumnChooser(viewport, alignPanel);
3383 * Action on the user checking or unchecking the option to apply the selected
3384 * colour scheme to all groups. If unchecked, groups may have their own
3385 * independent colour schemes.
3390 public void applyToAllGroups_actionPerformed(boolean selected)
3392 viewport.setColourAppliesToAllGroups(selected);
3396 * Action on user selecting a colour from the colour menu
3399 * the name (not the menu item label!) of the colour scheme
3402 public void changeColour_actionPerformed(String name)
3405 * 'User Defined' opens a panel to configure or load a
3406 * user-defined colour scheme
3408 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3410 new UserDefinedColours(alignPanel);
3415 * otherwise set the chosen colour scheme (or null for 'None')
3417 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3418 viewport.getAlignment(), viewport.getHiddenRepSequences());
3423 * Actions on setting or changing the alignment colour scheme
3428 public void changeColour(ColourSchemeI cs)
3430 // TODO: pull up to controller method
3431 ColourMenuHelper.setColourSelected(colourMenu, cs);
3433 viewport.setGlobalColourScheme(cs);
3435 alignPanel.paintAlignment(true, true);
3439 * Show the PID threshold slider panel
3442 protected void modifyPID_actionPerformed()
3444 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3445 alignPanel.getViewName());
3446 SliderPanel.showPIDSlider();
3450 * Show the Conservation slider panel
3453 protected void modifyConservation_actionPerformed()
3455 SliderPanel.setConservationSlider(alignPanel,
3456 viewport.getResidueShading(), alignPanel.getViewName());
3457 SliderPanel.showConservationSlider();
3461 * Action on selecting or deselecting (Colour) By Conservation
3464 public void conservationMenuItem_actionPerformed(boolean selected)
3466 modifyConservation.setEnabled(selected);
3467 viewport.setConservationSelected(selected);
3468 viewport.getResidueShading().setConservationApplied(selected);
3470 changeColour(viewport.getGlobalColourScheme());
3473 modifyConservation_actionPerformed();
3477 SliderPanel.hideConservationSlider();
3482 * Action on selecting or deselecting (Colour) Above PID Threshold
3485 public void abovePIDThreshold_actionPerformed(boolean selected)
3487 modifyPID.setEnabled(selected);
3488 viewport.setAbovePIDThreshold(selected);
3491 viewport.getResidueShading().setThreshold(0,
3492 viewport.isIgnoreGapsConsensus());
3495 changeColour(viewport.getGlobalColourScheme());
3498 modifyPID_actionPerformed();
3502 SliderPanel.hidePIDSlider();
3513 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3515 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3516 AlignmentSorter.sortByPID(viewport.getAlignment(),
3517 viewport.getAlignment().getSequenceAt(0));
3518 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3519 viewport.getAlignment()));
3520 alignPanel.paintAlignment(true, false);
3530 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3532 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3533 AlignmentSorter.sortByID(viewport.getAlignment());
3535 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3536 alignPanel.paintAlignment(true, false);
3546 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3548 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3549 AlignmentSorter.sortByLength(viewport.getAlignment());
3550 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3551 viewport.getAlignment()));
3552 alignPanel.paintAlignment(true, false);
3562 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3564 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3565 AlignmentSorter.sortByGroup(viewport.getAlignment());
3566 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3567 viewport.getAlignment()));
3569 alignPanel.paintAlignment(true, false);
3579 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3581 new RedundancyPanel(alignPanel, this);
3591 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3593 if ((viewport.getSelectionGroup() == null)
3594 || (viewport.getSelectionGroup().getSize() < 2))
3596 JvOptionPane.showInternalMessageDialog(this,
3597 MessageManager.getString(
3598 "label.you_must_select_least_two_sequences"),
3599 MessageManager.getString("label.invalid_selection"),
3600 JvOptionPane.WARNING_MESSAGE);
3604 JInternalFrame frame = new JInternalFrame();
3605 frame.setContentPane(new PairwiseAlignPanel(viewport));
3606 Desktop.addInternalFrame(frame,
3607 MessageManager.getString("action.pairwise_alignment"), 600,
3613 public void autoCalculate_actionPerformed(ActionEvent e)
3615 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3616 if (viewport.autoCalculateConsensus)
3618 viewport.firePropertyChange("alignment", null,
3619 viewport.getAlignment().getSequences());
3624 public void sortByTreeOption_actionPerformed(ActionEvent e)
3626 viewport.sortByTree = sortByTree.isSelected();
3630 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3632 viewport.followSelection = listenToViewSelections.isSelected();
3636 * Constructs a tree panel and adds it to the desktop
3639 * tree type (NJ or AV)
3641 * name of score model used to compute the tree
3643 * parameters for the distance or similarity calculation
3645 void newTreePanel(String type, String modelName,
3646 SimilarityParamsI options)
3648 String frameTitle = "";
3651 boolean onSelection = false;
3652 if (viewport.getSelectionGroup() != null
3653 && viewport.getSelectionGroup().getSize() > 0)
3655 SequenceGroup sg = viewport.getSelectionGroup();
3657 /* Decide if the selection is a column region */
3658 for (SequenceI _s : sg.getSequences())
3660 if (_s.getLength() < sg.getEndRes())
3662 JvOptionPane.showMessageDialog(Desktop.desktop,
3663 MessageManager.getString(
3664 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3665 MessageManager.getString(
3666 "label.sequences_selection_not_aligned"),
3667 JvOptionPane.WARNING_MESSAGE);
3676 if (viewport.getAlignment().getHeight() < 2)
3682 tp = new TreePanel(alignPanel, type, modelName, options);
3683 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3685 frameTitle += " from ";
3687 if (viewport.getViewName() != null)
3689 frameTitle += viewport.getViewName() + " of ";
3692 frameTitle += this.title;
3694 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3705 public void addSortByOrderMenuItem(String title,
3706 final AlignmentOrder order)
3708 final JMenuItem item = new JMenuItem(MessageManager
3709 .formatMessage("action.by_title_param", new Object[]
3712 item.addActionListener(new java.awt.event.ActionListener()
3715 public void actionPerformed(ActionEvent e)
3717 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3719 // TODO: JBPNote - have to map order entries to curent SequenceI
3721 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3723 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3724 viewport.getAlignment()));
3726 alignPanel.paintAlignment(true, false);
3732 * Add a new sort by annotation score menu item
3735 * the menu to add the option to
3737 * the label used to retrieve scores for each sequence on the
3740 public void addSortByAnnotScoreMenuItem(JMenu sort,
3741 final String scoreLabel)
3743 final JMenuItem item = new JMenuItem(scoreLabel);
3745 item.addActionListener(new java.awt.event.ActionListener()
3748 public void actionPerformed(ActionEvent e)
3750 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3751 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3752 viewport.getAlignment());// ,viewport.getSelectionGroup());
3753 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3754 viewport.getAlignment()));
3755 alignPanel.paintAlignment(true, false);
3761 * last hash for alignment's annotation array - used to minimise cost of
3764 protected int _annotationScoreVectorHash;
3767 * search the alignment and rebuild the sort by annotation score submenu the
3768 * last alignment annotation vector hash is stored to minimize cost of
3769 * rebuilding in subsequence calls.
3773 public void buildSortByAnnotationScoresMenu()
3775 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3780 if (viewport.getAlignment().getAlignmentAnnotation()
3781 .hashCode() != _annotationScoreVectorHash)
3783 sortByAnnotScore.removeAll();
3784 // almost certainly a quicker way to do this - but we keep it simple
3785 Hashtable scoreSorts = new Hashtable();
3786 AlignmentAnnotation aann[];
3787 for (SequenceI sqa : viewport.getAlignment().getSequences())
3789 aann = sqa.getAnnotation();
3790 for (int i = 0; aann != null && i < aann.length; i++)
3792 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3794 scoreSorts.put(aann[i].label, aann[i].label);
3798 Enumeration labels = scoreSorts.keys();
3799 while (labels.hasMoreElements())
3801 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3802 (String) labels.nextElement());
3804 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3807 _annotationScoreVectorHash = viewport.getAlignment()
3808 .getAlignmentAnnotation().hashCode();
3813 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3814 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3815 * call. Listeners are added to remove the menu item when the treePanel is
3816 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3820 public void buildTreeSortMenu()
3822 sortByTreeMenu.removeAll();
3824 List<Component> comps = PaintRefresher.components
3825 .get(viewport.getSequenceSetId());
3826 List<TreePanel> treePanels = new ArrayList<>();
3827 for (Component comp : comps)
3829 if (comp instanceof TreePanel)
3831 treePanels.add((TreePanel) comp);
3835 if (treePanels.size() < 1)
3837 sortByTreeMenu.setVisible(false);
3841 sortByTreeMenu.setVisible(true);
3843 for (final TreePanel tp : treePanels)
3845 final JMenuItem item = new JMenuItem(tp.getTitle());
3846 item.addActionListener(new java.awt.event.ActionListener()
3849 public void actionPerformed(ActionEvent e)
3851 tp.sortByTree_actionPerformed();
3852 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3857 sortByTreeMenu.add(item);
3861 public boolean sortBy(AlignmentOrder alorder, String undoname)
3863 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3864 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3865 if (undoname != null)
3867 addHistoryItem(new OrderCommand(undoname, oldOrder,
3868 viewport.getAlignment()));
3870 alignPanel.paintAlignment(true, false);
3875 * Work out whether the whole set of sequences or just the selected set will
3876 * be submitted for multiple alignment.
3879 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3881 // Now, check we have enough sequences
3882 AlignmentView msa = null;
3884 if ((viewport.getSelectionGroup() != null)
3885 && (viewport.getSelectionGroup().getSize() > 1))
3887 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3888 // some common interface!
3890 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3891 * SequenceI[sz = seqs.getSize(false)];
3893 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3894 * seqs.getSequenceAt(i); }
3896 msa = viewport.getAlignmentView(true);
3898 else if (viewport.getSelectionGroup() != null
3899 && viewport.getSelectionGroup().getSize() == 1)
3901 int option = JvOptionPane.showConfirmDialog(this,
3902 MessageManager.getString("warn.oneseq_msainput_selection"),
3903 MessageManager.getString("label.invalid_selection"),
3904 JvOptionPane.OK_CANCEL_OPTION);
3905 if (option == JvOptionPane.OK_OPTION)
3907 msa = viewport.getAlignmentView(false);
3912 msa = viewport.getAlignmentView(false);
3918 * Decides what is submitted to a secondary structure prediction service: the
3919 * first sequence in the alignment, or in the current selection, or, if the
3920 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3921 * region or the whole alignment. (where the first sequence in the set is the
3922 * one that the prediction will be for).
3924 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3926 AlignmentView seqs = null;
3928 if ((viewport.getSelectionGroup() != null)
3929 && (viewport.getSelectionGroup().getSize() > 0))
3931 seqs = viewport.getAlignmentView(true);
3935 seqs = viewport.getAlignmentView(false);
3937 // limit sequences - JBPNote in future - could spawn multiple prediction
3939 // TODO: viewport.getAlignment().isAligned is a global state - the local
3940 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3941 if (!viewport.getAlignment().isAligned(false))
3943 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3944 // TODO: if seqs.getSequences().length>1 then should really have warned
3958 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3960 // Pick the tree file
3961 JalviewFileChooser chooser = new JalviewFileChooser(
3962 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3963 chooser.setFileView(new JalviewFileView());
3964 chooser.setDialogTitle(
3965 MessageManager.getString("label.select_newick_like_tree_file"));
3966 chooser.setToolTipText(
3967 MessageManager.getString("label.load_tree_file"));
3969 chooser.response(new jalview.util.dialogrunner.RunResponse(
3970 JalviewFileChooser.APPROVE_OPTION)
3975 String filePath = chooser.getSelectedFile().getPath();
3976 Cache.setProperty("LAST_DIRECTORY", filePath);
3977 NewickFile fin = null;
3980 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
3981 DataSourceType.FILE));
3982 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
3983 } catch (Exception ex)
3985 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
3987 .getString("label.problem_reading_tree_file"),
3988 JvOptionPane.WARNING_MESSAGE);
3989 ex.printStackTrace();
3991 if (fin != null && fin.hasWarningMessage())
3993 JvOptionPane.showMessageDialog(Desktop.desktop,
3994 fin.getWarningMessage(),
3995 MessageManager.getString(
3996 "label.possible_problem_with_tree_file"),
3997 JvOptionPane.WARNING_MESSAGE);
4000 }).openDialog(this);
4003 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4005 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4008 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4009 int h, int x, int y)
4011 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4015 * Add a treeviewer for the tree extracted from a Newick file object to the
4016 * current alignment view
4023 * Associated alignment input data (or null)
4032 * @return TreePanel handle
4034 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4035 AlignmentView input, int w, int h, int x, int y)
4037 TreePanel tp = null;
4043 if (nf.getTree() != null)
4045 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4051 tp.setLocation(x, y);
4054 Desktop.addInternalFrame(tp, treeTitle, w, h);
4056 } catch (Exception ex)
4058 ex.printStackTrace();
4064 private boolean buildingMenu = false;
4067 * Generates menu items and listener event actions for web service clients
4070 public void BuildWebServiceMenu()
4072 while (buildingMenu)
4076 System.err.println("Waiting for building menu to finish.");
4078 } catch (Exception e)
4082 final AlignFrame me = this;
4083 buildingMenu = true;
4084 new Thread(new Runnable()
4089 final List<JMenuItem> legacyItems = new ArrayList<>();
4092 // System.err.println("Building ws menu again "
4093 // + Thread.currentThread());
4094 // TODO: add support for context dependent disabling of services based
4096 // alignment and current selection
4097 // TODO: add additional serviceHandle parameter to specify abstract
4099 // class independently of AbstractName
4100 // TODO: add in rediscovery GUI function to restart discoverer
4101 // TODO: group services by location as well as function and/or
4103 // object broker mechanism.
4104 final Vector<JMenu> wsmenu = new Vector<>();
4105 final IProgressIndicator af = me;
4108 * do not i18n these strings - they are hard-coded in class
4109 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4110 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4112 final JMenu msawsmenu = new JMenu("Alignment");
4113 final JMenu secstrmenu = new JMenu(
4114 "Secondary Structure Prediction");
4115 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4116 final JMenu analymenu = new JMenu("Analysis");
4117 final JMenu dismenu = new JMenu("Protein Disorder");
4118 // JAL-940 - only show secondary structure prediction services from
4119 // the legacy server
4120 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4122 Discoverer.services != null && (Discoverer.services.size() > 0))
4124 // TODO: refactor to allow list of AbstractName/Handler bindings to
4126 // stored or retrieved from elsewhere
4127 // No MSAWS used any more:
4128 // Vector msaws = null; // (Vector)
4129 // Discoverer.services.get("MsaWS");
4130 Vector secstrpr = (Vector) Discoverer.services
4132 if (secstrpr != null)
4134 // Add any secondary structure prediction services
4135 for (int i = 0, j = secstrpr.size(); i < j; i++)
4137 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4139 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4140 .getServiceClient(sh);
4141 int p = secstrmenu.getItemCount();
4142 impl.attachWSMenuEntry(secstrmenu, me);
4143 int q = secstrmenu.getItemCount();
4144 for (int litm = p; litm < q; litm++)
4146 legacyItems.add(secstrmenu.getItem(litm));
4152 // Add all submenus in the order they should appear on the web
4154 wsmenu.add(msawsmenu);
4155 wsmenu.add(secstrmenu);
4156 wsmenu.add(dismenu);
4157 wsmenu.add(analymenu);
4158 // No search services yet
4159 // wsmenu.add(seqsrchmenu);
4161 javax.swing.SwingUtilities.invokeLater(new Runnable()
4168 webService.removeAll();
4169 // first, add discovered services onto the webservices menu
4170 if (wsmenu.size() > 0)
4172 for (int i = 0, j = wsmenu.size(); i < j; i++)
4174 webService.add(wsmenu.get(i));
4179 webService.add(me.webServiceNoServices);
4181 // TODO: move into separate menu builder class.
4182 boolean new_sspred = false;
4183 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4185 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4186 if (jws2servs != null)
4188 if (jws2servs.hasServices())
4190 jws2servs.attachWSMenuEntry(webService, me);
4191 for (Jws2Instance sv : jws2servs.getServices())
4193 if (sv.description.toLowerCase().contains("jpred"))
4195 for (JMenuItem jmi : legacyItems)
4197 jmi.setVisible(false);
4203 if (jws2servs.isRunning())
4205 JMenuItem tm = new JMenuItem(
4206 "Still discovering JABA Services");
4207 tm.setEnabled(false);
4212 build_urlServiceMenu(me.webService);
4213 build_fetchdbmenu(webService);
4214 for (JMenu item : wsmenu)
4216 if (item.getItemCount() == 0)
4218 item.setEnabled(false);
4222 item.setEnabled(true);
4225 } catch (Exception e)
4228 "Exception during web service menu building process.",
4233 } catch (Exception e)
4236 buildingMenu = false;
4243 * construct any groupURL type service menu entries.
4247 private void build_urlServiceMenu(JMenu webService)
4249 // TODO: remove this code when 2.7 is released
4250 // DEBUG - alignmentView
4252 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4253 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4255 * @Override public void actionPerformed(ActionEvent e) {
4256 * jalview.datamodel.AlignmentView
4257 * .testSelectionViews(af.viewport.getAlignment(),
4258 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4260 * }); webService.add(testAlView);
4262 // TODO: refactor to RestClient discoverer and merge menu entries for
4263 // rest-style services with other types of analysis/calculation service
4264 // SHmmr test client - still being implemented.
4265 // DEBUG - alignmentView
4267 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4270 client.attachWSMenuEntry(
4271 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4277 * Searches the alignment sequences for xRefs and builds the Show
4278 * Cross-References menu (formerly called Show Products), with database
4279 * sources for which cross-references are found (protein sources for a
4280 * nucleotide alignment and vice versa)
4282 * @return true if Show Cross-references menu should be enabled
4284 public boolean canShowProducts()
4286 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4287 AlignmentI dataset = viewport.getAlignment().getDataset();
4289 showProducts.removeAll();
4290 final boolean dna = viewport.getAlignment().isNucleotide();
4292 if (seqs == null || seqs.length == 0)
4294 // nothing to see here.
4298 boolean showp = false;
4301 List<String> ptypes = new CrossRef(seqs, dataset)
4302 .findXrefSourcesForSequences(dna);
4304 for (final String source : ptypes)
4307 final AlignFrame af = this;
4308 JMenuItem xtype = new JMenuItem(source);
4309 xtype.addActionListener(new ActionListener()
4312 public void actionPerformed(ActionEvent e)
4314 showProductsFor(af.viewport.getSequenceSelection(), dna,
4318 showProducts.add(xtype);
4320 showProducts.setVisible(showp);
4321 showProducts.setEnabled(showp);
4322 } catch (Exception e)
4325 "canShowProducts threw an exception - please report to help@jalview.org",
4333 * Finds and displays cross-references for the selected sequences (protein
4334 * products for nucleotide sequences, dna coding sequences for peptides).
4337 * the sequences to show cross-references for
4339 * true if from a nucleotide alignment (so showing proteins)
4341 * the database to show cross-references for
4343 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4344 final String source)
4346 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4351 * Construct and display a new frame containing the translation of this
4352 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4355 public void showTranslation_actionPerformed(ActionEvent e)
4357 AlignmentI al = null;
4360 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4362 al = dna.translateCdna();
4363 } catch (Exception ex)
4365 jalview.bin.Cache.log.error(
4366 "Exception during translation. Please report this !", ex);
4367 final String msg = MessageManager.getString(
4368 "label.error_when_translating_sequences_submit_bug_report");
4369 final String errorTitle = MessageManager
4370 .getString("label.implementation_error")
4371 + MessageManager.getString("label.translation_failed");
4372 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4373 JvOptionPane.ERROR_MESSAGE);
4376 if (al == null || al.getHeight() == 0)
4378 final String msg = MessageManager.getString(
4379 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4380 final String errorTitle = MessageManager
4381 .getString("label.translation_failed");
4382 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4383 JvOptionPane.WARNING_MESSAGE);
4387 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4388 af.setFileFormat(this.currentFileFormat);
4389 final String newTitle = MessageManager
4390 .formatMessage("label.translation_of_params", new Object[]
4391 { this.getTitle() });
4392 af.setTitle(newTitle);
4393 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4395 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4396 viewport.openSplitFrame(af, new Alignment(seqs));
4400 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4407 * Set the file format
4411 public void setFileFormat(FileFormatI format)
4413 this.currentFileFormat = format;
4417 * Try to load a features file onto the alignment.
4420 * contents or path to retrieve file or a File object
4422 * access mode of file (see jalview.io.AlignFile)
4423 * @return true if features file was parsed correctly.
4425 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4428 return avc.parseFeaturesFile(file, sourceType,
4429 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4434 public void refreshFeatureUI(boolean enableIfNecessary)
4436 // note - currently this is only still here rather than in the controller
4437 // because of the featureSettings hard reference that is yet to be
4439 if (enableIfNecessary)
4441 viewport.setShowSequenceFeatures(true);
4442 showSeqFeatures.setSelected(true);
4448 public void dragEnter(DropTargetDragEvent evt)
4453 public void dragExit(DropTargetEvent evt)
4458 public void dragOver(DropTargetDragEvent evt)
4463 public void dropActionChanged(DropTargetDragEvent evt)
4468 public void drop(DropTargetDropEvent evt)
4470 // JAL-1552 - acceptDrop required before getTransferable call for
4471 // Java's Transferable for native dnd
4472 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4473 Transferable t = evt.getTransferable();
4475 final AlignFrame thisaf = this;
4476 final List<Object> files = new ArrayList<>();
4477 List<DataSourceType> protocols = new ArrayList<>();
4481 Desktop.transferFromDropTarget(files, protocols, evt, t);
4482 } catch (Exception e)
4484 e.printStackTrace();
4488 new Thread(new Runnable()
4495 // check to see if any of these files have names matching sequences
4498 SequenceIdMatcher idm = new SequenceIdMatcher(
4499 viewport.getAlignment().getSequencesArray());
4501 * Object[] { String,SequenceI}
4503 ArrayList<Object[]> filesmatched = new ArrayList<>();
4504 ArrayList<Object> filesnotmatched = new ArrayList<>();
4505 for (int i = 0; i < files.size(); i++)
4508 Object file = files.get(i);
4509 String fileName = file.toString();
4511 DataSourceType protocol = (file instanceof File
4512 ? DataSourceType.FILE
4513 : FormatAdapter.checkProtocol(fileName));
4514 if (protocol == DataSourceType.FILE)
4516 File fl = (file instanceof File ? (File) file
4517 : new File(fileName));
4518 pdbfn = fl.getName();
4520 else if (protocol == DataSourceType.URL)
4522 URL url = new URL(fileName);
4523 pdbfn = url.getFile();
4525 if (pdbfn.length() > 0)
4527 // attempt to find a match in the alignment
4528 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4529 int l = 0, c = pdbfn.indexOf(".");
4530 while (mtch == null && c != -1)
4535 } while ((c = pdbfn.indexOf(".", l)) > l);
4538 pdbfn = pdbfn.substring(0, l);
4540 mtch = idm.findAllIdMatches(pdbfn);
4547 type = new IdentifyFile().identify(file, protocol);
4548 } catch (Exception ex)
4552 if (type != null && type.isStructureFile())
4554 filesmatched.add(new Object[] { file, protocol, mtch });
4558 // File wasn't named like one of the sequences or wasn't a PDB
4560 filesnotmatched.add(file);
4564 if (filesmatched.size() > 0)
4566 boolean autoAssociate = Cache
4567 .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4570 String msg = MessageManager.formatMessage(
4571 "label.automatically_associate_structure_files_with_sequences_same_name",
4573 { Integer.valueOf(filesmatched.size())
4575 String ttl = MessageManager.getString(
4576 "label.automatically_associate_structure_files_by_name");
4577 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4578 ttl, JvOptionPane.YES_NO_OPTION);
4579 autoAssociate = choice == JvOptionPane.YES_OPTION;
4583 for (Object[] fm : filesmatched)
4585 // try and associate
4586 // TODO: may want to set a standard ID naming formalism for
4587 // associating PDB files which have no IDs.
4588 for (SequenceI toassoc : (SequenceI[]) fm[2])
4590 PDBEntry pe = new AssociatePdbFileWithSeq()
4591 .associatePdbWithSeq(fm[0].toString(),
4592 (DataSourceType) fm[1], toassoc, false,
4596 System.err.println("Associated file : "
4597 + (fm[0].toString()) + " with "
4598 + toassoc.getDisplayId(true));
4602 // TODO: do we need to update overview ? only if features are
4604 alignPanel.paintAlignment(true, false);
4610 * add declined structures as sequences
4612 for (Object[] o : filesmatched)
4614 filesnotmatched.add(o[0]);
4618 if (filesnotmatched.size() > 0)
4620 if (assocfiles > 0 && (Cache.getDefault(
4621 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4622 || JvOptionPane.showConfirmDialog(thisaf,
4623 "<html>" + MessageManager.formatMessage(
4624 "label.ignore_unmatched_dropped_files_info",
4627 filesnotmatched.size())
4630 MessageManager.getString(
4631 "label.ignore_unmatched_dropped_files"),
4632 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4636 for (Object fn : filesnotmatched)
4638 loadJalviewDataFile(fn, null, null, null);
4642 } catch (Exception ex)
4644 ex.printStackTrace();
4652 * Attempt to load a "dropped" file or URL string, by testing in turn for
4654 * <li>an Annotation file</li>
4655 * <li>a JNet file</li>
4656 * <li>a features file</li>
4657 * <li>else try to interpret as an alignment file</li>
4661 * either a filename or a URL string.
4663 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4664 FileFormatI format, SequenceI assocSeq)
4666 // BH 2018 was String file
4669 if (sourceType == null)
4671 sourceType = FormatAdapter.checkProtocol(file);
4673 // if the file isn't identified, or not positively identified as some
4674 // other filetype (PFAM is default unidentified alignment file type) then
4675 // try to parse as annotation.
4676 boolean isAnnotation = (format == null
4677 || FileFormat.Pfam.equals(format))
4678 ? new AnnotationFile().annotateAlignmentView(viewport,
4684 // first see if its a T-COFFEE score file
4685 TCoffeeScoreFile tcf = null;
4688 tcf = new TCoffeeScoreFile(file, sourceType);
4691 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4695 new TCoffeeColourScheme(viewport.getAlignment()));
4696 isAnnotation = true;
4697 setStatus(MessageManager.getString(
4698 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4702 // some problem - if no warning its probable that the ID matching
4703 // process didn't work
4704 JvOptionPane.showMessageDialog(Desktop.desktop,
4705 tcf.getWarningMessage() == null
4706 ? MessageManager.getString(
4707 "label.check_file_matches_sequence_ids_alignment")
4708 : tcf.getWarningMessage(),
4709 MessageManager.getString(
4710 "label.problem_reading_tcoffee_score_file"),
4711 JvOptionPane.WARNING_MESSAGE);
4718 } catch (Exception x)
4721 "Exception when processing data source as T-COFFEE score file",
4727 // try to see if its a JNet 'concise' style annotation file *before*
4729 // try to parse it as a features file
4732 format = new IdentifyFile().identify(file, sourceType);
4734 if (FileFormat.ScoreMatrix == format)
4736 ScoreMatrixFile sm = new ScoreMatrixFile(
4737 new FileParse(file, sourceType));
4739 // todo: i18n this message
4740 setStatus(MessageManager.formatMessage(
4741 "label.successfully_loaded_matrix",
4742 sm.getMatrixName()));
4744 else if (FileFormat.Jnet.equals(format))
4746 JPredFile predictions = new JPredFile(file, sourceType);
4747 new JnetAnnotationMaker();
4748 JnetAnnotationMaker.add_annotation(predictions,
4749 viewport.getAlignment(), 0, false);
4750 viewport.getAlignment().setupJPredAlignment();
4751 isAnnotation = true;
4753 // else if (IdentifyFile.FeaturesFile.equals(format))
4754 else if (FileFormat.Features.equals(format))
4756 if (parseFeaturesFile(file, sourceType))
4758 alignPanel.paintAlignment(true, true);
4763 new FileLoader().LoadFile(viewport, file, sourceType, format);
4770 alignPanel.adjustAnnotationHeight();
4771 viewport.updateSequenceIdColours();
4772 buildSortByAnnotationScoresMenu();
4773 alignPanel.paintAlignment(true, true);
4775 } catch (Exception ex)
4777 ex.printStackTrace();
4778 } catch (OutOfMemoryError oom)
4783 } catch (Exception x)
4788 + (sourceType != null
4789 ? (sourceType == DataSourceType.PASTE
4791 : "using " + sourceType + " from "
4795 ? "(parsing as '" + format + "' file)"
4797 oom, Desktop.desktop);
4802 * Method invoked by the ChangeListener on the tabbed pane, in other words
4803 * when a different tabbed pane is selected by the user or programmatically.
4806 public void tabSelectionChanged(int index)
4810 alignPanel = alignPanels.get(index);
4811 viewport = alignPanel.av;
4812 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4813 setMenusFromViewport(viewport);
4817 * 'focus' any colour slider that is open to the selected viewport
4819 if (viewport.getConservationSelected())
4821 SliderPanel.setConservationSlider(alignPanel,
4822 viewport.getResidueShading(), alignPanel.getViewName());
4826 SliderPanel.hideConservationSlider();
4828 if (viewport.getAbovePIDThreshold())
4830 SliderPanel.setPIDSliderSource(alignPanel,
4831 viewport.getResidueShading(), alignPanel.getViewName());
4835 SliderPanel.hidePIDSlider();
4839 * If there is a frame linked to this one in a SplitPane, switch it to the
4840 * same view tab index. No infinite recursion of calls should happen, since
4841 * tabSelectionChanged() should not get invoked on setting the selected
4842 * index to an unchanged value. Guard against setting an invalid index
4843 * before the new view peer tab has been created.
4845 final AlignViewportI peer = viewport.getCodingComplement();
4848 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4849 .getAlignPanel().alignFrame;
4850 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4852 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4858 * On right mouse click on view tab, prompt for and set new view name.
4861 public void tabbedPane_mousePressed(MouseEvent e)
4863 if (e.isPopupTrigger())
4865 String msg = MessageManager.getString("label.enter_view_name");
4866 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
4867 String reply = JvOptionPane.showInputDialog(msg, ttl);
4871 viewport.setViewName(reply);
4872 // TODO warn if reply is in getExistingViewNames()?
4873 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4878 public AlignViewport getCurrentView()
4884 * Open the dialog for regex description parsing.
4887 protected void extractScores_actionPerformed(ActionEvent e)
4889 ParseProperties pp = new jalview.analysis.ParseProperties(
4890 viewport.getAlignment());
4891 // TODO: verify regex and introduce GUI dialog for version 2.5
4892 // if (pp.getScoresFromDescription("col", "score column ",
4893 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4895 if (pp.getScoresFromDescription("description column",
4896 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4898 buildSortByAnnotationScoresMenu();
4906 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4910 protected void showDbRefs_actionPerformed(ActionEvent e)
4912 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4918 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4922 protected void showNpFeats_actionPerformed(ActionEvent e)
4924 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4928 * find the viewport amongst the tabs in this alignment frame and close that
4933 public boolean closeView(AlignViewportI av)
4937 this.closeMenuItem_actionPerformed(false);
4940 Component[] comp = tabbedPane.getComponents();
4941 for (int i = 0; comp != null && i < comp.length; i++)
4943 if (comp[i] instanceof AlignmentPanel)
4945 if (((AlignmentPanel) comp[i]).av == av)
4948 closeView((AlignmentPanel) comp[i]);
4956 protected void build_fetchdbmenu(JMenu webService)
4958 // Temporary hack - DBRef Fetcher always top level ws entry.
4959 // TODO We probably want to store a sequence database checklist in
4960 // preferences and have checkboxes.. rather than individual sources selected
4962 final JMenu rfetch = new JMenu(
4963 MessageManager.getString("action.fetch_db_references"));
4964 rfetch.setToolTipText(MessageManager.getString(
4965 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4966 webService.add(rfetch);
4968 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4969 MessageManager.getString("option.trim_retrieved_seqs"));
4970 trimrs.setToolTipText(
4971 MessageManager.getString("label.trim_retrieved_sequences"));
4973 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
4974 trimrs.addActionListener(new ActionListener()
4977 public void actionPerformed(ActionEvent e)
4979 trimrs.setSelected(trimrs.isSelected());
4980 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
4981 Boolean.valueOf(trimrs.isSelected()).toString());
4985 JMenuItem fetchr = new JMenuItem(
4986 MessageManager.getString("label.standard_databases"));
4987 fetchr.setToolTipText(
4988 MessageManager.getString("label.fetch_embl_uniprot"));
4989 fetchr.addActionListener(new ActionListener()
4993 public void actionPerformed(ActionEvent e)
4995 new Thread(new Runnable()
5000 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5001 .getAlignment().isNucleotide();
5002 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5003 alignPanel.av.getSequenceSelection(),
5004 alignPanel.alignFrame, null,
5005 alignPanel.alignFrame.featureSettings, isNucleotide);
5006 dbRefFetcher.addListener(new FetchFinishedListenerI()
5009 public void finished()
5011 AlignFrame.this.setMenusForViewport();
5014 dbRefFetcher.fetchDBRefs(false);
5022 final AlignFrame me = this;
5023 new Thread(new Runnable()
5028 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5029 .getSequenceFetcherSingleton(me);
5030 javax.swing.SwingUtilities.invokeLater(new Runnable()
5035 String[] dbclasses = sf.getOrderedSupportedSources();
5036 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5037 // jalview.util.QuickSort.sort(otherdb, otherdb);
5038 List<DbSourceProxy> otherdb;
5039 JMenu dfetch = new JMenu();
5040 JMenu ifetch = new JMenu();
5041 JMenuItem fetchr = null;
5042 int comp = 0, icomp = 0, mcomp = 15;
5043 String mname = null;
5045 for (String dbclass : dbclasses)
5047 otherdb = sf.getSourceProxy(dbclass);
5048 // add a single entry for this class, or submenu allowing 'fetch
5050 if (otherdb == null || otherdb.size() < 1)
5054 // List<DbSourceProxy> dbs=otherdb;
5055 // otherdb=new ArrayList<DbSourceProxy>();
5056 // for (DbSourceProxy db:dbs)
5058 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5062 mname = "From " + dbclass;
5064 if (otherdb.size() == 1)
5066 final DbSourceProxy[] dassource = otherdb
5067 .toArray(new DbSourceProxy[0]);
5068 DbSourceProxy src = otherdb.get(0);
5069 fetchr = new JMenuItem(src.getDbSource());
5070 fetchr.addActionListener(new ActionListener()
5074 public void actionPerformed(ActionEvent e)
5076 new Thread(new Runnable()
5082 boolean isNucleotide = alignPanel.alignFrame
5083 .getViewport().getAlignment()
5085 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5086 alignPanel.av.getSequenceSelection(),
5087 alignPanel.alignFrame, dassource,
5088 alignPanel.alignFrame.featureSettings,
5091 .addListener(new FetchFinishedListenerI()
5094 public void finished()
5096 AlignFrame.this.setMenusForViewport();
5099 dbRefFetcher.fetchDBRefs(false);
5105 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5106 MessageManager.formatMessage(
5107 "label.fetch_retrieve_from", new Object[]
5108 { src.getDbName() })));
5114 final DbSourceProxy[] dassource = otherdb
5115 .toArray(new DbSourceProxy[0]);
5117 DbSourceProxy src = otherdb.get(0);
5118 fetchr = new JMenuItem(MessageManager
5119 .formatMessage("label.fetch_all_param", new Object[]
5120 { src.getDbSource() }));
5121 fetchr.addActionListener(new ActionListener()
5124 public void actionPerformed(ActionEvent e)
5126 new Thread(new Runnable()
5132 boolean isNucleotide = alignPanel.alignFrame
5133 .getViewport().getAlignment()
5135 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5136 alignPanel.av.getSequenceSelection(),
5137 alignPanel.alignFrame, dassource,
5138 alignPanel.alignFrame.featureSettings,
5141 .addListener(new FetchFinishedListenerI()
5144 public void finished()
5146 AlignFrame.this.setMenusForViewport();
5149 dbRefFetcher.fetchDBRefs(false);
5155 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5156 MessageManager.formatMessage(
5157 "label.fetch_retrieve_from_all_sources",
5159 { Integer.valueOf(otherdb.size())
5161 src.getDbSource(), src.getDbName() })));
5164 // and then build the rest of the individual menus
5165 ifetch = new JMenu(MessageManager.formatMessage(
5166 "label.source_from_db_source", new Object[]
5167 { src.getDbSource() }));
5169 String imname = null;
5171 for (DbSourceProxy sproxy : otherdb)
5173 String dbname = sproxy.getDbName();
5174 String sname = dbname.length() > 5
5175 ? dbname.substring(0, 5) + "..."
5177 String msname = dbname.length() > 10
5178 ? dbname.substring(0, 10) + "..."
5182 imname = MessageManager
5183 .formatMessage("label.from_msname", new Object[]
5186 fetchr = new JMenuItem(msname);
5187 final DbSourceProxy[] dassrc = { sproxy };
5188 fetchr.addActionListener(new ActionListener()
5192 public void actionPerformed(ActionEvent e)
5194 new Thread(new Runnable()
5200 boolean isNucleotide = alignPanel.alignFrame
5201 .getViewport().getAlignment()
5203 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5204 alignPanel.av.getSequenceSelection(),
5205 alignPanel.alignFrame, dassrc,
5206 alignPanel.alignFrame.featureSettings,
5209 .addListener(new FetchFinishedListenerI()
5212 public void finished()
5214 AlignFrame.this.setMenusForViewport();
5217 dbRefFetcher.fetchDBRefs(false);
5223 fetchr.setToolTipText(
5224 "<html>" + MessageManager.formatMessage(
5225 "label.fetch_retrieve_from", new Object[]
5229 if (++icomp >= mcomp || i == (otherdb.size()))
5231 ifetch.setText(MessageManager.formatMessage(
5232 "label.source_to_target", imname, sname));
5234 ifetch = new JMenu();
5242 if (comp >= mcomp || dbi >= (dbclasses.length))
5244 dfetch.setText(MessageManager.formatMessage(
5245 "label.source_to_target", mname, dbclass));
5247 dfetch = new JMenu();
5260 * Left justify the whole alignment.
5263 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5265 AlignmentI al = viewport.getAlignment();
5267 viewport.firePropertyChange("alignment", null, al);
5271 * Right justify the whole alignment.
5274 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5276 AlignmentI al = viewport.getAlignment();
5278 viewport.firePropertyChange("alignment", null, al);
5282 public void setShowSeqFeatures(boolean b)
5284 showSeqFeatures.setSelected(b);
5285 viewport.setShowSequenceFeatures(b);
5292 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5293 * awt.event.ActionEvent)
5296 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5298 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5299 alignPanel.paintAlignment(false, false);
5306 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5310 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5312 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5313 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5321 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5322 * .event.ActionEvent)
5325 protected void showGroupConservation_actionPerformed(ActionEvent e)
5327 viewport.setShowGroupConservation(showGroupConservation.getState());
5328 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5335 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5336 * .event.ActionEvent)
5339 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5341 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5342 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5349 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5350 * .event.ActionEvent)
5353 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5355 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5356 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5360 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5362 showSequenceLogo.setState(true);
5363 viewport.setShowSequenceLogo(true);
5364 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5365 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5369 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5371 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5378 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5379 * .event.ActionEvent)
5382 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5384 if (avc.makeGroupsFromSelection())
5386 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5387 alignPanel.updateAnnotation();
5388 alignPanel.paintAlignment(true, true);
5392 public void clearAlignmentSeqRep()
5394 // TODO refactor alignmentseqrep to controller
5395 if (viewport.getAlignment().hasSeqrep())
5397 viewport.getAlignment().setSeqrep(null);
5398 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5399 alignPanel.updateAnnotation();
5400 alignPanel.paintAlignment(true, true);
5405 protected void createGroup_actionPerformed(ActionEvent e)
5407 if (avc.createGroup())
5409 if (applyAutoAnnotationSettings.isSelected())
5411 alignPanel.updateAnnotation(true, false);
5413 alignPanel.alignmentChanged();
5418 protected void unGroup_actionPerformed(ActionEvent e)
5422 alignPanel.alignmentChanged();
5427 * make the given alignmentPanel the currently selected tab
5429 * @param alignmentPanel
5431 public void setDisplayedView(AlignmentPanel alignmentPanel)
5433 if (!viewport.getSequenceSetId()
5434 .equals(alignmentPanel.av.getSequenceSetId()))
5436 throw new Error(MessageManager.getString(
5437 "error.implementation_error_cannot_show_view_alignment_frame"));
5439 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5440 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5442 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5447 * Action on selection of menu options to Show or Hide annotations.
5450 * @param forSequences
5451 * update sequence-related annotations
5452 * @param forAlignment
5453 * update non-sequence-related annotations
5456 protected void setAnnotationsVisibility(boolean visible,
5457 boolean forSequences, boolean forAlignment)
5459 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5460 .getAlignmentAnnotation();
5465 for (AlignmentAnnotation aa : anns)
5468 * don't display non-positional annotations on an alignment
5470 if (aa.annotations == null)
5474 boolean apply = (aa.sequenceRef == null && forAlignment)
5475 || (aa.sequenceRef != null && forSequences);
5478 aa.visible = visible;
5481 alignPanel.validateAnnotationDimensions(true);
5482 alignPanel.alignmentChanged();
5486 * Store selected annotation sort order for the view and repaint.
5489 protected void sortAnnotations_actionPerformed()
5491 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5493 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5494 alignPanel.paintAlignment(false, false);
5499 * @return alignment panels in this alignment frame
5501 public List<? extends AlignmentViewPanel> getAlignPanels()
5503 // alignPanels is never null
5504 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5509 * Open a new alignment window, with the cDNA associated with this (protein)
5510 * alignment, aligned as is the protein.
5512 protected void viewAsCdna_actionPerformed()
5514 // TODO no longer a menu action - refactor as required
5515 final AlignmentI alignment = getViewport().getAlignment();
5516 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5517 if (mappings == null)
5521 List<SequenceI> cdnaSeqs = new ArrayList<>();
5522 for (SequenceI aaSeq : alignment.getSequences())
5524 for (AlignedCodonFrame acf : mappings)
5526 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5530 * There is a cDNA mapping for this protein sequence - add to new
5531 * alignment. It will share the same dataset sequence as other mapped
5532 * cDNA (no new mappings need to be created).
5534 final Sequence newSeq = new Sequence(dnaSeq);
5535 newSeq.setDatasetSequence(dnaSeq);
5536 cdnaSeqs.add(newSeq);
5540 if (cdnaSeqs.size() == 0)
5542 // show a warning dialog no mapped cDNA
5545 AlignmentI cdna = new Alignment(
5546 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5547 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5548 AlignFrame.DEFAULT_HEIGHT);
5549 cdna.alignAs(alignment);
5550 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5552 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5553 AlignFrame.DEFAULT_HEIGHT);
5557 * Set visibility of dna/protein complement view (available when shown in a
5563 protected void showComplement_actionPerformed(boolean show)
5565 SplitContainerI sf = getSplitViewContainer();
5568 sf.setComplementVisible(this, show);
5573 * Generate the reverse (optionally complemented) of the selected sequences,
5574 * and add them to the alignment
5577 protected void showReverse_actionPerformed(boolean complement)
5579 AlignmentI al = null;
5582 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5583 al = dna.reverseCdna(complement);
5584 viewport.addAlignment(al, "");
5585 addHistoryItem(new EditCommand(
5586 MessageManager.getString("label.add_sequences"), Action.PASTE,
5587 al.getSequencesArray(), 0, al.getWidth(),
5588 viewport.getAlignment()));
5589 } catch (Exception ex)
5591 System.err.println(ex.getMessage());
5597 * Try to run a script in the Groovy console, having first ensured that this
5598 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5599 * be targeted at this alignment.
5602 protected void runGroovy_actionPerformed()
5604 Jalview.setCurrentAlignFrame(this);
5605 groovy.ui.Console console = Desktop.getGroovyConsole();
5606 if (console != null)
5610 console.runScript();
5611 } catch (Exception ex)
5613 System.err.println((ex.toString()));
5614 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5615 MessageManager.getString("label.couldnt_run_groovy_script"),
5616 MessageManager.getString("label.groovy_support_failed"),
5617 JvOptionPane.ERROR_MESSAGE);
5622 System.err.println("Can't run Groovy script as console not found");
5627 * Hides columns containing (or not containing) a specified feature, provided
5628 * that would not leave all columns hidden
5630 * @param featureType
5631 * @param columnsContaining
5634 public boolean hideFeatureColumns(String featureType,
5635 boolean columnsContaining)
5637 boolean notForHiding = avc.markColumnsContainingFeatures(
5638 columnsContaining, false, false, featureType);
5641 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5642 false, featureType))
5644 getViewport().hideSelectedColumns();
5652 protected void selectHighlightedColumns_actionPerformed(
5653 ActionEvent actionEvent)
5655 // include key modifier check in case user selects from menu
5656 avc.markHighlightedColumns(
5657 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5658 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5659 | ActionEvent.CTRL_MASK)) != 0);
5663 * Rebuilds the Colour menu, including any user-defined colours which have
5664 * been loaded either on startup or during the session
5666 public void buildColourMenu()
5668 colourMenu.removeAll();
5670 colourMenu.add(applyToAllGroups);
5671 colourMenu.add(textColour);
5672 colourMenu.addSeparator();
5674 ColourMenuHelper.addMenuItems(colourMenu, this, viewport.getAlignment(),
5677 colourMenu.addSeparator();
5678 colourMenu.add(conservationMenuItem);
5679 colourMenu.add(modifyConservation);
5680 colourMenu.add(abovePIDThreshold);
5681 colourMenu.add(modifyPID);
5682 colourMenu.add(annotationColour);
5684 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5685 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5689 * Open a dialog (if not already open) that allows the user to select and
5690 * calculate PCA or Tree analysis
5692 protected void openTreePcaDialog()
5694 if (alignPanel.getCalculationDialog() == null)
5696 new CalculationChooser(AlignFrame.this);
5701 protected void loadVcf_actionPerformed()
5703 JalviewFileChooser chooser = new JalviewFileChooser(
5704 Cache.getProperty("LAST_DIRECTORY"));
5705 chooser.setFileView(new JalviewFileView());
5706 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5707 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5708 final AlignFrame us = this;
5709 chooser.response(new RunResponse(JalviewFileChooser.APPROVE_OPTION)
5716 String choice = chooser.getSelectedFile().getPath();
5717 Cache.setProperty("LAST_DIRECTORY", choice);
5718 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5719 new VCFLoader(choice).loadVCF(seqs, us);
5723 }).openDialog(null);
5729 class PrintThread extends Thread
5733 public PrintThread(AlignmentPanel ap)
5738 static PageFormat pf;
5743 PrinterJob printJob = PrinterJob.getPrinterJob();
5747 printJob.setPrintable(ap, pf);
5751 printJob.setPrintable(ap);
5754 if (printJob.printDialog())
5759 } catch (Exception PrintException)
5761 PrintException.printStackTrace();