2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AlignmentSorter;
24 import jalview.analysis.AlignmentUtils;
25 import jalview.analysis.CrossRef;
26 import jalview.analysis.Dna;
27 import jalview.analysis.ParseProperties;
28 import jalview.analysis.SequenceIdMatcher;
29 import jalview.api.AlignExportSettingI;
30 import jalview.api.AlignViewControllerGuiI;
31 import jalview.api.AlignViewControllerI;
32 import jalview.api.AlignViewportI;
33 import jalview.api.AlignmentViewPanel;
34 import jalview.api.FeatureSettingsControllerI;
35 import jalview.api.SplitContainerI;
36 import jalview.api.ViewStyleI;
37 import jalview.api.analysis.SimilarityParamsI;
38 import jalview.bin.Cache;
39 import jalview.bin.Jalview;
40 import jalview.commands.CommandI;
41 import jalview.commands.EditCommand;
42 import jalview.commands.EditCommand.Action;
43 import jalview.commands.OrderCommand;
44 import jalview.commands.RemoveGapColCommand;
45 import jalview.commands.RemoveGapsCommand;
46 import jalview.commands.SlideSequencesCommand;
47 import jalview.commands.TrimRegionCommand;
48 import jalview.datamodel.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.HiddenColumns;
57 import jalview.datamodel.HiddenSequences;
58 import jalview.datamodel.PDBEntry;
59 import jalview.datamodel.SeqCigar;
60 import jalview.datamodel.Sequence;
61 import jalview.datamodel.SequenceGroup;
62 import jalview.datamodel.SequenceI;
63 import jalview.gui.ColourMenuHelper.ColourChangeListener;
64 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
65 import jalview.io.AlignmentProperties;
66 import jalview.io.AnnotationFile;
67 import jalview.io.BioJsHTMLOutput;
68 import jalview.io.DataSourceType;
69 import jalview.io.FileFormat;
70 import jalview.io.FileFormatI;
71 import jalview.io.FileFormats;
72 import jalview.io.FileLoader;
73 import jalview.io.FileParse;
74 import jalview.io.FormatAdapter;
75 import jalview.io.HtmlSvgOutput;
76 import jalview.io.IdentifyFile;
77 import jalview.io.JPredFile;
78 import jalview.io.JalviewFileChooser;
79 import jalview.io.JalviewFileView;
80 import jalview.io.JnetAnnotationMaker;
81 import jalview.io.NewickFile;
82 import jalview.io.ScoreMatrixFile;
83 import jalview.io.TCoffeeScoreFile;
84 import jalview.io.vcf.VCFLoader;
85 import jalview.jbgui.GAlignFrame;
86 import jalview.schemes.ColourSchemeI;
87 import jalview.schemes.ColourSchemes;
88 import jalview.schemes.ResidueColourScheme;
89 import jalview.schemes.TCoffeeColourScheme;
90 import jalview.util.MessageManager;
91 import jalview.viewmodel.AlignmentViewport;
92 import jalview.viewmodel.ViewportRanges;
93 import jalview.ws.DBRefFetcher;
94 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
95 import jalview.ws.jws1.Discoverer;
96 import jalview.ws.jws2.Jws2Discoverer;
97 import jalview.ws.jws2.jabaws2.Jws2Instance;
98 import jalview.ws.seqfetcher.DbSourceProxy;
100 import java.awt.BorderLayout;
101 import java.awt.Component;
102 import java.awt.Rectangle;
103 import java.awt.Toolkit;
104 import java.awt.datatransfer.Clipboard;
105 import java.awt.datatransfer.DataFlavor;
106 import java.awt.datatransfer.StringSelection;
107 import java.awt.datatransfer.Transferable;
108 import java.awt.dnd.DnDConstants;
109 import java.awt.dnd.DropTargetDragEvent;
110 import java.awt.dnd.DropTargetDropEvent;
111 import java.awt.dnd.DropTargetEvent;
112 import java.awt.dnd.DropTargetListener;
113 import java.awt.event.ActionEvent;
114 import java.awt.event.ActionListener;
115 import java.awt.event.FocusAdapter;
116 import java.awt.event.FocusEvent;
117 import java.awt.event.ItemEvent;
118 import java.awt.event.ItemListener;
119 import java.awt.event.KeyAdapter;
120 import java.awt.event.KeyEvent;
121 import java.awt.event.MouseEvent;
122 import java.awt.print.PageFormat;
123 import java.awt.print.PrinterJob;
124 import java.beans.PropertyChangeEvent;
125 import java.beans.PropertyChangeListener;
127 import java.io.FileWriter;
128 import java.io.PrintWriter;
130 import java.util.ArrayList;
131 import java.util.Arrays;
132 import java.util.Deque;
133 import java.util.Enumeration;
134 import java.util.Hashtable;
135 import java.util.List;
136 import java.util.Vector;
138 import javax.swing.JCheckBoxMenuItem;
139 import javax.swing.JEditorPane;
140 import javax.swing.JFileChooser;
141 import javax.swing.JInternalFrame;
142 import javax.swing.JLayeredPane;
143 import javax.swing.JMenu;
144 import javax.swing.JMenuItem;
145 import javax.swing.JScrollPane;
146 import javax.swing.SwingUtilities;
152 * @version $Revision$
154 public class AlignFrame extends GAlignFrame implements DropTargetListener,
155 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener,
156 PropertyChangeListener
159 public static final int DEFAULT_WIDTH = 700;
161 public static final int DEFAULT_HEIGHT = 500;
164 * The currently displayed panel (selected tabbed view if more than one)
166 public AlignmentPanel alignPanel;
168 AlignViewport viewport;
170 public AlignViewControllerI avc;
172 List<AlignmentPanel> alignPanels = new ArrayList<>();
175 * Last format used to load or save alignments in this window
177 FileFormatI currentFileFormat = null;
180 * Current filename for this alignment
182 String fileName = null;
185 * Creates a new AlignFrame object with specific width and height.
191 public AlignFrame(AlignmentI al, int width, int height)
193 this(al, null, width, height);
197 * Creates a new AlignFrame object with specific width, height and
203 * @param sequenceSetId
205 public AlignFrame(AlignmentI al, int width, int height,
206 String sequenceSetId)
208 this(al, null, width, height, sequenceSetId);
212 * Creates a new AlignFrame object with specific width, height and
218 * @param sequenceSetId
221 public AlignFrame(AlignmentI al, int width, int height,
222 String sequenceSetId, String viewId)
224 this(al, null, width, height, sequenceSetId, viewId);
228 * new alignment window with hidden columns
232 * @param hiddenColumns
233 * ColumnSelection or null
235 * Width of alignment frame
239 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
242 this(al, hiddenColumns, width, height, null);
246 * Create alignment frame for al with hiddenColumns, a specific width and
247 * height, and specific sequenceId
250 * @param hiddenColumns
253 * @param sequenceSetId
256 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
257 int height, String sequenceSetId)
259 this(al, hiddenColumns, width, height, sequenceSetId, null);
263 * Create alignment frame for al with hiddenColumns, a specific width and
264 * height, and specific sequenceId
267 * @param hiddenColumns
270 * @param sequenceSetId
275 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
276 int height, String sequenceSetId, String viewId)
278 setSize(width, height);
280 if (al.getDataset() == null)
285 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
287 alignPanel = new AlignmentPanel(this, viewport);
289 addAlignmentPanel(alignPanel, true);
293 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
294 HiddenColumns hiddenColumns, int width, int height)
296 setSize(width, height);
298 if (al.getDataset() == null)
303 viewport = new AlignViewport(al, hiddenColumns);
305 if (hiddenSeqs != null && hiddenSeqs.length > 0)
307 viewport.hideSequence(hiddenSeqs);
309 alignPanel = new AlignmentPanel(this, viewport);
310 addAlignmentPanel(alignPanel, true);
315 * Make a new AlignFrame from existing alignmentPanels
322 public AlignFrame(AlignmentPanel ap)
326 addAlignmentPanel(ap, false);
331 public void propertyChange(PropertyChangeEvent evt)
333 Desktop.getDesktop().propertyChange(evt);
337 * initalise the alignframe from the underlying viewport data and the
342 if (!Jalview.isHeadlessMode())
344 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
347 avc = new jalview.controller.AlignViewController(this, viewport,
349 if (viewport.getAlignmentConservationAnnotation() == null)
351 // BLOSUM62Colour.setEnabled(false);
352 conservationMenuItem.setEnabled(false);
353 modifyConservation.setEnabled(false);
354 // PIDColour.setEnabled(false);
355 // abovePIDThreshold.setEnabled(false);
356 // modifyPID.setEnabled(false);
359 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
362 if (sortby.equals("Id"))
364 sortIDMenuItem_actionPerformed(null);
366 else if (sortby.equals("Pairwise Identity"))
368 sortPairwiseMenuItem_actionPerformed(null);
372 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
374 setMenusFromViewport(viewport);
375 buildSortByAnnotationScoresMenu();
376 calculateTree.addActionListener(new ActionListener()
380 public void actionPerformed(ActionEvent e)
387 if (Desktop.desktop != null)
389 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
391 * BH 2018 ignore service listeners
397 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 loadVcf.setVisible(nucleotide);
861 showTranslation.setVisible(nucleotide);
862 showReverse.setVisible(nucleotide);
863 showReverseComplement.setVisible(nucleotide);
864 conservationMenuItem.setEnabled(!nucleotide);
866 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
867 showGroupConservation.setEnabled(!nucleotide);
869 showComplementMenuItem
870 .setText(nucleotide ? MessageManager.getString("label.protein")
871 : MessageManager.getString("label.nucleotide"));
875 * set up menus for the current viewport. This may be called after any
876 * operation that affects the data in the current view (selection changed,
877 * etc) to update the menus to reflect the new state.
880 public void setMenusForViewport()
882 setMenusFromViewport(viewport);
886 * Need to call this method when tabs are selected for multiple views, or when
887 * loading from Jalview2XML.java
892 void setMenusFromViewport(AlignViewport av)
894 padGapsMenuitem.setSelected(av.isPadGaps());
895 colourTextMenuItem.setSelected(av.isShowColourText());
896 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
897 modifyPID.setEnabled(abovePIDThreshold.isSelected());
898 conservationMenuItem.setSelected(av.getConservationSelected());
899 modifyConservation.setEnabled(conservationMenuItem.isSelected());
900 seqLimits.setSelected(av.getShowJVSuffix());
901 idRightAlign.setSelected(av.isRightAlignIds());
902 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
903 renderGapsMenuItem.setSelected(av.isRenderGaps());
904 wrapMenuItem.setSelected(av.getWrapAlignment());
905 scaleAbove.setVisible(av.getWrapAlignment());
906 scaleLeft.setVisible(av.getWrapAlignment());
907 scaleRight.setVisible(av.getWrapAlignment());
908 annotationPanelMenuItem.setState(av.isShowAnnotation());
910 * Show/hide annotations only enabled if annotation panel is shown
912 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
913 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
914 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
915 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
916 viewBoxesMenuItem.setSelected(av.getShowBoxes());
917 viewTextMenuItem.setSelected(av.getShowText());
918 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
919 showGroupConsensus.setSelected(av.isShowGroupConsensus());
920 showGroupConservation.setSelected(av.isShowGroupConservation());
921 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
922 showSequenceLogo.setSelected(av.isShowSequenceLogo());
923 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
925 ColourMenuHelper.setColourSelected(colourMenu,
926 av.getGlobalColourScheme());
928 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
929 hiddenMarkers.setState(av.getShowHiddenMarkers());
930 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
931 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
932 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
933 autoCalculate.setSelected(av.autoCalculateConsensus);
934 sortByTree.setSelected(av.sortByTree);
935 listenToViewSelections.setSelected(av.followSelection);
937 showProducts.setEnabled(canShowProducts());
938 setGroovyEnabled(Desktop.getGroovyConsole() != null);
944 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
948 public void setGroovyEnabled(boolean b)
950 runGroovy.setEnabled(b);
953 private IProgressIndicator progressBar;
958 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
961 public void setProgressBar(String message, long id)
963 progressBar.setProgressBar(message, id);
967 public void registerHandler(final long id,
968 final IProgressIndicatorHandler handler)
970 progressBar.registerHandler(id, handler);
975 * @return true if any progress bars are still active
978 public boolean operationInProgress()
980 return progressBar.operationInProgress();
984 public void setStatus(String text)
986 statusBar.setText(text);
990 * Added so Castor Mapping file can obtain Jalview Version
992 public String getVersion()
994 return jalview.bin.Cache.getProperty("VERSION");
997 public FeatureRenderer getFeatureRenderer()
999 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1003 public void fetchSequence_actionPerformed(ActionEvent e)
1005 new jalview.gui.SequenceFetcher(this);
1009 public void addFromFile_actionPerformed(ActionEvent e)
1011 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1015 public void reload_actionPerformed(ActionEvent e)
1017 if (fileName != null)
1019 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1020 // originating file's format
1021 // TODO: work out how to recover feature settings for correct view(s) when
1022 // file is reloaded.
1023 if (FileFormat.Jalview.equals(currentFileFormat))
1025 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1026 for (int i = 0; i < frames.length; i++)
1028 if (frames[i] instanceof AlignFrame && frames[i] != this
1029 && ((AlignFrame) frames[i]).fileName != null
1030 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1034 frames[i].setSelected(true);
1035 Desktop.instance.closeAssociatedWindows();
1036 } catch (java.beans.PropertyVetoException ex)
1042 Desktop.instance.closeAssociatedWindows();
1044 FileLoader loader = new FileLoader();
1045 DataSourceType protocol = fileName.startsWith("http:")
1046 ? DataSourceType.URL
1047 : DataSourceType.FILE;
1048 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1052 Rectangle bounds = this.getBounds();
1054 FileLoader loader = new FileLoader();
1055 DataSourceType protocol = fileName.startsWith("http:")
1056 ? DataSourceType.URL
1057 : DataSourceType.FILE;
1058 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1059 protocol, currentFileFormat);
1061 newframe.setBounds(bounds);
1062 if (featureSettings != null && featureSettings.isShowing())
1064 final Rectangle fspos = featureSettings.frame.getBounds();
1065 // TODO: need a 'show feature settings' function that takes bounds -
1066 // need to refactor Desktop.addFrame
1067 newframe.featureSettings_actionPerformed(null);
1068 final FeatureSettings nfs = newframe.featureSettings;
1069 SwingUtilities.invokeLater(new Runnable()
1074 nfs.frame.setBounds(fspos);
1077 this.featureSettings.close();
1078 this.featureSettings = null;
1080 this.closeMenuItem_actionPerformed(true);
1086 public void addFromText_actionPerformed(ActionEvent e)
1089 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1093 public void addFromURL_actionPerformed(ActionEvent e)
1095 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1099 public void save_actionPerformed(ActionEvent e)
1101 if (fileName == null || (currentFileFormat == null)
1102 || fileName.startsWith("http"))
1104 saveAs_actionPerformed(null);
1108 saveAlignment(fileName, currentFileFormat);
1119 public void saveAs_actionPerformed(ActionEvent e)
1121 String format = currentFileFormat == null ? null
1122 : currentFileFormat.getName();
1123 JalviewFileChooser chooser = JalviewFileChooser
1124 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1126 chooser.setFileView(new JalviewFileView());
1127 chooser.setDialogTitle(
1128 MessageManager.getString("label.save_alignment_to_file"));
1129 chooser.setToolTipText(MessageManager.getString("action.save"));
1131 int value = chooser.showSaveDialog(this);
1134 if (value == JalviewFileChooser.APPROVE_OPTION)
1136 currentFileFormat = chooser.getSelectedFormat();
1137 while (currentFileFormat == null)
1139 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1140 MessageManager.getString(
1141 "label.select_file_format_before_saving"),
1142 MessageManager.getString("label.file_format_not_specified"),
1143 JvOptionPane.WARNING_MESSAGE);
1144 currentFileFormat = chooser.getSelectedFormat();
1145 value = chooser.showSaveDialog(this);
1146 if (value != JalviewFileChooser.APPROVE_OPTION)
1152 fileName = chooser.getSelectedFile().getPath();
1154 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1156 Cache.setProperty("LAST_DIRECTORY", fileName);
1157 saveAlignment(fileName, currentFileFormat);
1161 public boolean saveAlignment(String file, FileFormatI format)
1163 boolean success = true;
1165 if (FileFormat.Jalview.equals(format))
1167 String shortName = title;
1169 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1171 shortName = shortName.substring(
1172 shortName.lastIndexOf(java.io.File.separatorChar) + 1);
1175 success = new Jalview2XML().saveAlignment(this, file, shortName);
1177 statusBar.setText(MessageManager.formatMessage(
1178 "label.successfully_saved_to_file_in_format", new Object[]
1179 { fileName, format }));
1184 AlignmentExportData exportData = getAlignmentForExport(format,
1186 if (exportData.getSettings().isCancelled())
1190 FormatAdapter f = new FormatAdapter(alignPanel,
1191 exportData.getSettings());
1192 String output = f.formatSequences(format, exportData.getAlignment(), // class
1196 // occur in the distant future
1197 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1198 f.getCacheSuffixDefault(format),
1199 viewport.getAlignment().getHiddenColumns());
1209 PrintWriter out = new PrintWriter(new FileWriter(file));
1213 this.setTitle(file);
1214 statusBar.setText(MessageManager.formatMessage(
1215 "label.successfully_saved_to_file_in_format", new Object[]
1216 { fileName, format.getName() }));
1217 } catch (Exception ex)
1220 ex.printStackTrace();
1227 JvOptionPane.showInternalMessageDialog(this, MessageManager
1228 .formatMessage("label.couldnt_save_file", new Object[]
1230 MessageManager.getString("label.error_saving_file"),
1231 JvOptionPane.WARNING_MESSAGE);
1237 private void warningMessage(String warning, String title)
1239 if (new jalview.util.Platform().isHeadless())
1241 System.err.println("Warning: " + title + "\nWarning: " + warning);
1246 JvOptionPane.showInternalMessageDialog(this, warning, title,
1247 JvOptionPane.WARNING_MESSAGE);
1259 protected void outputText_actionPerformed(ActionEvent e)
1261 FileFormatI fileFormat = FileFormats.getInstance()
1262 .forName(e.getActionCommand());
1263 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1265 if (exportData.getSettings().isCancelled())
1269 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1270 cap.setForInput(null);
1273 FileFormatI format = fileFormat;
1274 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1275 .formatSequences(format, exportData.getAlignment(),
1276 exportData.getOmitHidden(),
1277 exportData.getStartEndPostions(),
1278 viewport.getAlignment().getHiddenColumns()));
1279 Desktop.addInternalFrame(cap, MessageManager
1280 .formatMessage("label.alignment_output_command", new Object[]
1281 { e.getActionCommand() }), 600, 500);
1282 } catch (OutOfMemoryError oom)
1284 new OOMWarning("Outputting alignment as " + e.getActionCommand(),
1291 public static AlignmentExportData getAlignmentForExport(
1292 FileFormatI format, AlignViewportI viewport,
1293 AlignExportSettingI exportSettings)
1295 AlignmentI alignmentToExport = null;
1296 AlignExportSettingI settings = exportSettings;
1297 String[] omitHidden = null;
1299 HiddenSequences hiddenSeqs = viewport.getAlignment()
1300 .getHiddenSequences();
1302 alignmentToExport = viewport.getAlignment();
1304 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1305 if (settings == null)
1307 settings = new AlignExportSettings(hasHiddenSeqs,
1308 viewport.hasHiddenColumns(), format);
1310 // settings.isExportAnnotations();
1312 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1314 omitHidden = viewport.getViewAsString(false,
1315 settings.isExportHiddenSequences());
1318 int[] alignmentStartEnd = new int[2];
1319 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1321 alignmentToExport = hiddenSeqs.getFullAlignment();
1325 alignmentToExport = viewport.getAlignment();
1327 alignmentStartEnd = viewport.getAlignment().getHiddenColumns()
1328 .getVisibleStartAndEndIndex(alignmentToExport.getWidth());
1329 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1330 omitHidden, alignmentStartEnd, settings);
1341 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1343 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1344 htmlSVG.exportHTML(null);
1348 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1350 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1351 bjs.exportHTML(null);
1354 public void createImageMap(File file, String image)
1356 alignPanel.makePNGImageMap(file, image);
1366 public void createPNG(File f)
1368 alignPanel.makePNG(f);
1378 public void createEPS(File f)
1380 alignPanel.makeEPS(f);
1384 public void createSVG(File f)
1386 alignPanel.makeSVG(f);
1390 public void pageSetup_actionPerformed(ActionEvent e)
1392 PrinterJob printJob = PrinterJob.getPrinterJob();
1393 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1403 public void printMenuItem_actionPerformed(ActionEvent e)
1405 // Putting in a thread avoids Swing painting problems
1406 PrintThread thread = new PrintThread(alignPanel);
1411 public void exportFeatures_actionPerformed(ActionEvent e)
1413 new AnnotationExporter(alignPanel).exportFeatures();
1417 public void exportAnnotations_actionPerformed(ActionEvent e)
1419 new AnnotationExporter(alignPanel).exportAnnotations();
1423 public void associatedData_actionPerformed(ActionEvent e)
1425 // Pick the tree file
1426 JalviewFileChooser chooser = new JalviewFileChooser(
1427 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1428 chooser.setFileView(new JalviewFileView());
1429 chooser.setDialogTitle(
1430 MessageManager.getString("label.load_jalview_annotations"));
1431 chooser.setToolTipText(
1432 MessageManager.getString("label.load_jalview_annotations"));
1434 Desktop.getDesktop().dialogData = new Object[] { "SelectedFile",
1441 Object[] data = Desktop.getDesktop().dialogData;
1442 int value = ((Integer) data[0]).intValue();
1444 if (value == JFileChooser.APPROVE_OPTION)
1446 JalviewFileChooser chooser = (JalviewFileChooser) data[2];
1447 String choice = chooser.getSelectedFile().getPath();
1448 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1449 loadJalviewDataFile(choice, null, null, null);
1455 chooser.showOpenDialog(null);
1462 * Close the current view or all views in the alignment frame. If the frame
1463 * only contains one view then the alignment will be removed from memory.
1465 * @param closeAllTabs
1468 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1470 if (alignPanels != null && alignPanels.size() < 2)
1472 closeAllTabs = true;
1477 if (alignPanels != null)
1481 if (this.isClosed())
1483 // really close all the windows - otherwise wait till
1484 // setClosed(true) is called
1485 for (int i = 0; i < alignPanels.size(); i++)
1487 AlignmentPanel ap = alignPanels.get(i);
1494 closeView(alignPanel);
1501 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1502 * be called recursively, with the frame now in 'closed' state
1504 this.setClosed(true);
1506 } catch (Exception ex)
1508 ex.printStackTrace();
1513 * Close the specified panel and close up tabs appropriately.
1515 * @param panelToClose
1517 public void closeView(AlignmentPanel panelToClose)
1519 int index = tabbedPane.getSelectedIndex();
1520 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1521 alignPanels.remove(panelToClose);
1522 panelToClose.closePanel();
1523 panelToClose = null;
1525 tabbedPane.removeTabAt(closedindex);
1526 tabbedPane.validate();
1528 if (index > closedindex || index == tabbedPane.getTabCount())
1530 // modify currently selected tab index if necessary.
1534 this.tabSelectionChanged(index);
1540 void updateEditMenuBar()
1543 if (viewport.getHistoryList().size() > 0)
1545 undoMenuItem.setEnabled(true);
1546 CommandI command = viewport.getHistoryList().peek();
1547 undoMenuItem.setText(MessageManager
1548 .formatMessage("label.undo_command", new Object[]
1549 { command.getDescription() }));
1553 undoMenuItem.setEnabled(false);
1554 undoMenuItem.setText(MessageManager.getString("action.undo"));
1557 if (viewport.getRedoList().size() > 0)
1559 redoMenuItem.setEnabled(true);
1561 CommandI command = viewport.getRedoList().peek();
1562 redoMenuItem.setText(MessageManager
1563 .formatMessage("label.redo_command", new Object[]
1564 { command.getDescription() }));
1568 redoMenuItem.setEnabled(false);
1569 redoMenuItem.setText(MessageManager.getString("action.redo"));
1574 public void addHistoryItem(CommandI command)
1576 if (command.getSize() > 0)
1578 viewport.addToHistoryList(command);
1579 viewport.clearRedoList();
1580 updateEditMenuBar();
1581 viewport.updateHiddenColumns();
1582 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1583 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1584 // viewport.getColumnSelection()
1585 // .getHiddenColumns().size() > 0);
1591 * @return alignment objects for all views
1593 AlignmentI[] getViewAlignments()
1595 if (alignPanels != null)
1597 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1599 for (AlignmentPanel ap : alignPanels)
1601 als[i++] = ap.av.getAlignment();
1605 if (viewport != null)
1607 return new AlignmentI[] { viewport.getAlignment() };
1619 protected void undoMenuItem_actionPerformed(ActionEvent e)
1621 if (viewport.getHistoryList().isEmpty())
1625 CommandI command = viewport.getHistoryList().pop();
1626 viewport.addToRedoList(command);
1627 command.undoCommand(getViewAlignments());
1629 AlignmentViewport originalSource = getOriginatingSource(command);
1630 updateEditMenuBar();
1632 if (originalSource != null)
1634 if (originalSource != viewport)
1637 "Implementation worry: mismatch of viewport origin for undo");
1639 originalSource.updateHiddenColumns();
1640 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1642 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1643 // viewport.getColumnSelection()
1644 // .getHiddenColumns().size() > 0);
1645 originalSource.firePropertyChange("alignment", null,
1646 originalSource.getAlignment().getSequences());
1657 protected void redoMenuItem_actionPerformed(ActionEvent e)
1659 if (viewport.getRedoList().size() < 1)
1664 CommandI command = viewport.getRedoList().pop();
1665 viewport.addToHistoryList(command);
1666 command.doCommand(getViewAlignments());
1668 AlignmentViewport originalSource = getOriginatingSource(command);
1669 updateEditMenuBar();
1671 if (originalSource != null)
1674 if (originalSource != viewport)
1677 "Implementation worry: mismatch of viewport origin for redo");
1679 originalSource.updateHiddenColumns();
1680 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1682 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1683 // viewport.getColumnSelection()
1684 // .getHiddenColumns().size() > 0);
1685 originalSource.firePropertyChange("alignment", null,
1686 originalSource.getAlignment().getSequences());
1690 AlignmentViewport getOriginatingSource(CommandI command)
1692 AlignmentViewport originalSource = null;
1693 // For sequence removal and addition, we need to fire
1694 // the property change event FROM the viewport where the
1695 // original alignment was altered
1696 AlignmentI al = null;
1697 if (command instanceof EditCommand)
1699 EditCommand editCommand = (EditCommand) command;
1700 al = editCommand.getAlignment();
1701 List<Component> comps = PaintRefresher.components
1702 .get(viewport.getSequenceSetId());
1704 for (Component comp : comps)
1706 if (comp instanceof AlignmentPanel)
1708 if (al == ((AlignmentPanel) comp).av.getAlignment())
1710 originalSource = ((AlignmentPanel) comp).av;
1717 if (originalSource == null)
1719 // The original view is closed, we must validate
1720 // the current view against the closed view first
1723 PaintRefresher.validateSequences(al, viewport.getAlignment());
1726 originalSource = viewport;
1729 return originalSource;
1738 public void moveSelectedSequences(boolean up)
1740 SequenceGroup sg = viewport.getSelectionGroup();
1746 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1747 viewport.getHiddenRepSequences(), up);
1748 alignPanel.paintAlignment(true, false);
1751 synchronized void slideSequences(boolean right, int size)
1753 List<SequenceI> sg = new ArrayList<>();
1754 if (viewport.cursorMode)
1756 sg.add(viewport.getAlignment()
1757 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1759 else if (viewport.getSelectionGroup() != null
1760 && viewport.getSelectionGroup().getSize() != viewport
1761 .getAlignment().getHeight())
1763 sg = viewport.getSelectionGroup()
1764 .getSequences(viewport.getHiddenRepSequences());
1772 List<SequenceI> invertGroup = new ArrayList<>();
1774 for (SequenceI seq : viewport.getAlignment().getSequences())
1776 if (!sg.contains(seq))
1778 invertGroup.add(seq);
1782 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1784 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1785 for (int i = 0; i < invertGroup.size(); i++)
1787 seqs2[i] = invertGroup.get(i);
1790 SlideSequencesCommand ssc;
1793 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1794 viewport.getGapCharacter());
1798 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1799 viewport.getGapCharacter());
1802 int groupAdjustment = 0;
1803 if (ssc.getGapsInsertedBegin() && right)
1805 if (viewport.cursorMode)
1807 alignPanel.getSeqPanel().moveCursor(size, 0);
1811 groupAdjustment = size;
1814 else if (!ssc.getGapsInsertedBegin() && !right)
1816 if (viewport.cursorMode)
1818 alignPanel.getSeqPanel().moveCursor(-size, 0);
1822 groupAdjustment = -size;
1826 if (groupAdjustment != 0)
1828 viewport.getSelectionGroup().setStartRes(
1829 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1830 viewport.getSelectionGroup().setEndRes(
1831 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1835 * just extend the last slide command if compatible; but not if in
1836 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1838 boolean appendHistoryItem = false;
1839 Deque<CommandI> historyList = viewport.getHistoryList();
1840 boolean inSplitFrame = getSplitViewContainer() != null;
1841 if (!inSplitFrame && historyList != null && historyList.size() > 0
1842 && historyList.peek() instanceof SlideSequencesCommand)
1844 appendHistoryItem = ssc.appendSlideCommand(
1845 (SlideSequencesCommand) historyList.peek());
1848 if (!appendHistoryItem)
1850 addHistoryItem(ssc);
1863 protected void copy_actionPerformed(ActionEvent e)
1865 if (viewport.getSelectionGroup() == null)
1869 // TODO: preserve the ordering of displayed alignment annotation in any
1870 // internal paste (particularly sequence associated annotation)
1871 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1872 String[] omitHidden = null;
1874 if (viewport.hasHiddenColumns())
1876 omitHidden = viewport.getViewAsString(true);
1879 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1880 seqs, omitHidden, null);
1882 StringSelection ss = new StringSelection(output);
1886 jalview.gui.Desktop.internalCopy = true;
1887 // Its really worth setting the clipboard contents
1888 // to empty before setting the large StringSelection!!
1889 Toolkit.getDefaultToolkit().getSystemClipboard()
1890 .setContents(new StringSelection(""), null);
1892 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1894 } catch (OutOfMemoryError er)
1896 new OOMWarning("copying region", er);
1900 HiddenColumns hiddenColumns = null;
1901 if (viewport.hasHiddenColumns())
1903 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1904 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1906 // create new HiddenColumns object with copy of hidden regions
1907 // between startRes and endRes, offset by startRes
1908 hiddenColumns = new HiddenColumns(
1909 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
1910 hiddenCutoff, hiddenOffset);
1913 Desktop.jalviewClipboard = new Object[] { seqs,
1914 viewport.getAlignment().getDataset(), hiddenColumns };
1915 statusBar.setText(MessageManager.formatMessage(
1916 "label.copied_sequences_to_clipboard", new Object[]
1917 { Integer.valueOf(seqs.length).toString() }));
1927 protected void pasteNew_actionPerformed(ActionEvent e)
1939 protected void pasteThis_actionPerformed(ActionEvent e)
1945 * Paste contents of Jalview clipboard
1947 * @param newAlignment
1948 * true to paste to a new alignment, otherwise add to this.
1950 void paste(boolean newAlignment)
1952 boolean externalPaste = true;
1955 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1956 Transferable contents = c.getContents(this);
1958 if (contents == null)
1967 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1968 if (str.length() < 1)
1973 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
1975 } catch (OutOfMemoryError er)
1977 new OOMWarning("Out of memory pasting sequences!!", er);
1981 SequenceI[] sequences;
1982 boolean annotationAdded = false;
1983 AlignmentI alignment = null;
1985 if (Desktop.jalviewClipboard != null)
1987 // The clipboard was filled from within Jalview, we must use the
1989 // And dataset from the copied alignment
1990 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1991 // be doubly sure that we create *new* sequence objects.
1992 sequences = new SequenceI[newseq.length];
1993 for (int i = 0; i < newseq.length; i++)
1995 sequences[i] = new Sequence(newseq[i]);
1997 alignment = new Alignment(sequences);
1998 externalPaste = false;
2002 // parse the clipboard as an alignment.
2003 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2005 sequences = alignment.getSequencesArray();
2009 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2015 if (Desktop.jalviewClipboard != null)
2017 // dataset is inherited
2018 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2022 // new dataset is constructed
2023 alignment.setDataset(null);
2025 alwidth = alignment.getWidth() + 1;
2029 AlignmentI pastedal = alignment; // preserve pasted alignment object
2030 // Add pasted sequences and dataset into existing alignment.
2031 alignment = viewport.getAlignment();
2032 alwidth = alignment.getWidth() + 1;
2033 // decide if we need to import sequences from an existing dataset
2034 boolean importDs = Desktop.jalviewClipboard != null
2035 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2036 // importDs==true instructs us to copy over new dataset sequences from
2037 // an existing alignment
2038 Vector newDs = (importDs) ? new Vector() : null; // used to create
2039 // minimum dataset set
2041 for (int i = 0; i < sequences.length; i++)
2045 newDs.addElement(null);
2047 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2049 if (importDs && ds != null)
2051 if (!newDs.contains(ds))
2053 newDs.setElementAt(ds, i);
2054 ds = new Sequence(ds);
2055 // update with new dataset sequence
2056 sequences[i].setDatasetSequence(ds);
2060 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2065 // copy and derive new dataset sequence
2066 sequences[i] = sequences[i].deriveSequence();
2067 alignment.getDataset()
2068 .addSequence(sequences[i].getDatasetSequence());
2069 // TODO: avoid creation of duplicate dataset sequences with a
2070 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2072 alignment.addSequence(sequences[i]); // merges dataset
2076 newDs.clear(); // tidy up
2078 if (alignment.getAlignmentAnnotation() != null)
2080 for (AlignmentAnnotation alan : alignment
2081 .getAlignmentAnnotation())
2083 if (alan.graphGroup > fgroup)
2085 fgroup = alan.graphGroup;
2089 if (pastedal.getAlignmentAnnotation() != null)
2091 // Add any annotation attached to alignment.
2092 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2093 for (int i = 0; i < alann.length; i++)
2095 annotationAdded = true;
2096 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2098 AlignmentAnnotation newann = new AlignmentAnnotation(
2100 if (newann.graphGroup > -1)
2102 if (newGraphGroups.size() <= newann.graphGroup
2103 || newGraphGroups.get(newann.graphGroup) == null)
2105 for (int q = newGraphGroups
2106 .size(); q <= newann.graphGroup; q++)
2108 newGraphGroups.add(q, null);
2110 newGraphGroups.set(newann.graphGroup,
2111 new Integer(++fgroup));
2113 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2117 newann.padAnnotation(alwidth);
2118 alignment.addAnnotation(newann);
2128 addHistoryItem(new EditCommand(
2129 MessageManager.getString("label.add_sequences"),
2130 Action.PASTE, sequences, 0, alignment.getWidth(),
2133 // Add any annotations attached to sequences
2134 for (int i = 0; i < sequences.length; i++)
2136 if (sequences[i].getAnnotation() != null)
2138 AlignmentAnnotation newann;
2139 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2141 annotationAdded = true;
2142 newann = sequences[i].getAnnotation()[a];
2143 newann.adjustForAlignment();
2144 newann.padAnnotation(alwidth);
2145 if (newann.graphGroup > -1)
2147 if (newann.graphGroup > -1)
2149 if (newGraphGroups.size() <= newann.graphGroup
2150 || newGraphGroups.get(newann.graphGroup) == null)
2152 for (int q = newGraphGroups
2153 .size(); q <= newann.graphGroup; q++)
2155 newGraphGroups.add(q, null);
2157 newGraphGroups.set(newann.graphGroup,
2158 new Integer(++fgroup));
2160 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2164 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2168 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2176 // propagate alignment changed.
2177 viewport.getRanges().setEndSeq(alignment.getHeight());
2178 if (annotationAdded)
2180 // Duplicate sequence annotation in all views.
2181 AlignmentI[] alview = this.getViewAlignments();
2182 for (int i = 0; i < sequences.length; i++)
2184 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2189 for (int avnum = 0; avnum < alview.length; avnum++)
2191 if (alview[avnum] != alignment)
2193 // duplicate in a view other than the one with input focus
2194 int avwidth = alview[avnum].getWidth() + 1;
2195 // this relies on sann being preserved after we
2196 // modify the sequence's annotation array for each duplication
2197 for (int a = 0; a < sann.length; a++)
2199 AlignmentAnnotation newann = new AlignmentAnnotation(
2201 sequences[i].addAlignmentAnnotation(newann);
2202 newann.padAnnotation(avwidth);
2203 alview[avnum].addAnnotation(newann); // annotation was
2204 // duplicated earlier
2205 // TODO JAL-1145 graphGroups are not updated for sequence
2206 // annotation added to several views. This may cause
2208 alview[avnum].setAnnotationIndex(newann, a);
2213 buildSortByAnnotationScoresMenu();
2215 viewport.firePropertyChange("alignment", null,
2216 alignment.getSequences());
2217 if (alignPanels != null)
2219 for (AlignmentPanel ap : alignPanels)
2221 ap.validateAnnotationDimensions(false);
2226 alignPanel.validateAnnotationDimensions(false);
2232 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2234 String newtitle = new String("Copied sequences");
2236 if (Desktop.jalviewClipboard != null
2237 && Desktop.jalviewClipboard[2] != null)
2239 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2240 af.viewport.setHiddenColumns(hc);
2243 // >>>This is a fix for the moment, until a better solution is
2245 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2246 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2247 .getFeatureRenderer());
2249 // TODO: maintain provenance of an alignment, rather than just make the
2250 // title a concatenation of operations.
2253 if (title.startsWith("Copied sequences"))
2259 newtitle = newtitle.concat("- from " + title);
2264 newtitle = new String("Pasted sequences");
2267 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2272 } catch (Exception ex)
2274 ex.printStackTrace();
2275 System.out.println("Exception whilst pasting: " + ex);
2276 // could be anything being pasted in here
2282 protected void expand_newalign(ActionEvent e)
2286 AlignmentI alignment = AlignmentUtils
2287 .expandContext(getViewport().getAlignment(), -1);
2288 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2290 String newtitle = new String("Flanking alignment");
2292 if (Desktop.jalviewClipboard != null
2293 && Desktop.jalviewClipboard[2] != null)
2295 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2296 af.viewport.setHiddenColumns(hc);
2299 // >>>This is a fix for the moment, until a better solution is
2301 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2302 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2303 .getFeatureRenderer());
2305 // TODO: maintain provenance of an alignment, rather than just make the
2306 // title a concatenation of operations.
2308 if (title.startsWith("Copied sequences"))
2314 newtitle = newtitle.concat("- from " + title);
2318 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2320 } catch (Exception ex)
2322 ex.printStackTrace();
2323 System.out.println("Exception whilst pasting: " + ex);
2324 // could be anything being pasted in here
2325 } catch (OutOfMemoryError oom)
2327 new OOMWarning("Viewing flanking region of alignment", oom);
2338 protected void cut_actionPerformed(ActionEvent e)
2340 copy_actionPerformed(null);
2341 delete_actionPerformed(null);
2351 protected void delete_actionPerformed(ActionEvent evt)
2354 SequenceGroup sg = viewport.getSelectionGroup();
2361 * If the cut affects all sequences, warn, remove highlighted columns
2363 if (sg.getSize() == viewport.getAlignment().getHeight())
2365 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2366 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2367 if (isEntireAlignWidth)
2369 int confirm = JvOptionPane.showConfirmDialog(this,
2370 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2371 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2372 JvOptionPane.OK_CANCEL_OPTION);
2374 if (confirm == JvOptionPane.CANCEL_OPTION
2375 || confirm == JvOptionPane.CLOSED_OPTION)
2380 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2381 sg.getEndRes() + 1);
2383 SequenceI[] cut = sg.getSequences()
2384 .toArray(new SequenceI[sg.getSize()]);
2386 addHistoryItem(new EditCommand(
2387 MessageManager.getString("label.cut_sequences"), Action.CUT,
2388 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2389 viewport.getAlignment()));
2391 viewport.setSelectionGroup(null);
2392 viewport.sendSelection();
2393 viewport.getAlignment().deleteGroup(sg);
2395 viewport.firePropertyChange("alignment", null,
2396 viewport.getAlignment().getSequences());
2397 if (viewport.getAlignment().getHeight() < 1)
2401 this.setClosed(true);
2402 } catch (Exception ex)
2415 protected void deleteGroups_actionPerformed(ActionEvent e)
2417 if (avc.deleteGroups())
2419 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2420 alignPanel.updateAnnotation();
2421 alignPanel.paintAlignment(true, true);
2432 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2434 SequenceGroup sg = new SequenceGroup();
2436 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2438 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2441 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2442 viewport.setSelectionGroup(sg);
2443 viewport.sendSelection();
2444 // JAL-2034 - should delegate to
2445 // alignPanel to decide if overview needs
2447 alignPanel.paintAlignment(false, false);
2448 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2458 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2460 if (viewport.cursorMode)
2462 alignPanel.getSeqPanel().keyboardNo1 = null;
2463 alignPanel.getSeqPanel().keyboardNo2 = null;
2465 viewport.setSelectionGroup(null);
2466 viewport.getColumnSelection().clear();
2467 viewport.setSelectionGroup(null);
2468 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2469 // JAL-2034 - should delegate to
2470 // alignPanel to decide if overview needs
2472 alignPanel.paintAlignment(false, false);
2473 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2474 viewport.sendSelection();
2484 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2486 SequenceGroup sg = viewport.getSelectionGroup();
2490 selectAllSequenceMenuItem_actionPerformed(null);
2495 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2497 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2499 // JAL-2034 - should delegate to
2500 // alignPanel to decide if overview needs
2503 alignPanel.paintAlignment(true, false);
2504 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2505 viewport.sendSelection();
2509 public void invertColSel_actionPerformed(ActionEvent e)
2511 viewport.invertColumnSelection();
2512 alignPanel.paintAlignment(true, false);
2513 viewport.sendSelection();
2523 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2525 trimAlignment(true);
2535 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2537 trimAlignment(false);
2540 void trimAlignment(boolean trimLeft)
2542 ColumnSelection colSel = viewport.getColumnSelection();
2545 if (!colSel.isEmpty())
2549 column = colSel.getMin();
2553 column = colSel.getMax();
2557 if (viewport.getSelectionGroup() != null)
2559 seqs = viewport.getSelectionGroup()
2560 .getSequencesAsArray(viewport.getHiddenRepSequences());
2564 seqs = viewport.getAlignment().getSequencesArray();
2567 TrimRegionCommand trimRegion;
2570 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2571 column, viewport.getAlignment());
2572 viewport.getRanges().setStartRes(0);
2576 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2577 column, viewport.getAlignment());
2580 statusBar.setText(MessageManager
2581 .formatMessage("label.removed_columns", new String[]
2582 { Integer.valueOf(trimRegion.getSize()).toString() }));
2584 addHistoryItem(trimRegion);
2586 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2588 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2589 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2591 viewport.getAlignment().deleteGroup(sg);
2595 viewport.firePropertyChange("alignment", null,
2596 viewport.getAlignment().getSequences());
2607 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2609 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2612 if (viewport.getSelectionGroup() != null)
2614 seqs = viewport.getSelectionGroup()
2615 .getSequencesAsArray(viewport.getHiddenRepSequences());
2616 start = viewport.getSelectionGroup().getStartRes();
2617 end = viewport.getSelectionGroup().getEndRes();
2621 seqs = viewport.getAlignment().getSequencesArray();
2624 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2625 "Remove Gapped Columns", seqs, start, end,
2626 viewport.getAlignment());
2628 addHistoryItem(removeGapCols);
2630 statusBar.setText(MessageManager
2631 .formatMessage("label.removed_empty_columns", new Object[]
2632 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2634 // This is to maintain viewport position on first residue
2635 // of first sequence
2636 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2637 ViewportRanges ranges = viewport.getRanges();
2638 int startRes = seq.findPosition(ranges.getStartRes());
2639 // ShiftList shifts;
2640 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2641 // edit.alColumnChanges=shifts.getInverse();
2642 // if (viewport.hasHiddenColumns)
2643 // viewport.getColumnSelection().compensateForEdits(shifts);
2644 ranges.setStartRes(seq.findIndex(startRes) - 1);
2645 viewport.firePropertyChange("alignment", null,
2646 viewport.getAlignment().getSequences());
2657 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2659 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2662 if (viewport.getSelectionGroup() != null)
2664 seqs = viewport.getSelectionGroup()
2665 .getSequencesAsArray(viewport.getHiddenRepSequences());
2666 start = viewport.getSelectionGroup().getStartRes();
2667 end = viewport.getSelectionGroup().getEndRes();
2671 seqs = viewport.getAlignment().getSequencesArray();
2674 // This is to maintain viewport position on first residue
2675 // of first sequence
2676 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2677 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2679 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2680 viewport.getAlignment()));
2682 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2684 viewport.firePropertyChange("alignment", null,
2685 viewport.getAlignment().getSequences());
2696 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2698 viewport.setPadGaps(padGapsMenuitem.isSelected());
2699 viewport.firePropertyChange("alignment", null,
2700 viewport.getAlignment().getSequences());
2710 public void findMenuItem_actionPerformed(ActionEvent e)
2716 * Create a new view of the current alignment.
2719 public void newView_actionPerformed(ActionEvent e)
2721 newView(null, true);
2725 * Creates and shows a new view of the current alignment.
2728 * title of newly created view; if null, one will be generated
2729 * @param copyAnnotation
2730 * if true then duplicate all annnotation, groups and settings
2731 * @return new alignment panel, already displayed.
2733 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2736 * Create a new AlignmentPanel (with its own, new Viewport)
2738 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel);
2739 if (!copyAnnotation)
2742 * remove all groups and annotation except for the automatic stuff
2744 newap.av.getAlignment().deleteAllGroups();
2745 newap.av.getAlignment().deleteAllAnnotations(false);
2748 newap.av.setGatherViewsHere(false);
2750 if (viewport.viewName == null)
2752 viewport.viewName = MessageManager
2753 .getString("label.view_name_original");
2757 * Views share the same edits undo and redo stacks
2759 newap.av.setHistoryList(viewport.getHistoryList());
2760 newap.av.setRedoList(viewport.getRedoList());
2763 * Views share the same mappings; need to deregister any new mappings
2764 * created by copyAlignPanel, and register the new reference to the shared
2767 newap.av.replaceMappings(viewport.getAlignment());
2770 * start up cDNA consensus (if applicable) now mappings are in place
2772 if (newap.av.initComplementConsensus())
2774 newap.refresh(true); // adjust layout of annotations
2777 newap.av.viewName = getNewViewName(viewTitle);
2779 addAlignmentPanel(newap, true);
2780 newap.alignmentChanged();
2782 if (alignPanels.size() == 2)
2784 viewport.setGatherViewsHere(true);
2786 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2791 * Make a new name for the view, ensuring it is unique within the current
2792 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2793 * these now use viewId. Unique view names are still desirable for usability.)
2798 protected String getNewViewName(String viewTitle)
2800 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2801 boolean addFirstIndex = false;
2802 if (viewTitle == null || viewTitle.trim().length() == 0)
2804 viewTitle = MessageManager.getString("action.view");
2805 addFirstIndex = true;
2809 index = 1;// we count from 1 if given a specific name
2811 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2813 List<Component> comps = PaintRefresher.components
2814 .get(viewport.getSequenceSetId());
2816 List<String> existingNames = getExistingViewNames(comps);
2818 while (existingNames.contains(newViewName))
2820 newViewName = viewTitle + " " + (++index);
2826 * Returns a list of distinct view names found in the given list of
2827 * components. View names are held on the viewport of an AlignmentPanel.
2832 protected List<String> getExistingViewNames(List<Component> comps)
2834 List<String> existingNames = new ArrayList<>();
2835 for (Component comp : comps)
2837 if (comp instanceof AlignmentPanel)
2839 AlignmentPanel ap = (AlignmentPanel) comp;
2840 if (!existingNames.contains(ap.av.viewName))
2842 existingNames.add(ap.av.viewName);
2846 return existingNames;
2850 * Explode tabbed views into separate windows.
2853 public void expandViews_actionPerformed(ActionEvent e)
2855 Desktop.explodeViews(this);
2859 * Gather views in separate windows back into a tabbed presentation.
2862 public void gatherViews_actionPerformed(ActionEvent e)
2864 Desktop.instance.gatherViews(this);
2874 public void font_actionPerformed(ActionEvent e)
2876 new FontChooser(alignPanel);
2886 protected void seqLimit_actionPerformed(ActionEvent e)
2888 viewport.setShowJVSuffix(seqLimits.isSelected());
2890 alignPanel.getIdPanel().getIdCanvas()
2891 .setPreferredSize(alignPanel.calculateIdWidth());
2892 alignPanel.paintAlignment(true, false);
2896 public void idRightAlign_actionPerformed(ActionEvent e)
2898 viewport.setRightAlignIds(idRightAlign.isSelected());
2899 alignPanel.paintAlignment(false, false);
2903 public void centreColumnLabels_actionPerformed(ActionEvent e)
2905 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2906 alignPanel.paintAlignment(false, false);
2912 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2915 protected void followHighlight_actionPerformed()
2918 * Set the 'follow' flag on the Viewport (and scroll to position if now
2921 final boolean state = this.followHighlightMenuItem.getState();
2922 viewport.setFollowHighlight(state);
2925 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2936 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2938 viewport.setColourText(colourTextMenuItem.isSelected());
2939 alignPanel.paintAlignment(false, false);
2949 public void wrapMenuItem_actionPerformed(ActionEvent e)
2951 scaleAbove.setVisible(wrapMenuItem.isSelected());
2952 scaleLeft.setVisible(wrapMenuItem.isSelected());
2953 scaleRight.setVisible(wrapMenuItem.isSelected());
2954 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2955 alignPanel.updateLayout();
2959 public void showAllSeqs_actionPerformed(ActionEvent e)
2961 viewport.showAllHiddenSeqs();
2965 public void showAllColumns_actionPerformed(ActionEvent e)
2967 viewport.showAllHiddenColumns();
2968 alignPanel.paintAlignment(true, true);
2969 viewport.sendSelection();
2973 public void hideSelSequences_actionPerformed(ActionEvent e)
2975 viewport.hideAllSelectedSeqs();
2979 * called by key handler and the hide all/show all menu items
2984 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2987 boolean hide = false;
2988 SequenceGroup sg = viewport.getSelectionGroup();
2989 if (!toggleSeqs && !toggleCols)
2991 // Hide everything by the current selection - this is a hack - we do the
2992 // invert and then hide
2993 // first check that there will be visible columns after the invert.
2994 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
2995 && sg.getStartRes() <= sg.getEndRes()))
2997 // now invert the sequence set, if required - empty selection implies
2998 // that no hiding is required.
3001 invertSequenceMenuItem_actionPerformed(null);
3002 sg = viewport.getSelectionGroup();
3006 viewport.expandColSelection(sg, true);
3007 // finally invert the column selection and get the new sequence
3009 invertColSel_actionPerformed(null);
3016 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3018 hideSelSequences_actionPerformed(null);
3021 else if (!(toggleCols && viewport.hasSelectedColumns()))
3023 showAllSeqs_actionPerformed(null);
3029 if (viewport.hasSelectedColumns())
3031 hideSelColumns_actionPerformed(null);
3034 viewport.setSelectionGroup(sg);
3039 showAllColumns_actionPerformed(null);
3048 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3049 * event.ActionEvent)
3052 public void hideAllButSelection_actionPerformed(ActionEvent e)
3054 toggleHiddenRegions(false, false);
3055 viewport.sendSelection();
3062 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3066 public void hideAllSelection_actionPerformed(ActionEvent e)
3068 SequenceGroup sg = viewport.getSelectionGroup();
3069 viewport.expandColSelection(sg, false);
3070 viewport.hideAllSelectedSeqs();
3071 viewport.hideSelectedColumns();
3072 alignPanel.paintAlignment(true, true);
3073 viewport.sendSelection();
3080 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3084 public void showAllhidden_actionPerformed(ActionEvent e)
3086 viewport.showAllHiddenColumns();
3087 viewport.showAllHiddenSeqs();
3088 alignPanel.paintAlignment(true, true);
3089 viewport.sendSelection();
3093 public void hideSelColumns_actionPerformed(ActionEvent e)
3095 viewport.hideSelectedColumns();
3096 alignPanel.paintAlignment(true, true);
3097 viewport.sendSelection();
3101 public void hiddenMarkers_actionPerformed(ActionEvent e)
3103 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3114 protected void scaleAbove_actionPerformed(ActionEvent e)
3116 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3117 // TODO: do we actually need to update overview for scale above change ?
3118 alignPanel.paintAlignment(true, false);
3128 protected void scaleLeft_actionPerformed(ActionEvent e)
3130 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3131 alignPanel.paintAlignment(true, false);
3141 protected void scaleRight_actionPerformed(ActionEvent e)
3143 viewport.setScaleRightWrapped(scaleRight.isSelected());
3144 alignPanel.paintAlignment(true, false);
3154 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3156 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3157 alignPanel.paintAlignment(false, false);
3167 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3169 viewport.setShowText(viewTextMenuItem.isSelected());
3170 alignPanel.paintAlignment(false, false);
3180 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3182 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3183 alignPanel.paintAlignment(false, false);
3186 public FeatureSettings featureSettings;
3189 public FeatureSettingsControllerI getFeatureSettingsUI()
3191 return featureSettings;
3195 public void featureSettings_actionPerformed(ActionEvent e)
3197 if (featureSettings != null)
3199 featureSettings.close();
3200 featureSettings = null;
3202 if (!showSeqFeatures.isSelected())
3204 // make sure features are actually displayed
3205 showSeqFeatures.setSelected(true);
3206 showSeqFeatures_actionPerformed(null);
3208 featureSettings = new FeatureSettings(this);
3212 * Set or clear 'Show Sequence Features'
3218 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3220 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3221 alignPanel.paintAlignment(true, true);
3225 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3226 * the annotations panel as a whole.
3228 * The options to show/hide all annotations should be enabled when the panel
3229 * is shown, and disabled when the panel is hidden.
3234 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3236 final boolean setVisible = annotationPanelMenuItem.isSelected();
3237 viewport.setShowAnnotation(setVisible);
3238 this.showAllSeqAnnotations.setEnabled(setVisible);
3239 this.hideAllSeqAnnotations.setEnabled(setVisible);
3240 this.showAllAlAnnotations.setEnabled(setVisible);
3241 this.hideAllAlAnnotations.setEnabled(setVisible);
3242 alignPanel.updateLayout();
3246 public void alignmentProperties()
3248 JEditorPane editPane = new JEditorPane("text/html", "");
3249 editPane.setEditable(false);
3250 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3253 MessageManager.formatMessage("label.html_content", new Object[]
3254 { contents.toString() }));
3255 JInternalFrame frame = new JInternalFrame();
3256 frame.getContentPane().add(new JScrollPane(editPane));
3258 Desktop.addInternalFrame(frame, MessageManager
3259 .formatMessage("label.alignment_properties", new Object[]
3260 { getTitle() }), 500, 400);
3270 public void overviewMenuItem_actionPerformed(ActionEvent e)
3272 if (alignPanel.overviewPanel != null)
3277 JInternalFrame frame = new JInternalFrame();
3278 final OverviewPanel overview = new OverviewPanel(alignPanel);
3279 frame.setContentPane(overview);
3280 Desktop.addInternalFrame(frame, MessageManager
3281 .formatMessage("label.overview_params", new Object[]
3282 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3285 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3286 frame.addInternalFrameListener(
3287 new javax.swing.event.InternalFrameAdapter()
3290 public void internalFrameClosed(
3291 javax.swing.event.InternalFrameEvent evt)
3294 alignPanel.setOverviewPanel(null);
3297 if (getKeyListeners().length > 0)
3299 frame.addKeyListener(getKeyListeners()[0]);
3302 alignPanel.setOverviewPanel(overview);
3306 public void textColour_actionPerformed()
3308 new TextColourChooser().chooseColour(alignPanel, null);
3312 * public void covariationColour_actionPerformed() {
3314 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3318 public void annotationColour_actionPerformed()
3320 new AnnotationColourChooser(viewport, alignPanel);
3324 public void annotationColumn_actionPerformed(ActionEvent e)
3326 new AnnotationColumnChooser(viewport, alignPanel);
3330 * Action on the user checking or unchecking the option to apply the selected
3331 * colour scheme to all groups. If unchecked, groups may have their own
3332 * independent colour schemes.
3337 public void applyToAllGroups_actionPerformed(boolean selected)
3339 viewport.setColourAppliesToAllGroups(selected);
3343 * Action on user selecting a colour from the colour menu
3346 * the name (not the menu item label!) of the colour scheme
3349 public void changeColour_actionPerformed(String name)
3352 * 'User Defined' opens a panel to configure or load a
3353 * user-defined colour scheme
3355 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3357 new UserDefinedColours(alignPanel);
3362 * otherwise set the chosen colour scheme (or null for 'None')
3364 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3365 viewport.getAlignment(), viewport.getHiddenRepSequences());
3370 * Actions on setting or changing the alignment colour scheme
3375 public void changeColour(ColourSchemeI cs)
3377 // TODO: pull up to controller method
3378 ColourMenuHelper.setColourSelected(colourMenu, cs);
3380 viewport.setGlobalColourScheme(cs);
3382 alignPanel.paintAlignment(true, true);
3386 * Show the PID threshold slider panel
3389 protected void modifyPID_actionPerformed()
3391 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3392 alignPanel.getViewName());
3393 SliderPanel.showPIDSlider();
3397 * Show the Conservation slider panel
3400 protected void modifyConservation_actionPerformed()
3402 SliderPanel.setConservationSlider(alignPanel,
3403 viewport.getResidueShading(), alignPanel.getViewName());
3404 SliderPanel.showConservationSlider();
3408 * Action on selecting or deselecting (Colour) By Conservation
3411 public void conservationMenuItem_actionPerformed(boolean selected)
3413 modifyConservation.setEnabled(selected);
3414 viewport.setConservationSelected(selected);
3415 viewport.getResidueShading().setConservationApplied(selected);
3417 changeColour(viewport.getGlobalColourScheme());
3420 modifyConservation_actionPerformed();
3424 SliderPanel.hideConservationSlider();
3429 * Action on selecting or deselecting (Colour) Above PID Threshold
3432 public void abovePIDThreshold_actionPerformed(boolean selected)
3434 modifyPID.setEnabled(selected);
3435 viewport.setAbovePIDThreshold(selected);
3438 viewport.getResidueShading().setThreshold(0,
3439 viewport.isIgnoreGapsConsensus());
3442 changeColour(viewport.getGlobalColourScheme());
3445 modifyPID_actionPerformed();
3449 SliderPanel.hidePIDSlider();
3460 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3462 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3463 AlignmentSorter.sortByPID(viewport.getAlignment(),
3464 viewport.getAlignment().getSequenceAt(0));
3465 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3466 viewport.getAlignment()));
3467 alignPanel.paintAlignment(true, false);
3477 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3479 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3480 AlignmentSorter.sortByID(viewport.getAlignment());
3482 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3483 alignPanel.paintAlignment(true, false);
3493 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3495 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3496 AlignmentSorter.sortByLength(viewport.getAlignment());
3497 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3498 viewport.getAlignment()));
3499 alignPanel.paintAlignment(true, false);
3509 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3511 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3512 AlignmentSorter.sortByGroup(viewport.getAlignment());
3513 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3514 viewport.getAlignment()));
3516 alignPanel.paintAlignment(true, false);
3526 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3528 new RedundancyPanel(alignPanel, this);
3538 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3540 if ((viewport.getSelectionGroup() == null)
3541 || (viewport.getSelectionGroup().getSize() < 2))
3543 JvOptionPane.showInternalMessageDialog(this,
3544 MessageManager.getString(
3545 "label.you_must_select_least_two_sequences"),
3546 MessageManager.getString("label.invalid_selection"),
3547 JvOptionPane.WARNING_MESSAGE);
3551 JInternalFrame frame = new JInternalFrame();
3552 frame.setContentPane(new PairwiseAlignPanel(viewport));
3553 Desktop.addInternalFrame(frame,
3554 MessageManager.getString("action.pairwise_alignment"), 600,
3560 public void autoCalculate_actionPerformed(ActionEvent e)
3562 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3563 if (viewport.autoCalculateConsensus)
3565 viewport.firePropertyChange("alignment", null,
3566 viewport.getAlignment().getSequences());
3571 public void sortByTreeOption_actionPerformed(ActionEvent e)
3573 viewport.sortByTree = sortByTree.isSelected();
3577 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3579 viewport.followSelection = listenToViewSelections.isSelected();
3583 * Constructs a tree panel and adds it to the desktop
3586 * tree type (NJ or AV)
3588 * name of score model used to compute the tree
3590 * parameters for the distance or similarity calculation
3592 void newTreePanel(String type, String modelName,
3593 SimilarityParamsI options)
3595 String frameTitle = "";
3598 boolean onSelection = false;
3599 if (viewport.getSelectionGroup() != null
3600 && viewport.getSelectionGroup().getSize() > 0)
3602 SequenceGroup sg = viewport.getSelectionGroup();
3604 /* Decide if the selection is a column region */
3605 for (SequenceI _s : sg.getSequences())
3607 if (_s.getLength() < sg.getEndRes())
3609 JvOptionPane.showMessageDialog(Desktop.desktop,
3610 MessageManager.getString(
3611 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3612 MessageManager.getString(
3613 "label.sequences_selection_not_aligned"),
3614 JvOptionPane.WARNING_MESSAGE);
3623 if (viewport.getAlignment().getHeight() < 2)
3629 tp = new TreePanel(alignPanel, type, modelName, options);
3630 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3632 frameTitle += " from ";
3634 if (viewport.viewName != null)
3636 frameTitle += viewport.viewName + " of ";
3639 frameTitle += this.title;
3641 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3652 public void addSortByOrderMenuItem(String title,
3653 final AlignmentOrder order)
3655 final JMenuItem item = new JMenuItem(MessageManager
3656 .formatMessage("action.by_title_param", new Object[]
3659 item.addActionListener(new java.awt.event.ActionListener()
3662 public void actionPerformed(ActionEvent e)
3664 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3666 // TODO: JBPNote - have to map order entries to curent SequenceI
3668 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3670 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3671 viewport.getAlignment()));
3673 alignPanel.paintAlignment(true, false);
3679 * Add a new sort by annotation score menu item
3682 * the menu to add the option to
3684 * the label used to retrieve scores for each sequence on the
3687 public void addSortByAnnotScoreMenuItem(JMenu sort,
3688 final String scoreLabel)
3690 final JMenuItem item = new JMenuItem(scoreLabel);
3692 item.addActionListener(new java.awt.event.ActionListener()
3695 public void actionPerformed(ActionEvent e)
3697 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3698 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3699 viewport.getAlignment());// ,viewport.getSelectionGroup());
3700 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3701 viewport.getAlignment()));
3702 alignPanel.paintAlignment(true, false);
3708 * last hash for alignment's annotation array - used to minimise cost of
3711 protected int _annotationScoreVectorHash;
3714 * search the alignment and rebuild the sort by annotation score submenu the
3715 * last alignment annotation vector hash is stored to minimize cost of
3716 * rebuilding in subsequence calls.
3720 public void buildSortByAnnotationScoresMenu()
3722 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3727 if (viewport.getAlignment().getAlignmentAnnotation()
3728 .hashCode() != _annotationScoreVectorHash)
3730 sortByAnnotScore.removeAll();
3731 // almost certainly a quicker way to do this - but we keep it simple
3732 Hashtable scoreSorts = new Hashtable();
3733 AlignmentAnnotation aann[];
3734 for (SequenceI sqa : viewport.getAlignment().getSequences())
3736 aann = sqa.getAnnotation();
3737 for (int i = 0; aann != null && i < aann.length; i++)
3739 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3741 scoreSorts.put(aann[i].label, aann[i].label);
3745 Enumeration labels = scoreSorts.keys();
3746 while (labels.hasMoreElements())
3748 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3749 (String) labels.nextElement());
3751 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3754 _annotationScoreVectorHash = viewport.getAlignment()
3755 .getAlignmentAnnotation().hashCode();
3760 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3761 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3762 * call. Listeners are added to remove the menu item when the treePanel is
3763 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3767 public void buildTreeSortMenu()
3769 sortByTreeMenu.removeAll();
3771 List<Component> comps = PaintRefresher.components
3772 .get(viewport.getSequenceSetId());
3773 List<TreePanel> treePanels = new ArrayList<>();
3774 for (Component comp : comps)
3776 if (comp instanceof TreePanel)
3778 treePanels.add((TreePanel) comp);
3782 if (treePanels.size() < 1)
3784 sortByTreeMenu.setVisible(false);
3788 sortByTreeMenu.setVisible(true);
3790 for (final TreePanel tp : treePanels)
3792 final JMenuItem item = new JMenuItem(tp.getTitle());
3793 item.addActionListener(new java.awt.event.ActionListener()
3796 public void actionPerformed(ActionEvent e)
3798 tp.sortByTree_actionPerformed();
3799 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3804 sortByTreeMenu.add(item);
3808 public boolean sortBy(AlignmentOrder alorder, String undoname)
3810 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3811 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3812 if (undoname != null)
3814 addHistoryItem(new OrderCommand(undoname, oldOrder,
3815 viewport.getAlignment()));
3817 alignPanel.paintAlignment(true, false);
3822 * Work out whether the whole set of sequences or just the selected set will
3823 * be submitted for multiple alignment.
3826 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3828 // Now, check we have enough sequences
3829 AlignmentView msa = null;
3831 if ((viewport.getSelectionGroup() != null)
3832 && (viewport.getSelectionGroup().getSize() > 1))
3834 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3835 // some common interface!
3837 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3838 * SequenceI[sz = seqs.getSize(false)];
3840 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3841 * seqs.getSequenceAt(i); }
3843 msa = viewport.getAlignmentView(true);
3845 else if (viewport.getSelectionGroup() != null
3846 && viewport.getSelectionGroup().getSize() == 1)
3848 int option = JvOptionPane.showConfirmDialog(this,
3849 MessageManager.getString("warn.oneseq_msainput_selection"),
3850 MessageManager.getString("label.invalid_selection"),
3851 JvOptionPane.OK_CANCEL_OPTION);
3852 if (option == JvOptionPane.OK_OPTION)
3854 msa = viewport.getAlignmentView(false);
3859 msa = viewport.getAlignmentView(false);
3865 * Decides what is submitted to a secondary structure prediction service: the
3866 * first sequence in the alignment, or in the current selection, or, if the
3867 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3868 * region or the whole alignment. (where the first sequence in the set is the
3869 * one that the prediction will be for).
3871 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3873 AlignmentView seqs = null;
3875 if ((viewport.getSelectionGroup() != null)
3876 && (viewport.getSelectionGroup().getSize() > 0))
3878 seqs = viewport.getAlignmentView(true);
3882 seqs = viewport.getAlignmentView(false);
3884 // limit sequences - JBPNote in future - could spawn multiple prediction
3886 // TODO: viewport.getAlignment().isAligned is a global state - the local
3887 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3888 if (!viewport.getAlignment().isAligned(false))
3890 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3891 // TODO: if seqs.getSequences().length>1 then should really have warned
3905 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3907 // Pick the tree file
3908 JalviewFileChooser chooser = new JalviewFileChooser(
3909 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3910 chooser.setFileView(new JalviewFileView());
3911 chooser.setDialogTitle(
3912 MessageManager.getString("label.select_newick_like_tree_file"));
3913 chooser.setToolTipText(
3914 MessageManager.getString("label.load_tree_file"));
3916 int value = chooser.showOpenDialog(null);
3918 if (value == JalviewFileChooser.APPROVE_OPTION)
3920 String filePath = chooser.getSelectedFile().getPath();
3921 Cache.setProperty("LAST_DIRECTORY", filePath);
3922 NewickFile fin = null;
3925 fin = new NewickFile(filePath, DataSourceType.FILE);
3926 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
3927 } catch (Exception ex)
3929 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
3930 MessageManager.getString("label.problem_reading_tree_file"),
3931 JvOptionPane.WARNING_MESSAGE);
3932 ex.printStackTrace();
3934 if (fin != null && fin.hasWarningMessage())
3936 JvOptionPane.showMessageDialog(Desktop.desktop,
3937 fin.getWarningMessage(),
3939 .getString("label.possible_problem_with_tree_file"),
3940 JvOptionPane.WARNING_MESSAGE);
3945 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
3947 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
3950 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
3951 int h, int x, int y)
3953 return showNewickTree(nf, treeTitle, null, w, h, x, y);
3957 * Add a treeviewer for the tree extracted from a Newick file object to the
3958 * current alignment view
3965 * Associated alignment input data (or null)
3974 * @return TreePanel handle
3976 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
3977 AlignmentView input, int w, int h, int x, int y)
3979 TreePanel tp = null;
3985 if (nf.getTree() != null)
3987 tp = new TreePanel(alignPanel, nf, treeTitle, input);
3993 tp.setLocation(x, y);
3996 Desktop.addInternalFrame(tp, treeTitle, w, h);
3998 } catch (Exception ex)
4000 ex.printStackTrace();
4006 private boolean buildingMenu = false;
4009 * Generates menu items and listener event actions for web service clients
4012 public void BuildWebServiceMenu()
4014 while (buildingMenu)
4018 System.err.println("Waiting for building menu to finish.");
4020 } catch (Exception e)
4024 final AlignFrame me = this;
4025 buildingMenu = true;
4026 new Thread(new Runnable()
4031 final List<JMenuItem> legacyItems = new ArrayList<>();
4034 // System.err.println("Building ws menu again "
4035 // + Thread.currentThread());
4036 // TODO: add support for context dependent disabling of services based
4038 // alignment and current selection
4039 // TODO: add additional serviceHandle parameter to specify abstract
4041 // class independently of AbstractName
4042 // TODO: add in rediscovery GUI function to restart discoverer
4043 // TODO: group services by location as well as function and/or
4045 // object broker mechanism.
4046 final Vector<JMenu> wsmenu = new Vector<>();
4047 final IProgressIndicator af = me;
4050 * do not i18n these strings - they are hard-coded in class
4051 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4052 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4054 final JMenu msawsmenu = new JMenu("Alignment");
4055 final JMenu secstrmenu = new JMenu(
4056 "Secondary Structure Prediction");
4057 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4058 final JMenu analymenu = new JMenu("Analysis");
4059 final JMenu dismenu = new JMenu("Protein Disorder");
4060 // JAL-940 - only show secondary structure prediction services from
4061 // the legacy server
4062 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4064 Discoverer.services != null && (Discoverer.services.size() > 0))
4066 // TODO: refactor to allow list of AbstractName/Handler bindings to
4068 // stored or retrieved from elsewhere
4069 // No MSAWS used any more:
4070 // Vector msaws = null; // (Vector)
4071 // Discoverer.services.get("MsaWS");
4072 Vector secstrpr = (Vector) Discoverer.services
4074 if (secstrpr != null)
4076 // Add any secondary structure prediction services
4077 for (int i = 0, j = secstrpr.size(); i < j; i++)
4079 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4081 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4082 .getServiceClient(sh);
4083 int p = secstrmenu.getItemCount();
4084 impl.attachWSMenuEntry(secstrmenu, me);
4085 int q = secstrmenu.getItemCount();
4086 for (int litm = p; litm < q; litm++)
4088 legacyItems.add(secstrmenu.getItem(litm));
4094 // Add all submenus in the order they should appear on the web
4096 wsmenu.add(msawsmenu);
4097 wsmenu.add(secstrmenu);
4098 wsmenu.add(dismenu);
4099 wsmenu.add(analymenu);
4100 // No search services yet
4101 // wsmenu.add(seqsrchmenu);
4103 javax.swing.SwingUtilities.invokeLater(new Runnable()
4110 webService.removeAll();
4111 // first, add discovered services onto the webservices menu
4112 if (wsmenu.size() > 0)
4114 for (int i = 0, j = wsmenu.size(); i < j; i++)
4116 webService.add(wsmenu.get(i));
4121 webService.add(me.webServiceNoServices);
4123 // TODO: move into separate menu builder class.
4124 boolean new_sspred = false;
4125 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4127 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4128 if (jws2servs != null)
4130 if (jws2servs.hasServices())
4132 jws2servs.attachWSMenuEntry(webService, me);
4133 for (Jws2Instance sv : jws2servs.getServices())
4135 if (sv.description.toLowerCase().contains("jpred"))
4137 for (JMenuItem jmi : legacyItems)
4139 jmi.setVisible(false);
4145 if (jws2servs.isRunning())
4147 JMenuItem tm = new JMenuItem(
4148 "Still discovering JABA Services");
4149 tm.setEnabled(false);
4154 build_urlServiceMenu(me.webService);
4155 build_fetchdbmenu(webService);
4156 for (JMenu item : wsmenu)
4158 if (item.getItemCount() == 0)
4160 item.setEnabled(false);
4164 item.setEnabled(true);
4167 } catch (Exception e)
4170 "Exception during web service menu building process.",
4175 } catch (Exception e)
4178 buildingMenu = false;
4185 * construct any groupURL type service menu entries.
4189 private void build_urlServiceMenu(JMenu webService)
4191 // TODO: remove this code when 2.7 is released
4192 // DEBUG - alignmentView
4194 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4195 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4197 * @Override public void actionPerformed(ActionEvent e) {
4198 * jalview.datamodel.AlignmentView
4199 * .testSelectionViews(af.viewport.getAlignment(),
4200 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4202 * }); webService.add(testAlView);
4204 // TODO: refactor to RestClient discoverer and merge menu entries for
4205 // rest-style services with other types of analysis/calculation service
4206 // SHmmr test client - still being implemented.
4207 // DEBUG - alignmentView
4209 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4212 client.attachWSMenuEntry(
4213 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4219 * Searches the alignment sequences for xRefs and builds the Show
4220 * Cross-References menu (formerly called Show Products), with database
4221 * sources for which cross-references are found (protein sources for a
4222 * nucleotide alignment and vice versa)
4224 * @return true if Show Cross-references menu should be enabled
4226 public boolean canShowProducts()
4228 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4229 AlignmentI dataset = viewport.getAlignment().getDataset();
4231 showProducts.removeAll();
4232 final boolean dna = viewport.getAlignment().isNucleotide();
4234 if (seqs == null || seqs.length == 0)
4236 // nothing to see here.
4240 boolean showp = false;
4243 List<String> ptypes = new CrossRef(seqs, dataset)
4244 .findXrefSourcesForSequences(dna);
4246 for (final String source : ptypes)
4249 final AlignFrame af = this;
4250 JMenuItem xtype = new JMenuItem(source);
4251 xtype.addActionListener(new ActionListener()
4254 public void actionPerformed(ActionEvent e)
4256 showProductsFor(af.viewport.getSequenceSelection(), dna,
4260 showProducts.add(xtype);
4262 showProducts.setVisible(showp);
4263 showProducts.setEnabled(showp);
4264 } catch (Exception e)
4267 "canShowProducts threw an exception - please report to help@jalview.org",
4275 * Finds and displays cross-references for the selected sequences (protein
4276 * products for nucleotide sequences, dna coding sequences for peptides).
4279 * the sequences to show cross-references for
4281 * true if from a nucleotide alignment (so showing proteins)
4283 * the database to show cross-references for
4285 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4286 final String source)
4288 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4293 * Construct and display a new frame containing the translation of this
4294 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4297 public void showTranslation_actionPerformed(ActionEvent e)
4299 AlignmentI al = null;
4302 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4304 al = dna.translateCdna();
4305 } catch (Exception ex)
4307 jalview.bin.Cache.log.error(
4308 "Exception during translation. Please report this !", ex);
4309 final String msg = MessageManager.getString(
4310 "label.error_when_translating_sequences_submit_bug_report");
4311 final String errorTitle = MessageManager
4312 .getString("label.implementation_error")
4313 + MessageManager.getString("label.translation_failed");
4314 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4315 JvOptionPane.ERROR_MESSAGE);
4318 if (al == null || al.getHeight() == 0)
4320 final String msg = MessageManager.getString(
4321 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4322 final String errorTitle = MessageManager
4323 .getString("label.translation_failed");
4324 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4325 JvOptionPane.WARNING_MESSAGE);
4329 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4330 af.setFileFormat(this.currentFileFormat);
4331 final String newTitle = MessageManager
4332 .formatMessage("label.translation_of_params", new Object[]
4333 { this.getTitle() });
4334 af.setTitle(newTitle);
4335 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4337 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4338 viewport.openSplitFrame(af, new Alignment(seqs));
4342 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4349 * Set the file format
4353 public void setFileFormat(FileFormatI format)
4355 this.currentFileFormat = format;
4359 * Try to load a features file onto the alignment.
4362 * contents or path to retrieve file or a File object
4364 * access mode of file (see jalview.io.AlignFile)
4365 * @return true if features file was parsed correctly.
4367 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4370 return avc.parseFeaturesFile(file, sourceType,
4371 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4376 public void refreshFeatureUI(boolean enableIfNecessary)
4378 // note - currently this is only still here rather than in the controller
4379 // because of the featureSettings hard reference that is yet to be
4381 if (enableIfNecessary)
4383 viewport.setShowSequenceFeatures(true);
4384 showSeqFeatures.setSelected(true);
4390 public void dragEnter(DropTargetDragEvent evt)
4395 public void dragExit(DropTargetEvent evt)
4400 public void dragOver(DropTargetDragEvent evt)
4405 public void dropActionChanged(DropTargetDragEvent evt)
4410 public void drop(DropTargetDropEvent evt)
4412 // JAL-1552 - acceptDrop required before getTransferable call for
4413 // Java's Transferable for native dnd
4414 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4415 Transferable t = evt.getTransferable();
4418 final AlignFrame thisaf = this;
4419 final List<Object> files = new ArrayList<>();
4420 List<DataSourceType> protocols = new ArrayList<>();
4424 Desktop.transferFromDropTarget(files, protocols, evt, t);
4425 } catch (Exception e)
4427 e.printStackTrace();
4431 new Thread(new Runnable()
4438 // check to see if any of these files have names matching sequences
4441 SequenceIdMatcher idm = new SequenceIdMatcher(
4442 viewport.getAlignment().getSequencesArray());
4444 * Object[] { String,SequenceI}
4446 ArrayList<Object[]> filesmatched = new ArrayList<>();
4447 ArrayList<Object> filesnotmatched = new ArrayList<>();
4448 for (int i = 0; i < files.size(); i++)
4451 Object file = files.get(i);
4452 String fileName = file.toString();
4454 DataSourceType protocol = (file instanceof File ? DataSourceType.FILE : FormatAdapter.checkProtocol(fileName));
4455 if (protocol == DataSourceType.FILE)
4457 File fl = (file instanceof File ? (File) file : new File(fileName));
4458 pdbfn = fl.getName();
4460 else if (protocol == DataSourceType.URL)
4462 URL url = new URL(fileName);
4463 pdbfn = url.getFile();
4465 if (pdbfn.length() > 0)
4467 // attempt to find a match in the alignment
4468 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4469 int l = 0, c = pdbfn.indexOf(".");
4470 while (mtch == null && c != -1)
4475 } while ((c = pdbfn.indexOf(".", l)) > l);
4478 pdbfn = pdbfn.substring(0, l);
4480 mtch = idm.findAllIdMatches(pdbfn);
4487 type = new IdentifyFile().identify(file, protocol);
4488 } catch (Exception ex)
4492 if (type != null && type.isStructureFile())
4494 filesmatched.add(new Object[] { file, protocol, mtch });
4498 // File wasn't named like one of the sequences or wasn't a PDB
4500 filesnotmatched.add(file);
4504 if (filesmatched.size() > 0)
4506 boolean autoAssociate = Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4509 String msg = MessageManager.formatMessage(
4510 "label.automatically_associate_structure_files_with_sequences_same_name",
4512 { Integer.valueOf(filesmatched.size())
4514 String ttl = MessageManager.getString(
4515 "label.automatically_associate_structure_files_by_name");
4516 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4517 ttl, JvOptionPane.YES_NO_OPTION);
4518 autoAssociate = choice == JvOptionPane.YES_OPTION;
4522 for (Object[] fm : filesmatched)
4524 // try and associate
4525 // TODO: may want to set a standard ID naming formalism for
4526 // associating PDB files which have no IDs.
4527 for (SequenceI toassoc : (SequenceI[]) fm[2])
4529 PDBEntry pe = new AssociatePdbFileWithSeq()
4530 .associatePdbWithSeq((String) fm[0],
4531 (DataSourceType) fm[1], toassoc, false,
4535 System.err.println("Associated file : "
4536 + ((String) fm[0]) + " with "
4537 + toassoc.getDisplayId(true));
4541 // TODO: do we need to update overview ? only if features are
4543 alignPanel.paintAlignment(true, false);
4549 * add declined structures as sequences
4551 for (Object[] o : filesmatched)
4553 filesnotmatched.add((String) o[0]);
4557 if (filesnotmatched.size() > 0)
4559 if (assocfiles > 0 && (Cache.getDefault(
4560 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4561 || JvOptionPane.showConfirmDialog(thisaf,
4562 "<html>" + MessageManager.formatMessage(
4563 "label.ignore_unmatched_dropped_files_info",
4566 filesnotmatched.size())
4569 MessageManager.getString(
4570 "label.ignore_unmatched_dropped_files"),
4571 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4575 for (Object fn : filesnotmatched)
4577 loadJalviewDataFile(fn, null, null, null);
4581 } catch (Exception ex)
4583 ex.printStackTrace();
4591 * Attempt to load a "dropped" file or URL string, by testing in turn for
4593 * <li>an Annotation file</li>
4594 * <li>a JNet file</li>
4595 * <li>a features file</li>
4596 * <li>else try to interpret as an alignment file</li>
4600 * either a filename or a URL string.
4602 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4603 FileFormatI format, SequenceI assocSeq)
4605 // BH 2018 was String file
4608 if (sourceType == null)
4610 sourceType = FormatAdapter.checkProtocol(file);
4612 // if the file isn't identified, or not positively identified as some
4613 // other filetype (PFAM is default unidentified alignment file type) then
4614 // try to parse as annotation.
4615 boolean isAnnotation = (format == null
4616 || FileFormat.Pfam.equals(format))
4617 ? new AnnotationFile().annotateAlignmentView(viewport,
4623 // first see if its a T-COFFEE score file
4624 TCoffeeScoreFile tcf = null;
4627 tcf = new TCoffeeScoreFile(file, sourceType);
4630 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4634 new TCoffeeColourScheme(viewport.getAlignment()));
4635 isAnnotation = true;
4636 statusBar.setText(MessageManager.getString(
4637 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4641 // some problem - if no warning its probable that the ID matching
4642 // process didn't work
4643 JvOptionPane.showMessageDialog(Desktop.desktop,
4644 tcf.getWarningMessage() == null
4645 ? MessageManager.getString(
4646 "label.check_file_matches_sequence_ids_alignment")
4647 : tcf.getWarningMessage(),
4648 MessageManager.getString(
4649 "label.problem_reading_tcoffee_score_file"),
4650 JvOptionPane.WARNING_MESSAGE);
4657 } catch (Exception x)
4660 "Exception when processing data source as T-COFFEE score file",
4666 // try to see if its a JNet 'concise' style annotation file *before*
4668 // try to parse it as a features file
4671 format = new IdentifyFile().identify(file, sourceType);
4673 if (FileFormat.ScoreMatrix == format)
4675 ScoreMatrixFile sm = new ScoreMatrixFile(
4676 new FileParse(file, sourceType));
4678 // todo: i18n this message
4679 statusBar.setText(MessageManager.formatMessage(
4680 "label.successfully_loaded_matrix",
4681 sm.getMatrixName()));
4683 else if (FileFormat.Jnet.equals(format))
4685 JPredFile predictions = new JPredFile(file, sourceType);
4686 new JnetAnnotationMaker();
4687 JnetAnnotationMaker.add_annotation(predictions,
4688 viewport.getAlignment(), 0, false);
4689 viewport.getAlignment().setupJPredAlignment();
4690 isAnnotation = true;
4692 // else if (IdentifyFile.FeaturesFile.equals(format))
4693 else if (FileFormat.Features.equals(format))
4695 if (parseFeaturesFile(file, sourceType))
4697 alignPanel.paintAlignment(true, true);
4702 new FileLoader().LoadFile(viewport, file, sourceType, format);
4709 alignPanel.adjustAnnotationHeight();
4710 viewport.updateSequenceIdColours();
4711 buildSortByAnnotationScoresMenu();
4712 alignPanel.paintAlignment(true, true);
4714 } catch (Exception ex)
4716 ex.printStackTrace();
4717 } catch (OutOfMemoryError oom)
4722 } catch (Exception x)
4727 + (sourceType != null
4728 ? (sourceType == DataSourceType.PASTE
4730 : "using " + sourceType + " from "
4734 ? "(parsing as '" + format + "' file)"
4736 oom, Desktop.desktop);
4741 * Method invoked by the ChangeListener on the tabbed pane, in other words
4742 * when a different tabbed pane is selected by the user or programmatically.
4745 public void tabSelectionChanged(int index)
4749 alignPanel = alignPanels.get(index);
4750 viewport = alignPanel.av;
4751 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4752 setMenusFromViewport(viewport);
4756 * 'focus' any colour slider that is open to the selected viewport
4758 if (viewport.getConservationSelected())
4760 SliderPanel.setConservationSlider(alignPanel,
4761 viewport.getResidueShading(), alignPanel.getViewName());
4765 SliderPanel.hideConservationSlider();
4767 if (viewport.getAbovePIDThreshold())
4769 SliderPanel.setPIDSliderSource(alignPanel,
4770 viewport.getResidueShading(), alignPanel.getViewName());
4774 SliderPanel.hidePIDSlider();
4778 * If there is a frame linked to this one in a SplitPane, switch it to the
4779 * same view tab index. No infinite recursion of calls should happen, since
4780 * tabSelectionChanged() should not get invoked on setting the selected
4781 * index to an unchanged value. Guard against setting an invalid index
4782 * before the new view peer tab has been created.
4784 final AlignViewportI peer = viewport.getCodingComplement();
4787 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4788 .getAlignPanel().alignFrame;
4789 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4791 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4797 * On right mouse click on view tab, prompt for and set new view name.
4800 public void tabbedPane_mousePressed(MouseEvent e)
4802 if (e.isPopupTrigger())
4804 String msg = MessageManager.getString("label.enter_view_name");
4805 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4806 JvOptionPane.QUESTION_MESSAGE);
4810 viewport.viewName = reply;
4811 // TODO warn if reply is in getExistingViewNames()?
4812 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4817 public AlignViewport getCurrentView()
4823 * Open the dialog for regex description parsing.
4826 protected void extractScores_actionPerformed(ActionEvent e)
4828 ParseProperties pp = new jalview.analysis.ParseProperties(
4829 viewport.getAlignment());
4830 // TODO: verify regex and introduce GUI dialog for version 2.5
4831 // if (pp.getScoresFromDescription("col", "score column ",
4832 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4834 if (pp.getScoresFromDescription("description column",
4835 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4837 buildSortByAnnotationScoresMenu();
4845 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4849 protected void showDbRefs_actionPerformed(ActionEvent e)
4851 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4857 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4861 protected void showNpFeats_actionPerformed(ActionEvent e)
4863 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4867 * find the viewport amongst the tabs in this alignment frame and close that
4872 public boolean closeView(AlignViewportI av)
4876 this.closeMenuItem_actionPerformed(false);
4879 Component[] comp = tabbedPane.getComponents();
4880 for (int i = 0; comp != null && i < comp.length; i++)
4882 if (comp[i] instanceof AlignmentPanel)
4884 if (((AlignmentPanel) comp[i]).av == av)
4887 closeView((AlignmentPanel) comp[i]);
4895 protected void build_fetchdbmenu(JMenu webService)
4897 // Temporary hack - DBRef Fetcher always top level ws entry.
4898 // TODO We probably want to store a sequence database checklist in
4899 // preferences and have checkboxes.. rather than individual sources selected
4901 final JMenu rfetch = new JMenu(
4902 MessageManager.getString("action.fetch_db_references"));
4903 rfetch.setToolTipText(MessageManager.getString(
4904 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4905 webService.add(rfetch);
4907 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4908 MessageManager.getString("option.trim_retrieved_seqs"));
4909 trimrs.setToolTipText(
4910 MessageManager.getString("label.trim_retrieved_sequences"));
4912 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
4913 trimrs.addActionListener(new ActionListener()
4916 public void actionPerformed(ActionEvent e)
4918 trimrs.setSelected(trimrs.isSelected());
4919 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
4920 Boolean.valueOf(trimrs.isSelected()).toString());
4924 JMenuItem fetchr = new JMenuItem(
4925 MessageManager.getString("label.standard_databases"));
4926 fetchr.setToolTipText(
4927 MessageManager.getString("label.fetch_embl_uniprot"));
4928 fetchr.addActionListener(new ActionListener()
4932 public void actionPerformed(ActionEvent e)
4934 new Thread(new Runnable()
4939 boolean isNucleotide = alignPanel.alignFrame.getViewport()
4940 .getAlignment().isNucleotide();
4941 DBRefFetcher dbRefFetcher = new DBRefFetcher(
4942 alignPanel.av.getSequenceSelection(),
4943 alignPanel.alignFrame, null,
4944 alignPanel.alignFrame.featureSettings, isNucleotide);
4945 dbRefFetcher.addListener(new FetchFinishedListenerI()
4948 public void finished()
4950 AlignFrame.this.setMenusForViewport();
4953 dbRefFetcher.fetchDBRefs(false);
4961 final AlignFrame me = this;
4962 new Thread(new Runnable()
4967 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
4968 .getSequenceFetcherSingleton(me);
4969 javax.swing.SwingUtilities.invokeLater(new Runnable()
4974 String[] dbclasses = sf.getOrderedSupportedSources();
4975 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
4976 // jalview.util.QuickSort.sort(otherdb, otherdb);
4977 List<DbSourceProxy> otherdb;
4978 JMenu dfetch = new JMenu();
4979 JMenu ifetch = new JMenu();
4980 JMenuItem fetchr = null;
4981 int comp = 0, icomp = 0, mcomp = 15;
4982 String mname = null;
4984 for (String dbclass : dbclasses)
4986 otherdb = sf.getSourceProxy(dbclass);
4987 // add a single entry for this class, or submenu allowing 'fetch
4989 if (otherdb == null || otherdb.size() < 1)
4993 // List<DbSourceProxy> dbs=otherdb;
4994 // otherdb=new ArrayList<DbSourceProxy>();
4995 // for (DbSourceProxy db:dbs)
4997 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5001 mname = "From " + dbclass;
5003 if (otherdb.size() == 1)
5005 final DbSourceProxy[] dassource = otherdb
5006 .toArray(new DbSourceProxy[0]);
5007 DbSourceProxy src = otherdb.get(0);
5008 fetchr = new JMenuItem(src.getDbSource());
5009 fetchr.addActionListener(new ActionListener()
5013 public void actionPerformed(ActionEvent e)
5015 new Thread(new Runnable()
5021 boolean isNucleotide = alignPanel.alignFrame
5022 .getViewport().getAlignment()
5024 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5025 alignPanel.av.getSequenceSelection(),
5026 alignPanel.alignFrame, dassource,
5027 alignPanel.alignFrame.featureSettings,
5030 .addListener(new FetchFinishedListenerI()
5033 public void finished()
5035 AlignFrame.this.setMenusForViewport();
5038 dbRefFetcher.fetchDBRefs(false);
5044 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5045 MessageManager.formatMessage(
5046 "label.fetch_retrieve_from", new Object[]
5047 { src.getDbName() })));
5053 final DbSourceProxy[] dassource = otherdb
5054 .toArray(new DbSourceProxy[0]);
5056 DbSourceProxy src = otherdb.get(0);
5057 fetchr = new JMenuItem(MessageManager
5058 .formatMessage("label.fetch_all_param", new Object[]
5059 { src.getDbSource() }));
5060 fetchr.addActionListener(new ActionListener()
5063 public void actionPerformed(ActionEvent e)
5065 new Thread(new Runnable()
5071 boolean isNucleotide = alignPanel.alignFrame
5072 .getViewport().getAlignment()
5074 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5075 alignPanel.av.getSequenceSelection(),
5076 alignPanel.alignFrame, dassource,
5077 alignPanel.alignFrame.featureSettings,
5080 .addListener(new FetchFinishedListenerI()
5083 public void finished()
5085 AlignFrame.this.setMenusForViewport();
5088 dbRefFetcher.fetchDBRefs(false);
5094 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5095 MessageManager.formatMessage(
5096 "label.fetch_retrieve_from_all_sources",
5098 { Integer.valueOf(otherdb.size())
5100 src.getDbSource(), src.getDbName() })));
5103 // and then build the rest of the individual menus
5104 ifetch = new JMenu(MessageManager.formatMessage(
5105 "label.source_from_db_source", new Object[]
5106 { src.getDbSource() }));
5108 String imname = null;
5110 for (DbSourceProxy sproxy : otherdb)
5112 String dbname = sproxy.getDbName();
5113 String sname = dbname.length() > 5
5114 ? dbname.substring(0, 5) + "..."
5116 String msname = dbname.length() > 10
5117 ? dbname.substring(0, 10) + "..."
5121 imname = MessageManager
5122 .formatMessage("label.from_msname", new Object[]
5125 fetchr = new JMenuItem(msname);
5126 final DbSourceProxy[] dassrc = { sproxy };
5127 fetchr.addActionListener(new ActionListener()
5131 public void actionPerformed(ActionEvent e)
5133 new Thread(new Runnable()
5139 boolean isNucleotide = alignPanel.alignFrame
5140 .getViewport().getAlignment()
5142 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5143 alignPanel.av.getSequenceSelection(),
5144 alignPanel.alignFrame, dassrc,
5145 alignPanel.alignFrame.featureSettings,
5148 .addListener(new FetchFinishedListenerI()
5151 public void finished()
5153 AlignFrame.this.setMenusForViewport();
5156 dbRefFetcher.fetchDBRefs(false);
5162 fetchr.setToolTipText(
5163 "<html>" + MessageManager.formatMessage(
5164 "label.fetch_retrieve_from", new Object[]
5168 if (++icomp >= mcomp || i == (otherdb.size()))
5170 ifetch.setText(MessageManager.formatMessage(
5171 "label.source_to_target", imname, sname));
5173 ifetch = new JMenu();
5181 if (comp >= mcomp || dbi >= (dbclasses.length))
5183 dfetch.setText(MessageManager.formatMessage(
5184 "label.source_to_target", mname, dbclass));
5186 dfetch = new JMenu();
5199 * Left justify the whole alignment.
5202 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5204 AlignmentI al = viewport.getAlignment();
5206 viewport.firePropertyChange("alignment", null, al);
5210 * Right justify the whole alignment.
5213 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5215 AlignmentI al = viewport.getAlignment();
5217 viewport.firePropertyChange("alignment", null, al);
5221 public void setShowSeqFeatures(boolean b)
5223 showSeqFeatures.setSelected(b);
5224 viewport.setShowSequenceFeatures(b);
5231 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5232 * awt.event.ActionEvent)
5235 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5237 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5238 alignPanel.paintAlignment(false, false);
5245 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5249 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5251 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5252 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5260 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5261 * .event.ActionEvent)
5264 protected void showGroupConservation_actionPerformed(ActionEvent e)
5266 viewport.setShowGroupConservation(showGroupConservation.getState());
5267 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5274 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5275 * .event.ActionEvent)
5278 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5280 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5281 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5288 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5289 * .event.ActionEvent)
5292 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5294 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5295 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5299 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5301 showSequenceLogo.setState(true);
5302 viewport.setShowSequenceLogo(true);
5303 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5304 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5308 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5310 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5317 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5318 * .event.ActionEvent)
5321 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5323 if (avc.makeGroupsFromSelection())
5325 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5326 alignPanel.updateAnnotation();
5327 alignPanel.paintAlignment(true, true);
5331 public void clearAlignmentSeqRep()
5333 // TODO refactor alignmentseqrep to controller
5334 if (viewport.getAlignment().hasSeqrep())
5336 viewport.getAlignment().setSeqrep(null);
5337 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5338 alignPanel.updateAnnotation();
5339 alignPanel.paintAlignment(true, true);
5344 protected void createGroup_actionPerformed(ActionEvent e)
5346 if (avc.createGroup())
5348 alignPanel.alignmentChanged();
5353 protected void unGroup_actionPerformed(ActionEvent e)
5357 alignPanel.alignmentChanged();
5362 * make the given alignmentPanel the currently selected tab
5364 * @param alignmentPanel
5366 public void setDisplayedView(AlignmentPanel alignmentPanel)
5368 if (!viewport.getSequenceSetId()
5369 .equals(alignmentPanel.av.getSequenceSetId()))
5371 throw new Error(MessageManager.getString(
5372 "error.implementation_error_cannot_show_view_alignment_frame"));
5374 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5375 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5377 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5382 * Action on selection of menu options to Show or Hide annotations.
5385 * @param forSequences
5386 * update sequence-related annotations
5387 * @param forAlignment
5388 * update non-sequence-related annotations
5391 protected void setAnnotationsVisibility(boolean visible,
5392 boolean forSequences, boolean forAlignment)
5394 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5395 .getAlignmentAnnotation();
5400 for (AlignmentAnnotation aa : anns)
5403 * don't display non-positional annotations on an alignment
5405 if (aa.annotations == null)
5409 boolean apply = (aa.sequenceRef == null && forAlignment)
5410 || (aa.sequenceRef != null && forSequences);
5413 aa.visible = visible;
5416 alignPanel.validateAnnotationDimensions(true);
5417 alignPanel.alignmentChanged();
5421 * Store selected annotation sort order for the view and repaint.
5424 protected void sortAnnotations_actionPerformed()
5426 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5428 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5429 alignPanel.paintAlignment(false, false);
5434 * @return alignment panels in this alignment frame
5436 public List<? extends AlignmentViewPanel> getAlignPanels()
5438 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5442 * Open a new alignment window, with the cDNA associated with this (protein)
5443 * alignment, aligned as is the protein.
5445 protected void viewAsCdna_actionPerformed()
5447 // TODO no longer a menu action - refactor as required
5448 final AlignmentI alignment = getViewport().getAlignment();
5449 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5450 if (mappings == null)
5454 List<SequenceI> cdnaSeqs = new ArrayList<>();
5455 for (SequenceI aaSeq : alignment.getSequences())
5457 for (AlignedCodonFrame acf : mappings)
5459 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5463 * There is a cDNA mapping for this protein sequence - add to new
5464 * alignment. It will share the same dataset sequence as other mapped
5465 * cDNA (no new mappings need to be created).
5467 final Sequence newSeq = new Sequence(dnaSeq);
5468 newSeq.setDatasetSequence(dnaSeq);
5469 cdnaSeqs.add(newSeq);
5473 if (cdnaSeqs.size() == 0)
5475 // show a warning dialog no mapped cDNA
5478 AlignmentI cdna = new Alignment(
5479 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5480 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5481 AlignFrame.DEFAULT_HEIGHT);
5482 cdna.alignAs(alignment);
5483 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5485 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5486 AlignFrame.DEFAULT_HEIGHT);
5490 * Set visibility of dna/protein complement view (available when shown in a
5496 protected void showComplement_actionPerformed(boolean show)
5498 SplitContainerI sf = getSplitViewContainer();
5501 sf.setComplementVisible(this, show);
5506 * Generate the reverse (optionally complemented) of the selected sequences,
5507 * and add them to the alignment
5510 protected void showReverse_actionPerformed(boolean complement)
5512 AlignmentI al = null;
5515 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5516 al = dna.reverseCdna(complement);
5517 viewport.addAlignment(al, "");
5518 addHistoryItem(new EditCommand(
5519 MessageManager.getString("label.add_sequences"), Action.PASTE,
5520 al.getSequencesArray(), 0, al.getWidth(),
5521 viewport.getAlignment()));
5522 } catch (Exception ex)
5524 System.err.println(ex.getMessage());
5530 * Try to run a script in the Groovy console, having first ensured that this
5531 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5532 * be targeted at this alignment.
5535 protected void runGroovy_actionPerformed()
5537 Jalview.setCurrentAlignFrame(this);
5538 groovy.ui.Console console = Desktop.getGroovyConsole();
5539 if (console != null)
5543 console.runScript();
5544 } catch (Exception ex)
5546 System.err.println((ex.toString()));
5547 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5548 MessageManager.getString("label.couldnt_run_groovy_script"),
5549 MessageManager.getString("label.groovy_support_failed"),
5550 JvOptionPane.ERROR_MESSAGE);
5555 System.err.println("Can't run Groovy script as console not found");
5560 * Hides columns containing (or not containing) a specified feature, provided
5561 * that would not leave all columns hidden
5563 * @param featureType
5564 * @param columnsContaining
5567 public boolean hideFeatureColumns(String featureType,
5568 boolean columnsContaining)
5570 boolean notForHiding = avc.markColumnsContainingFeatures(
5571 columnsContaining, false, false, featureType);
5574 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5575 false, featureType))
5577 getViewport().hideSelectedColumns();
5585 protected void selectHighlightedColumns_actionPerformed(
5586 ActionEvent actionEvent)
5588 // include key modifier check in case user selects from menu
5589 avc.markHighlightedColumns(
5590 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5591 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5592 | ActionEvent.CTRL_MASK)) != 0);
5596 * Rebuilds the Colour menu, including any user-defined colours which have
5597 * been loaded either on startup or during the session
5599 public void buildColourMenu()
5601 colourMenu.removeAll();
5603 colourMenu.add(applyToAllGroups);
5604 colourMenu.add(textColour);
5605 colourMenu.addSeparator();
5607 ColourMenuHelper.addMenuItems(colourMenu, this, viewport.getAlignment(),
5610 colourMenu.addSeparator();
5611 colourMenu.add(conservationMenuItem);
5612 colourMenu.add(modifyConservation);
5613 colourMenu.add(abovePIDThreshold);
5614 colourMenu.add(modifyPID);
5615 colourMenu.add(annotationColour);
5617 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5618 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5622 * Open a dialog (if not already open) that allows the user to select and
5623 * calculate PCA or Tree analysis
5625 protected void openTreePcaDialog()
5627 if (alignPanel.getCalculationDialog() == null)
5629 new CalculationChooser(AlignFrame.this);
5634 protected void loadVcf_actionPerformed()
5636 // TODO: JAL-3048 - No VCF support in JsJalview
5637 JalviewFileChooser chooser = new JalviewFileChooser(
5638 Cache.getProperty("LAST_DIRECTORY"));
5639 chooser.setFileView(new JalviewFileView());
5640 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5641 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5643 int value = chooser.showOpenDialog(null);
5645 if (value == JalviewFileChooser.APPROVE_OPTION)
5647 String choice = chooser.getSelectedFile().getPath();
5648 Cache.setProperty("LAST_DIRECTORY", choice);
5649 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5650 new VCFLoader(choice).loadVCF(seqs, this);
5657 class PrintThread extends Thread
5661 public PrintThread(AlignmentPanel ap)
5666 static PageFormat pf;
5671 PrinterJob printJob = PrinterJob.getPrinterJob();
5675 printJob.setPrintable(ap, pf);
5679 printJob.setPrintable(ap);
5682 if (printJob.printDialog())
5687 } catch (Exception PrintException)
5689 PrintException.printStackTrace();