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.analysis.TreeModel;
30 import jalview.api.AlignExportSettingI;
31 import jalview.api.AlignViewControllerGuiI;
32 import jalview.api.AlignViewControllerI;
33 import jalview.api.AlignViewportI;
34 import jalview.api.AlignmentViewPanel;
35 import jalview.api.FeatureSettingsControllerI;
36 import jalview.api.SplitContainerI;
37 import jalview.api.ViewStyleI;
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.AlignedCodonFrame;
49 import jalview.datamodel.Alignment;
50 import jalview.datamodel.AlignmentAnnotation;
51 import jalview.datamodel.AlignmentExportData;
52 import jalview.datamodel.AlignmentI;
53 import jalview.datamodel.AlignmentOrder;
54 import jalview.datamodel.AlignmentView;
55 import jalview.datamodel.ColumnSelection;
56 import jalview.datamodel.DBRefEntry;
57 import jalview.datamodel.HiddenColumns;
58 import jalview.datamodel.HiddenSequences;
59 import jalview.datamodel.PDBEntry;
60 import jalview.datamodel.SeqCigar;
61 import jalview.datamodel.Sequence;
62 import jalview.datamodel.SequenceGroup;
63 import jalview.datamodel.SequenceI;
64 import jalview.ext.archaeopteryx.AptxInit;
65 import jalview.ext.archaeopteryx.JalviewBinding;
66 import jalview.ext.forester.io.SupportedTreeFileFilter;
67 import jalview.ext.forester.io.TreeParser;
68 import jalview.gui.ColourMenuHelper.ColourChangeListener;
69 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
70 import jalview.io.AlignmentProperties;
71 import jalview.io.AnnotationFile;
72 import jalview.io.BioJsHTMLOutput;
73 import jalview.io.DataSourceType;
74 import jalview.io.FileFormat;
75 import jalview.io.FileFormatI;
76 import jalview.io.FileFormats;
77 import jalview.io.FileLoader;
78 import jalview.io.FileParse;
79 import jalview.io.FormatAdapter;
80 import jalview.io.HtmlSvgOutput;
81 import jalview.io.IdentifyFile;
82 import jalview.io.JPredFile;
83 import jalview.io.JalviewFileChooser;
84 import jalview.io.JalviewFileView;
85 import jalview.io.JnetAnnotationMaker;
86 import jalview.io.NewickFile;
87 import jalview.io.ScoreMatrixFile;
88 import jalview.io.TCoffeeScoreFile;
89 import jalview.jbgui.GAlignFrame;
90 import jalview.schemes.ColourSchemeI;
91 import jalview.schemes.ColourSchemes;
92 import jalview.schemes.ResidueColourScheme;
93 import jalview.schemes.TCoffeeColourScheme;
94 import jalview.util.DBRefUtils;
95 import jalview.util.MessageManager;
96 import jalview.viewmodel.AlignmentViewport;
97 import jalview.viewmodel.ViewportRanges;
98 import jalview.ws.DBRefFetcher;
99 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
100 import jalview.ws.jws1.Discoverer;
101 import jalview.ws.jws2.Jws2Discoverer;
102 import jalview.ws.jws2.jabaws2.Jws2Instance;
103 import jalview.ws.seqfetcher.DbSourceProxy;
105 import java.awt.BorderLayout;
106 import java.awt.Component;
107 import java.awt.Dimension;
108 import java.awt.GridLayout;
109 import java.awt.Rectangle;
110 import java.awt.Toolkit;
111 import java.awt.datatransfer.Clipboard;
112 import java.awt.datatransfer.DataFlavor;
113 import java.awt.datatransfer.StringSelection;
114 import java.awt.datatransfer.Transferable;
115 import java.awt.dnd.DnDConstants;
116 import java.awt.dnd.DropTargetDragEvent;
117 import java.awt.dnd.DropTargetDropEvent;
118 import java.awt.dnd.DropTargetEvent;
119 import java.awt.dnd.DropTargetListener;
120 import java.awt.event.ActionEvent;
121 import java.awt.event.ActionListener;
122 import java.awt.event.FocusAdapter;
123 import java.awt.event.FocusEvent;
124 import java.awt.event.ItemEvent;
125 import java.awt.event.ItemListener;
126 import java.awt.event.KeyAdapter;
127 import java.awt.event.KeyEvent;
128 import java.awt.event.MouseEvent;
129 import java.awt.print.PageFormat;
130 import java.awt.print.PrinterJob;
131 import java.beans.PropertyChangeEvent;
133 import java.io.FileWriter;
134 import java.io.IOException;
135 import java.io.PrintWriter;
137 import java.util.ArrayList;
138 import java.util.Arrays;
139 import java.util.Deque;
140 import java.util.Enumeration;
141 import java.util.Hashtable;
142 import java.util.List;
143 import java.util.Map;
144 import java.util.StringTokenizer;
145 import java.util.Vector;
147 import javax.swing.JCheckBoxMenuItem;
148 import javax.swing.JComboBox;
149 import javax.swing.JEditorPane;
150 import javax.swing.JInternalFrame;
151 import javax.swing.JLabel;
152 import javax.swing.JLayeredPane;
153 import javax.swing.JMenu;
154 import javax.swing.JMenuItem;
155 import javax.swing.JPanel;
156 import javax.swing.JScrollPane;
157 import javax.swing.SwingUtilities;
159 import org.forester.archaeopteryx.MainFrame;
160 import org.forester.archaeopteryx.webservices.PhylogeniesWebserviceClient;
161 import org.forester.archaeopteryx.webservices.WebservicesManager;
167 * @version $Revision$
169 public class AlignFrame extends GAlignFrame implements DropTargetListener,
170 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
173 public static final int DEFAULT_WIDTH = 700;
175 public static final int DEFAULT_HEIGHT = 500;
178 * The currently displayed panel (selected tabbed view if more than one)
180 public AlignmentPanel alignPanel;
182 AlignViewport viewport;
184 public AlignViewControllerI avc;
186 List<AlignmentPanel> alignPanels = new ArrayList<>();
189 * Last format used to load or save alignments in this window
191 FileFormatI currentFileFormat = null;
194 * Current filename for this alignment
196 String fileName = null;
199 * Creates a new AlignFrame object with specific width and height.
205 public AlignFrame(AlignmentI al, int width, int height)
207 this(al, null, width, height);
211 * Creates a new AlignFrame object with specific width, height and
217 * @param sequenceSetId
219 public AlignFrame(AlignmentI al, int width, int height,
220 String sequenceSetId)
222 this(al, null, width, height, sequenceSetId);
226 * Creates a new AlignFrame object with specific width, height and
232 * @param sequenceSetId
235 public AlignFrame(AlignmentI al, int width, int height,
236 String sequenceSetId, String viewId)
238 this(al, null, width, height, sequenceSetId, viewId);
242 * new alignment window with hidden columns
246 * @param hiddenColumns
247 * ColumnSelection or null
249 * Width of alignment frame
253 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
256 this(al, hiddenColumns, width, height, null);
260 * Create alignment frame for al with hiddenColumns, a specific width and
261 * height, and specific sequenceId
264 * @param hiddenColumns
267 * @param sequenceSetId
270 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
271 int height, String sequenceSetId)
273 this(al, hiddenColumns, width, height, sequenceSetId, null);
277 * Create alignment frame for al with hiddenColumns, a specific width and
278 * height, and specific sequenceId
281 * @param hiddenColumns
284 * @param sequenceSetId
289 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
290 int height, String sequenceSetId, String viewId)
292 setSize(width, height);
294 if (al.getDataset() == null)
299 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
301 alignPanel = new AlignmentPanel(this, viewport);
303 addAlignmentPanel(alignPanel, true);
307 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
308 HiddenColumns hiddenColumns, int width, int height)
310 setSize(width, height);
312 if (al.getDataset() == null)
317 viewport = new AlignViewport(al, hiddenColumns);
319 if (hiddenSeqs != null && hiddenSeqs.length > 0)
321 viewport.hideSequence(hiddenSeqs);
323 alignPanel = new AlignmentPanel(this, viewport);
324 addAlignmentPanel(alignPanel, true);
329 * Make a new AlignFrame from existing alignmentPanels
336 public AlignFrame(AlignmentPanel ap)
340 addAlignmentPanel(ap, false);
345 * initalise the alignframe from the underlying viewport data and the
350 if (!Jalview.isHeadlessMode())
352 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
355 avc = new jalview.controller.AlignViewController(this, viewport,
357 if (viewport.getAlignmentConservationAnnotation() == null)
359 // BLOSUM62Colour.setEnabled(false);
360 conservationMenuItem.setEnabled(false);
361 modifyConservation.setEnabled(false);
362 // PIDColour.setEnabled(false);
363 // abovePIDThreshold.setEnabled(false);
364 // modifyPID.setEnabled(false);
367 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
370 if (sortby.equals("Id"))
372 sortIDMenuItem_actionPerformed(null);
374 else if (sortby.equals("Pairwise Identity"))
376 sortPairwiseMenuItem_actionPerformed(null);
380 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
382 setMenusFromViewport(viewport);
383 buildSortByAnnotationScoresMenu();
384 calculateTree.addActionListener(new ActionListener()
388 public void actionPerformed(ActionEvent e)
395 if (Desktop.desktop != null)
397 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
398 addServiceListeners();
402 if (viewport.getWrapAlignment())
404 wrapMenuItem_actionPerformed(null);
407 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
409 this.overviewMenuItem_actionPerformed(null);
414 final List<AlignmentPanel> selviews = new ArrayList<>();
415 final List<AlignmentPanel> origview = new ArrayList<>();
416 final String menuLabel = MessageManager
417 .getString("label.copy_format_from");
418 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
419 new ViewSetProvider()
423 public AlignmentPanel[] getAllAlignmentPanels()
426 origview.add(alignPanel);
427 // make an array of all alignment panels except for this one
428 List<AlignmentPanel> aps = new ArrayList<>(
429 Arrays.asList(Desktop.getAlignmentPanels(null)));
430 aps.remove(AlignFrame.this.alignPanel);
431 return aps.toArray(new AlignmentPanel[aps.size()]);
433 }, selviews, new ItemListener()
437 public void itemStateChanged(ItemEvent e)
439 if (origview.size() > 0)
441 final AlignmentPanel ap = origview.get(0);
444 * Copy the ViewStyle of the selected panel to 'this one'.
445 * Don't change value of 'scaleProteinAsCdna' unless copying
448 ViewStyleI vs = selviews.get(0).getAlignViewport()
450 boolean fromSplitFrame = selviews.get(0)
451 .getAlignViewport().getCodingComplement() != null;
454 vs.setScaleProteinAsCdna(ap.getAlignViewport()
455 .getViewStyle().isScaleProteinAsCdna());
457 ap.getAlignViewport().setViewStyle(vs);
460 * Also rescale ViewStyle of SplitFrame complement if there is
461 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
462 * the whole ViewStyle (allow cDNA protein to have different
465 AlignViewportI complement = ap.getAlignViewport()
466 .getCodingComplement();
467 if (complement != null && vs.isScaleProteinAsCdna())
469 AlignFrame af = Desktop.getAlignFrameFor(complement);
470 ((SplitFrame) af.getSplitViewContainer())
472 af.setMenusForViewport();
476 ap.setSelected(true);
477 ap.alignFrame.setMenusForViewport();
482 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
483 .indexOf("devel") > -1
484 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
485 .indexOf("test") > -1)
487 formatMenu.add(vsel);
489 addFocusListener(new FocusAdapter()
492 public void focusGained(FocusEvent e)
494 Jalview.setCurrentAlignFrame(AlignFrame.this);
501 * Change the filename and format for the alignment, and enable the 'reload'
502 * button functionality.
509 public void setFileName(String file, FileFormatI format)
512 setFileFormat(format);
513 reload.setEnabled(true);
517 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
520 void addKeyListener()
522 addKeyListener(new KeyAdapter()
525 public void keyPressed(KeyEvent evt)
527 if (viewport.cursorMode
528 && ((evt.getKeyCode() >= KeyEvent.VK_0
529 && evt.getKeyCode() <= KeyEvent.VK_9)
530 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
531 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
532 && Character.isDigit(evt.getKeyChar()))
534 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
537 switch (evt.getKeyCode())
540 case 27: // escape key
541 deselectAllSequenceMenuItem_actionPerformed(null);
545 case KeyEvent.VK_DOWN:
546 if (evt.isAltDown() || !viewport.cursorMode)
548 moveSelectedSequences(false);
550 if (viewport.cursorMode)
552 alignPanel.getSeqPanel().moveCursor(0, 1);
557 if (evt.isAltDown() || !viewport.cursorMode)
559 moveSelectedSequences(true);
561 if (viewport.cursorMode)
563 alignPanel.getSeqPanel().moveCursor(0, -1);
568 case KeyEvent.VK_LEFT:
569 if (evt.isAltDown() || !viewport.cursorMode)
571 slideSequences(false,
572 alignPanel.getSeqPanel().getKeyboardNo1());
576 alignPanel.getSeqPanel().moveCursor(-1, 0);
581 case KeyEvent.VK_RIGHT:
582 if (evt.isAltDown() || !viewport.cursorMode)
584 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
588 alignPanel.getSeqPanel().moveCursor(1, 0);
592 case KeyEvent.VK_SPACE:
593 if (viewport.cursorMode)
595 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
596 || evt.isShiftDown() || evt.isAltDown());
600 // case KeyEvent.VK_A:
601 // if (viewport.cursorMode)
603 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
604 // //System.out.println("A");
608 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
609 * System.out.println("closing bracket"); } break;
611 case KeyEvent.VK_DELETE:
612 case KeyEvent.VK_BACK_SPACE:
613 if (!viewport.cursorMode)
615 cut_actionPerformed(null);
619 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
620 || evt.isShiftDown() || evt.isAltDown());
626 if (viewport.cursorMode)
628 alignPanel.getSeqPanel().setCursorRow();
632 if (viewport.cursorMode && !evt.isControlDown())
634 alignPanel.getSeqPanel().setCursorColumn();
638 if (viewport.cursorMode)
640 alignPanel.getSeqPanel().setCursorPosition();
644 case KeyEvent.VK_ENTER:
645 case KeyEvent.VK_COMMA:
646 if (viewport.cursorMode)
648 alignPanel.getSeqPanel().setCursorRowAndColumn();
653 if (viewport.cursorMode)
655 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
659 if (viewport.cursorMode)
661 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
666 viewport.cursorMode = !viewport.cursorMode;
667 statusBar.setText(MessageManager
668 .formatMessage("label.keyboard_editing_mode", new String[]
669 { (viewport.cursorMode ? "on" : "off") }));
670 if (viewport.cursorMode)
672 ViewportRanges ranges = viewport.getRanges();
673 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
675 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
678 alignPanel.getSeqPanel().seqCanvas.repaint();
684 Help.showHelpWindow();
685 } catch (Exception ex)
687 ex.printStackTrace();
692 boolean toggleSeqs = !evt.isControlDown();
693 boolean toggleCols = !evt.isShiftDown();
694 toggleHiddenRegions(toggleSeqs, toggleCols);
699 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
700 boolean modifyExisting = true; // always modify, don't clear
701 // evt.isShiftDown();
702 boolean invertHighlighted = evt.isAltDown();
703 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
707 case KeyEvent.VK_PAGE_UP:
708 viewport.getRanges().pageUp();
710 case KeyEvent.VK_PAGE_DOWN:
711 viewport.getRanges().pageDown();
717 public void keyReleased(KeyEvent evt)
719 switch (evt.getKeyCode())
721 case KeyEvent.VK_LEFT:
722 if (evt.isAltDown() || !viewport.cursorMode)
724 viewport.firePropertyChange("alignment", null,
725 viewport.getAlignment().getSequences());
729 case KeyEvent.VK_RIGHT:
730 if (evt.isAltDown() || !viewport.cursorMode)
732 viewport.firePropertyChange("alignment", null,
733 viewport.getAlignment().getSequences());
741 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
743 ap.alignFrame = this;
744 avc = new jalview.controller.AlignViewController(this, viewport,
749 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
751 int aSize = alignPanels.size();
753 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
755 if (aSize == 1 && ap.av.viewName == null)
757 this.getContentPane().add(ap, BorderLayout.CENTER);
763 setInitialTabVisible();
766 expandViews.setEnabled(true);
767 gatherViews.setEnabled(true);
768 tabbedPane.addTab(ap.av.viewName, ap);
770 ap.setVisible(false);
775 if (ap.av.isPadGaps())
777 ap.av.getAlignment().padGaps();
779 ap.av.updateConservation(ap);
780 ap.av.updateConsensus(ap);
781 ap.av.updateStrucConsensus(ap);
785 public void setInitialTabVisible()
787 expandViews.setEnabled(true);
788 gatherViews.setEnabled(true);
789 tabbedPane.setVisible(true);
790 AlignmentPanel first = alignPanels.get(0);
791 tabbedPane.addTab(first.av.viewName, first);
792 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
795 public AlignViewport getViewport()
800 /* Set up intrinsic listeners for dynamically generated GUI bits. */
801 private void addServiceListeners()
803 final java.beans.PropertyChangeListener thisListener;
804 Desktop.instance.addJalviewPropertyChangeListener("services",
805 thisListener = new java.beans.PropertyChangeListener()
808 public void propertyChange(PropertyChangeEvent evt)
810 // // System.out.println("Discoverer property change.");
811 // if (evt.getPropertyName().equals("services"))
813 SwingUtilities.invokeLater(new Runnable()
820 "Rebuild WS Menu for service change");
821 BuildWebServiceMenu();
828 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
831 public void internalFrameClosed(
832 javax.swing.event.InternalFrameEvent evt)
834 // System.out.println("deregistering discoverer listener");
835 Desktop.instance.removeJalviewPropertyChangeListener("services",
837 closeMenuItem_actionPerformed(true);
840 // Finally, build the menu once to get current service state
841 new Thread(new Runnable()
846 BuildWebServiceMenu();
852 * Configure menu items that vary according to whether the alignment is
853 * nucleotide or protein
855 public void setGUINucleotide()
857 AlignmentI al = getViewport().getAlignment();
858 boolean nucleotide = al.isNucleotide();
860 showTranslation.setVisible(nucleotide);
861 showReverse.setVisible(nucleotide);
862 showReverseComplement.setVisible(nucleotide);
863 conservationMenuItem.setEnabled(!nucleotide);
865 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
866 showGroupConservation.setEnabled(!nucleotide);
868 showComplementMenuItem
869 .setText(nucleotide ? MessageManager.getString("label.protein")
870 : MessageManager.getString("label.nucleotide"));
874 * set up menus for the current viewport. This may be called after any
875 * operation that affects the data in the current view (selection changed,
876 * etc) to update the menus to reflect the new state.
879 public void setMenusForViewport()
881 setMenusFromViewport(viewport);
885 * Need to call this method when tabs are selected for multiple views, or when
886 * loading from Jalview2XML.java
891 void setMenusFromViewport(AlignViewport av)
893 padGapsMenuitem.setSelected(av.isPadGaps());
894 colourTextMenuItem.setSelected(av.isShowColourText());
895 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
896 modifyPID.setEnabled(abovePIDThreshold.isSelected());
897 conservationMenuItem.setSelected(av.getConservationSelected());
898 modifyConservation.setEnabled(conservationMenuItem.isSelected());
899 seqLimits.setSelected(av.getShowJVSuffix());
900 idRightAlign.setSelected(av.isRightAlignIds());
901 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
902 renderGapsMenuItem.setSelected(av.isRenderGaps());
903 wrapMenuItem.setSelected(av.getWrapAlignment());
904 scaleAbove.setVisible(av.getWrapAlignment());
905 scaleLeft.setVisible(av.getWrapAlignment());
906 scaleRight.setVisible(av.getWrapAlignment());
907 annotationPanelMenuItem.setState(av.isShowAnnotation());
909 * Show/hide annotations only enabled if annotation panel is shown
911 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
912 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
913 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
914 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
915 viewBoxesMenuItem.setSelected(av.getShowBoxes());
916 viewTextMenuItem.setSelected(av.getShowText());
917 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
918 showGroupConsensus.setSelected(av.isShowGroupConsensus());
919 showGroupConservation.setSelected(av.isShowGroupConservation());
920 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
921 showSequenceLogo.setSelected(av.isShowSequenceLogo());
922 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
924 ColourMenuHelper.setColourSelected(colourMenu,
925 av.getGlobalColourScheme());
927 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
928 hiddenMarkers.setState(av.getShowHiddenMarkers());
929 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
930 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
931 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
932 autoCalculate.setSelected(av.autoCalculateConsensus);
933 sortByTree.setSelected(av.sortByTree);
934 listenToViewSelections.setSelected(av.followSelection);
936 showProducts.setEnabled(canShowProducts());
937 setGroovyEnabled(Desktop.getGroovyConsole() != null);
943 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
947 public void setGroovyEnabled(boolean b)
949 runGroovy.setEnabled(b);
952 private IProgressIndicator progressBar;
957 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
960 public void setProgressBar(String message, long id)
962 progressBar.setProgressBar(message, id);
966 public void registerHandler(final long id,
967 final IProgressIndicatorHandler handler)
969 progressBar.registerHandler(id, handler);
974 * @return true if any progress bars are still active
977 public boolean operationInProgress()
979 return progressBar.operationInProgress();
983 public void setStatus(String text)
985 statusBar.setText(text);
989 * Added so Castor Mapping file can obtain Jalview Version
991 public String getVersion()
993 return jalview.bin.Cache.getProperty("VERSION");
996 public FeatureRenderer getFeatureRenderer()
998 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1002 public void fetchSequence_actionPerformed(ActionEvent e)
1004 new jalview.gui.SequenceFetcher(this);
1008 public void addFromFile_actionPerformed(ActionEvent e)
1010 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1014 public void reload_actionPerformed(ActionEvent e)
1016 if (fileName != null)
1018 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1019 // originating file's format
1020 // TODO: work out how to recover feature settings for correct view(s) when
1021 // file is reloaded.
1022 if (FileFormat.Jalview.equals(currentFileFormat))
1024 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1025 for (int i = 0; i < frames.length; i++)
1027 if (frames[i] instanceof AlignFrame && frames[i] != this
1028 && ((AlignFrame) frames[i]).fileName != null
1029 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1033 frames[i].setSelected(true);
1034 Desktop.instance.closeAssociatedWindows();
1035 } catch (java.beans.PropertyVetoException ex)
1041 Desktop.instance.closeAssociatedWindows();
1043 FileLoader loader = new FileLoader();
1044 DataSourceType protocol = fileName.startsWith("http:")
1045 ? DataSourceType.URL
1046 : DataSourceType.FILE;
1047 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1051 Rectangle bounds = this.getBounds();
1053 FileLoader loader = new FileLoader();
1054 DataSourceType protocol = fileName.startsWith("http:")
1055 ? DataSourceType.URL
1056 : DataSourceType.FILE;
1057 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1058 protocol, currentFileFormat);
1060 newframe.setBounds(bounds);
1061 if (featureSettings != null && featureSettings.isShowing())
1063 final Rectangle fspos = featureSettings.frame.getBounds();
1064 // TODO: need a 'show feature settings' function that takes bounds -
1065 // need to refactor Desktop.addFrame
1066 newframe.featureSettings_actionPerformed(null);
1067 final FeatureSettings nfs = newframe.featureSettings;
1068 SwingUtilities.invokeLater(new Runnable()
1073 nfs.frame.setBounds(fspos);
1076 this.featureSettings.close();
1077 this.featureSettings = null;
1079 this.closeMenuItem_actionPerformed(true);
1085 public void addFromText_actionPerformed(ActionEvent e)
1088 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1092 public void addFromURL_actionPerformed(ActionEvent e)
1094 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1098 public void save_actionPerformed(ActionEvent e)
1100 if (fileName == null || (currentFileFormat == null)
1101 || fileName.startsWith("http"))
1103 saveAs_actionPerformed(null);
1107 saveAlignment(fileName, currentFileFormat);
1118 public void saveAs_actionPerformed(ActionEvent e)
1120 String format = currentFileFormat == null ? null
1121 : currentFileFormat.getName();
1122 JalviewFileChooser chooser = JalviewFileChooser
1123 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1125 chooser.setFileView(new JalviewFileView());
1126 chooser.setDialogTitle(
1127 MessageManager.getString("label.save_alignment_to_file"));
1128 chooser.setToolTipText(MessageManager.getString("action.save"));
1130 int value = chooser.showSaveDialog(this);
1132 if (value == JalviewFileChooser.APPROVE_OPTION)
1134 currentFileFormat = chooser.getSelectedFormat();
1135 while (currentFileFormat == null)
1137 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1138 MessageManager.getString(
1139 "label.select_file_format_before_saving"),
1140 MessageManager.getString("label.file_format_not_specified"),
1141 JvOptionPane.WARNING_MESSAGE);
1142 currentFileFormat = chooser.getSelectedFormat();
1143 value = chooser.showSaveDialog(this);
1144 if (value != JalviewFileChooser.APPROVE_OPTION)
1150 fileName = chooser.getSelectedFile().getPath();
1152 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1154 Cache.setProperty("LAST_DIRECTORY", fileName);
1155 saveAlignment(fileName, currentFileFormat);
1159 public boolean saveAlignment(String file, FileFormatI format)
1161 boolean success = true;
1163 if (FileFormat.Jalview.equals(format))
1165 String shortName = title;
1167 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1169 shortName = shortName.substring(
1170 shortName.lastIndexOf(java.io.File.separatorChar) + 1);
1173 success = new Jalview2XML().saveAlignment(this, file, shortName);
1175 statusBar.setText(MessageManager.formatMessage(
1176 "label.successfully_saved_to_file_in_format", new Object[]
1177 { fileName, format }));
1182 AlignmentExportData exportData = getAlignmentForExport(format,
1184 if (exportData.getSettings().isCancelled())
1188 FormatAdapter f = new FormatAdapter(alignPanel,
1189 exportData.getSettings());
1190 String output = f.formatSequences(format, exportData.getAlignment(), // class
1194 // occur in the distant future
1195 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1196 f.getCacheSuffixDefault(format),
1197 viewport.getAlignment().getHiddenColumns());
1207 PrintWriter out = new PrintWriter(new FileWriter(file));
1211 this.setTitle(file);
1212 statusBar.setText(MessageManager.formatMessage(
1213 "label.successfully_saved_to_file_in_format", new Object[]
1214 { fileName, format.getName() }));
1215 } catch (Exception ex)
1218 ex.printStackTrace();
1225 JvOptionPane.showInternalMessageDialog(this, MessageManager
1226 .formatMessage("label.couldnt_save_file", new Object[]
1228 MessageManager.getString("label.error_saving_file"),
1229 JvOptionPane.WARNING_MESSAGE);
1235 private void warningMessage(String warning, String title)
1237 if (new jalview.util.Platform().isHeadless())
1239 System.err.println("Warning: " + title + "\nWarning: " + warning);
1244 JvOptionPane.showInternalMessageDialog(this, warning, title,
1245 JvOptionPane.WARNING_MESSAGE);
1257 protected void outputText_actionPerformed(ActionEvent e)
1259 FileFormatI fileFormat = FileFormats.getInstance()
1260 .forName(e.getActionCommand());
1261 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1263 if (exportData.getSettings().isCancelled())
1267 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1268 cap.setForInput(null);
1271 FileFormatI format = fileFormat;
1272 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1273 .formatSequences(format, exportData.getAlignment(),
1274 exportData.getOmitHidden(),
1275 exportData.getStartEndPostions(),
1276 viewport.getAlignment().getHiddenColumns()));
1277 Desktop.addInternalFrame(cap, MessageManager
1278 .formatMessage("label.alignment_output_command", new Object[]
1279 { e.getActionCommand() }), 600, 500);
1280 } catch (OutOfMemoryError oom)
1282 new OOMWarning("Outputting alignment as " + e.getActionCommand(),
1289 public static AlignmentExportData getAlignmentForExport(
1290 FileFormatI format, AlignViewportI viewport,
1291 AlignExportSettingI exportSettings)
1293 AlignmentI alignmentToExport = null;
1294 AlignExportSettingI settings = exportSettings;
1295 String[] omitHidden = null;
1297 HiddenSequences hiddenSeqs = viewport.getAlignment()
1298 .getHiddenSequences();
1300 alignmentToExport = viewport.getAlignment();
1302 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1303 if (settings == null)
1305 settings = new AlignExportSettings(hasHiddenSeqs,
1306 viewport.hasHiddenColumns(), format);
1308 // settings.isExportAnnotations();
1310 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1312 omitHidden = viewport.getViewAsString(false,
1313 settings.isExportHiddenSequences());
1316 int[] alignmentStartEnd = new int[2];
1317 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1319 alignmentToExport = hiddenSeqs.getFullAlignment();
1323 alignmentToExport = viewport.getAlignment();
1325 alignmentStartEnd = viewport.getAlignment().getHiddenColumns()
1326 .getVisibleStartAndEndIndex(alignmentToExport.getWidth());
1327 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1328 omitHidden, alignmentStartEnd, settings);
1339 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1341 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1342 htmlSVG.exportHTML(null);
1346 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1348 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1349 bjs.exportHTML(null);
1352 public void createImageMap(File file, String image)
1354 alignPanel.makePNGImageMap(file, image);
1364 public void createPNG(File f)
1366 alignPanel.makePNG(f);
1376 public void createEPS(File f)
1378 alignPanel.makeEPS(f);
1382 public void createSVG(File f)
1384 alignPanel.makeSVG(f);
1388 public void pageSetup_actionPerformed(ActionEvent e)
1390 PrinterJob printJob = PrinterJob.getPrinterJob();
1391 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1401 public void printMenuItem_actionPerformed(ActionEvent e)
1403 // Putting in a thread avoids Swing painting problems
1404 PrintThread thread = new PrintThread(alignPanel);
1409 public void exportFeatures_actionPerformed(ActionEvent e)
1411 new AnnotationExporter().exportFeatures(alignPanel);
1415 public void exportAnnotations_actionPerformed(ActionEvent e)
1417 new AnnotationExporter().exportAnnotations(alignPanel);
1421 public void associatedData_actionPerformed(ActionEvent e)
1423 // Pick the tree file
1424 JalviewFileChooser chooser = new JalviewFileChooser(
1425 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1426 chooser.setFileView(new JalviewFileView());
1427 chooser.setDialogTitle(
1428 MessageManager.getString("label.load_jalview_annotations"));
1429 chooser.setToolTipText(
1430 MessageManager.getString("label.load_jalview_annotations"));
1432 int value = chooser.showOpenDialog(null);
1434 if (value == JalviewFileChooser.APPROVE_OPTION)
1436 String choice = chooser.getSelectedFile().getPath();
1437 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1438 loadJalviewDataFile(choice, null, null, null);
1444 * Close the current view or all views in the alignment frame. If the frame
1445 * only contains one view then the alignment will be removed from memory.
1447 * @param closeAllTabs
1450 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1452 if (alignPanels != null && alignPanels.size() < 2)
1454 closeAllTabs = true;
1459 if (alignPanels != null)
1463 if (this.isClosed())
1465 // really close all the windows - otherwise wait till
1466 // setClosed(true) is called
1467 for (int i = 0; i < alignPanels.size(); i++)
1469 AlignmentPanel ap = alignPanels.get(i);
1476 closeView(alignPanel);
1483 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1484 * be called recursively, with the frame now in 'closed' state
1486 this.setClosed(true);
1488 } catch (Exception ex)
1490 ex.printStackTrace();
1495 * Close the specified panel and close up tabs appropriately.
1497 * @param panelToClose
1499 public void closeView(AlignmentPanel panelToClose)
1501 int index = tabbedPane.getSelectedIndex();
1502 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1503 alignPanels.remove(panelToClose);
1504 panelToClose.closePanel();
1505 panelToClose = null;
1507 tabbedPane.removeTabAt(closedindex);
1508 tabbedPane.validate();
1510 if (index > closedindex || index == tabbedPane.getTabCount())
1512 // modify currently selected tab index if necessary.
1516 this.tabSelectionChanged(index);
1522 void updateEditMenuBar()
1525 if (viewport.getHistoryList().size() > 0)
1527 undoMenuItem.setEnabled(true);
1528 CommandI command = viewport.getHistoryList().peek();
1529 undoMenuItem.setText(MessageManager
1530 .formatMessage("label.undo_command", new Object[]
1531 { command.getDescription() }));
1535 undoMenuItem.setEnabled(false);
1536 undoMenuItem.setText(MessageManager.getString("action.undo"));
1539 if (viewport.getRedoList().size() > 0)
1541 redoMenuItem.setEnabled(true);
1543 CommandI command = viewport.getRedoList().peek();
1544 redoMenuItem.setText(MessageManager
1545 .formatMessage("label.redo_command", new Object[]
1546 { command.getDescription() }));
1550 redoMenuItem.setEnabled(false);
1551 redoMenuItem.setText(MessageManager.getString("action.redo"));
1556 public void addHistoryItem(CommandI command)
1558 if (command.getSize() > 0)
1560 viewport.addToHistoryList(command);
1561 viewport.clearRedoList();
1562 updateEditMenuBar();
1563 viewport.updateHiddenColumns();
1564 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1565 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1566 // viewport.getColumnSelection()
1567 // .getHiddenColumns().size() > 0);
1573 * @return alignment objects for all views
1575 AlignmentI[] getViewAlignments()
1577 if (alignPanels != null)
1579 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1581 for (AlignmentPanel ap : alignPanels)
1583 als[i++] = ap.av.getAlignment();
1587 if (viewport != null)
1589 return new AlignmentI[] { viewport.getAlignment() };
1601 protected void undoMenuItem_actionPerformed(ActionEvent e)
1603 if (viewport.getHistoryList().isEmpty())
1607 CommandI command = viewport.getHistoryList().pop();
1608 viewport.addToRedoList(command);
1609 command.undoCommand(getViewAlignments());
1611 AlignmentViewport originalSource = getOriginatingSource(command);
1612 updateEditMenuBar();
1614 if (originalSource != null)
1616 if (originalSource != viewport)
1619 "Implementation worry: mismatch of viewport origin for undo");
1621 originalSource.updateHiddenColumns();
1622 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1624 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1625 // viewport.getColumnSelection()
1626 // .getHiddenColumns().size() > 0);
1627 originalSource.firePropertyChange("alignment", null,
1628 originalSource.getAlignment().getSequences());
1639 protected void redoMenuItem_actionPerformed(ActionEvent e)
1641 if (viewport.getRedoList().size() < 1)
1646 CommandI command = viewport.getRedoList().pop();
1647 viewport.addToHistoryList(command);
1648 command.doCommand(getViewAlignments());
1650 AlignmentViewport originalSource = getOriginatingSource(command);
1651 updateEditMenuBar();
1653 if (originalSource != null)
1656 if (originalSource != viewport)
1659 "Implementation worry: mismatch of viewport origin for redo");
1661 originalSource.updateHiddenColumns();
1662 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1664 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1665 // viewport.getColumnSelection()
1666 // .getHiddenColumns().size() > 0);
1667 originalSource.firePropertyChange("alignment", null,
1668 originalSource.getAlignment().getSequences());
1672 AlignmentViewport getOriginatingSource(CommandI command)
1674 AlignmentViewport originalSource = null;
1675 // For sequence removal and addition, we need to fire
1676 // the property change event FROM the viewport where the
1677 // original alignment was altered
1678 AlignmentI al = null;
1679 if (command instanceof EditCommand)
1681 EditCommand editCommand = (EditCommand) command;
1682 al = editCommand.getAlignment();
1683 List<Component> comps = PaintRefresher.components
1684 .get(viewport.getSequenceSetId());
1686 for (Component comp : comps)
1688 if (comp instanceof AlignmentPanel)
1690 if (al == ((AlignmentPanel) comp).av.getAlignment())
1692 originalSource = ((AlignmentPanel) comp).av;
1699 if (originalSource == null)
1701 // The original view is closed, we must validate
1702 // the current view against the closed view first
1705 PaintRefresher.validateSequences(al, viewport.getAlignment());
1708 originalSource = viewport;
1711 return originalSource;
1720 public void moveSelectedSequences(boolean up)
1722 SequenceGroup sg = viewport.getSelectionGroup();
1728 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1729 viewport.getHiddenRepSequences(), up);
1730 alignPanel.paintAlignment(true, false);
1733 synchronized void slideSequences(boolean right, int size)
1735 List<SequenceI> sg = new ArrayList<>();
1736 if (viewport.cursorMode)
1738 sg.add(viewport.getAlignment()
1739 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1741 else if (viewport.getSelectionGroup() != null
1742 && viewport.getSelectionGroup().getSize() != viewport
1743 .getAlignment().getHeight())
1745 sg = viewport.getSelectionGroup()
1746 .getSequences(viewport.getHiddenRepSequences());
1754 List<SequenceI> invertGroup = new ArrayList<>();
1756 for (SequenceI seq : viewport.getAlignment().getSequences())
1758 if (!sg.contains(seq))
1760 invertGroup.add(seq);
1764 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1766 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1767 for (int i = 0; i < invertGroup.size(); i++)
1769 seqs2[i] = invertGroup.get(i);
1772 SlideSequencesCommand ssc;
1775 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1776 viewport.getGapCharacter());
1780 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1781 viewport.getGapCharacter());
1784 int groupAdjustment = 0;
1785 if (ssc.getGapsInsertedBegin() && right)
1787 if (viewport.cursorMode)
1789 alignPanel.getSeqPanel().moveCursor(size, 0);
1793 groupAdjustment = size;
1796 else if (!ssc.getGapsInsertedBegin() && !right)
1798 if (viewport.cursorMode)
1800 alignPanel.getSeqPanel().moveCursor(-size, 0);
1804 groupAdjustment = -size;
1808 if (groupAdjustment != 0)
1810 viewport.getSelectionGroup().setStartRes(
1811 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1812 viewport.getSelectionGroup().setEndRes(
1813 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1817 * just extend the last slide command if compatible; but not if in
1818 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1820 boolean appendHistoryItem = false;
1821 Deque<CommandI> historyList = viewport.getHistoryList();
1822 boolean inSplitFrame = getSplitViewContainer() != null;
1823 if (!inSplitFrame && historyList != null && historyList.size() > 0
1824 && historyList.peek() instanceof SlideSequencesCommand)
1826 appendHistoryItem = ssc.appendSlideCommand(
1827 (SlideSequencesCommand) historyList.peek());
1830 if (!appendHistoryItem)
1832 addHistoryItem(ssc);
1845 protected void copy_actionPerformed(ActionEvent e)
1848 if (viewport.getSelectionGroup() == null)
1852 // TODO: preserve the ordering of displayed alignment annotation in any
1853 // internal paste (particularly sequence associated annotation)
1854 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1855 String[] omitHidden = null;
1857 if (viewport.hasHiddenColumns())
1859 omitHidden = viewport.getViewAsString(true);
1862 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1863 seqs, omitHidden, null);
1865 StringSelection ss = new StringSelection(output);
1869 jalview.gui.Desktop.internalCopy = true;
1870 // Its really worth setting the clipboard contents
1871 // to empty before setting the large StringSelection!!
1872 Toolkit.getDefaultToolkit().getSystemClipboard()
1873 .setContents(new StringSelection(""), null);
1875 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1877 } catch (OutOfMemoryError er)
1879 new OOMWarning("copying region", er);
1883 ArrayList<int[]> hiddenColumns = null;
1884 if (viewport.hasHiddenColumns())
1886 hiddenColumns = new ArrayList<>();
1887 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1888 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1889 ArrayList<int[]> hiddenRegions = viewport.getAlignment()
1890 .getHiddenColumns().getHiddenColumnsCopy();
1891 for (int[] region : hiddenRegions)
1893 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1897 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1902 Desktop.jalviewClipboard = new Object[] { seqs,
1903 viewport.getAlignment().getDataset(), hiddenColumns };
1904 statusBar.setText(MessageManager.formatMessage(
1905 "label.copied_sequences_to_clipboard", new Object[]
1906 { Integer.valueOf(seqs.length).toString() }));
1916 protected void pasteNew_actionPerformed(ActionEvent e)
1928 protected void pasteThis_actionPerformed(ActionEvent e)
1934 * Paste contents of Jalview clipboard
1936 * @param newAlignment
1937 * true to paste to a new alignment, otherwise add to this.
1939 void paste(boolean newAlignment)
1941 boolean externalPaste = true;
1944 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1945 Transferable contents = c.getContents(this);
1947 if (contents == null)
1956 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1957 if (str.length() < 1)
1962 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
1964 } catch (OutOfMemoryError er)
1966 new OOMWarning("Out of memory pasting sequences!!", er);
1970 SequenceI[] sequences;
1971 boolean annotationAdded = false;
1972 AlignmentI alignment = null;
1974 if (Desktop.jalviewClipboard != null)
1976 // The clipboard was filled from within Jalview, we must use the
1978 // And dataset from the copied alignment
1979 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1980 // be doubly sure that we create *new* sequence objects.
1981 sequences = new SequenceI[newseq.length];
1982 for (int i = 0; i < newseq.length; i++)
1984 sequences[i] = new Sequence(newseq[i]);
1986 alignment = new Alignment(sequences);
1987 externalPaste = false;
1991 // parse the clipboard as an alignment.
1992 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
1994 sequences = alignment.getSequencesArray();
1998 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2004 if (Desktop.jalviewClipboard != null)
2006 // dataset is inherited
2007 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2011 // new dataset is constructed
2012 alignment.setDataset(null);
2014 alwidth = alignment.getWidth() + 1;
2018 AlignmentI pastedal = alignment; // preserve pasted alignment object
2019 // Add pasted sequences and dataset into existing alignment.
2020 alignment = viewport.getAlignment();
2021 alwidth = alignment.getWidth() + 1;
2022 // decide if we need to import sequences from an existing dataset
2023 boolean importDs = Desktop.jalviewClipboard != null
2024 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2025 // importDs==true instructs us to copy over new dataset sequences from
2026 // an existing alignment
2027 Vector newDs = (importDs) ? new Vector() : null; // used to create
2028 // minimum dataset set
2030 for (int i = 0; i < sequences.length; i++)
2034 newDs.addElement(null);
2036 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2038 if (importDs && ds != null)
2040 if (!newDs.contains(ds))
2042 newDs.setElementAt(ds, i);
2043 ds = new Sequence(ds);
2044 // update with new dataset sequence
2045 sequences[i].setDatasetSequence(ds);
2049 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2054 // copy and derive new dataset sequence
2055 sequences[i] = sequences[i].deriveSequence();
2056 alignment.getDataset()
2057 .addSequence(sequences[i].getDatasetSequence());
2058 // TODO: avoid creation of duplicate dataset sequences with a
2059 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2061 alignment.addSequence(sequences[i]); // merges dataset
2065 newDs.clear(); // tidy up
2067 if (alignment.getAlignmentAnnotation() != null)
2069 for (AlignmentAnnotation alan : alignment
2070 .getAlignmentAnnotation())
2072 if (alan.graphGroup > fgroup)
2074 fgroup = alan.graphGroup;
2078 if (pastedal.getAlignmentAnnotation() != null)
2080 // Add any annotation attached to alignment.
2081 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2082 for (int i = 0; i < alann.length; i++)
2084 annotationAdded = true;
2085 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2087 AlignmentAnnotation newann = new AlignmentAnnotation(
2089 if (newann.graphGroup > -1)
2091 if (newGraphGroups.size() <= newann.graphGroup
2092 || newGraphGroups.get(newann.graphGroup) == null)
2094 for (int q = newGraphGroups
2095 .size(); q <= newann.graphGroup; q++)
2097 newGraphGroups.add(q, null);
2099 newGraphGroups.set(newann.graphGroup,
2100 new Integer(++fgroup));
2102 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2106 newann.padAnnotation(alwidth);
2107 alignment.addAnnotation(newann);
2117 addHistoryItem(new EditCommand(
2118 MessageManager.getString("label.add_sequences"),
2119 Action.PASTE, sequences, 0, alignment.getWidth(),
2122 // Add any annotations attached to sequences
2123 for (int i = 0; i < sequences.length; i++)
2125 if (sequences[i].getAnnotation() != null)
2127 AlignmentAnnotation newann;
2128 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2130 annotationAdded = true;
2131 newann = sequences[i].getAnnotation()[a];
2132 newann.adjustForAlignment();
2133 newann.padAnnotation(alwidth);
2134 if (newann.graphGroup > -1)
2136 if (newann.graphGroup > -1)
2138 if (newGraphGroups.size() <= newann.graphGroup
2139 || newGraphGroups.get(newann.graphGroup) == null)
2141 for (int q = newGraphGroups
2142 .size(); q <= newann.graphGroup; q++)
2144 newGraphGroups.add(q, null);
2146 newGraphGroups.set(newann.graphGroup,
2147 new Integer(++fgroup));
2149 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2153 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2157 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2165 // propagate alignment changed.
2166 viewport.getRanges().setEndSeq(alignment.getHeight());
2167 if (annotationAdded)
2169 // Duplicate sequence annotation in all views.
2170 AlignmentI[] alview = this.getViewAlignments();
2171 for (int i = 0; i < sequences.length; i++)
2173 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2178 for (int avnum = 0; avnum < alview.length; avnum++)
2180 if (alview[avnum] != alignment)
2182 // duplicate in a view other than the one with input focus
2183 int avwidth = alview[avnum].getWidth() + 1;
2184 // this relies on sann being preserved after we
2185 // modify the sequence's annotation array for each duplication
2186 for (int a = 0; a < sann.length; a++)
2188 AlignmentAnnotation newann = new AlignmentAnnotation(
2190 sequences[i].addAlignmentAnnotation(newann);
2191 newann.padAnnotation(avwidth);
2192 alview[avnum].addAnnotation(newann); // annotation was
2193 // duplicated earlier
2194 // TODO JAL-1145 graphGroups are not updated for sequence
2195 // annotation added to several views. This may cause
2197 alview[avnum].setAnnotationIndex(newann, a);
2202 buildSortByAnnotationScoresMenu();
2204 viewport.firePropertyChange("alignment", null,
2205 alignment.getSequences());
2206 if (alignPanels != null)
2208 for (AlignmentPanel ap : alignPanels)
2210 ap.validateAnnotationDimensions(false);
2215 alignPanel.validateAnnotationDimensions(false);
2221 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2223 String newtitle = new String("Copied sequences");
2225 if (Desktop.jalviewClipboard != null
2226 && Desktop.jalviewClipboard[2] != null)
2228 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2229 for (int[] region : hc)
2231 af.viewport.hideColumns(region[0], region[1]);
2235 // >>>This is a fix for the moment, until a better solution is
2237 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2238 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2239 .getFeatureRenderer());
2241 // TODO: maintain provenance of an alignment, rather than just make the
2242 // title a concatenation of operations.
2245 if (title.startsWith("Copied sequences"))
2251 newtitle = newtitle.concat("- from " + title);
2256 newtitle = new String("Pasted sequences");
2259 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2264 } catch (Exception ex)
2266 ex.printStackTrace();
2267 System.out.println("Exception whilst pasting: " + ex);
2268 // could be anything being pasted in here
2274 protected void expand_newalign(ActionEvent e)
2278 AlignmentI alignment = AlignmentUtils
2279 .expandContext(getViewport().getAlignment(), -1);
2280 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2282 String newtitle = new String("Flanking alignment");
2284 if (Desktop.jalviewClipboard != null
2285 && Desktop.jalviewClipboard[2] != null)
2287 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2288 for (int region[] : hc)
2290 af.viewport.hideColumns(region[0], region[1]);
2294 // >>>This is a fix for the moment, until a better solution is
2296 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2297 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2298 .getFeatureRenderer());
2300 // TODO: maintain provenance of an alignment, rather than just make the
2301 // title a concatenation of operations.
2303 if (title.startsWith("Copied sequences"))
2309 newtitle = newtitle.concat("- from " + title);
2313 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2315 } catch (Exception ex)
2317 ex.printStackTrace();
2318 System.out.println("Exception whilst pasting: " + ex);
2319 // could be anything being pasted in here
2320 } catch (OutOfMemoryError oom)
2322 new OOMWarning("Viewing flanking region of alignment", oom);
2333 protected void cut_actionPerformed(ActionEvent e)
2335 copy_actionPerformed(null);
2336 delete_actionPerformed(null);
2346 protected void delete_actionPerformed(ActionEvent evt)
2349 SequenceGroup sg = viewport.getSelectionGroup();
2356 * If the cut affects all sequences, warn, remove highlighted columns
2358 if (sg.getSize() == viewport.getAlignment().getHeight())
2360 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2361 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2362 if (isEntireAlignWidth)
2364 int confirm = JvOptionPane.showConfirmDialog(this,
2365 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2366 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2367 JvOptionPane.OK_CANCEL_OPTION);
2369 if (confirm == JvOptionPane.CANCEL_OPTION
2370 || confirm == JvOptionPane.CLOSED_OPTION)
2375 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2376 sg.getEndRes() + 1);
2378 SequenceI[] cut = sg.getSequences()
2379 .toArray(new SequenceI[sg.getSize()]);
2381 addHistoryItem(new EditCommand(
2382 MessageManager.getString("label.cut_sequences"), Action.CUT,
2383 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2384 viewport.getAlignment()));
2386 viewport.setSelectionGroup(null);
2387 viewport.sendSelection();
2388 viewport.getAlignment().deleteGroup(sg);
2390 viewport.firePropertyChange("alignment", null,
2391 viewport.getAlignment().getSequences());
2392 if (viewport.getAlignment().getHeight() < 1)
2396 this.setClosed(true);
2397 } catch (Exception ex)
2410 protected void deleteGroups_actionPerformed(ActionEvent e)
2412 if (avc.deleteGroups())
2414 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2415 alignPanel.updateAnnotation();
2416 alignPanel.paintAlignment(true, true);
2427 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2429 SequenceGroup sg = new SequenceGroup();
2431 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2433 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2436 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2437 viewport.setSelectionGroup(sg);
2438 viewport.sendSelection();
2439 // JAL-2034 - should delegate to
2440 // alignPanel to decide if overview needs
2442 alignPanel.paintAlignment(false, false);
2443 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2453 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2455 if (viewport.cursorMode)
2457 alignPanel.getSeqPanel().keyboardNo1 = null;
2458 alignPanel.getSeqPanel().keyboardNo2 = null;
2460 viewport.setSelectionGroup(null);
2461 viewport.getColumnSelection().clear();
2462 viewport.setSelectionGroup(null);
2463 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2464 // JAL-2034 - should delegate to
2465 // alignPanel to decide if overview needs
2467 alignPanel.paintAlignment(false, false);
2468 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2469 viewport.sendSelection();
2479 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2481 SequenceGroup sg = viewport.getSelectionGroup();
2485 selectAllSequenceMenuItem_actionPerformed(null);
2490 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2492 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2494 // JAL-2034 - should delegate to
2495 // alignPanel to decide if overview needs
2498 alignPanel.paintAlignment(true, false);
2499 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2500 viewport.sendSelection();
2504 public void invertColSel_actionPerformed(ActionEvent e)
2506 viewport.invertColumnSelection();
2507 alignPanel.paintAlignment(true, false);
2508 viewport.sendSelection();
2518 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2520 trimAlignment(true);
2530 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2532 trimAlignment(false);
2535 void trimAlignment(boolean trimLeft)
2537 ColumnSelection colSel = viewport.getColumnSelection();
2540 if (!colSel.isEmpty())
2544 column = colSel.getMin();
2548 column = colSel.getMax();
2552 if (viewport.getSelectionGroup() != null)
2554 seqs = viewport.getSelectionGroup()
2555 .getSequencesAsArray(viewport.getHiddenRepSequences());
2559 seqs = viewport.getAlignment().getSequencesArray();
2562 TrimRegionCommand trimRegion;
2565 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2566 column, viewport.getAlignment());
2567 viewport.getRanges().setStartRes(0);
2571 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2572 column, viewport.getAlignment());
2575 statusBar.setText(MessageManager
2576 .formatMessage("label.removed_columns", new String[]
2577 { Integer.valueOf(trimRegion.getSize()).toString() }));
2579 addHistoryItem(trimRegion);
2581 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2583 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2584 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2586 viewport.getAlignment().deleteGroup(sg);
2590 viewport.firePropertyChange("alignment", null,
2591 viewport.getAlignment().getSequences());
2602 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2604 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2607 if (viewport.getSelectionGroup() != null)
2609 seqs = viewport.getSelectionGroup()
2610 .getSequencesAsArray(viewport.getHiddenRepSequences());
2611 start = viewport.getSelectionGroup().getStartRes();
2612 end = viewport.getSelectionGroup().getEndRes();
2616 seqs = viewport.getAlignment().getSequencesArray();
2619 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2620 "Remove Gapped Columns", seqs, start, end,
2621 viewport.getAlignment());
2623 addHistoryItem(removeGapCols);
2625 statusBar.setText(MessageManager
2626 .formatMessage("label.removed_empty_columns", new Object[]
2627 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2629 // This is to maintain viewport position on first residue
2630 // of first sequence
2631 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2632 ViewportRanges ranges = viewport.getRanges();
2633 int startRes = seq.findPosition(ranges.getStartRes());
2634 // ShiftList shifts;
2635 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2636 // edit.alColumnChanges=shifts.getInverse();
2637 // if (viewport.hasHiddenColumns)
2638 // viewport.getColumnSelection().compensateForEdits(shifts);
2639 ranges.setStartRes(seq.findIndex(startRes) - 1);
2640 viewport.firePropertyChange("alignment", null,
2641 viewport.getAlignment().getSequences());
2652 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2654 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2657 if (viewport.getSelectionGroup() != null)
2659 seqs = viewport.getSelectionGroup()
2660 .getSequencesAsArray(viewport.getHiddenRepSequences());
2661 start = viewport.getSelectionGroup().getStartRes();
2662 end = viewport.getSelectionGroup().getEndRes();
2666 seqs = viewport.getAlignment().getSequencesArray();
2669 // This is to maintain viewport position on first residue
2670 // of first sequence
2671 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2672 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2674 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2675 viewport.getAlignment()));
2677 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2679 viewport.firePropertyChange("alignment", null,
2680 viewport.getAlignment().getSequences());
2691 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2693 viewport.setPadGaps(padGapsMenuitem.isSelected());
2694 viewport.firePropertyChange("alignment", null,
2695 viewport.getAlignment().getSequences());
2705 public void findMenuItem_actionPerformed(ActionEvent e)
2711 * Create a new view of the current alignment.
2714 public void newView_actionPerformed(ActionEvent e)
2716 newView(null, true);
2720 * Creates and shows a new view of the current alignment.
2723 * title of newly created view; if null, one will be generated
2724 * @param copyAnnotation
2725 * if true then duplicate all annnotation, groups and settings
2726 * @return new alignment panel, already displayed.
2728 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2731 * Create a new AlignmentPanel (with its own, new Viewport)
2733 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel);
2734 if (!copyAnnotation)
2737 * remove all groups and annotation except for the automatic stuff
2739 newap.av.getAlignment().deleteAllGroups();
2740 newap.av.getAlignment().deleteAllAnnotations(false);
2743 newap.av.setGatherViewsHere(false);
2745 if (viewport.viewName == null)
2747 viewport.viewName = MessageManager
2748 .getString("label.view_name_original");
2752 * Views share the same edits undo and redo stacks
2754 newap.av.setHistoryList(viewport.getHistoryList());
2755 newap.av.setRedoList(viewport.getRedoList());
2758 * Views share the same mappings; need to deregister any new mappings
2759 * created by copyAlignPanel, and register the new reference to the shared
2762 newap.av.replaceMappings(viewport.getAlignment());
2765 * start up cDNA consensus (if applicable) now mappings are in place
2767 if (newap.av.initComplementConsensus())
2769 newap.refresh(true); // adjust layout of annotations
2772 newap.av.viewName = getNewViewName(viewTitle);
2774 addAlignmentPanel(newap, true);
2775 newap.alignmentChanged();
2777 if (alignPanels.size() == 2)
2779 viewport.setGatherViewsHere(true);
2781 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2786 * Make a new name for the view, ensuring it is unique within the current
2787 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2788 * these now use viewId. Unique view names are still desirable for usability.)
2793 protected String getNewViewName(String viewTitle)
2795 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2796 boolean addFirstIndex = false;
2797 if (viewTitle == null || viewTitle.trim().length() == 0)
2799 viewTitle = MessageManager.getString("action.view");
2800 addFirstIndex = true;
2804 index = 1;// we count from 1 if given a specific name
2806 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2808 List<Component> comps = PaintRefresher.components
2809 .get(viewport.getSequenceSetId());
2811 List<String> existingNames = getExistingViewNames(comps);
2813 while (existingNames.contains(newViewName))
2815 newViewName = viewTitle + " " + (++index);
2821 * Returns a list of distinct view names found in the given list of
2822 * components. View names are held on the viewport of an AlignmentPanel.
2827 protected List<String> getExistingViewNames(List<Component> comps)
2829 List<String> existingNames = new ArrayList<>();
2830 for (Component comp : comps)
2832 if (comp instanceof AlignmentPanel)
2834 AlignmentPanel ap = (AlignmentPanel) comp;
2835 if (!existingNames.contains(ap.av.viewName))
2837 existingNames.add(ap.av.viewName);
2841 return existingNames;
2845 * Explode tabbed views into separate windows.
2848 public void expandViews_actionPerformed(ActionEvent e)
2850 Desktop.explodeViews(this);
2854 * Gather views in separate windows back into a tabbed presentation.
2857 public void gatherViews_actionPerformed(ActionEvent e)
2859 Desktop.instance.gatherViews(this);
2869 public void font_actionPerformed(ActionEvent e)
2871 new FontChooser(alignPanel);
2881 protected void seqLimit_actionPerformed(ActionEvent e)
2883 viewport.setShowJVSuffix(seqLimits.isSelected());
2885 alignPanel.getIdPanel().getIdCanvas()
2886 .setPreferredSize(alignPanel.calculateIdWidth());
2887 alignPanel.paintAlignment(true, false);
2891 public void idRightAlign_actionPerformed(ActionEvent e)
2893 viewport.setRightAlignIds(idRightAlign.isSelected());
2894 alignPanel.paintAlignment(false, false);
2898 public void centreColumnLabels_actionPerformed(ActionEvent e)
2900 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2901 alignPanel.paintAlignment(false, false);
2907 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2910 protected void followHighlight_actionPerformed()
2913 * Set the 'follow' flag on the Viewport (and scroll to position if now
2916 final boolean state = this.followHighlightMenuItem.getState();
2917 viewport.setFollowHighlight(state);
2920 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2931 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2933 viewport.setColourText(colourTextMenuItem.isSelected());
2934 alignPanel.paintAlignment(false, false);
2944 public void wrapMenuItem_actionPerformed(ActionEvent e)
2946 scaleAbove.setVisible(wrapMenuItem.isSelected());
2947 scaleLeft.setVisible(wrapMenuItem.isSelected());
2948 scaleRight.setVisible(wrapMenuItem.isSelected());
2949 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2950 alignPanel.updateLayout();
2954 public void showAllSeqs_actionPerformed(ActionEvent e)
2956 viewport.showAllHiddenSeqs();
2960 public void showAllColumns_actionPerformed(ActionEvent e)
2962 viewport.showAllHiddenColumns();
2963 alignPanel.paintAlignment(true, true);
2964 viewport.sendSelection();
2968 public void hideSelSequences_actionPerformed(ActionEvent e)
2970 viewport.hideAllSelectedSeqs();
2974 * called by key handler and the hide all/show all menu items
2979 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2982 boolean hide = false;
2983 SequenceGroup sg = viewport.getSelectionGroup();
2984 if (!toggleSeqs && !toggleCols)
2986 // Hide everything by the current selection - this is a hack - we do the
2987 // invert and then hide
2988 // first check that there will be visible columns after the invert.
2989 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
2990 && sg.getStartRes() <= sg.getEndRes()))
2992 // now invert the sequence set, if required - empty selection implies
2993 // that no hiding is required.
2996 invertSequenceMenuItem_actionPerformed(null);
2997 sg = viewport.getSelectionGroup();
3001 viewport.expandColSelection(sg, true);
3002 // finally invert the column selection and get the new sequence
3004 invertColSel_actionPerformed(null);
3011 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3013 hideSelSequences_actionPerformed(null);
3016 else if (!(toggleCols && viewport.hasSelectedColumns()))
3018 showAllSeqs_actionPerformed(null);
3024 if (viewport.hasSelectedColumns())
3026 hideSelColumns_actionPerformed(null);
3029 viewport.setSelectionGroup(sg);
3034 showAllColumns_actionPerformed(null);
3043 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3044 * event.ActionEvent)
3047 public void hideAllButSelection_actionPerformed(ActionEvent e)
3049 toggleHiddenRegions(false, false);
3050 viewport.sendSelection();
3057 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3061 public void hideAllSelection_actionPerformed(ActionEvent e)
3063 SequenceGroup sg = viewport.getSelectionGroup();
3064 viewport.expandColSelection(sg, false);
3065 viewport.hideAllSelectedSeqs();
3066 viewport.hideSelectedColumns();
3067 alignPanel.paintAlignment(true, true);
3068 viewport.sendSelection();
3075 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3079 public void showAllhidden_actionPerformed(ActionEvent e)
3081 viewport.showAllHiddenColumns();
3082 viewport.showAllHiddenSeqs();
3083 alignPanel.paintAlignment(true, true);
3084 viewport.sendSelection();
3088 public void hideSelColumns_actionPerformed(ActionEvent e)
3090 viewport.hideSelectedColumns();
3091 alignPanel.paintAlignment(true, true);
3092 viewport.sendSelection();
3096 public void hiddenMarkers_actionPerformed(ActionEvent e)
3098 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3109 protected void scaleAbove_actionPerformed(ActionEvent e)
3111 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3112 // TODO: do we actually need to update overview for scale above change ?
3113 alignPanel.paintAlignment(true, false);
3123 protected void scaleLeft_actionPerformed(ActionEvent e)
3125 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3126 alignPanel.paintAlignment(true, false);
3136 protected void scaleRight_actionPerformed(ActionEvent e)
3138 viewport.setScaleRightWrapped(scaleRight.isSelected());
3139 alignPanel.paintAlignment(true, false);
3149 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3151 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3152 alignPanel.paintAlignment(false, false);
3162 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3164 viewport.setShowText(viewTextMenuItem.isSelected());
3165 alignPanel.paintAlignment(false, false);
3175 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3177 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3178 alignPanel.paintAlignment(false, false);
3181 public FeatureSettings featureSettings;
3184 public FeatureSettingsControllerI getFeatureSettingsUI()
3186 return featureSettings;
3190 public void featureSettings_actionPerformed(ActionEvent e)
3192 if (featureSettings != null)
3194 featureSettings.close();
3195 featureSettings = null;
3197 if (!showSeqFeatures.isSelected())
3199 // make sure features are actually displayed
3200 showSeqFeatures.setSelected(true);
3201 showSeqFeatures_actionPerformed(null);
3203 featureSettings = new FeatureSettings(this);
3207 * Set or clear 'Show Sequence Features'
3213 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3215 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3216 alignPanel.paintAlignment(true, true);
3220 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3221 * the annotations panel as a whole.
3223 * The options to show/hide all annotations should be enabled when the panel
3224 * is shown, and disabled when the panel is hidden.
3229 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3231 final boolean setVisible = annotationPanelMenuItem.isSelected();
3232 viewport.setShowAnnotation(setVisible);
3233 this.showAllSeqAnnotations.setEnabled(setVisible);
3234 this.hideAllSeqAnnotations.setEnabled(setVisible);
3235 this.showAllAlAnnotations.setEnabled(setVisible);
3236 this.hideAllAlAnnotations.setEnabled(setVisible);
3237 alignPanel.updateLayout();
3241 public void alignmentProperties()
3243 JEditorPane editPane = new JEditorPane("text/html", "");
3244 editPane.setEditable(false);
3245 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3248 MessageManager.formatMessage("label.html_content", new Object[]
3249 { contents.toString() }));
3250 JInternalFrame frame = new JInternalFrame();
3251 frame.getContentPane().add(new JScrollPane(editPane));
3253 Desktop.addInternalFrame(frame, MessageManager
3254 .formatMessage("label.alignment_properties", new Object[]
3255 { getTitle() }), 500, 400);
3265 public void overviewMenuItem_actionPerformed(ActionEvent e)
3267 if (alignPanel.overviewPanel != null)
3272 JInternalFrame frame = new JInternalFrame();
3273 final OverviewPanel overview = new OverviewPanel(alignPanel);
3274 frame.setContentPane(overview);
3275 Desktop.addInternalFrame(frame, MessageManager
3276 .formatMessage("label.overview_params", new Object[]
3277 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3280 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3281 frame.addInternalFrameListener(
3282 new javax.swing.event.InternalFrameAdapter()
3285 public void internalFrameClosed(
3286 javax.swing.event.InternalFrameEvent evt)
3289 alignPanel.setOverviewPanel(null);
3293 alignPanel.setOverviewPanel(overview);
3297 public void textColour_actionPerformed()
3299 new TextColourChooser().chooseColour(alignPanel, null);
3303 * public void covariationColour_actionPerformed() {
3305 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3309 public void annotationColour_actionPerformed()
3311 new AnnotationColourChooser(viewport, alignPanel);
3315 public void annotationColumn_actionPerformed(ActionEvent e)
3317 new AnnotationColumnChooser(viewport, alignPanel);
3321 * Action on the user checking or unchecking the option to apply the selected
3322 * colour scheme to all groups. If unchecked, groups may have their own
3323 * independent colour schemes.
3328 public void applyToAllGroups_actionPerformed(boolean selected)
3330 viewport.setColourAppliesToAllGroups(selected);
3334 * Action on user selecting a colour from the colour menu
3337 * the name (not the menu item label!) of the colour scheme
3340 public void changeColour_actionPerformed(String name)
3343 * 'User Defined' opens a panel to configure or load a
3344 * user-defined colour scheme
3346 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3348 new UserDefinedColours(alignPanel);
3353 * otherwise set the chosen colour scheme (or null for 'None')
3355 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3356 viewport.getAlignment(), viewport.getHiddenRepSequences());
3361 * Actions on setting or changing the alignment colour scheme
3366 public void changeColour(ColourSchemeI cs)
3368 // TODO: pull up to controller method
3369 ColourMenuHelper.setColourSelected(colourMenu, cs);
3371 viewport.setGlobalColourScheme(cs);
3373 alignPanel.paintAlignment(true, true);
3377 * Show the PID threshold slider panel
3380 protected void modifyPID_actionPerformed()
3382 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3383 alignPanel.getViewName());
3384 SliderPanel.showPIDSlider();
3388 * Show the Conservation slider panel
3391 protected void modifyConservation_actionPerformed()
3393 SliderPanel.setConservationSlider(alignPanel,
3394 viewport.getResidueShading(), alignPanel.getViewName());
3395 SliderPanel.showConservationSlider();
3399 * Action on selecting or deselecting (Colour) By Conservation
3402 public void conservationMenuItem_actionPerformed(boolean selected)
3404 modifyConservation.setEnabled(selected);
3405 viewport.setConservationSelected(selected);
3406 viewport.getResidueShading().setConservationApplied(selected);
3408 changeColour(viewport.getGlobalColourScheme());
3411 modifyConservation_actionPerformed();
3415 SliderPanel.hideConservationSlider();
3420 * Action on selecting or deselecting (Colour) Above PID Threshold
3423 public void abovePIDThreshold_actionPerformed(boolean selected)
3425 modifyPID.setEnabled(selected);
3426 viewport.setAbovePIDThreshold(selected);
3429 viewport.getResidueShading().setThreshold(0,
3430 viewport.isIgnoreGapsConsensus());
3433 changeColour(viewport.getGlobalColourScheme());
3436 modifyPID_actionPerformed();
3440 SliderPanel.hidePIDSlider();
3451 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3453 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3454 AlignmentSorter.sortByPID(viewport.getAlignment(),
3455 viewport.getAlignment().getSequenceAt(0));
3456 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3457 viewport.getAlignment()));
3458 alignPanel.paintAlignment(true, false);
3468 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3470 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3471 AlignmentSorter.sortByID(viewport.getAlignment());
3473 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3474 alignPanel.paintAlignment(true, false);
3484 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3486 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3487 AlignmentSorter.sortByLength(viewport.getAlignment());
3488 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3489 viewport.getAlignment()));
3490 alignPanel.paintAlignment(true, false);
3500 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3502 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3503 AlignmentSorter.sortByGroup(viewport.getAlignment());
3504 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3505 viewport.getAlignment()));
3507 alignPanel.paintAlignment(true, false);
3517 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3519 new RedundancyPanel(alignPanel, this);
3529 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3531 if ((viewport.getSelectionGroup() == null)
3532 || (viewport.getSelectionGroup().getSize() < 2))
3534 JvOptionPane.showInternalMessageDialog(this,
3535 MessageManager.getString(
3536 "label.you_must_select_least_two_sequences"),
3537 MessageManager.getString("label.invalid_selection"),
3538 JvOptionPane.WARNING_MESSAGE);
3542 JInternalFrame frame = new JInternalFrame();
3543 frame.setContentPane(new PairwiseAlignPanel(viewport));
3544 Desktop.addInternalFrame(frame,
3545 MessageManager.getString("action.pairwise_alignment"), 600,
3551 public void autoCalculate_actionPerformed(ActionEvent e)
3553 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3554 if (viewport.autoCalculateConsensus)
3556 viewport.firePropertyChange("alignment", null,
3557 viewport.getAlignment().getSequences());
3562 public void sortByTreeOption_actionPerformed(ActionEvent e)
3564 viewport.sortByTree = sortByTree.isSelected();
3568 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3570 viewport.followSelection = listenToViewSelections.isSelected();
3574 * Constructs a tree panel and adds it to the desktop
3583 void newTreePanel(TreeModel tree, String treeAlgo,
3584 String substitutionMatrix)
3586 String frameTitle = "";
3589 boolean onSelection = false;
3590 if (viewport.getSelectionGroup() != null
3591 && viewport.getSelectionGroup().getSize() > 0)
3593 SequenceGroup sg = viewport.getSelectionGroup();
3595 /* Decide if the selection is a column region */
3596 for (SequenceI _s : sg.getSequences()) // port this to Archaeopteryx?
3598 if (_s.getLength() < sg.getEndRes())
3600 JvOptionPane.showMessageDialog(Desktop.desktop,
3601 MessageManager.getString(
3602 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3603 MessageManager.getString(
3604 "label.sequences_selection_not_aligned"),
3605 JvOptionPane.WARNING_MESSAGE);
3614 if (viewport.getAlignment().getHeight() < 2)
3620 tp = new TreePanel(alignPanel, tree, treeAlgo, substitutionMatrix);
3621 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3623 frameTitle += " from ";
3625 if (viewport.viewName != null)
3627 frameTitle += viewport.viewName + " of ";
3630 frameTitle += this.title;
3632 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3643 public void addSortByOrderMenuItem(String title,
3644 final AlignmentOrder order)
3646 final JMenuItem item = new JMenuItem(MessageManager
3647 .formatMessage("action.by_title_param", new Object[]
3650 item.addActionListener(new java.awt.event.ActionListener()
3653 public void actionPerformed(ActionEvent e)
3655 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3657 // TODO: JBPNote - have to map order entries to curent SequenceI
3659 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3661 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3662 viewport.getAlignment()));
3664 alignPanel.paintAlignment(true, false);
3670 * Add a new sort by annotation score menu item
3673 * the menu to add the option to
3675 * the label used to retrieve scores for each sequence on the
3678 public void addSortByAnnotScoreMenuItem(JMenu sort,
3679 final String scoreLabel)
3681 final JMenuItem item = new JMenuItem(scoreLabel);
3683 item.addActionListener(new java.awt.event.ActionListener()
3686 public void actionPerformed(ActionEvent e)
3688 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3689 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3690 viewport.getAlignment());// ,viewport.getSelectionGroup());
3691 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3692 viewport.getAlignment()));
3693 alignPanel.paintAlignment(true, false);
3699 * last hash for alignment's annotation array - used to minimise cost of
3702 protected int _annotationScoreVectorHash;
3705 * search the alignment and rebuild the sort by annotation score submenu the
3706 * last alignment annotation vector hash is stored to minimize cost of
3707 * rebuilding in subsequence calls.
3711 public void buildSortByAnnotationScoresMenu()
3713 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3718 if (viewport.getAlignment().getAlignmentAnnotation()
3719 .hashCode() != _annotationScoreVectorHash)
3721 sortByAnnotScore.removeAll();
3722 // almost certainly a quicker way to do this - but we keep it simple
3723 Hashtable scoreSorts = new Hashtable();
3724 AlignmentAnnotation aann[];
3725 for (SequenceI sqa : viewport.getAlignment().getSequences())
3727 aann = sqa.getAnnotation();
3728 for (int i = 0; aann != null && i < aann.length; i++)
3730 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3732 scoreSorts.put(aann[i].label, aann[i].label);
3736 Enumeration labels = scoreSorts.keys();
3737 while (labels.hasMoreElements())
3739 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3740 (String) labels.nextElement());
3742 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3745 _annotationScoreVectorHash = viewport.getAlignment()
3746 .getAlignmentAnnotation().hashCode();
3752 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3753 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3754 * call. Listeners are added to remove the menu item when the treePanel is
3755 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3759 public void buildTreeSortMenu()
3761 sortByTreeMenu.removeAll();
3763 List<Component> comps = PaintRefresher.components
3764 .get(viewport.getSequenceSetId());
3765 List<TreePanel> treePanels = new ArrayList<>();
3767 Map<MainFrame, JalviewBinding> aptxFrames = AptxInit.getAllAptxFrames();
3769 for (Component comp : comps)
3772 if (comp instanceof TreePanel)
3774 treePanels.add((TreePanel) comp);
3779 if (treePanels.isEmpty() && aptxFrames.isEmpty())
3781 sortByTreeMenu.setVisible(false);
3785 sortByTreeMenu.setVisible(true);
3787 for (Map.Entry<MainFrame, JalviewBinding> aptxFrameWithBinding : aptxFrames
3790 MainFrame aptxFrame = aptxFrameWithBinding.getKey();
3791 JalviewBinding binding = aptxFrameWithBinding.getValue();
3793 // future support for multiple tabs
3794 // for (org.forester.archaeopteryx.TreePanel aptxTree : aptxFrame
3795 // .getMainPanel().getTreePanels())
3797 final JMenuItem item = new JMenuItem(
3798 aptxFrame.getMainPanel().getCurrentTreePanel()
3799 .getPhylogeny().getName());
3801 item.addActionListener(new ActionListener()
3805 public void actionPerformed(ActionEvent e)
3807 binding.sortByTree_actionPerformed();
3808 addHistoryItem(binding.sortAlignmentIn(alignPanel));
3812 sortByTreeMenu.add(item);
3824 for (final TreePanel tp : treePanels)
3826 final JMenuItem item = new JMenuItem(tp.getTitle());
3827 item.addActionListener(new java.awt.event.ActionListener()
3830 public void actionPerformed(ActionEvent e)
3832 tp.sortByTree_actionPerformed();
3833 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3838 sortByTreeMenu.add(item);
3842 public boolean sortBy(AlignmentOrder alorder, String undoname)
3844 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3845 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3846 if (undoname != null)
3848 addHistoryItem(new OrderCommand(undoname, oldOrder,
3849 viewport.getAlignment()));
3851 alignPanel.paintAlignment(true, false);
3856 * Work out whether the whole set of sequences or just the selected set will
3857 * be submitted for multiple alignment.
3860 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3862 // Now, check we have enough sequences
3863 AlignmentView msa = null;
3865 if ((viewport.getSelectionGroup() != null)
3866 && (viewport.getSelectionGroup().getSize() > 1))
3868 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3869 // some common interface!
3871 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3872 * SequenceI[sz = seqs.getSize(false)];
3874 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3875 * seqs.getSequenceAt(i); }
3877 msa = viewport.getAlignmentView(true);
3879 else if (viewport.getSelectionGroup() != null
3880 && viewport.getSelectionGroup().getSize() == 1)
3882 int option = JvOptionPane.showConfirmDialog(this,
3883 MessageManager.getString("warn.oneseq_msainput_selection"),
3884 MessageManager.getString("label.invalid_selection"),
3885 JvOptionPane.OK_CANCEL_OPTION);
3886 if (option == JvOptionPane.OK_OPTION)
3888 msa = viewport.getAlignmentView(false);
3893 msa = viewport.getAlignmentView(false);
3899 * Decides what is submitted to a secondary structure prediction service: the
3900 * first sequence in the alignment, or in the current selection, or, if the
3901 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3902 * region or the whole alignment. (where the first sequence in the set is the
3903 * one that the prediction will be for).
3905 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3907 AlignmentView seqs = null;
3909 if ((viewport.getSelectionGroup() != null)
3910 && (viewport.getSelectionGroup().getSize() > 0))
3912 seqs = viewport.getAlignmentView(true);
3916 seqs = viewport.getAlignmentView(false);
3918 // limit sequences - JBPNote in future - could spawn multiple prediction
3920 // TODO: viewport.getAlignment().isAligned is a global state - the local
3921 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3922 if (!viewport.getAlignment().isAligned(false))
3924 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3925 // TODO: if seqs.getSequences().length>1 then should really have warned
3939 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3945 protected void loadTreeUrlItem_actionPerformed(ActionEvent e)
3951 protected void loadTreeBaseStudy_actionPerformed(ActionEvent e)
3953 chooseTreeDb(0, null);
3958 protected void loadTreeBase_actionPerformed(ActionEvent e)
3960 chooseTreeDb(1, null);
3964 protected void loadTreePfam_actionPerformed(ActionEvent e)
3967 // only DBRefs of first sequence are checked for matching DB for now,
3968 // iterating through them all seems excessive
3969 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3971 for (DBRefEntry pfamRef : DBRefUtils
3972 .searchRefsForSource(seq.getDBRefs(), "pfam"))
3974 if (pfamRef.getAccessionId().startsWith("PF"))
3976 dbId = pfamRef.getAccessionId().replaceAll("[A-Za-z]", "");
3980 chooseTreeDb(2, dbId);
3984 protected void loadTreeFam_actionPerformed(ActionEvent e)
3986 chooseTreeDb(3, null);
3991 protected void loadTreeOfLife_actionPerformed(ActionEvent e)
3993 chooseTreeDb(4, null);
4001 public void chooseTreeFile()
4003 // Pick the tree file
4004 JalviewFileChooser chooser = new JalviewFileChooser(
4005 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4006 chooser.setFileView(new JalviewFileView());
4007 chooser.setDialogTitle(
4008 MessageManager.getString("label.select_tree_file")); // modify
4009 chooser.setToolTipText(
4010 MessageManager.getString("label.load_tree_for_sequence_set"));
4011 for (SupportedTreeFileFilter treeFormat : SupportedTreeFileFilter
4014 chooser.setFileFilter(treeFormat.getTreeFilter());
4017 int value = chooser.showOpenDialog(null);
4019 if (value == JalviewFileChooser.APPROVE_OPTION)
4021 String filePath = chooser.getSelectedFile().getPath();
4022 Cache.setProperty("LAST_DIRECTORY", filePath);
4025 TreeParser treeParser = new TreeParser(filePath);
4026 treeParser.loadTree(viewport);
4032 * Break up and move to TreeParser?
4034 public void chooseTreeUrl()
4037 JLabel label = new JLabel(
4038 MessageManager.getString("label.tree_url_example"));
4039 // add "example" button
4040 final JComboBox<String> history = new JComboBox<>();
4042 JPanel panel = new JPanel(new GridLayout(2, 1));
4045 history.setPreferredSize(new Dimension(400, 20));
4046 history.setEditable(true);
4047 history.addItem("http://www.");
4049 String historyItems = jalview.bin.Cache.getProperty("RECENT_URL");
4053 if (historyItems != null)
4055 st = new StringTokenizer(historyItems, "\t");
4057 while (st.hasMoreTokens())
4059 history.addItem(st.nextToken());
4063 int reply = JvOptionPane.showInternalConfirmDialog(this, panel,
4064 MessageManager.getString("label.load_tree_url"),
4065 JvOptionPane.OK_CANCEL_OPTION);
4067 if (reply == JvOptionPane.OK_OPTION)
4070 String urlString = history.getSelectedItem().toString();
4075 FileFormatI format = null;
4077 format = new IdentifyFile().identify(urlString, DataSourceType.URL);
4078 // add actual use for the format identification (jalview .jar files)
4079 treeUrl = new URL(urlString);
4080 AptxInit.createInstancesFromUrl(treeUrl, viewport);
4082 } catch (IOException | RuntimeException e)
4084 JvOptionPane.showMessageDialog(this, MessageManager.formatMessage(
4085 "exception.failed_to_read_data_from_source", new String[]
4087 MessageManager.getString("label.url_not_found"),
4088 JvOptionPane.ERROR_MESSAGE);
4089 e.printStackTrace();
4099 * Disgustingly hardcoded atm.
4101 * @param databaseIndex
4103 public void chooseTreeDb(int databaseIndex, String defaultIdentifier)
4105 final WebservicesManager webservices_manager = WebservicesManager
4107 final PhylogeniesWebserviceClient client = webservices_manager
4108 .getAvailablePhylogeniesWebserviceClient(databaseIndex);
4109 String identifier = JvOptionPane
4110 .showInternalInputDialog(Desktop.desktop,
4111 client.getInstructions() + "\n(Reference: "
4112 + client.getReference() + ")",
4113 client.getDescription(), JvOptionPane.QUESTION_MESSAGE,
4114 null, null, defaultIdentifier)
4117 AptxInit.createInstancesFromDb(client, identifier, viewport);
4120 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4122 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4125 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4126 int h, int x, int y)
4128 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4132 * Add a treeviewer for the tree extracted from a Newick file object to the
4133 * current alignment view
4140 * Associated alignment input data (or null)
4149 * @return TreePanel handle
4151 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4152 AlignmentView input, int w, int h, int x, int y)
4154 TreePanel tp = null;
4160 if (nf.getTree() != null)
4162 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4168 tp.setLocation(x, y);
4171 Desktop.addInternalFrame(tp, treeTitle, w, h);
4173 } catch (Exception ex)
4175 ex.printStackTrace();
4181 private boolean buildingMenu = false;
4183 public void BuildTreeDbMenu()
4188 * Generates menu items and listener event actions for web service clients
4191 public void BuildWebServiceMenu()
4193 while (buildingMenu)
4197 System.err.println("Waiting for building menu to finish.");
4199 } catch (Exception e)
4203 final AlignFrame me = this;
4204 buildingMenu = true;
4205 new Thread(new Runnable()
4210 final List<JMenuItem> legacyItems = new ArrayList<>();
4213 // System.err.println("Building ws menu again "
4214 // + Thread.currentThread());
4215 // TODO: add support for context dependent disabling of services based
4217 // alignment and current selection
4218 // TODO: add additional serviceHandle parameter to specify abstract
4220 // class independently of AbstractName
4221 // TODO: add in rediscovery GUI function to restart discoverer
4222 // TODO: group services by location as well as function and/or
4224 // object broker mechanism.
4225 final Vector<JMenu> wsmenu = new Vector<>();
4226 final IProgressIndicator af = me;
4229 * do not i18n these strings - they are hard-coded in class
4230 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4231 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4233 final JMenu msawsmenu = new JMenu("Alignment");
4234 final JMenu secstrmenu = new JMenu(
4235 "Secondary Structure Prediction");
4236 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4237 final JMenu analymenu = new JMenu("Analysis");
4238 final JMenu dismenu = new JMenu("Protein Disorder");
4239 final JMenu phylogenmenu = new JMenu("Phylogenetic inference");
4241 // JAL-940 - only show secondary structure prediction services from
4242 // the legacy server
4243 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4245 Discoverer.services != null && (Discoverer.services.size() > 0))
4247 // TODO: refactor to allow list of AbstractName/Handler bindings to
4249 // stored or retrieved from elsewhere
4250 // No MSAWS used any more:
4251 // Vector msaws = null; // (Vector)
4252 // Discoverer.services.get("MsaWS");
4253 Vector secstrpr = (Vector) Discoverer.services
4255 if (secstrpr != null)
4257 // Add any secondary structure prediction services
4258 for (int i = 0, j = secstrpr.size(); i < j; i++)
4260 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4262 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4263 .getServiceClient(sh);
4264 int p = secstrmenu.getItemCount();
4265 impl.attachWSMenuEntry(secstrmenu, me);
4266 int q = secstrmenu.getItemCount();
4267 for (int litm = p; litm < q; litm++)
4269 legacyItems.add(secstrmenu.getItem(litm));
4275 // Add all submenus in the order they should appear on the web
4277 wsmenu.add(msawsmenu);
4278 wsmenu.add(secstrmenu);
4279 wsmenu.add(dismenu);
4280 wsmenu.add(analymenu);
4281 wsmenu.add(phylogenmenu);
4282 // No search services yet
4283 // wsmenu.add(seqsrchmenu);
4285 javax.swing.SwingUtilities.invokeLater(new Runnable()
4292 webService.removeAll();
4293 // first, add discovered services onto the webservices menu
4294 if (wsmenu.size() > 0)
4296 for (int i = 0, j = wsmenu.size(); i < j; i++)
4298 webService.add(wsmenu.get(i));
4303 webService.add(me.webServiceNoServices);
4305 // TODO: move into separate menu builder class.
4306 boolean new_sspred = false;
4307 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4309 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4310 if (jws2servs != null)
4312 if (jws2servs.hasServices())
4314 jws2servs.attachWSMenuEntry(webService, me);
4315 for (Jws2Instance sv : jws2servs.getServices())
4317 if (sv.description.toLowerCase().contains("jpred"))
4319 for (JMenuItem jmi : legacyItems)
4321 jmi.setVisible(false);
4327 if (jws2servs.isRunning())
4329 JMenuItem tm = new JMenuItem(
4330 "Still discovering JABA Services");
4331 tm.setEnabled(false);
4336 build_urlServiceMenu(me.webService);
4337 build_fetchdbmenu(webService);
4338 for (JMenu item : wsmenu)
4340 if (item.getItemCount() == 0)
4342 item.setEnabled(false);
4346 item.setEnabled(true);
4349 } catch (Exception e)
4352 "Exception during web service menu building process.",
4357 } catch (Exception e)
4360 buildingMenu = false;
4362 }, "BuildWebServiceThread").start();
4367 * construct any groupURL type service menu entries.
4371 private void build_urlServiceMenu(JMenu webService)
4373 // TODO: remove this code when 2.7 is released
4374 // DEBUG - alignmentView
4376 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4377 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4379 * @Override public void actionPerformed(ActionEvent e) {
4380 * jalview.datamodel.AlignmentView
4381 * .testSelectionViews(af.viewport.getAlignment(),
4382 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4384 * }); webService.add(testAlView);
4386 // TODO: refactor to RestClient discoverer and merge menu entries for
4387 // rest-style services with other types of analysis/calculation service
4388 // SHmmr test client - still being implemented.
4389 // DEBUG - alignmentView
4391 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4394 client.attachWSMenuEntry(
4395 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4401 * Searches the alignment sequences for xRefs and builds the Show
4402 * Cross-References menu (formerly called Show Products), with database
4403 * sources for which cross-references are found (protein sources for a
4404 * nucleotide alignment and vice versa)
4406 * @return true if Show Cross-references menu should be enabled
4408 public boolean canShowProducts()
4410 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4411 AlignmentI dataset = viewport.getAlignment().getDataset();
4413 showProducts.removeAll();
4414 final boolean dna = viewport.getAlignment().isNucleotide();
4416 if (seqs == null || seqs.length == 0)
4418 // nothing to see here.
4422 boolean showp = false;
4425 List<String> ptypes = new CrossRef(seqs, dataset)
4426 .findXrefSourcesForSequences(dna);
4428 for (final String source : ptypes)
4431 final AlignFrame af = this;
4432 JMenuItem xtype = new JMenuItem(source);
4433 xtype.addActionListener(new ActionListener()
4436 public void actionPerformed(ActionEvent e)
4438 showProductsFor(af.viewport.getSequenceSelection(), dna,
4442 showProducts.add(xtype);
4444 showProducts.setVisible(showp);
4445 showProducts.setEnabled(showp);
4446 } catch (Exception e)
4449 "canShowProducts threw an exception - please report to help@jalview.org",
4457 * Finds and displays cross-references for the selected sequences (protein
4458 * products for nucleotide sequences, dna coding sequences for peptides).
4461 * the sequences to show cross-references for
4463 * true if from a nucleotide alignment (so showing proteins)
4465 * the database to show cross-references for
4467 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4468 final String source)
4470 new Thread(CrossRefAction.showProductsFor(sel, _odna, source, this),
4471 "CrossReferencesThread")
4476 * Construct and display a new frame containing the translation of this
4477 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4480 public void showTranslation_actionPerformed(ActionEvent e)
4482 AlignmentI al = null;
4485 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4487 al = dna.translateCdna();
4488 } catch (Exception ex)
4490 jalview.bin.Cache.log.error(
4491 "Exception during translation. Please report this !", ex);
4492 final String msg = MessageManager.getString(
4493 "label.error_when_translating_sequences_submit_bug_report");
4494 final String errorTitle = MessageManager
4495 .getString("label.implementation_error")
4496 + MessageManager.getString("label.translation_failed");
4497 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4498 JvOptionPane.ERROR_MESSAGE);
4501 if (al == null || al.getHeight() == 0)
4503 final String msg = MessageManager.getString(
4504 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4505 final String errorTitle = MessageManager
4506 .getString("label.translation_failed");
4507 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4508 JvOptionPane.WARNING_MESSAGE);
4512 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4513 af.setFileFormat(this.currentFileFormat);
4514 final String newTitle = MessageManager
4515 .formatMessage("label.translation_of_params", new Object[]
4516 { this.getTitle() });
4517 af.setTitle(newTitle);
4518 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4520 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4521 viewport.openSplitFrame(af, new Alignment(seqs));
4525 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4532 * Set the file format
4536 public void setFileFormat(FileFormatI format)
4538 this.currentFileFormat = format;
4542 * Try to load a features file onto the alignment.
4545 * contents or path to retrieve file
4547 * access mode of file (see jalview.io.AlignFile)
4548 * @return true if features file was parsed correctly.
4550 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4552 return avc.parseFeaturesFile(file, sourceType,
4553 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4558 public void refreshFeatureUI(boolean enableIfNecessary)
4560 // note - currently this is only still here rather than in the controller
4561 // because of the featureSettings hard reference that is yet to be
4563 if (enableIfNecessary)
4565 viewport.setShowSequenceFeatures(true);
4566 showSeqFeatures.setSelected(true);
4572 public void dragEnter(DropTargetDragEvent evt)
4577 public void dragExit(DropTargetEvent evt)
4582 public void dragOver(DropTargetDragEvent evt)
4587 public void dropActionChanged(DropTargetDragEvent evt)
4592 public void drop(DropTargetDropEvent evt)
4594 // JAL-1552 - acceptDrop required before getTransferable call for
4595 // Java's Transferable for native dnd
4596 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4597 Transferable t = evt.getTransferable();
4598 final AlignFrame thisaf = this;
4599 final List<String> files = new ArrayList<>();
4600 List<DataSourceType> protocols = new ArrayList<>();
4604 Desktop.transferFromDropTarget(files, protocols, evt, t);
4605 } catch (Exception e)
4607 e.printStackTrace();
4611 new Thread(new Runnable()
4618 // check to see if any of these files have names matching sequences
4621 SequenceIdMatcher idm = new SequenceIdMatcher(
4622 viewport.getAlignment().getSequencesArray());
4624 * Object[] { String,SequenceI}
4626 ArrayList<Object[]> filesmatched = new ArrayList<>();
4627 ArrayList<String> filesnotmatched = new ArrayList<>();
4628 for (int i = 0; i < files.size(); i++)
4630 String file = files.get(i).toString();
4632 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4633 if (protocol == DataSourceType.FILE)
4635 File fl = new File(file);
4636 pdbfn = fl.getName();
4638 else if (protocol == DataSourceType.URL)
4640 URL url = new URL(file);
4641 pdbfn = url.getFile();
4643 if (pdbfn.length() > 0)
4645 // attempt to find a match in the alignment
4646 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4647 int l = 0, c = pdbfn.indexOf(".");
4648 while (mtch == null && c != -1)
4653 } while ((c = pdbfn.indexOf(".", l)) > l);
4656 pdbfn = pdbfn.substring(0, l);
4658 mtch = idm.findAllIdMatches(pdbfn);
4662 FileFormatI type = null;
4665 type = new IdentifyFile().identify(file, protocol);
4666 } catch (Exception ex)
4670 if (type != null && type.isStructureFile())
4672 filesmatched.add(new Object[] { file, protocol, mtch });
4676 // File wasn't named like one of the sequences or wasn't a PDB
4678 filesnotmatched.add(file);
4682 if (filesmatched.size() > 0)
4684 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4685 || JvOptionPane.showConfirmDialog(thisaf,
4686 MessageManager.formatMessage(
4687 "label.automatically_associate_structure_files_with_sequences_same_name",
4689 { Integer.valueOf(filesmatched.size())
4691 MessageManager.getString(
4692 "label.automatically_associate_structure_files_by_name"),
4693 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION)
4696 for (Object[] fm : filesmatched)
4698 // try and associate
4699 // TODO: may want to set a standard ID naming formalism for
4700 // associating PDB files which have no IDs.
4701 for (SequenceI toassoc : (SequenceI[]) fm[2])
4703 PDBEntry pe = new AssociatePdbFileWithSeq()
4704 .associatePdbWithSeq((String) fm[0],
4705 (DataSourceType) fm[1], toassoc, false,
4709 System.err.println("Associated file : "
4710 + ((String) fm[0]) + " with "
4711 + toassoc.getDisplayId(true));
4715 // TODO: do we need to update overview ? only if features are
4717 alignPanel.paintAlignment(true, false);
4721 if (filesnotmatched.size() > 0)
4723 if (assocfiles > 0 && (Cache.getDefault(
4724 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4725 || JvOptionPane.showConfirmDialog(thisaf,
4726 "<html>" + MessageManager.formatMessage(
4727 "label.ignore_unmatched_dropped_files_info",
4730 filesnotmatched.size())
4733 MessageManager.getString(
4734 "label.ignore_unmatched_dropped_files"),
4735 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4739 for (String fn : filesnotmatched)
4741 loadJalviewDataFile(fn, null, null, null);
4745 } catch (Exception ex)
4747 ex.printStackTrace();
4750 }, "DropFileThread").start();
4755 * Attempt to load a "dropped" file or URL string, by testing in turn for
4757 * <li>an Annotation file</li>
4758 * <li>a JNet file</li>
4759 * <li>a features file</li>
4760 * <li>else try to interpret as an alignment file</li>
4764 * either a filename or a URL string.
4766 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4767 FileFormatI format, SequenceI assocSeq)
4771 if (sourceType == null)
4773 sourceType = FormatAdapter.checkProtocol(file);
4775 // if the file isn't identified, or not positively identified as some
4776 // other filetype (PFAM is default unidentified alignment file type) then
4777 // try to parse as annotation.
4778 boolean isAnnotation = (format == null
4779 || FileFormat.Pfam.equals(format))
4780 ? new AnnotationFile().annotateAlignmentView(viewport,
4786 // first see if its a T-COFFEE score file
4787 TCoffeeScoreFile tcf = null;
4790 tcf = new TCoffeeScoreFile(file, sourceType);
4793 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4797 new TCoffeeColourScheme(viewport.getAlignment()));
4798 isAnnotation = true;
4799 statusBar.setText(MessageManager.getString(
4800 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4804 // some problem - if no warning its probable that the ID matching
4805 // process didn't work
4806 JvOptionPane.showMessageDialog(Desktop.desktop,
4807 tcf.getWarningMessage() == null
4808 ? MessageManager.getString(
4809 "label.check_file_matches_sequence_ids_alignment")
4810 : tcf.getWarningMessage(),
4811 MessageManager.getString(
4812 "label.problem_reading_tcoffee_score_file"),
4813 JvOptionPane.WARNING_MESSAGE);
4820 } catch (Exception x)
4823 "Exception when processing data source as T-COFFEE score file",
4829 // try to see if its a JNet 'concise' style annotation file *before*
4831 // try to parse it as a features file
4834 format = new IdentifyFile().identify(file, sourceType);
4836 if (FileFormat.ScoreMatrix == format)
4838 ScoreMatrixFile sm = new ScoreMatrixFile(
4839 new FileParse(file, sourceType));
4841 // todo: i18n this message
4842 statusBar.setText(MessageManager.formatMessage(
4843 "label.successfully_loaded_matrix",
4844 sm.getMatrixName()));
4846 else if (FileFormat.Jnet.equals(format))
4848 JPredFile predictions = new JPredFile(file, sourceType);
4849 new JnetAnnotationMaker();
4850 JnetAnnotationMaker.add_annotation(predictions,
4851 viewport.getAlignment(), 0, false);
4852 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
4853 viewport.getAlignment().setSeqrep(repseq);
4854 HiddenColumns cs = new HiddenColumns();
4855 cs.hideInsertionsFor(repseq);
4856 viewport.getAlignment().setHiddenColumns(cs);
4857 isAnnotation = true;
4859 // else if (IdentifyFile.FeaturesFile.equals(format))
4860 else if (FileFormat.Features.equals(format))
4862 if (parseFeaturesFile(file, sourceType))
4864 alignPanel.paintAlignment(true, true);
4869 new FileLoader().LoadFile(viewport, file, sourceType, format);
4876 alignPanel.adjustAnnotationHeight();
4877 viewport.updateSequenceIdColours();
4878 buildSortByAnnotationScoresMenu();
4879 alignPanel.paintAlignment(true, true);
4881 } catch (Exception ex)
4883 ex.printStackTrace();
4884 } catch (OutOfMemoryError oom)
4889 } catch (Exception x)
4894 + (sourceType != null
4895 ? (sourceType == DataSourceType.PASTE
4897 : "using " + sourceType + " from "
4901 ? "(parsing as '" + format + "' file)"
4903 oom, Desktop.desktop);
4908 * Method invoked by the ChangeListener on the tabbed pane, in other words
4909 * when a different tabbed pane is selected by the user or programmatically.
4912 public void tabSelectionChanged(int index)
4916 alignPanel = alignPanels.get(index);
4917 viewport = alignPanel.av;
4918 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4919 setMenusFromViewport(viewport);
4923 * 'focus' any colour slider that is open to the selected viewport
4925 if (viewport.getConservationSelected())
4927 SliderPanel.setConservationSlider(alignPanel,
4928 viewport.getResidueShading(), alignPanel.getViewName());
4932 SliderPanel.hideConservationSlider();
4934 if (viewport.getAbovePIDThreshold())
4936 SliderPanel.setPIDSliderSource(alignPanel,
4937 viewport.getResidueShading(), alignPanel.getViewName());
4941 SliderPanel.hidePIDSlider();
4945 * If there is a frame linked to this one in a SplitPane, switch it to the
4946 * same view tab index. No infinite recursion of calls should happen, since
4947 * tabSelectionChanged() should not get invoked on setting the selected
4948 * index to an unchanged value. Guard against setting an invalid index
4949 * before the new view peer tab has been created.
4951 final AlignViewportI peer = viewport.getCodingComplement();
4954 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4955 .getAlignPanel().alignFrame;
4956 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4958 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4964 * On right mouse click on view tab, prompt for and set new view name.
4967 public void tabbedPane_mousePressed(MouseEvent e)
4969 if (e.isPopupTrigger())
4971 String msg = MessageManager.getString("label.enter_view_name");
4972 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4973 JvOptionPane.QUESTION_MESSAGE);
4977 viewport.viewName = reply;
4978 // TODO warn if reply is in getExistingViewNames()?
4979 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4984 public AlignViewport getCurrentView()
4990 * Open the dialog for regex description parsing.
4993 protected void extractScores_actionPerformed(ActionEvent e)
4995 ParseProperties pp = new jalview.analysis.ParseProperties(
4996 viewport.getAlignment());
4997 // TODO: verify regex and introduce GUI dialog for version 2.5
4998 // if (pp.getScoresFromDescription("col", "score column ",
4999 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5001 if (pp.getScoresFromDescription("description column",
5002 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5004 buildSortByAnnotationScoresMenu();
5012 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5016 protected void showDbRefs_actionPerformed(ActionEvent e)
5018 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5024 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5028 protected void showNpFeats_actionPerformed(ActionEvent e)
5030 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5034 * find the viewport amongst the tabs in this alignment frame and close that
5039 public boolean closeView(AlignViewportI av)
5043 this.closeMenuItem_actionPerformed(false);
5046 Component[] comp = tabbedPane.getComponents();
5047 for (int i = 0; comp != null && i < comp.length; i++)
5049 if (comp[i] instanceof AlignmentPanel)
5051 if (((AlignmentPanel) comp[i]).av == av)
5054 closeView((AlignmentPanel) comp[i]);
5062 protected void build_fetchdbmenu(JMenu webService)
5064 // Temporary hack - DBRef Fetcher always top level ws entry.
5065 // TODO We probably want to store a sequence database checklist in
5066 // preferences and have checkboxes.. rather than individual sources selected
5068 final JMenu rfetch = new JMenu(
5069 MessageManager.getString("action.fetch_db_references"));
5070 rfetch.setToolTipText(MessageManager.getString(
5071 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5072 webService.add(rfetch);
5074 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5075 MessageManager.getString("option.trim_retrieved_seqs"));
5076 trimrs.setToolTipText(
5077 MessageManager.getString("label.trim_retrieved_sequences"));
5078 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5079 trimrs.addActionListener(new ActionListener()
5082 public void actionPerformed(ActionEvent e)
5084 trimrs.setSelected(trimrs.isSelected());
5085 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5086 Boolean.valueOf(trimrs.isSelected()).toString());
5090 JMenuItem fetchr = new JMenuItem(
5091 MessageManager.getString("label.standard_databases"));
5092 fetchr.setToolTipText(
5093 MessageManager.getString("label.fetch_embl_uniprot"));
5094 fetchr.addActionListener(new ActionListener()
5098 public void actionPerformed(ActionEvent e)
5100 new Thread(new Runnable()
5105 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5106 .getAlignment().isNucleotide();
5107 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5108 alignPanel.av.getSequenceSelection(),
5109 alignPanel.alignFrame, null,
5110 alignPanel.alignFrame.featureSettings, isNucleotide);
5111 dbRefFetcher.addListener(new FetchFinishedListenerI()
5114 public void finished()
5116 AlignFrame.this.setMenusForViewport();
5119 dbRefFetcher.fetchDBRefs(false);
5121 }, "BuildFetchDBMenuThread").start();
5127 final AlignFrame me = this;
5128 new Thread(new Runnable()
5133 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5134 .getSequenceFetcherSingleton(me);
5135 javax.swing.SwingUtilities.invokeLater(new Runnable()
5140 String[] dbclasses = sf.getOrderedSupportedSources();
5141 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5142 // jalview.util.QuickSort.sort(otherdb, otherdb);
5143 List<DbSourceProxy> otherdb;
5144 JMenu dfetch = new JMenu();
5145 JMenu ifetch = new JMenu();
5146 JMenuItem fetchr = null;
5147 int comp = 0, icomp = 0, mcomp = 15;
5148 String mname = null;
5150 for (String dbclass : dbclasses)
5152 otherdb = sf.getSourceProxy(dbclass);
5153 // add a single entry for this class, or submenu allowing 'fetch
5155 if (otherdb == null || otherdb.size() < 1)
5159 // List<DbSourceProxy> dbs=otherdb;
5160 // otherdb=new ArrayList<DbSourceProxy>();
5161 // for (DbSourceProxy db:dbs)
5163 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5167 mname = "From " + dbclass;
5169 if (otherdb.size() == 1)
5171 final DbSourceProxy[] dassource = otherdb
5172 .toArray(new DbSourceProxy[0]);
5173 DbSourceProxy src = otherdb.get(0);
5174 fetchr = new JMenuItem(src.getDbSource());
5175 fetchr.addActionListener(new ActionListener()
5179 public void actionPerformed(ActionEvent e)
5181 new Thread(new Runnable()
5187 boolean isNucleotide = alignPanel.alignFrame
5188 .getViewport().getAlignment()
5190 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5191 alignPanel.av.getSequenceSelection(),
5192 alignPanel.alignFrame, dassource,
5193 alignPanel.alignFrame.featureSettings,
5196 .addListener(new FetchFinishedListenerI()
5199 public void finished()
5201 AlignFrame.this.setMenusForViewport();
5204 dbRefFetcher.fetchDBRefs(false);
5210 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5211 MessageManager.formatMessage(
5212 "label.fetch_retrieve_from", new Object[]
5213 { src.getDbName() })));
5219 final DbSourceProxy[] dassource = otherdb
5220 .toArray(new DbSourceProxy[0]);
5222 DbSourceProxy src = otherdb.get(0);
5223 fetchr = new JMenuItem(MessageManager
5224 .formatMessage("label.fetch_all_param", new Object[]
5225 { src.getDbSource() }));
5226 fetchr.addActionListener(new ActionListener()
5229 public void actionPerformed(ActionEvent e)
5231 new Thread(new Runnable()
5237 boolean isNucleotide = alignPanel.alignFrame
5238 .getViewport().getAlignment()
5240 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5241 alignPanel.av.getSequenceSelection(),
5242 alignPanel.alignFrame, dassource,
5243 alignPanel.alignFrame.featureSettings,
5246 .addListener(new FetchFinishedListenerI()
5249 public void finished()
5251 AlignFrame.this.setMenusForViewport();
5254 dbRefFetcher.fetchDBRefs(false);
5260 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5261 MessageManager.formatMessage(
5262 "label.fetch_retrieve_from_all_sources",
5264 { Integer.valueOf(otherdb.size())
5266 src.getDbSource(), src.getDbName() })));
5269 // and then build the rest of the individual menus
5270 ifetch = new JMenu(MessageManager.formatMessage(
5271 "label.source_from_db_source", new Object[]
5272 { src.getDbSource() }));
5274 String imname = null;
5276 for (DbSourceProxy sproxy : otherdb)
5278 String dbname = sproxy.getDbName();
5279 String sname = dbname.length() > 5
5280 ? dbname.substring(0, 5) + "..."
5282 String msname = dbname.length() > 10
5283 ? dbname.substring(0, 10) + "..."
5287 imname = MessageManager
5288 .formatMessage("label.from_msname", new Object[]
5291 fetchr = new JMenuItem(msname);
5292 final DbSourceProxy[] dassrc = { sproxy };
5293 fetchr.addActionListener(new ActionListener()
5297 public void actionPerformed(ActionEvent e)
5299 new Thread(new Runnable()
5305 boolean isNucleotide = alignPanel.alignFrame
5306 .getViewport().getAlignment()
5308 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5309 alignPanel.av.getSequenceSelection(),
5310 alignPanel.alignFrame, dassrc,
5311 alignPanel.alignFrame.featureSettings,
5314 .addListener(new FetchFinishedListenerI()
5317 public void finished()
5319 AlignFrame.this.setMenusForViewport();
5322 dbRefFetcher.fetchDBRefs(false);
5328 fetchr.setToolTipText(
5329 "<html>" + MessageManager.formatMessage(
5330 "label.fetch_retrieve_from", new Object[]
5334 if (++icomp >= mcomp || i == (otherdb.size()))
5336 ifetch.setText(MessageManager.formatMessage(
5337 "label.source_to_target", imname, sname));
5339 ifetch = new JMenu();
5347 if (comp >= mcomp || dbi >= (dbclasses.length))
5349 dfetch.setText(MessageManager.formatMessage(
5350 "label.source_to_target", mname, dbclass));
5352 dfetch = new JMenu();
5365 * Left justify the whole alignment.
5368 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5370 AlignmentI al = viewport.getAlignment();
5372 viewport.firePropertyChange("alignment", null, al);
5376 * Right justify the whole alignment.
5379 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5381 AlignmentI al = viewport.getAlignment();
5383 viewport.firePropertyChange("alignment", null, al);
5387 public void setShowSeqFeatures(boolean b)
5389 showSeqFeatures.setSelected(b);
5390 viewport.setShowSequenceFeatures(b);
5397 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5398 * awt.event.ActionEvent)
5401 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5403 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5404 alignPanel.paintAlignment(false, false);
5411 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5415 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5417 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5418 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5426 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5427 * .event.ActionEvent)
5430 protected void showGroupConservation_actionPerformed(ActionEvent e)
5432 viewport.setShowGroupConservation(showGroupConservation.getState());
5433 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5440 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5441 * .event.ActionEvent)
5444 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5446 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5447 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5454 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5455 * .event.ActionEvent)
5458 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5460 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5461 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5465 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5467 showSequenceLogo.setState(true);
5468 viewport.setShowSequenceLogo(true);
5469 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5470 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5474 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5476 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5483 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5484 * .event.ActionEvent)
5487 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5489 if (avc.makeGroupsFromSelection())
5491 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5492 alignPanel.updateAnnotation();
5493 alignPanel.paintAlignment(true, true);
5497 public void clearAlignmentSeqRep()
5499 // TODO refactor alignmentseqrep to controller
5500 if (viewport.getAlignment().hasSeqrep())
5502 viewport.getAlignment().setSeqrep(null);
5503 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5504 alignPanel.updateAnnotation();
5505 alignPanel.paintAlignment(true, true);
5510 protected void createGroup_actionPerformed(ActionEvent e)
5512 if (avc.createGroup())
5514 alignPanel.alignmentChanged();
5519 protected void unGroup_actionPerformed(ActionEvent e)
5523 alignPanel.alignmentChanged();
5528 * make the given alignmentPanel the currently selected tab
5530 * @param alignmentPanel
5532 public void setDisplayedView(AlignmentPanel alignmentPanel)
5534 if (!viewport.getSequenceSetId()
5535 .equals(alignmentPanel.av.getSequenceSetId()))
5537 throw new Error(MessageManager.getString(
5538 "error.implementation_error_cannot_show_view_alignment_frame"));
5540 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5541 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5543 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5548 * Action on selection of menu options to Show or Hide annotations.
5551 * @param forSequences
5552 * update sequence-related annotations
5553 * @param forAlignment
5554 * update non-sequence-related annotations
5557 protected void setAnnotationsVisibility(boolean visible,
5558 boolean forSequences, boolean forAlignment)
5560 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5561 .getAlignmentAnnotation();
5566 for (AlignmentAnnotation aa : anns)
5569 * don't display non-positional annotations on an alignment
5571 if (aa.annotations == null)
5575 boolean apply = (aa.sequenceRef == null && forAlignment)
5576 || (aa.sequenceRef != null && forSequences);
5579 aa.visible = visible;
5582 alignPanel.validateAnnotationDimensions(true);
5583 alignPanel.alignmentChanged();
5587 * Store selected annotation sort order for the view and repaint.
5590 protected void sortAnnotations_actionPerformed()
5592 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5594 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5595 alignPanel.paintAlignment(false, false);
5600 * @return alignment panels in this alignment frame
5602 public List<? extends AlignmentViewPanel> getAlignPanels()
5604 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5608 * Open a new alignment window, with the cDNA associated with this (protein)
5609 * alignment, aligned as is the protein.
5611 protected void viewAsCdna_actionPerformed()
5613 // TODO no longer a menu action - refactor as required
5614 final AlignmentI alignment = getViewport().getAlignment();
5615 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5616 if (mappings == null)
5620 List<SequenceI> cdnaSeqs = new ArrayList<>();
5621 for (SequenceI aaSeq : alignment.getSequences())
5623 for (AlignedCodonFrame acf : mappings)
5625 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5629 * There is a cDNA mapping for this protein sequence - add to new
5630 * alignment. It will share the same dataset sequence as other mapped
5631 * cDNA (no new mappings need to be created).
5633 final Sequence newSeq = new Sequence(dnaSeq);
5634 newSeq.setDatasetSequence(dnaSeq);
5635 cdnaSeqs.add(newSeq);
5639 if (cdnaSeqs.size() == 0)
5641 // show a warning dialog no mapped cDNA
5644 AlignmentI cdna = new Alignment(
5645 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5646 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5647 AlignFrame.DEFAULT_HEIGHT);
5648 cdna.alignAs(alignment);
5649 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5651 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5652 AlignFrame.DEFAULT_HEIGHT);
5656 * Set visibility of dna/protein complement view (available when shown in a
5662 protected void showComplement_actionPerformed(boolean show)
5664 SplitContainerI sf = getSplitViewContainer();
5667 sf.setComplementVisible(this, show);
5672 * Generate the reverse (optionally complemented) of the selected sequences,
5673 * and add them to the alignment
5676 protected void showReverse_actionPerformed(boolean complement)
5678 AlignmentI al = null;
5681 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5682 al = dna.reverseCdna(complement);
5683 viewport.addAlignment(al, "");
5684 addHistoryItem(new EditCommand(
5685 MessageManager.getString("label.add_sequences"), Action.PASTE,
5686 al.getSequencesArray(), 0, al.getWidth(),
5687 viewport.getAlignment()));
5688 } catch (Exception ex)
5690 System.err.println(ex.getMessage());
5696 * Try to run a script in the Groovy console, having first ensured that this
5697 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5698 * be targeted at this alignment.
5701 protected void runGroovy_actionPerformed()
5703 Jalview.setCurrentAlignFrame(this);
5704 groovy.ui.Console console = Desktop.getGroovyConsole();
5705 if (console != null)
5709 console.runScript();
5710 } catch (Exception ex)
5712 System.err.println((ex.toString()));
5713 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5714 MessageManager.getString("label.couldnt_run_groovy_script"),
5715 MessageManager.getString("label.groovy_support_failed"),
5716 JvOptionPane.ERROR_MESSAGE);
5721 System.err.println("Can't run Groovy script as console not found");
5726 * Hides columns containing (or not containing) a specified feature, provided
5727 * that would not leave all columns hidden
5729 * @param featureType
5730 * @param columnsContaining
5733 public boolean hideFeatureColumns(String featureType,
5734 boolean columnsContaining)
5736 boolean notForHiding = avc.markColumnsContainingFeatures(
5737 columnsContaining, false, false, featureType);
5740 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5741 false, featureType))
5743 getViewport().hideSelectedColumns();
5751 protected void selectHighlightedColumns_actionPerformed(
5752 ActionEvent actionEvent)
5754 // include key modifier check in case user selects from menu
5755 avc.markHighlightedColumns(
5756 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5757 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5758 | ActionEvent.CTRL_MASK)) != 0);
5762 * Rebuilds the Colour menu, including any user-defined colours which have
5763 * been loaded either on startup or during the session
5765 public void buildColourMenu()
5767 colourMenu.removeAll();
5769 colourMenu.add(applyToAllGroups);
5770 colourMenu.add(textColour);
5771 colourMenu.addSeparator();
5773 ColourMenuHelper.addMenuItems(colourMenu, this, viewport.getAlignment(),
5776 colourMenu.addSeparator();
5777 colourMenu.add(conservationMenuItem);
5778 colourMenu.add(modifyConservation);
5779 colourMenu.add(abovePIDThreshold);
5780 colourMenu.add(modifyPID);
5781 colourMenu.add(annotationColour);
5783 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5784 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5788 * Open a dialog (if not already open) that allows the user to select and
5789 * calculate PCA or Tree analysis
5791 protected void openTreePcaDialog()
5793 if (alignPanel.getCalculationDialog() == null)
5795 new CalculationChooser(AlignFrame.this);
5800 class PrintThread extends Thread
5804 public PrintThread(AlignmentPanel ap)
5809 static PageFormat pf;
5814 PrinterJob printJob = PrinterJob.getPrinterJob();
5818 printJob.setPrintable(ap, pf);
5822 printJob.setPrintable(ap);
5825 if (printJob.printDialog())
5830 } catch (Exception PrintException)
5832 PrintException.printStackTrace();