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.HiddenMarkovModel;
58 import jalview.datamodel.HiddenSequences;
59 import jalview.datamodel.PDBEntry;
60 import jalview.datamodel.SeqCigar;
61 import jalview.datamodel.Sequence;
62 import jalview.datamodel.SequenceGroup;
63 import jalview.datamodel.SequenceI;
64 import jalview.gui.ColourMenuHelper.ColourChangeListener;
65 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
66 import jalview.hmmer.HMMERCommands;
67 import jalview.io.AlignmentProperties;
68 import jalview.io.AnnotationFile;
69 import jalview.io.BioJsHTMLOutput;
70 import jalview.io.DataSourceType;
71 import jalview.io.FileFormat;
72 import jalview.io.FileFormatI;
73 import jalview.io.FileFormats;
74 import jalview.io.FileLoader;
75 import jalview.io.FileParse;
76 import jalview.io.FormatAdapter;
77 import jalview.io.HMMFile;
78 import jalview.io.HtmlSvgOutput;
79 import jalview.io.IdentifyFile;
80 import jalview.io.JPredFile;
81 import jalview.io.JalviewFileChooser;
82 import jalview.io.JalviewFileView;
83 import jalview.io.JnetAnnotationMaker;
84 import jalview.io.NewickFile;
85 import jalview.io.ScoreMatrixFile;
86 import jalview.io.TCoffeeScoreFile;
87 import jalview.jbgui.GAlignFrame;
88 import jalview.schemes.ColourSchemeI;
89 import jalview.schemes.ColourSchemes;
90 import jalview.schemes.ResidueColourScheme;
91 import jalview.schemes.TCoffeeColourScheme;
92 import jalview.util.MessageManager;
93 import jalview.viewmodel.AlignmentViewport;
94 import jalview.viewmodel.ViewportRanges;
95 import jalview.workers.InformationThread;
96 import jalview.ws.DBRefFetcher;
97 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
98 import jalview.ws.jws1.Discoverer;
99 import jalview.ws.jws2.Jws2Discoverer;
100 import jalview.ws.jws2.jabaws2.Jws2Instance;
101 import jalview.ws.seqfetcher.DbSourceProxy;
103 import java.awt.BorderLayout;
104 import java.awt.Component;
105 import java.awt.Rectangle;
106 import java.awt.Toolkit;
107 import java.awt.datatransfer.Clipboard;
108 import java.awt.datatransfer.DataFlavor;
109 import java.awt.datatransfer.StringSelection;
110 import java.awt.datatransfer.Transferable;
111 import java.awt.dnd.DnDConstants;
112 import java.awt.dnd.DropTargetDragEvent;
113 import java.awt.dnd.DropTargetDropEvent;
114 import java.awt.dnd.DropTargetEvent;
115 import java.awt.dnd.DropTargetListener;
116 import java.awt.event.ActionEvent;
117 import java.awt.event.ActionListener;
118 import java.awt.event.FocusAdapter;
119 import java.awt.event.FocusEvent;
120 import java.awt.event.ItemEvent;
121 import java.awt.event.ItemListener;
122 import java.awt.event.KeyAdapter;
123 import java.awt.event.KeyEvent;
124 import java.awt.event.MouseEvent;
125 import java.awt.print.PageFormat;
126 import java.awt.print.PrinterJob;
127 import java.beans.PropertyChangeEvent;
129 import java.io.FileWriter;
130 import java.io.IOException;
131 import java.io.PrintWriter;
133 import java.util.ArrayList;
134 import java.util.Arrays;
135 import java.util.Deque;
136 import java.util.Enumeration;
137 import java.util.HashMap;
138 import java.util.Hashtable;
139 import java.util.List;
140 import java.util.Map;
141 import java.util.Vector;
143 import javax.swing.JCheckBoxMenuItem;
144 import javax.swing.JEditorPane;
145 import javax.swing.JInternalFrame;
146 import javax.swing.JLayeredPane;
147 import javax.swing.JMenu;
148 import javax.swing.JMenuItem;
149 import javax.swing.JScrollPane;
150 import javax.swing.SwingUtilities;
156 * @version $Revision$
158 public class AlignFrame extends GAlignFrame implements DropTargetListener,
159 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
162 Map<String, Float> distribution = new HashMap<>(); // temporary
164 public static final int DEFAULT_WIDTH = 700;
166 public static final int DEFAULT_HEIGHT = 500;
169 * The currently displayed panel (selected tabbed view if more than one)
171 public AlignmentPanel alignPanel;
173 AlignViewport viewport;
175 ViewportRanges vpRanges;
177 public AlignViewControllerI avc;
179 List<AlignmentPanel> alignPanels = new ArrayList<>();
182 * Last format used to load or save alignments in this window
184 FileFormatI currentFileFormat = null;
187 * Current filename for this alignment
189 String fileName = null;
193 * Creates a new AlignFrame object with specific width and height.
199 public AlignFrame(AlignmentI al, int width, int height)
201 this(al, null, width, height);
205 * Creates a new AlignFrame object with specific width, height and
211 * @param sequenceSetId
213 public AlignFrame(AlignmentI al, int width, int height,
214 String sequenceSetId)
216 this(al, null, width, height, sequenceSetId);
220 * Creates a new AlignFrame object with specific width, height and
226 * @param sequenceSetId
229 public AlignFrame(AlignmentI al, int width, int height,
230 String sequenceSetId, String viewId)
232 this(al, null, width, height, sequenceSetId, viewId);
236 * new alignment window with hidden columns
240 * @param hiddenColumns
241 * ColumnSelection or null
243 * Width of alignment frame
247 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns,
248 int width, int height)
250 this(al, hiddenColumns, width, height, null);
254 * Create alignment frame for al with hiddenColumns, a specific width and
255 * height, and specific sequenceId
258 * @param hiddenColumns
261 * @param sequenceSetId
264 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns,
265 int width, int height, String sequenceSetId)
267 this(al, hiddenColumns, width, height, sequenceSetId, null);
271 * Create alignment frame for al with hiddenColumns, a specific width and
272 * height, and specific sequenceId
275 * @param hiddenColumns
278 * @param sequenceSetId
283 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns,
284 int width, int height, String sequenceSetId, String viewId)
286 setSize(width, height);
288 if (al.getDataset() == null)
293 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
295 alignPanel = new AlignmentPanel(this, viewport);
297 addAlignmentPanel(alignPanel, true);
301 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
302 HiddenColumns hiddenColumns, int width, int height)
304 setSize(width, height);
306 if (al.getDataset() == null)
311 viewport = new AlignViewport(al, hiddenColumns);
313 if (hiddenSeqs != null && hiddenSeqs.length > 0)
315 viewport.hideSequence(hiddenSeqs);
317 alignPanel = new AlignmentPanel(this, viewport);
318 addAlignmentPanel(alignPanel, true);
323 * Make a new AlignFrame from existing alignmentPanels
330 public AlignFrame(AlignmentPanel ap)
334 addAlignmentPanel(ap, false);
339 * initalise the alignframe from the underlying viewport data and the
344 if (!Jalview.isHeadlessMode())
346 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
349 vpRanges = viewport.getRanges();
350 avc = new jalview.controller.AlignViewController(this, viewport,
352 if (viewport.getAlignmentConservationAnnotation() == null)
354 // BLOSUM62Colour.setEnabled(false);
355 conservationMenuItem.setEnabled(false);
356 modifyConservation.setEnabled(false);
357 // PIDColour.setEnabled(false);
358 // abovePIDThreshold.setEnabled(false);
359 // modifyPID.setEnabled(false);
362 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
365 if (sortby.equals("Id"))
367 sortIDMenuItem_actionPerformed(null);
369 else if (sortby.equals("Pairwise Identity"))
371 sortPairwiseMenuItem_actionPerformed(null);
375 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
377 setMenusFromViewport(viewport);
378 buildSortByAnnotationScoresMenu();
379 calculateTree.addActionListener(new ActionListener()
383 public void actionPerformed(ActionEvent e)
391 if (Desktop.desktop != null)
393 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
394 addServiceListeners();
398 if (viewport.getWrapAlignment())
400 wrapMenuItem_actionPerformed(null);
403 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
405 this.overviewMenuItem_actionPerformed(null);
410 final List<AlignmentPanel> selviews = new ArrayList<>();
411 final List<AlignmentPanel> origview = new ArrayList<>();
412 final String menuLabel = MessageManager
413 .getString("label.copy_format_from");
414 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
415 new ViewSetProvider()
419 public AlignmentPanel[] getAllAlignmentPanels()
422 origview.add(alignPanel);
423 // make an array of all alignment panels except for this one
424 List<AlignmentPanel> aps = new ArrayList<>(
425 Arrays.asList(Desktop.getAlignmentPanels(null)));
426 aps.remove(AlignFrame.this.alignPanel);
427 return aps.toArray(new AlignmentPanel[aps.size()]);
429 }, selviews, new ItemListener()
433 public void itemStateChanged(ItemEvent e)
435 if (origview.size() > 0)
437 final AlignmentPanel ap = origview.get(0);
440 * Copy the ViewStyle of the selected panel to 'this one'.
441 * Don't change value of 'scaleProteinAsCdna' unless copying
444 ViewStyleI vs = selviews.get(0).getAlignViewport()
446 boolean fromSplitFrame = selviews.get(0)
447 .getAlignViewport().getCodingComplement() != null;
450 vs.setScaleProteinAsCdna(ap.getAlignViewport()
451 .getViewStyle().isScaleProteinAsCdna());
453 ap.getAlignViewport().setViewStyle(vs);
456 * Also rescale ViewStyle of SplitFrame complement if there is
457 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
458 * the whole ViewStyle (allow cDNA protein to have different
461 AlignViewportI complement = ap.getAlignViewport()
462 .getCodingComplement();
463 if (complement != null && vs.isScaleProteinAsCdna())
465 AlignFrame af = Desktop.getAlignFrameFor(complement);
466 ((SplitFrame) af.getSplitViewContainer())
468 af.setMenusForViewport();
472 ap.setSelected(true);
473 ap.alignFrame.setMenusForViewport();
478 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
479 .indexOf("devel") > -1
480 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
481 .indexOf("test") > -1)
483 formatMenu.add(vsel);
485 addFocusListener(new FocusAdapter()
488 public void focusGained(FocusEvent e)
490 Jalview.setCurrentAlignFrame(AlignFrame.this);
496 private void buildHMMERMenu()
498 hmmerMenu.removeAll();
500 hmmerMenu.add(autoAlignSeqs);
501 hmmerMenu.addSeparator();
503 hmmerMenu.add(hmmAlign);
504 hmmerMenu.add(hmmBuild);
505 hmmerMenu.add(hmmSearch);
510 * Change the filename and format for the alignment, and enable the 'reload'
511 * button functionality.
518 public void setFileName(String file, FileFormatI format)
521 setFileFormat(format);
522 reload.setEnabled(true);
526 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
529 void addKeyListener()
531 addKeyListener(new KeyAdapter()
534 public void keyPressed(KeyEvent evt)
536 if (viewport.cursorMode
537 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
538 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
539 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
540 && Character.isDigit(evt.getKeyChar()))
542 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
545 switch (evt.getKeyCode())
548 case 27: // escape key
549 deselectAllSequenceMenuItem_actionPerformed(null);
553 case KeyEvent.VK_DOWN:
554 if (evt.isAltDown() || !viewport.cursorMode)
556 moveSelectedSequences(false);
558 if (viewport.cursorMode)
560 alignPanel.getSeqPanel().moveCursor(0, 1);
565 if (evt.isAltDown() || !viewport.cursorMode)
567 moveSelectedSequences(true);
569 if (viewport.cursorMode)
571 alignPanel.getSeqPanel().moveCursor(0, -1);
576 case KeyEvent.VK_LEFT:
577 if (evt.isAltDown() || !viewport.cursorMode)
579 slideSequences(false, alignPanel.getSeqPanel().getKeyboardNo1());
583 alignPanel.getSeqPanel().moveCursor(-1, 0);
588 case KeyEvent.VK_RIGHT:
589 if (evt.isAltDown() || !viewport.cursorMode)
591 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
595 alignPanel.getSeqPanel().moveCursor(1, 0);
599 case KeyEvent.VK_SPACE:
600 if (viewport.cursorMode)
602 alignPanel.getSeqPanel().insertGapAtCursor(
603 evt.isControlDown() || evt.isShiftDown()
608 // case KeyEvent.VK_A:
609 // if (viewport.cursorMode)
611 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
612 // //System.out.println("A");
616 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
617 * System.out.println("closing bracket"); } break;
619 case KeyEvent.VK_DELETE:
620 case KeyEvent.VK_BACK_SPACE:
621 if (!viewport.cursorMode)
623 cut_actionPerformed(null);
627 alignPanel.getSeqPanel().deleteGapAtCursor(
628 evt.isControlDown() || evt.isShiftDown()
635 if (viewport.cursorMode)
637 alignPanel.getSeqPanel().setCursorRow();
641 if (viewport.cursorMode && !evt.isControlDown())
643 alignPanel.getSeqPanel().setCursorColumn();
647 if (viewport.cursorMode)
649 alignPanel.getSeqPanel().setCursorPosition();
653 case KeyEvent.VK_ENTER:
654 case KeyEvent.VK_COMMA:
655 if (viewport.cursorMode)
657 alignPanel.getSeqPanel().setCursorRowAndColumn();
662 if (viewport.cursorMode)
664 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
668 if (viewport.cursorMode)
670 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
675 viewport.cursorMode = !viewport.cursorMode;
676 statusBar.setText(MessageManager.formatMessage(
677 "label.keyboard_editing_mode",
678 new String[] { (viewport.cursorMode ? "on" : "off") }));
679 if (viewport.cursorMode)
681 alignPanel.getSeqPanel().seqCanvas.cursorX = vpRanges
683 alignPanel.getSeqPanel().seqCanvas.cursorY = vpRanges
686 alignPanel.getSeqPanel().seqCanvas.repaint();
692 Help.showHelpWindow();
693 } catch (Exception ex)
695 ex.printStackTrace();
700 boolean toggleSeqs = !evt.isControlDown();
701 boolean toggleCols = !evt.isShiftDown();
702 toggleHiddenRegions(toggleSeqs, toggleCols);
707 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
708 boolean modifyExisting = true; // always modify, don't clear
709 // evt.isShiftDown();
710 boolean invertHighlighted = evt.isAltDown();
711 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
715 case KeyEvent.VK_PAGE_UP:
716 if (viewport.getWrapAlignment())
718 vpRanges.scrollUp(true);
725 case KeyEvent.VK_PAGE_DOWN:
726 if (viewport.getWrapAlignment())
728 vpRanges.scrollUp(false);
739 public void keyReleased(KeyEvent evt)
741 switch (evt.getKeyCode())
743 case KeyEvent.VK_LEFT:
744 if (evt.isAltDown() || !viewport.cursorMode)
746 viewport.firePropertyChange("alignment", null, viewport
747 .getAlignment().getSequences());
751 case KeyEvent.VK_RIGHT:
752 if (evt.isAltDown() || !viewport.cursorMode)
754 viewport.firePropertyChange("alignment", null, viewport
755 .getAlignment().getSequences());
763 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
765 ap.alignFrame = this;
766 avc = new jalview.controller.AlignViewController(this, viewport,
771 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
773 int aSize = alignPanels.size();
775 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
777 if (aSize == 1 && ap.av.viewName == null)
779 this.getContentPane().add(ap, BorderLayout.CENTER);
785 setInitialTabVisible();
788 expandViews.setEnabled(true);
789 gatherViews.setEnabled(true);
790 tabbedPane.addTab(ap.av.viewName, ap);
792 ap.setVisible(false);
797 if (ap.av.isPadGaps())
799 ap.av.getAlignment().padGaps();
801 ap.av.updateConservation(ap);
802 ap.av.updateConsensus(ap);
803 ap.av.updateStrucConsensus(ap);
804 ap.av.updateInformation(ap);
808 public void setInitialTabVisible()
810 expandViews.setEnabled(true);
811 gatherViews.setEnabled(true);
812 tabbedPane.setVisible(true);
813 AlignmentPanel first = alignPanels.get(0);
814 tabbedPane.addTab(first.av.viewName, first);
815 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
818 public AlignViewport getViewport()
823 /* Set up intrinsic listeners for dynamically generated GUI bits. */
824 private void addServiceListeners()
826 final java.beans.PropertyChangeListener thisListener;
827 Desktop.instance.addJalviewPropertyChangeListener("services",
828 thisListener = new java.beans.PropertyChangeListener()
831 public void propertyChange(PropertyChangeEvent evt)
833 // // System.out.println("Discoverer property change.");
834 // if (evt.getPropertyName().equals("services"))
836 SwingUtilities.invokeLater(new Runnable()
843 .println("Rebuild WS Menu for service change");
844 BuildWebServiceMenu();
851 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
854 public void internalFrameClosed(
855 javax.swing.event.InternalFrameEvent evt)
857 // System.out.println("deregistering discoverer listener");
858 Desktop.instance.removeJalviewPropertyChangeListener("services",
860 closeMenuItem_actionPerformed(true);
863 // Finally, build the menu once to get current service state
864 new Thread(new Runnable()
869 BuildWebServiceMenu();
875 * Configure menu items that vary according to whether the alignment is
876 * nucleotide or protein
878 public void setGUINucleotide()
880 AlignmentI al = getViewport().getAlignment();
881 boolean nucleotide = al.isNucleotide();
883 showTranslation.setVisible(nucleotide);
884 showReverse.setVisible(nucleotide);
885 showReverseComplement.setVisible(nucleotide);
886 conservationMenuItem.setEnabled(!nucleotide);
887 modifyConservation.setEnabled(!nucleotide
888 && conservationMenuItem.isSelected());
889 showGroupConservation.setEnabled(!nucleotide);
891 showComplementMenuItem.setText(nucleotide ? MessageManager
892 .getString("label.protein") : MessageManager
893 .getString("label.nucleotide"));
897 * set up menus for the current viewport. This may be called after any
898 * operation that affects the data in the current view (selection changed,
899 * etc) to update the menus to reflect the new state.
902 public void setMenusForViewport()
904 setMenusFromViewport(viewport);
908 * Need to call this method when tabs are selected for multiple views, or when
909 * loading from Jalview2XML.java
914 void setMenusFromViewport(AlignViewport av)
916 padGapsMenuitem.setSelected(av.isPadGaps());
917 colourTextMenuItem.setSelected(av.isShowColourText());
918 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
919 modifyPID.setEnabled(abovePIDThreshold.isSelected());
920 conservationMenuItem.setSelected(av.getConservationSelected());
921 modifyConservation.setEnabled(conservationMenuItem.isSelected());
922 seqLimits.setSelected(av.getShowJVSuffix());
923 idRightAlign.setSelected(av.isRightAlignIds());
924 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
925 renderGapsMenuItem.setSelected(av.isRenderGaps());
926 wrapMenuItem.setSelected(av.getWrapAlignment());
927 scaleAbove.setVisible(av.getWrapAlignment());
928 scaleLeft.setVisible(av.getWrapAlignment());
929 scaleRight.setVisible(av.getWrapAlignment());
930 annotationPanelMenuItem.setState(av.isShowAnnotation());
932 * Show/hide annotations only enabled if annotation panel is shown
934 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
935 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
936 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
937 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
938 viewBoxesMenuItem.setSelected(av.getShowBoxes());
939 viewTextMenuItem.setSelected(av.getShowText());
940 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
941 showGroupConsensus.setSelected(av.isShowGroupConsensus());
942 showGroupConservation.setSelected(av.isShowGroupConservation());
943 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
944 showSequenceLogo.setSelected(av.isShowSequenceLogo());
945 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
946 showInformationHistogram.setSelected(av.isShowInformationHistogram());
947 showHMMSequenceLogo.setSelected(av.isShowHMMSequenceLogo());
948 normaliseHMMSequenceLogo.setSelected(av.isNormaliseHMMSequenceLogo());
950 ColourMenuHelper.setColourSelected(colourMenu,
951 av.getGlobalColourScheme());
953 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
954 hiddenMarkers.setState(av.getShowHiddenMarkers());
955 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
956 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
957 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
958 autoCalculate.setSelected(av.autoCalculateConsensus);
959 sortByTree.setSelected(av.sortByTree);
960 listenToViewSelections.setSelected(av.followSelection);
962 showProducts.setEnabled(canShowProducts());
963 setGroovyEnabled(Desktop.getGroovyConsole() != null);
969 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
973 public void setGroovyEnabled(boolean b)
975 runGroovy.setEnabled(b);
978 private IProgressIndicator progressBar;
983 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
986 public void setProgressBar(String message, long id)
988 progressBar.setProgressBar(message, id);
992 public void registerHandler(final long id,
993 final IProgressIndicatorHandler handler)
995 progressBar.registerHandler(id, handler);
1000 * @return true if any progress bars are still active
1003 public boolean operationInProgress()
1005 return progressBar.operationInProgress();
1009 public void setStatus(String text)
1011 statusBar.setText(text);
1015 * Added so Castor Mapping file can obtain Jalview Version
1017 public String getVersion()
1019 return jalview.bin.Cache.getProperty("VERSION");
1022 public FeatureRenderer getFeatureRenderer()
1024 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1028 public void fetchSequence_actionPerformed(ActionEvent e)
1030 new jalview.gui.SequenceFetcher(this);
1034 public void addFromFile_actionPerformed(ActionEvent e)
1036 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1040 public void hmmBuild_actionPerformed(ActionEvent e)
1041 throws IOException, InterruptedException
1044 HMMERCommands.hmmBuild(this);
1045 alignPanel.repaint();
1050 public void hmmAlign_actionPerformed(ActionEvent e)
1051 throws IOException, InterruptedException
1053 HMMERCommands.hmmAlign(this);
1054 alignPanel.repaint();
1058 public void hmmSearch_actionPerformed(ActionEvent e)
1061 alignPanel.repaint();
1065 public void reload_actionPerformed(ActionEvent e)
1067 if (fileName != null)
1069 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1070 // originating file's format
1071 // TODO: work out how to recover feature settings for correct view(s) when
1072 // file is reloaded.
1073 if (FileFormat.Jalview.equals(currentFileFormat))
1075 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1076 for (int i = 0; i < frames.length; i++)
1078 if (frames[i] instanceof AlignFrame && frames[i] != this
1079 && ((AlignFrame) frames[i]).fileName != null
1080 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1084 frames[i].setSelected(true);
1085 Desktop.instance.closeAssociatedWindows();
1086 } catch (java.beans.PropertyVetoException ex)
1092 Desktop.instance.closeAssociatedWindows();
1094 FileLoader loader = new FileLoader();
1095 DataSourceType protocol = fileName.startsWith("http:") ? DataSourceType.URL
1096 : DataSourceType.FILE;
1097 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1101 Rectangle bounds = this.getBounds();
1103 FileLoader loader = new FileLoader();
1104 DataSourceType protocol = fileName.startsWith("http:") ? DataSourceType.URL
1105 : DataSourceType.FILE;
1106 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1107 protocol, currentFileFormat);
1109 newframe.setBounds(bounds);
1110 if (featureSettings != null && featureSettings.isShowing())
1112 final Rectangle fspos = featureSettings.frame.getBounds();
1113 // TODO: need a 'show feature settings' function that takes bounds -
1114 // need to refactor Desktop.addFrame
1115 newframe.featureSettings_actionPerformed(null);
1116 final FeatureSettings nfs = newframe.featureSettings;
1117 SwingUtilities.invokeLater(new Runnable()
1122 nfs.frame.setBounds(fspos);
1125 this.featureSettings.close();
1126 this.featureSettings = null;
1128 this.closeMenuItem_actionPerformed(true);
1134 public void addFromText_actionPerformed(ActionEvent e)
1136 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport
1141 public void addFromURL_actionPerformed(ActionEvent e)
1143 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1147 public void save_actionPerformed(ActionEvent e)
1149 if (fileName == null || (currentFileFormat == null)
1150 || fileName.startsWith("http"))
1152 saveAs_actionPerformed(null);
1156 saveAlignment(fileName, currentFileFormat);
1167 public void saveAs_actionPerformed(ActionEvent e)
1169 String format = currentFileFormat == null ? null : currentFileFormat
1171 JalviewFileChooser chooser = JalviewFileChooser.forWrite(
1172 Cache.getProperty("LAST_DIRECTORY"), format);
1174 chooser.setFileView(new JalviewFileView());
1175 chooser.setDialogTitle(MessageManager
1176 .getString("label.save_alignment_to_file"));
1177 chooser.setToolTipText(MessageManager.getString("action.save"));
1179 int value = chooser.showSaveDialog(this);
1181 if (value == JalviewFileChooser.APPROVE_OPTION)
1183 currentFileFormat = chooser.getSelectedFormat();
1184 while (currentFileFormat == null)
1187 .showInternalMessageDialog(
1190 .getString("label.select_file_format_before_saving"),
1192 .getString("label.file_format_not_specified"),
1193 JvOptionPane.WARNING_MESSAGE);
1194 currentFileFormat = chooser.getSelectedFormat();
1195 value = chooser.showSaveDialog(this);
1196 if (value != JalviewFileChooser.APPROVE_OPTION)
1202 fileName = chooser.getSelectedFile().getPath();
1204 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1206 Cache.setProperty("LAST_DIRECTORY", fileName);
1207 saveAlignment(fileName, currentFileFormat);
1211 public boolean saveAlignment(String file, FileFormatI format)
1213 boolean success = true;
1215 if (FileFormat.Jalview.equals(format))
1217 String shortName = title;
1219 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1221 shortName = shortName.substring(shortName
1222 .lastIndexOf(java.io.File.separatorChar) + 1);
1225 success = new Jalview2XML().saveAlignment(this, file, shortName);
1227 statusBar.setText(MessageManager.formatMessage(
1228 "label.successfully_saved_to_file_in_format", new Object[] {
1229 fileName, format }));
1234 AlignmentExportData exportData = getAlignmentForExport(format,
1236 if (exportData.getSettings().isCancelled())
1240 FormatAdapter f = new FormatAdapter(alignPanel,
1241 exportData.getSettings());
1242 String output = f.formatSequences(
1244 exportData.getAlignment(), // class cast exceptions will
1245 // occur in the distant future
1246 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1247 f.getCacheSuffixDefault(format), viewport.getAlignment()
1248 .getHiddenColumns());
1258 PrintWriter out = new PrintWriter(new FileWriter(file));
1262 this.setTitle(file);
1263 statusBar.setText(MessageManager.formatMessage(
1264 "label.successfully_saved_to_file_in_format",
1265 new Object[] { fileName, format.getName() }));
1266 } catch (Exception ex)
1269 ex.printStackTrace();
1276 JvOptionPane.showInternalMessageDialog(this, MessageManager
1277 .formatMessage("label.couldnt_save_file",
1278 new Object[] { fileName }), MessageManager
1279 .getString("label.error_saving_file"),
1280 JvOptionPane.WARNING_MESSAGE);
1286 private void warningMessage(String warning, String title)
1288 if (new jalview.util.Platform().isHeadless())
1290 System.err.println("Warning: " + title + "\nWarning: " + warning);
1295 JvOptionPane.showInternalMessageDialog(this, warning, title,
1296 JvOptionPane.WARNING_MESSAGE);
1308 protected void outputText_actionPerformed(ActionEvent e)
1310 FileFormatI fileFormat = FileFormats.getInstance().forName(
1311 e.getActionCommand());
1312 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1314 if (exportData.getSettings().isCancelled())
1318 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1319 cap.setForInput(null);
1322 FileFormatI format = fileFormat;
1323 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1324 .formatSequences(format, exportData.getAlignment(),
1325 exportData.getOmitHidden(),
1327 .getStartEndPostions(), viewport
1328 .getAlignment().getHiddenColumns()));
1329 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1330 "label.alignment_output_command",
1331 new Object[] { e.getActionCommand() }), 600, 500);
1332 } catch (OutOfMemoryError oom)
1334 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1340 public static AlignmentExportData getAlignmentForExport(
1341 FileFormatI format, AlignViewportI viewport,
1342 AlignExportSettingI exportSettings)
1344 AlignmentI alignmentToExport = null;
1345 AlignExportSettingI settings = exportSettings;
1346 String[] omitHidden = null;
1348 HiddenSequences hiddenSeqs = viewport.getAlignment()
1349 .getHiddenSequences();
1351 alignmentToExport = viewport.getAlignment();
1353 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1354 if (settings == null)
1356 settings = new AlignExportSettings(hasHiddenSeqs,
1357 viewport.hasHiddenColumns(), format);
1359 // settings.isExportAnnotations();
1361 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1363 omitHidden = viewport.getViewAsString(false,
1364 settings.isExportHiddenSequences());
1367 int[] alignmentStartEnd = new int[2];
1368 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1370 alignmentToExport = hiddenSeqs.getFullAlignment();
1374 alignmentToExport = viewport.getAlignment();
1376 alignmentStartEnd = alignmentToExport
1377 .getVisibleStartAndEndIndex(viewport.getAlignment()
1379 .getHiddenRegions());
1380 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1381 omitHidden, alignmentStartEnd, settings);
1392 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1394 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1395 htmlSVG.exportHTML(null);
1399 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1401 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1402 bjs.exportHTML(null);
1405 public void createImageMap(File file, String image)
1407 alignPanel.makePNGImageMap(file, image);
1417 public void createPNG(File f)
1419 alignPanel.makePNG(f);
1429 public void createEPS(File f)
1431 alignPanel.makeEPS(f);
1435 public void createSVG(File f)
1437 alignPanel.makeSVG(f);
1441 public void pageSetup_actionPerformed(ActionEvent e)
1443 PrinterJob printJob = PrinterJob.getPrinterJob();
1444 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1454 public void printMenuItem_actionPerformed(ActionEvent e)
1456 // Putting in a thread avoids Swing painting problems
1457 PrintThread thread = new PrintThread(alignPanel);
1462 public void exportFeatures_actionPerformed(ActionEvent e)
1464 new AnnotationExporter().exportFeatures(alignPanel);
1468 public void exportAnnotations_actionPerformed(ActionEvent e)
1470 new AnnotationExporter().exportAnnotations(alignPanel);
1474 public void associatedData_actionPerformed(ActionEvent e)
1476 // Pick the tree file
1477 JalviewFileChooser chooser = new JalviewFileChooser(
1478 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1479 chooser.setFileView(new JalviewFileView());
1480 chooser.setDialogTitle(MessageManager
1481 .getString("label.load_jalview_annotations"));
1482 chooser.setToolTipText(MessageManager
1483 .getString("label.load_jalview_annotations"));
1485 int value = chooser.showOpenDialog(null);
1487 if (value == JalviewFileChooser.APPROVE_OPTION)
1489 String choice = chooser.getSelectedFile().getPath();
1490 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1491 loadJalviewDataFile(choice, null, null, null);
1497 * Close the current view or all views in the alignment frame. If the frame
1498 * only contains one view then the alignment will be removed from memory.
1500 * @param closeAllTabs
1503 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1505 if (alignPanels != null && alignPanels.size() < 2)
1507 closeAllTabs = true;
1512 if (alignPanels != null)
1516 if (this.isClosed())
1518 // really close all the windows - otherwise wait till
1519 // setClosed(true) is called
1520 for (int i = 0; i < alignPanels.size(); i++)
1522 AlignmentPanel ap = alignPanels.get(i);
1529 closeView(alignPanel);
1536 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1537 * be called recursively, with the frame now in 'closed' state
1539 this.setClosed(true);
1541 } catch (Exception ex)
1543 ex.printStackTrace();
1548 * Close the specified panel and close up tabs appropriately.
1550 * @param panelToClose
1552 public void closeView(AlignmentPanel panelToClose)
1554 int index = tabbedPane.getSelectedIndex();
1555 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1556 alignPanels.remove(panelToClose);
1557 panelToClose.closePanel();
1558 panelToClose = null;
1560 tabbedPane.removeTabAt(closedindex);
1561 tabbedPane.validate();
1563 if (index > closedindex || index == tabbedPane.getTabCount())
1565 // modify currently selected tab index if necessary.
1569 this.tabSelectionChanged(index);
1575 void updateEditMenuBar()
1578 if (viewport.getHistoryList().size() > 0)
1580 undoMenuItem.setEnabled(true);
1581 CommandI command = viewport.getHistoryList().peek();
1582 undoMenuItem.setText(MessageManager.formatMessage(
1583 "label.undo_command",
1584 new Object[] { command.getDescription() }));
1588 undoMenuItem.setEnabled(false);
1589 undoMenuItem.setText(MessageManager.getString("action.undo"));
1592 if (viewport.getRedoList().size() > 0)
1594 redoMenuItem.setEnabled(true);
1596 CommandI command = viewport.getRedoList().peek();
1597 redoMenuItem.setText(MessageManager.formatMessage(
1598 "label.redo_command",
1599 new Object[] { command.getDescription() }));
1603 redoMenuItem.setEnabled(false);
1604 redoMenuItem.setText(MessageManager.getString("action.redo"));
1609 public void addHistoryItem(CommandI command)
1611 if (command.getSize() > 0)
1613 viewport.addToHistoryList(command);
1614 viewport.clearRedoList();
1615 updateEditMenuBar();
1616 viewport.updateHiddenColumns();
1617 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1618 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1619 // viewport.getColumnSelection()
1620 // .getHiddenColumns().size() > 0);
1626 * @return alignment objects for all views
1628 AlignmentI[] getViewAlignments()
1630 if (alignPanels != null)
1632 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1634 for (AlignmentPanel ap : alignPanels)
1636 als[i++] = ap.av.getAlignment();
1640 if (viewport != null)
1642 return new AlignmentI[] { viewport.getAlignment() };
1654 protected void undoMenuItem_actionPerformed(ActionEvent e)
1656 if (viewport.getHistoryList().isEmpty())
1660 CommandI command = viewport.getHistoryList().pop();
1661 viewport.addToRedoList(command);
1662 command.undoCommand(getViewAlignments());
1664 AlignmentViewport originalSource = getOriginatingSource(command);
1665 updateEditMenuBar();
1667 if (originalSource != null)
1669 if (originalSource != viewport)
1672 .warn("Implementation worry: mismatch of viewport origin for undo");
1674 originalSource.updateHiddenColumns();
1675 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1677 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1678 // viewport.getColumnSelection()
1679 // .getHiddenColumns().size() > 0);
1680 originalSource.firePropertyChange("alignment", null, originalSource
1681 .getAlignment().getSequences());
1692 protected void redoMenuItem_actionPerformed(ActionEvent e)
1694 if (viewport.getRedoList().size() < 1)
1699 CommandI command = viewport.getRedoList().pop();
1700 viewport.addToHistoryList(command);
1701 command.doCommand(getViewAlignments());
1703 AlignmentViewport originalSource = getOriginatingSource(command);
1704 updateEditMenuBar();
1706 if (originalSource != null)
1709 if (originalSource != viewport)
1712 .warn("Implementation worry: mismatch of viewport origin for redo");
1714 originalSource.updateHiddenColumns();
1715 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1717 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1718 // viewport.getColumnSelection()
1719 // .getHiddenColumns().size() > 0);
1720 originalSource.firePropertyChange("alignment", null, originalSource
1721 .getAlignment().getSequences());
1725 AlignmentViewport getOriginatingSource(CommandI command)
1727 AlignmentViewport originalSource = null;
1728 // For sequence removal and addition, we need to fire
1729 // the property change event FROM the viewport where the
1730 // original alignment was altered
1731 AlignmentI al = null;
1732 if (command instanceof EditCommand)
1734 EditCommand editCommand = (EditCommand) command;
1735 al = editCommand.getAlignment();
1736 List<Component> comps = PaintRefresher.components.get(viewport
1737 .getSequenceSetId());
1739 for (Component comp : comps)
1741 if (comp instanceof AlignmentPanel)
1743 if (al == ((AlignmentPanel) comp).av.getAlignment())
1745 originalSource = ((AlignmentPanel) comp).av;
1752 if (originalSource == null)
1754 // The original view is closed, we must validate
1755 // the current view against the closed view first
1758 PaintRefresher.validateSequences(al, viewport.getAlignment());
1761 originalSource = viewport;
1764 return originalSource;
1773 public void moveSelectedSequences(boolean up)
1775 SequenceGroup sg = viewport.getSelectionGroup();
1781 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1782 viewport.getHiddenRepSequences(), up);
1783 alignPanel.paintAlignment(true);
1786 synchronized void slideSequences(boolean right, int size)
1788 List<SequenceI> sg = new ArrayList<>();
1789 if (viewport.cursorMode)
1791 sg.add(viewport.getAlignment().getSequenceAt(
1792 alignPanel.getSeqPanel().seqCanvas.cursorY));
1794 else if (viewport.getSelectionGroup() != null
1795 && viewport.getSelectionGroup().getSize() != viewport
1796 .getAlignment().getHeight())
1798 sg = viewport.getSelectionGroup().getSequences(
1799 viewport.getHiddenRepSequences());
1807 List<SequenceI> invertGroup = new ArrayList<>();
1809 for (SequenceI seq : viewport.getAlignment().getSequences())
1811 if (!sg.contains(seq))
1813 invertGroup.add(seq);
1817 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1819 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1820 for (int i = 0; i < invertGroup.size(); i++)
1822 seqs2[i] = invertGroup.get(i);
1825 SlideSequencesCommand ssc;
1828 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1829 size, viewport.getGapCharacter());
1833 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1834 size, viewport.getGapCharacter());
1837 int groupAdjustment = 0;
1838 if (ssc.getGapsInsertedBegin() && right)
1840 if (viewport.cursorMode)
1842 alignPanel.getSeqPanel().moveCursor(size, 0);
1846 groupAdjustment = size;
1849 else if (!ssc.getGapsInsertedBegin() && !right)
1851 if (viewport.cursorMode)
1853 alignPanel.getSeqPanel().moveCursor(-size, 0);
1857 groupAdjustment = -size;
1861 if (groupAdjustment != 0)
1863 viewport.getSelectionGroup().setStartRes(
1864 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1865 viewport.getSelectionGroup().setEndRes(
1866 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1870 * just extend the last slide command if compatible; but not if in
1871 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1873 boolean appendHistoryItem = false;
1874 Deque<CommandI> historyList = viewport.getHistoryList();
1875 boolean inSplitFrame = getSplitViewContainer() != null;
1876 if (!inSplitFrame && historyList != null && historyList.size() > 0
1877 && historyList.peek() instanceof SlideSequencesCommand)
1879 appendHistoryItem = ssc
1880 .appendSlideCommand((SlideSequencesCommand) historyList
1884 if (!appendHistoryItem)
1886 addHistoryItem(ssc);
1899 protected void copy_actionPerformed(ActionEvent e)
1902 if (viewport.getSelectionGroup() == null)
1906 // TODO: preserve the ordering of displayed alignment annotation in any
1907 // internal paste (particularly sequence associated annotation)
1908 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1909 String[] omitHidden = null;
1911 if (viewport.hasHiddenColumns())
1913 omitHidden = viewport.getViewAsString(true);
1916 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1917 seqs, omitHidden, null);
1919 StringSelection ss = new StringSelection(output);
1923 jalview.gui.Desktop.internalCopy = true;
1924 // Its really worth setting the clipboard contents
1925 // to empty before setting the large StringSelection!!
1926 Toolkit.getDefaultToolkit().getSystemClipboard()
1927 .setContents(new StringSelection(""), null);
1929 Toolkit.getDefaultToolkit().getSystemClipboard()
1930 .setContents(ss, Desktop.instance);
1931 } catch (OutOfMemoryError er)
1933 new OOMWarning("copying region", er);
1937 ArrayList<int[]> hiddenColumns = null;
1938 if (viewport.hasHiddenColumns())
1940 hiddenColumns = new ArrayList<>();
1941 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1942 .getSelectionGroup().getEndRes();
1943 for (int[] region : viewport.getAlignment().getHiddenColumns()
1944 .getHiddenRegions())
1946 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1948 hiddenColumns.add(new int[] { region[0] - hiddenOffset,
1949 region[1] - hiddenOffset });
1954 Desktop.jalviewClipboard = new Object[] { seqs,
1955 viewport.getAlignment().getDataset(), hiddenColumns };
1956 statusBar.setText(MessageManager.formatMessage(
1957 "label.copied_sequences_to_clipboard", new Object[] { Integer
1958 .valueOf(seqs.length).toString() }));
1968 protected void pasteNew_actionPerformed(ActionEvent e)
1980 protected void pasteThis_actionPerformed(ActionEvent e)
1986 * Paste contents of Jalview clipboard
1988 * @param newAlignment
1989 * true to paste to a new alignment, otherwise add to this.
1991 void paste(boolean newAlignment)
1993 boolean externalPaste = true;
1996 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1997 Transferable contents = c.getContents(this);
1999 if (contents == null)
2008 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2009 if (str.length() < 1)
2014 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2016 } catch (OutOfMemoryError er)
2018 new OOMWarning("Out of memory pasting sequences!!", er);
2022 SequenceI[] sequences;
2023 boolean annotationAdded = false;
2024 AlignmentI alignment = null;
2026 if (Desktop.jalviewClipboard != null)
2028 // The clipboard was filled from within Jalview, we must use the
2030 // And dataset from the copied alignment
2031 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2032 // be doubly sure that we create *new* sequence objects.
2033 sequences = new SequenceI[newseq.length];
2034 for (int i = 0; i < newseq.length; i++)
2036 sequences[i] = new Sequence(newseq[i]);
2038 alignment = new Alignment(sequences);
2039 externalPaste = false;
2043 // parse the clipboard as an alignment.
2044 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2046 sequences = alignment.getSequencesArray();
2050 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2056 if (Desktop.jalviewClipboard != null)
2058 // dataset is inherited
2059 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2063 // new dataset is constructed
2064 alignment.setDataset(null);
2066 alwidth = alignment.getWidth() + 1;
2070 AlignmentI pastedal = alignment; // preserve pasted alignment object
2071 // Add pasted sequences and dataset into existing alignment.
2072 alignment = viewport.getAlignment();
2073 alwidth = alignment.getWidth() + 1;
2074 // decide if we need to import sequences from an existing dataset
2075 boolean importDs = Desktop.jalviewClipboard != null
2076 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2077 // importDs==true instructs us to copy over new dataset sequences from
2078 // an existing alignment
2079 Vector newDs = (importDs) ? new Vector() : null; // used to create
2080 // minimum dataset set
2082 for (int i = 0; i < sequences.length; i++)
2086 newDs.addElement(null);
2088 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2090 if (importDs && ds != null)
2092 if (!newDs.contains(ds))
2094 newDs.setElementAt(ds, i);
2095 ds = new Sequence(ds);
2096 // update with new dataset sequence
2097 sequences[i].setDatasetSequence(ds);
2101 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2106 // copy and derive new dataset sequence
2107 sequences[i] = sequences[i].deriveSequence();
2108 alignment.getDataset().addSequence(
2109 sequences[i].getDatasetSequence());
2110 // TODO: avoid creation of duplicate dataset sequences with a
2111 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2113 alignment.addSequence(sequences[i]); // merges dataset
2117 newDs.clear(); // tidy up
2119 if (alignment.getAlignmentAnnotation() != null)
2121 for (AlignmentAnnotation alan : alignment
2122 .getAlignmentAnnotation())
2124 if (alan.graphGroup > fgroup)
2126 fgroup = alan.graphGroup;
2130 if (pastedal.getAlignmentAnnotation() != null)
2132 // Add any annotation attached to alignment.
2133 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2134 for (int i = 0; i < alann.length; i++)
2136 annotationAdded = true;
2137 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2139 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2140 if (newann.graphGroup > -1)
2142 if (newGraphGroups.size() <= newann.graphGroup
2143 || newGraphGroups.get(newann.graphGroup) == null)
2145 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2147 newGraphGroups.add(q, null);
2149 newGraphGroups.set(newann.graphGroup, new Integer(
2152 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2156 newann.padAnnotation(alwidth);
2157 alignment.addAnnotation(newann);
2167 addHistoryItem(new EditCommand(
2168 MessageManager.getString("label.add_sequences"),
2169 Action.PASTE, sequences, 0, alignment.getWidth(), alignment));
2171 // Add any annotations attached to sequences
2172 for (int i = 0; i < sequences.length; i++)
2174 if (sequences[i].getAnnotation() != null)
2176 AlignmentAnnotation newann;
2177 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2179 annotationAdded = true;
2180 newann = sequences[i].getAnnotation()[a];
2181 newann.adjustForAlignment();
2182 newann.padAnnotation(alwidth);
2183 if (newann.graphGroup > -1)
2185 if (newann.graphGroup > -1)
2187 if (newGraphGroups.size() <= newann.graphGroup
2188 || newGraphGroups.get(newann.graphGroup) == null)
2190 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2192 newGraphGroups.add(q, null);
2194 newGraphGroups.set(newann.graphGroup, new Integer(
2197 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2201 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2206 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2213 // propagate alignment changed.
2214 vpRanges.setEndSeq(alignment.getHeight());
2215 if (annotationAdded)
2217 // Duplicate sequence annotation in all views.
2218 AlignmentI[] alview = this.getViewAlignments();
2219 for (int i = 0; i < sequences.length; i++)
2221 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2226 for (int avnum = 0; avnum < alview.length; avnum++)
2228 if (alview[avnum] != alignment)
2230 // duplicate in a view other than the one with input focus
2231 int avwidth = alview[avnum].getWidth() + 1;
2232 // this relies on sann being preserved after we
2233 // modify the sequence's annotation array for each duplication
2234 for (int a = 0; a < sann.length; a++)
2236 AlignmentAnnotation newann = new AlignmentAnnotation(
2238 sequences[i].addAlignmentAnnotation(newann);
2239 newann.padAnnotation(avwidth);
2240 alview[avnum].addAnnotation(newann); // annotation was
2241 // duplicated earlier
2242 // TODO JAL-1145 graphGroups are not updated for sequence
2243 // annotation added to several views. This may cause
2245 alview[avnum].setAnnotationIndex(newann, a);
2250 buildSortByAnnotationScoresMenu();
2252 viewport.firePropertyChange("alignment", null,
2253 alignment.getSequences());
2254 if (alignPanels != null)
2256 for (AlignmentPanel ap : alignPanels)
2258 ap.validateAnnotationDimensions(false);
2263 alignPanel.validateAnnotationDimensions(false);
2269 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2271 String newtitle = new String("Copied sequences");
2273 if (Desktop.jalviewClipboard != null
2274 && Desktop.jalviewClipboard[2] != null)
2276 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2277 for (int[] region : hc)
2279 af.viewport.hideColumns(region[0], region[1]);
2283 // >>>This is a fix for the moment, until a better solution is
2285 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2287 alignPanel.getSeqPanel().seqCanvas
2288 .getFeatureRenderer());
2290 // TODO: maintain provenance of an alignment, rather than just make the
2291 // title a concatenation of operations.
2294 if (title.startsWith("Copied sequences"))
2300 newtitle = newtitle.concat("- from " + title);
2305 newtitle = new String("Pasted sequences");
2308 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2313 } catch (Exception ex)
2315 ex.printStackTrace();
2316 System.out.println("Exception whilst pasting: " + ex);
2317 // could be anything being pasted in here
2323 protected void expand_newalign(ActionEvent e)
2327 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2328 .getAlignment(), -1);
2329 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2331 String newtitle = new String("Flanking alignment");
2333 if (Desktop.jalviewClipboard != null
2334 && Desktop.jalviewClipboard[2] != null)
2336 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2337 for (int region[] : hc)
2339 af.viewport.hideColumns(region[0], region[1]);
2343 // >>>This is a fix for the moment, until a better solution is
2345 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2347 alignPanel.getSeqPanel().seqCanvas
2348 .getFeatureRenderer());
2350 // TODO: maintain provenance of an alignment, rather than just make the
2351 // title a concatenation of operations.
2353 if (title.startsWith("Copied sequences"))
2359 newtitle = newtitle.concat("- from " + title);
2363 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2365 } catch (Exception ex)
2367 ex.printStackTrace();
2368 System.out.println("Exception whilst pasting: " + ex);
2369 // could be anything being pasted in here
2370 } catch (OutOfMemoryError oom)
2372 new OOMWarning("Viewing flanking region of alignment", oom);
2383 protected void cut_actionPerformed(ActionEvent e)
2385 copy_actionPerformed(null);
2386 delete_actionPerformed(null);
2396 protected void delete_actionPerformed(ActionEvent evt)
2399 SequenceGroup sg = viewport.getSelectionGroup();
2406 * If the cut affects all sequences, warn, remove highlighted columns
2408 if (sg.getSize() == viewport.getAlignment().getHeight())
2410 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes()) + 1) == viewport
2411 .getAlignment().getWidth()) ? true : false;
2412 if (isEntireAlignWidth)
2414 int confirm = JvOptionPane.showConfirmDialog(this,
2415 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2416 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2417 JvOptionPane.OK_CANCEL_OPTION);
2419 if (confirm == JvOptionPane.CANCEL_OPTION
2420 || confirm == JvOptionPane.CLOSED_OPTION)
2425 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2426 sg.getEndRes() + 1);
2428 SequenceI[] cut = sg.getSequences()
2429 .toArray(new SequenceI[sg.getSize()]);
2431 addHistoryItem(new EditCommand(
2432 MessageManager.getString("label.cut_sequences"), Action.CUT,
2433 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2434 viewport.getAlignment()));
2436 viewport.setSelectionGroup(null);
2437 viewport.sendSelection();
2438 viewport.getAlignment().deleteGroup(sg);
2440 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2442 if (viewport.getAlignment().getHeight() < 1)
2446 this.setClosed(true);
2447 } catch (Exception ex)
2460 protected void deleteGroups_actionPerformed(ActionEvent e)
2462 if (avc.deleteGroups())
2464 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2465 alignPanel.updateAnnotation();
2466 alignPanel.paintAlignment(true);
2477 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2479 SequenceGroup sg = new SequenceGroup();
2481 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2483 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2486 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2487 viewport.setSelectionGroup(sg);
2488 viewport.sendSelection();
2489 // JAL-2034 - should delegate to
2490 // alignPanel to decide if overview needs
2492 alignPanel.paintAlignment(false);
2493 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2503 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2505 if (viewport.cursorMode)
2507 alignPanel.getSeqPanel().keyboardNo1 = null;
2508 alignPanel.getSeqPanel().keyboardNo2 = null;
2510 viewport.setSelectionGroup(null);
2511 viewport.getColumnSelection().clear();
2512 viewport.setSelectionGroup(null);
2513 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2514 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2515 // JAL-2034 - should delegate to
2516 // alignPanel to decide if overview needs
2518 alignPanel.paintAlignment(false);
2519 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2520 viewport.sendSelection();
2530 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2532 SequenceGroup sg = viewport.getSelectionGroup();
2536 selectAllSequenceMenuItem_actionPerformed(null);
2541 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2543 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2545 // JAL-2034 - should delegate to
2546 // alignPanel to decide if overview needs
2549 alignPanel.paintAlignment(true);
2550 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2551 viewport.sendSelection();
2555 public void invertColSel_actionPerformed(ActionEvent e)
2557 viewport.invertColumnSelection();
2558 alignPanel.paintAlignment(true);
2559 viewport.sendSelection();
2569 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2571 trimAlignment(true);
2581 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2583 trimAlignment(false);
2586 void trimAlignment(boolean trimLeft)
2588 ColumnSelection colSel = viewport.getColumnSelection();
2591 if (!colSel.isEmpty())
2595 column = colSel.getMin();
2599 column = colSel.getMax();
2603 if (viewport.getSelectionGroup() != null)
2605 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2606 viewport.getHiddenRepSequences());
2610 seqs = viewport.getAlignment().getSequencesArray();
2613 TrimRegionCommand trimRegion;
2616 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2617 column, viewport.getAlignment());
2618 vpRanges.setStartRes(0);
2622 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2623 column, viewport.getAlignment());
2626 statusBar.setText(MessageManager.formatMessage(
2627 "label.removed_columns",
2628 new String[] { Integer.valueOf(trimRegion.getSize())
2631 addHistoryItem(trimRegion);
2633 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2635 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2636 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2638 viewport.getAlignment().deleteGroup(sg);
2642 viewport.firePropertyChange("alignment", null, viewport
2643 .getAlignment().getSequences());
2654 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2656 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2659 if (viewport.getSelectionGroup() != null)
2661 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2662 viewport.getHiddenRepSequences());
2663 start = viewport.getSelectionGroup().getStartRes();
2664 end = viewport.getSelectionGroup().getEndRes();
2668 seqs = viewport.getAlignment().getSequencesArray();
2671 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2672 "Remove Gapped Columns", seqs, start, end,
2673 viewport.getAlignment());
2675 addHistoryItem(removeGapCols);
2677 statusBar.setText(MessageManager.formatMessage(
2678 "label.removed_empty_columns",
2679 new Object[] { Integer.valueOf(removeGapCols.getSize())
2682 // This is to maintain viewport position on first residue
2683 // of first sequence
2684 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2685 int startRes = seq.findPosition(vpRanges.getStartRes());
2686 // ShiftList shifts;
2687 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2688 // edit.alColumnChanges=shifts.getInverse();
2689 // if (viewport.hasHiddenColumns)
2690 // viewport.getColumnSelection().compensateForEdits(shifts);
2691 vpRanges.setStartRes(seq.findIndex(startRes) - 1);
2692 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2704 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2706 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2709 if (viewport.getSelectionGroup() != null)
2711 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2712 viewport.getHiddenRepSequences());
2713 start = viewport.getSelectionGroup().getStartRes();
2714 end = viewport.getSelectionGroup().getEndRes();
2718 seqs = viewport.getAlignment().getSequencesArray();
2721 // This is to maintain viewport position on first residue
2722 // of first sequence
2723 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2724 int startRes = seq.findPosition(vpRanges.getStartRes());
2726 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2727 viewport.getAlignment()));
2729 vpRanges.setStartRes(seq.findIndex(startRes) - 1);
2731 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2743 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2745 viewport.setPadGaps(padGapsMenuitem.isSelected());
2746 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2757 public void findMenuItem_actionPerformed(ActionEvent e)
2763 * Create a new view of the current alignment.
2766 public void newView_actionPerformed(ActionEvent e)
2768 newView(null, true);
2772 * Creates and shows a new view of the current alignment.
2775 * title of newly created view; if null, one will be generated
2776 * @param copyAnnotation
2777 * if true then duplicate all annnotation, groups and settings
2778 * @return new alignment panel, already displayed.
2780 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2783 * Create a new AlignmentPanel (with its own, new Viewport)
2785 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2787 if (!copyAnnotation)
2790 * remove all groups and annotation except for the automatic stuff
2792 newap.av.getAlignment().deleteAllGroups();
2793 newap.av.getAlignment().deleteAllAnnotations(false);
2796 newap.av.setGatherViewsHere(false);
2798 if (viewport.viewName == null)
2800 viewport.viewName = MessageManager
2801 .getString("label.view_name_original");
2805 * Views share the same edits undo and redo stacks
2807 newap.av.setHistoryList(viewport.getHistoryList());
2808 newap.av.setRedoList(viewport.getRedoList());
2811 * Views share the same mappings; need to deregister any new mappings
2812 * created by copyAlignPanel, and register the new reference to the shared
2815 newap.av.replaceMappings(viewport.getAlignment());
2818 * start up cDNA consensus (if applicable) now mappings are in place
2820 if (newap.av.initComplementConsensus())
2822 newap.refresh(true); // adjust layout of annotations
2825 newap.av.viewName = getNewViewName(viewTitle);
2827 addAlignmentPanel(newap, true);
2828 newap.alignmentChanged();
2830 if (alignPanels.size() == 2)
2832 viewport.setGatherViewsHere(true);
2834 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2839 * Make a new name for the view, ensuring it is unique within the current
2840 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2841 * these now use viewId. Unique view names are still desirable for usability.)
2846 protected String getNewViewName(String viewTitle)
2848 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2849 boolean addFirstIndex = false;
2850 if (viewTitle == null || viewTitle.trim().length() == 0)
2852 viewTitle = MessageManager.getString("action.view");
2853 addFirstIndex = true;
2857 index = 1;// we count from 1 if given a specific name
2859 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2861 List<Component> comps = PaintRefresher.components.get(viewport
2862 .getSequenceSetId());
2864 List<String> existingNames = getExistingViewNames(comps);
2866 while (existingNames.contains(newViewName))
2868 newViewName = viewTitle + " " + (++index);
2874 * Returns a list of distinct view names found in the given list of
2875 * components. View names are held on the viewport of an AlignmentPanel.
2880 protected List<String> getExistingViewNames(List<Component> comps)
2882 List<String> existingNames = new ArrayList<>();
2883 for (Component comp : comps)
2885 if (comp instanceof AlignmentPanel)
2887 AlignmentPanel ap = (AlignmentPanel) comp;
2888 if (!existingNames.contains(ap.av.viewName))
2890 existingNames.add(ap.av.viewName);
2894 return existingNames;
2898 * Explode tabbed views into separate windows.
2901 public void expandViews_actionPerformed(ActionEvent e)
2903 Desktop.explodeViews(this);
2907 * Gather views in separate windows back into a tabbed presentation.
2910 public void gatherViews_actionPerformed(ActionEvent e)
2912 Desktop.instance.gatherViews(this);
2922 public void font_actionPerformed(ActionEvent e)
2924 new FontChooser(alignPanel);
2934 protected void seqLimit_actionPerformed(ActionEvent e)
2936 viewport.setShowJVSuffix(seqLimits.isSelected());
2938 alignPanel.getIdPanel().getIdCanvas()
2939 .setPreferredSize(alignPanel.calculateIdWidth());
2940 alignPanel.paintAlignment(true);
2944 public void idRightAlign_actionPerformed(ActionEvent e)
2946 viewport.setRightAlignIds(idRightAlign.isSelected());
2947 alignPanel.paintAlignment(true);
2951 public void centreColumnLabels_actionPerformed(ActionEvent e)
2953 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2954 alignPanel.paintAlignment(true);
2960 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2963 protected void followHighlight_actionPerformed()
2966 * Set the 'follow' flag on the Viewport (and scroll to position if now
2969 final boolean state = this.followHighlightMenuItem.getState();
2970 viewport.setFollowHighlight(state);
2973 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2984 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2986 viewport.setColourText(colourTextMenuItem.isSelected());
2987 alignPanel.paintAlignment(true);
2997 public void wrapMenuItem_actionPerformed(ActionEvent e)
2999 scaleAbove.setVisible(wrapMenuItem.isSelected());
3000 scaleLeft.setVisible(wrapMenuItem.isSelected());
3001 scaleRight.setVisible(wrapMenuItem.isSelected());
3002 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3003 alignPanel.updateLayout();
3007 public void showAllSeqs_actionPerformed(ActionEvent e)
3009 viewport.showAllHiddenSeqs();
3013 public void showAllColumns_actionPerformed(ActionEvent e)
3015 viewport.showAllHiddenColumns();
3017 viewport.sendSelection();
3021 public void hideSelSequences_actionPerformed(ActionEvent e)
3023 viewport.hideAllSelectedSeqs();
3024 // alignPanel.paintAlignment(true);
3028 * called by key handler and the hide all/show all menu items
3033 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3036 boolean hide = false;
3037 SequenceGroup sg = viewport.getSelectionGroup();
3038 if (!toggleSeqs && !toggleCols)
3040 // Hide everything by the current selection - this is a hack - we do the
3041 // invert and then hide
3042 // first check that there will be visible columns after the invert.
3043 if (viewport.hasSelectedColumns()
3044 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
3047 // now invert the sequence set, if required - empty selection implies
3048 // that no hiding is required.
3051 invertSequenceMenuItem_actionPerformed(null);
3052 sg = viewport.getSelectionGroup();
3056 viewport.expandColSelection(sg, true);
3057 // finally invert the column selection and get the new sequence
3059 invertColSel_actionPerformed(null);
3066 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3068 hideSelSequences_actionPerformed(null);
3071 else if (!(toggleCols && viewport.hasSelectedColumns()))
3073 showAllSeqs_actionPerformed(null);
3079 if (viewport.hasSelectedColumns())
3081 hideSelColumns_actionPerformed(null);
3084 viewport.setSelectionGroup(sg);
3089 showAllColumns_actionPerformed(null);
3098 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3099 * event.ActionEvent)
3102 public void hideAllButSelection_actionPerformed(ActionEvent e)
3104 toggleHiddenRegions(false, false);
3105 viewport.sendSelection();
3112 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3116 public void hideAllSelection_actionPerformed(ActionEvent e)
3118 SequenceGroup sg = viewport.getSelectionGroup();
3119 viewport.expandColSelection(sg, false);
3120 viewport.hideAllSelectedSeqs();
3121 viewport.hideSelectedColumns();
3122 alignPanel.paintAlignment(true);
3123 viewport.sendSelection();
3130 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3134 public void showAllhidden_actionPerformed(ActionEvent e)
3136 viewport.showAllHiddenColumns();
3137 viewport.showAllHiddenSeqs();
3138 alignPanel.paintAlignment(true);
3139 viewport.sendSelection();
3143 public void hideSelColumns_actionPerformed(ActionEvent e)
3145 viewport.hideSelectedColumns();
3146 alignPanel.paintAlignment(true);
3147 viewport.sendSelection();
3151 public void hiddenMarkers_actionPerformed(ActionEvent e)
3153 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3164 protected void scaleAbove_actionPerformed(ActionEvent e)
3166 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3167 alignPanel.paintAlignment(true);
3177 protected void scaleLeft_actionPerformed(ActionEvent e)
3179 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3180 alignPanel.paintAlignment(true);
3190 protected void scaleRight_actionPerformed(ActionEvent e)
3192 viewport.setScaleRightWrapped(scaleRight.isSelected());
3193 alignPanel.paintAlignment(true);
3203 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3205 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3206 alignPanel.paintAlignment(true);
3216 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3218 viewport.setShowText(viewTextMenuItem.isSelected());
3219 alignPanel.paintAlignment(true);
3229 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3231 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3232 alignPanel.paintAlignment(true);
3235 public FeatureSettings featureSettings;
3238 public FeatureSettingsControllerI getFeatureSettingsUI()
3240 return featureSettings;
3244 public void featureSettings_actionPerformed(ActionEvent e)
3246 if (featureSettings != null)
3248 featureSettings.close();
3249 featureSettings = null;
3251 if (!showSeqFeatures.isSelected())
3253 // make sure features are actually displayed
3254 showSeqFeatures.setSelected(true);
3255 showSeqFeatures_actionPerformed(null);
3257 featureSettings = new FeatureSettings(this);
3261 * Set or clear 'Show Sequence Features'
3267 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3269 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3270 alignPanel.paintAlignment(true);
3271 if (alignPanel.getOverviewPanel() != null)
3273 alignPanel.getOverviewPanel().updateOverviewImage();
3278 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3279 * the annotations panel as a whole.
3281 * The options to show/hide all annotations should be enabled when the panel
3282 * is shown, and disabled when the panel is hidden.
3287 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3289 final boolean setVisible = annotationPanelMenuItem.isSelected();
3290 viewport.setShowAnnotation(setVisible);
3291 this.showAllSeqAnnotations.setEnabled(setVisible);
3292 this.hideAllSeqAnnotations.setEnabled(setVisible);
3293 this.showAllAlAnnotations.setEnabled(setVisible);
3294 this.hideAllAlAnnotations.setEnabled(setVisible);
3295 alignPanel.updateLayout();
3299 public void alignmentProperties()
3301 JEditorPane editPane = new JEditorPane("text/html", "");
3302 editPane.setEditable(false);
3303 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3305 editPane.setText(MessageManager.formatMessage("label.html_content",
3306 new Object[] { contents.toString() }));
3307 JInternalFrame frame = new JInternalFrame();
3308 frame.getContentPane().add(new JScrollPane(editPane));
3310 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3311 "label.alignment_properties", new Object[] { getTitle() }),
3322 public void overviewMenuItem_actionPerformed(ActionEvent e)
3324 if (alignPanel.overviewPanel != null)
3329 JInternalFrame frame = new JInternalFrame();
3330 OverviewPanel overview = new OverviewPanel(alignPanel);
3331 frame.setContentPane(overview);
3332 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3333 "label.overview_params", new Object[] { this.getTitle() }),
3334 true, frame.getWidth(), frame.getHeight(), true, true);
3336 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3337 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3340 public void internalFrameClosed(
3341 javax.swing.event.InternalFrameEvent evt)
3343 alignPanel.setOverviewPanel(null);
3347 alignPanel.setOverviewPanel(overview);
3351 public void textColour_actionPerformed()
3353 new TextColourChooser().chooseColour(alignPanel, null);
3357 * public void covariationColour_actionPerformed() {
3359 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3363 public void annotationColour_actionPerformed()
3365 new AnnotationColourChooser(viewport, alignPanel);
3369 public void annotationColumn_actionPerformed(ActionEvent e)
3371 new AnnotationColumnChooser(viewport, alignPanel);
3375 * Action on the user checking or unchecking the option to apply the selected
3376 * colour scheme to all groups. If unchecked, groups may have their own
3377 * independent colour schemes.
3382 public void applyToAllGroups_actionPerformed(boolean selected)
3384 viewport.setColourAppliesToAllGroups(selected);
3388 * Action on user selecting a colour from the colour menu
3391 * the name (not the menu item label!) of the colour scheme
3394 public void changeColour_actionPerformed(String name)
3397 * 'User Defined' opens a panel to configure or load a
3398 * user-defined colour scheme
3400 if (ResidueColourScheme.USER_DEFINED.equals(name))
3402 new UserDefinedColours(alignPanel);
3407 * otherwise set the chosen colour scheme (or null for 'None')
3409 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3410 viewport.getAlignment(), viewport.getHiddenRepSequences());
3415 * Actions on setting or changing the alignment colour scheme
3420 public void changeColour(ColourSchemeI cs)
3422 // TODO: pull up to controller method
3423 ColourMenuHelper.setColourSelected(colourMenu, cs);
3425 viewport.setGlobalColourScheme(cs);
3427 alignPanel.paintAlignment(true);
3431 * Show the PID threshold slider panel
3434 protected void modifyPID_actionPerformed()
3436 SliderPanel.setPIDSliderSource(alignPanel,
3437 viewport.getResidueShading(), alignPanel.getViewName());
3438 SliderPanel.showPIDSlider();
3442 * Show the Conservation slider panel
3445 protected void modifyConservation_actionPerformed()
3447 SliderPanel.setConservationSlider(alignPanel,
3448 viewport.getResidueShading(), alignPanel.getViewName());
3449 SliderPanel.showConservationSlider();
3453 * Action on selecting or deselecting (Colour) By Conservation
3456 public void conservationMenuItem_actionPerformed(boolean selected)
3458 modifyConservation.setEnabled(selected);
3459 viewport.setConservationSelected(selected);
3460 viewport.getResidueShading().setConservationApplied(selected);
3462 changeColour(viewport.getGlobalColourScheme());
3465 modifyConservation_actionPerformed();
3469 SliderPanel.hideConservationSlider();
3474 * Action on selecting or deselecting (Colour) Above PID Threshold
3477 public void abovePIDThreshold_actionPerformed(boolean selected)
3479 modifyPID.setEnabled(selected);
3480 viewport.setAbovePIDThreshold(selected);
3483 viewport.getResidueShading().setThreshold(0,
3484 viewport.isIgnoreGapsConsensus());
3487 changeColour(viewport.getGlobalColourScheme());
3490 modifyPID_actionPerformed();
3494 SliderPanel.hidePIDSlider();
3505 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3507 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3508 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3509 .getAlignment().getSequenceAt(0));
3510 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3511 viewport.getAlignment()));
3512 alignPanel.paintAlignment(true);
3522 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3524 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3525 AlignmentSorter.sortByID(viewport.getAlignment());
3526 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3527 viewport.getAlignment()));
3528 alignPanel.paintAlignment(true);
3538 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3540 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3541 AlignmentSorter.sortByLength(viewport.getAlignment());
3542 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3543 viewport.getAlignment()));
3544 alignPanel.paintAlignment(true);
3554 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3556 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3557 AlignmentSorter.sortByGroup(viewport.getAlignment());
3558 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3559 viewport.getAlignment()));
3561 alignPanel.paintAlignment(true);
3571 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3573 new RedundancyPanel(alignPanel, this);
3583 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3585 if ((viewport.getSelectionGroup() == null)
3586 || (viewport.getSelectionGroup().getSize() < 2))
3588 JvOptionPane.showInternalMessageDialog(this, MessageManager
3589 .getString("label.you_must_select_least_two_sequences"),
3590 MessageManager.getString("label.invalid_selection"),
3591 JvOptionPane.WARNING_MESSAGE);
3595 JInternalFrame frame = new JInternalFrame();
3596 frame.setContentPane(new PairwiseAlignPanel(viewport));
3597 Desktop.addInternalFrame(frame,
3598 MessageManager.getString("action.pairwise_alignment"), 600,
3604 public void autoCalculate_actionPerformed(ActionEvent e)
3606 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3607 if (viewport.autoCalculateConsensus)
3609 viewport.firePropertyChange("alignment", null, viewport
3610 .getAlignment().getSequences());
3615 public void sortByTreeOption_actionPerformed(ActionEvent e)
3617 viewport.sortByTree = sortByTree.isSelected();
3621 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3623 viewport.followSelection = listenToViewSelections.isSelected();
3627 * Constructs a tree panel and adds it to the desktop
3630 * tree type (NJ or AV)
3632 * name of score model used to compute the tree
3634 * parameters for the distance or similarity calculation
3636 void newTreePanel(String type, String modelName, SimilarityParamsI options)
3638 String frameTitle = "";
3641 boolean onSelection = false;
3642 if (viewport.getSelectionGroup() != null
3643 && viewport.getSelectionGroup().getSize() > 0)
3645 SequenceGroup sg = viewport.getSelectionGroup();
3647 /* Decide if the selection is a column region */
3648 for (SequenceI _s : sg.getSequences())
3650 if (_s.getLength() < sg.getEndRes())
3656 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3658 .getString("label.sequences_selection_not_aligned"),
3659 JvOptionPane.WARNING_MESSAGE);
3668 if (viewport.getAlignment().getHeight() < 2)
3674 tp = new TreePanel(alignPanel, type, modelName, options);
3675 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3677 frameTitle += " from ";
3679 if (viewport.viewName != null)
3681 frameTitle += viewport.viewName + " of ";
3684 frameTitle += this.title;
3686 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3697 public void addSortByOrderMenuItem(String title,
3698 final AlignmentOrder order)
3700 final JMenuItem item = new JMenuItem(MessageManager.formatMessage(
3701 "action.by_title_param", new Object[] { title }));
3703 item.addActionListener(new java.awt.event.ActionListener()
3706 public void actionPerformed(ActionEvent e)
3708 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3710 // TODO: JBPNote - have to map order entries to curent SequenceI
3712 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3714 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
3717 alignPanel.paintAlignment(true);
3723 * Add a new sort by annotation score menu item
3726 * the menu to add the option to
3728 * the label used to retrieve scores for each sequence on the
3731 public void addSortByAnnotScoreMenuItem(JMenu sort,
3732 final String scoreLabel)
3734 final JMenuItem item = new JMenuItem(scoreLabel);
3736 item.addActionListener(new java.awt.event.ActionListener()
3739 public void actionPerformed(ActionEvent e)
3741 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3742 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3743 viewport.getAlignment());// ,viewport.getSelectionGroup());
3744 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3745 viewport.getAlignment()));
3746 alignPanel.paintAlignment(true);
3752 * last hash for alignment's annotation array - used to minimise cost of
3755 protected int _annotationScoreVectorHash;
3758 * search the alignment and rebuild the sort by annotation score submenu the
3759 * last alignment annotation vector hash is stored to minimize cost of
3760 * rebuilding in subsequence calls.
3764 public void buildSortByAnnotationScoresMenu()
3766 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3771 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
3773 sortByAnnotScore.removeAll();
3774 // almost certainly a quicker way to do this - but we keep it simple
3775 Hashtable scoreSorts = new Hashtable();
3776 AlignmentAnnotation aann[];
3777 for (SequenceI sqa : viewport.getAlignment().getSequences())
3779 aann = sqa.getAnnotation();
3780 for (int i = 0; aann != null && i < aann.length; i++)
3782 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3784 scoreSorts.put(aann[i].label, aann[i].label);
3788 Enumeration labels = scoreSorts.keys();
3789 while (labels.hasMoreElements())
3791 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3792 (String) labels.nextElement());
3794 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3797 _annotationScoreVectorHash = viewport.getAlignment()
3798 .getAlignmentAnnotation().hashCode();
3803 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3804 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3805 * call. Listeners are added to remove the menu item when the treePanel is
3806 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3810 public void buildTreeSortMenu()
3812 sortByTreeMenu.removeAll();
3814 List<Component> comps = PaintRefresher.components.get(viewport
3815 .getSequenceSetId());
3816 List<TreePanel> treePanels = new ArrayList<>();
3817 for (Component comp : comps)
3819 if (comp instanceof TreePanel)
3821 treePanels.add((TreePanel) comp);
3825 if (treePanels.size() < 1)
3827 sortByTreeMenu.setVisible(false);
3831 sortByTreeMenu.setVisible(true);
3833 for (final TreePanel tp : treePanels)
3835 final JMenuItem item = new JMenuItem(tp.getTitle());
3836 item.addActionListener(new java.awt.event.ActionListener()
3839 public void actionPerformed(ActionEvent e)
3841 tp.sortByTree_actionPerformed();
3842 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3847 sortByTreeMenu.add(item);
3851 public boolean sortBy(AlignmentOrder alorder, String undoname)
3853 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3854 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3855 if (undoname != null)
3857 addHistoryItem(new OrderCommand(undoname, oldOrder,
3858 viewport.getAlignment()));
3860 alignPanel.paintAlignment(true);
3865 * Work out whether the whole set of sequences or just the selected set will
3866 * be submitted for multiple alignment.
3869 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3871 // Now, check we have enough sequences
3872 AlignmentView msa = null;
3874 if ((viewport.getSelectionGroup() != null)
3875 && (viewport.getSelectionGroup().getSize() > 1))
3877 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3878 // some common interface!
3880 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3881 * SequenceI[sz = seqs.getSize(false)];
3883 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3884 * seqs.getSequenceAt(i); }
3886 msa = viewport.getAlignmentView(true);
3888 else if (viewport.getSelectionGroup() != null
3889 && viewport.getSelectionGroup().getSize() == 1)
3891 int option = JvOptionPane.showConfirmDialog(this,
3892 MessageManager.getString("warn.oneseq_msainput_selection"),
3893 MessageManager.getString("label.invalid_selection"),
3894 JvOptionPane.OK_CANCEL_OPTION);
3895 if (option == JvOptionPane.OK_OPTION)
3897 msa = viewport.getAlignmentView(false);
3902 msa = viewport.getAlignmentView(false);
3908 * Decides what is submitted to a secondary structure prediction service: the
3909 * first sequence in the alignment, or in the current selection, or, if the
3910 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3911 * region or the whole alignment. (where the first sequence in the set is the
3912 * one that the prediction will be for).
3914 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3916 AlignmentView seqs = null;
3918 if ((viewport.getSelectionGroup() != null)
3919 && (viewport.getSelectionGroup().getSize() > 0))
3921 seqs = viewport.getAlignmentView(true);
3925 seqs = viewport.getAlignmentView(false);
3927 // limit sequences - JBPNote in future - could spawn multiple prediction
3929 // TODO: viewport.getAlignment().isAligned is a global state - the local
3930 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3931 if (!viewport.getAlignment().isAligned(false))
3933 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3934 // TODO: if seqs.getSequences().length>1 then should really have warned
3948 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3950 // Pick the tree file
3951 JalviewFileChooser chooser = new JalviewFileChooser(
3952 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3953 chooser.setFileView(new JalviewFileView());
3954 chooser.setDialogTitle(MessageManager
3955 .getString("label.select_newick_like_tree_file"));
3956 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
3958 int value = chooser.showOpenDialog(null);
3960 if (value == JalviewFileChooser.APPROVE_OPTION)
3962 String filePath = chooser.getSelectedFile().getPath();
3963 Cache.setProperty("LAST_DIRECTORY", filePath);
3964 NewickFile fin = null;
3967 fin = new NewickFile(filePath, DataSourceType.FILE);
3968 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
3969 } catch (Exception ex)
3976 .getString("label.problem_reading_tree_file"),
3977 JvOptionPane.WARNING_MESSAGE);
3978 ex.printStackTrace();
3980 if (fin != null && fin.hasWarningMessage())
3982 JvOptionPane.showMessageDialog(Desktop.desktop, fin
3983 .getWarningMessage(), MessageManager
3984 .getString("label.possible_problem_with_tree_file"),
3985 JvOptionPane.WARNING_MESSAGE);
3990 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
3992 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
3995 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
3996 int h, int x, int y)
3998 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4002 * Add a treeviewer for the tree extracted from a Newick file object to the
4003 * current alignment view
4010 * Associated alignment input data (or null)
4019 * @return TreePanel handle
4021 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4022 AlignmentView input, int w, int h, int x, int y)
4024 TreePanel tp = null;
4030 if (nf.getTree() != null)
4032 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4038 tp.setLocation(x, y);
4041 Desktop.addInternalFrame(tp, treeTitle, w, h);
4043 } catch (Exception ex)
4045 ex.printStackTrace();
4051 private boolean buildingMenu = false;
4054 * Generates menu items and listener event actions for web service clients
4057 public void BuildWebServiceMenu()
4059 while (buildingMenu)
4063 System.err.println("Waiting for building menu to finish.");
4065 } catch (Exception e)
4069 final AlignFrame me = this;
4070 buildingMenu = true;
4071 new Thread(new Runnable()
4076 final List<JMenuItem> legacyItems = new ArrayList<>();
4079 // System.err.println("Building ws menu again "
4080 // + Thread.currentThread());
4081 // TODO: add support for context dependent disabling of services based
4083 // alignment and current selection
4084 // TODO: add additional serviceHandle parameter to specify abstract
4086 // class independently of AbstractName
4087 // TODO: add in rediscovery GUI function to restart discoverer
4088 // TODO: group services by location as well as function and/or
4090 // object broker mechanism.
4091 final Vector<JMenu> wsmenu = new Vector<>();
4092 final IProgressIndicator af = me;
4095 * do not i18n these strings - they are hard-coded in class
4096 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4097 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4099 final JMenu msawsmenu = new JMenu("Alignment");
4100 final JMenu secstrmenu = new JMenu(
4101 "Secondary Structure Prediction");
4102 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4103 final JMenu analymenu = new JMenu("Analysis");
4104 final JMenu dismenu = new JMenu("Protein Disorder");
4105 // JAL-940 - only show secondary structure prediction services from
4106 // the legacy server
4107 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4109 Discoverer.services != null && (Discoverer.services.size() > 0))
4111 // TODO: refactor to allow list of AbstractName/Handler bindings to
4113 // stored or retrieved from elsewhere
4114 // No MSAWS used any more:
4115 // Vector msaws = null; // (Vector)
4116 // Discoverer.services.get("MsaWS");
4117 Vector secstrpr = (Vector) Discoverer.services
4119 if (secstrpr != null)
4121 // Add any secondary structure prediction services
4122 for (int i = 0, j = secstrpr.size(); i < j; i++)
4124 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4126 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4127 .getServiceClient(sh);
4128 int p = secstrmenu.getItemCount();
4129 impl.attachWSMenuEntry(secstrmenu, me);
4130 int q = secstrmenu.getItemCount();
4131 for (int litm = p; litm < q; litm++)
4133 legacyItems.add(secstrmenu.getItem(litm));
4139 // Add all submenus in the order they should appear on the web
4141 wsmenu.add(msawsmenu);
4142 wsmenu.add(secstrmenu);
4143 wsmenu.add(dismenu);
4144 wsmenu.add(analymenu);
4145 // No search services yet
4146 // wsmenu.add(seqsrchmenu);
4148 javax.swing.SwingUtilities.invokeLater(new Runnable()
4155 webService.removeAll();
4156 // first, add discovered services onto the webservices menu
4157 if (wsmenu.size() > 0)
4159 for (int i = 0, j = wsmenu.size(); i < j; i++)
4161 webService.add(wsmenu.get(i));
4166 webService.add(me.webServiceNoServices);
4168 // TODO: move into separate menu builder class.
4169 boolean new_sspred = false;
4170 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4172 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4173 if (jws2servs != null)
4175 if (jws2servs.hasServices())
4177 jws2servs.attachWSMenuEntry(webService, me);
4178 for (Jws2Instance sv : jws2servs.getServices())
4180 if (sv.description.toLowerCase().contains("jpred"))
4182 for (JMenuItem jmi : legacyItems)
4184 jmi.setVisible(false);
4190 if (jws2servs.isRunning())
4192 JMenuItem tm = new JMenuItem(
4193 "Still discovering JABA Services");
4194 tm.setEnabled(false);
4199 build_urlServiceMenu(me.webService);
4200 build_fetchdbmenu(webService);
4201 for (JMenu item : wsmenu)
4203 if (item.getItemCount() == 0)
4205 item.setEnabled(false);
4209 item.setEnabled(true);
4212 } catch (Exception e)
4215 .debug("Exception during web service menu building process.",
4220 } catch (Exception e)
4223 buildingMenu = false;
4230 * construct any groupURL type service menu entries.
4234 private void build_urlServiceMenu(JMenu webService)
4236 // TODO: remove this code when 2.7 is released
4237 // DEBUG - alignmentView
4239 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4240 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4242 * @Override public void actionPerformed(ActionEvent e) {
4243 * jalview.datamodel.AlignmentView
4244 * .testSelectionViews(af.viewport.getAlignment(),
4245 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4247 * }); webService.add(testAlView);
4249 // TODO: refactor to RestClient discoverer and merge menu entries for
4250 // rest-style services with other types of analysis/calculation service
4251 // SHmmr test client - still being implemented.
4252 // DEBUG - alignmentView
4254 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4257 client.attachWSMenuEntry(
4258 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4264 * Searches the alignment sequences for xRefs and builds the Show
4265 * Cross-References menu (formerly called Show Products), with database
4266 * sources for which cross-references are found (protein sources for a
4267 * nucleotide alignment and vice versa)
4269 * @return true if Show Cross-references menu should be enabled
4271 public boolean canShowProducts()
4273 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4274 AlignmentI dataset = viewport.getAlignment().getDataset();
4276 showProducts.removeAll();
4277 final boolean dna = viewport.getAlignment().isNucleotide();
4279 if (seqs == null || seqs.length == 0)
4281 // nothing to see here.
4285 boolean showp = false;
4288 List<String> ptypes = new CrossRef(seqs, dataset)
4289 .findXrefSourcesForSequences(dna);
4291 for (final String source : ptypes)
4294 final AlignFrame af = this;
4295 JMenuItem xtype = new JMenuItem(source);
4296 xtype.addActionListener(new ActionListener()
4299 public void actionPerformed(ActionEvent e)
4301 showProductsFor(af.viewport.getSequenceSelection(), dna, source);
4304 showProducts.add(xtype);
4306 showProducts.setVisible(showp);
4307 showProducts.setEnabled(showp);
4308 } catch (Exception e)
4311 .warn("canShowProducts threw an exception - please report to help@jalview.org",
4319 * Finds and displays cross-references for the selected sequences (protein
4320 * products for nucleotide sequences, dna coding sequences for peptides).
4323 * the sequences to show cross-references for
4325 * true if from a nucleotide alignment (so showing proteins)
4327 * the database to show cross-references for
4329 protected void showProductsFor(final SequenceI[] sel,
4330 final boolean _odna, final String source)
4332 new Thread(CrossRefAction.showProductsFor(sel, _odna, source, this))
4337 * Construct and display a new frame containing the translation of this
4338 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4341 public void showTranslation_actionPerformed(ActionEvent e)
4343 AlignmentI al = null;
4346 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4348 al = dna.translateCdna();
4349 } catch (Exception ex)
4351 jalview.bin.Cache.log.error(
4352 "Exception during translation. Please report this !", ex);
4353 final String msg = MessageManager
4354 .getString("label.error_when_translating_sequences_submit_bug_report");
4355 final String errorTitle = MessageManager
4356 .getString("label.implementation_error")
4357 + MessageManager.getString("label.translation_failed");
4358 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4359 JvOptionPane.ERROR_MESSAGE);
4362 if (al == null || al.getHeight() == 0)
4364 final String msg = MessageManager
4365 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4366 final String errorTitle = MessageManager
4367 .getString("label.translation_failed");
4368 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4369 JvOptionPane.WARNING_MESSAGE);
4373 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4374 af.setFileFormat(this.currentFileFormat);
4375 final String newTitle = MessageManager.formatMessage(
4376 "label.translation_of_params",
4377 new Object[] { this.getTitle() });
4378 af.setTitle(newTitle);
4379 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4381 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4382 viewport.openSplitFrame(af, new Alignment(seqs));
4386 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4393 * Set the file format
4397 public void setFileFormat(FileFormatI format)
4399 this.currentFileFormat = format;
4403 * Try to load a features file onto the alignment.
4406 * contents or path to retrieve file
4408 * access mode of file (see jalview.io.AlignFile)
4409 * @return true if features file was parsed correctly.
4411 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4413 return avc.parseFeaturesFile(file, sourceType,
4414 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4419 public void refreshFeatureUI(boolean enableIfNecessary)
4421 // note - currently this is only still here rather than in the controller
4422 // because of the featureSettings hard reference that is yet to be
4424 if (enableIfNecessary)
4426 viewport.setShowSequenceFeatures(true);
4427 showSeqFeatures.setSelected(true);
4433 public void dragEnter(DropTargetDragEvent evt)
4438 public void dragExit(DropTargetEvent evt)
4443 public void dragOver(DropTargetDragEvent evt)
4448 public void dropActionChanged(DropTargetDragEvent evt)
4453 public void drop(DropTargetDropEvent evt)
4455 // JAL-1552 - acceptDrop required before getTransferable call for
4456 // Java's Transferable for native dnd
4457 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4458 Transferable t = evt.getTransferable();
4459 List<String> files = new ArrayList<>();
4460 List<DataSourceType> protocols = new ArrayList<>();
4464 Desktop.transferFromDropTarget(files, protocols, evt, t);
4465 } catch (Exception e)
4467 e.printStackTrace();
4473 // check to see if any of these files have names matching sequences in
4475 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4476 .getAlignment().getSequencesArray());
4478 * Object[] { String,SequenceI}
4480 ArrayList<Object[]> filesmatched = new ArrayList<>();
4481 ArrayList<String> filesnotmatched = new ArrayList<>();
4482 for (int i = 0; i < files.size(); i++)
4484 String file = files.get(i).toString();
4486 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4487 if (protocol == DataSourceType.FILE)
4489 File fl = new File(file);
4490 pdbfn = fl.getName();
4492 else if (protocol == DataSourceType.URL)
4494 URL url = new URL(file);
4495 pdbfn = url.getFile();
4497 if (pdbfn.length() > 0)
4499 // attempt to find a match in the alignment
4500 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4501 int l = 0, c = pdbfn.indexOf(".");
4502 while (mtch == null && c != -1)
4507 } while ((c = pdbfn.indexOf(".", l)) > l);
4510 pdbfn = pdbfn.substring(0, l);
4512 mtch = idm.findAllIdMatches(pdbfn);
4516 FileFormatI type = null;
4519 type = new IdentifyFile().identify(file, protocol);
4520 } catch (Exception ex)
4524 if (type != null && type.isStructureFile())
4526 filesmatched.add(new Object[] { file, protocol, mtch });
4530 // File wasn't named like one of the sequences or wasn't a PDB file.
4531 filesnotmatched.add(file);
4535 if (filesmatched.size() > 0)
4537 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4543 "label.automatically_associate_structure_files_with_sequences_same_name",
4544 new Object[] { Integer
4550 .getString("label.automatically_associate_structure_files_by_name"),
4551 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION)
4554 for (Object[] fm : filesmatched)
4556 // try and associate
4557 // TODO: may want to set a standard ID naming formalism for
4558 // associating PDB files which have no IDs.
4559 for (SequenceI toassoc : (SequenceI[]) fm[2])
4561 PDBEntry pe = new AssociatePdbFileWithSeq()
4562 .associatePdbWithSeq((String) fm[0],
4563 (DataSourceType) fm[1], toassoc, false,
4567 System.err.println("Associated file : "
4568 + ((String) fm[0]) + " with "
4569 + toassoc.getDisplayId(true));
4573 alignPanel.paintAlignment(true);
4577 if (filesnotmatched.size() > 0)
4580 && (Cache.getDefault(
4581 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JvOptionPane
4587 "label.ignore_unmatched_dropped_files_info",
4588 new Object[] { Integer
4595 .getString("label.ignore_unmatched_dropped_files"),
4596 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4600 for (String fn : filesnotmatched)
4602 loadJalviewDataFile(fn, null, null, null);
4606 } catch (Exception ex)
4608 ex.printStackTrace();
4614 * Attempt to load a "dropped" file or URL string, by testing in turn for
4616 * <li>an Annotation file</li>
4617 * <li>a JNet file</li>
4618 * <li>a features file</li>
4619 * <li>else try to interpret as an alignment file</li>
4623 * either a filename or a URL string.
4625 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4626 FileFormatI format, SequenceI assocSeq)
4630 if (sourceType == null)
4632 sourceType = FormatAdapter.checkProtocol(file);
4634 // if the file isn't identified, or not positively identified as some
4635 // other filetype (PFAM is default unidentified alignment file type) then
4636 // try to parse as annotation.
4637 boolean isAnnotation = (format == null || FileFormat.Pfam
4638 .equals(format)) ? new AnnotationFile()
4639 .annotateAlignmentView(viewport, file, sourceType) : false;
4643 // first see if its a T-COFFEE score file
4644 TCoffeeScoreFile tcf = null;
4647 tcf = new TCoffeeScoreFile(file, sourceType);
4650 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4653 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
4654 isAnnotation = true;
4656 .setText(MessageManager
4657 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
4661 // some problem - if no warning its probable that the ID matching
4662 // process didn't work
4666 tcf.getWarningMessage() == null ? MessageManager
4667 .getString("label.check_file_matches_sequence_ids_alignment")
4668 : tcf.getWarningMessage(),
4670 .getString("label.problem_reading_tcoffee_score_file"),
4671 JvOptionPane.WARNING_MESSAGE);
4678 } catch (Exception x)
4681 .debug("Exception when processing data source as T-COFFEE score file",
4687 // try to see if its a JNet 'concise' style annotation file *before*
4689 // try to parse it as a features file
4692 format = new IdentifyFile().identify(file, sourceType);
4694 if (FileFormat.ScoreMatrix == format)
4696 ScoreMatrixFile sm = new ScoreMatrixFile(new FileParse(file,
4699 // todo: i18n this message
4701 .setText(MessageManager.formatMessage(
4702 "label.successfully_loaded_matrix",
4703 sm.getMatrixName()));
4705 else if (FileFormat.HMMER3.equals(format))
4707 HMMFile hmmFile = new HMMFile(new FileParse(file, sourceType)); // TODO
4714 HiddenMarkovModel hmm = hmmFile.getHMM();
4716 hmm.mapToReferenceAnnotation(this);
4717 SequenceI hmmSeq = hmm.initPlaceholder(this);
4718 getViewport().initInformation(hmmSeq);
4719 new Thread(new InformationThread(getViewport(),
4720 getViewport().getAlignPanel())
4724 isAnnotation = true;
4725 alignPanel.repaint();
4728 else if (FileFormat.Jnet.equals(format))
4730 JPredFile predictions = new JPredFile(file, sourceType);
4731 new JnetAnnotationMaker();
4732 JnetAnnotationMaker.add_annotation(predictions,
4733 viewport.getAlignment(), 0, false);
4734 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
4735 viewport.getAlignment().setSeqrep(repseq);
4736 HiddenColumns cs = new HiddenColumns();
4737 cs.hideInsertionsFor(repseq);
4738 viewport.getAlignment().setHiddenColumns(cs);
4739 isAnnotation = true;
4741 // else if (IdentifyFile.FeaturesFile.equals(format))
4742 else if (FileFormat.Features.equals(format))
4744 if (parseFeaturesFile(file, sourceType))
4746 alignPanel.paintAlignment(true);
4751 new FileLoader().LoadFile(viewport, file, sourceType, format);
4757 alignPanel.adjustAnnotationHeight();
4758 viewport.updateSequenceIdColours();
4759 buildSortByAnnotationScoresMenu();
4760 alignPanel.paintAlignment(true);
4762 } catch (Exception ex)
4764 ex.printStackTrace();
4765 } catch (OutOfMemoryError oom)
4770 } catch (Exception x)
4775 + (sourceType != null ? (sourceType == DataSourceType.PASTE ? "from clipboard."
4776 : "using " + sourceType + " from " + file)
4778 + (format != null ? "(parsing as '" + format
4779 + "' file)" : ""), oom, Desktop.desktop);
4784 * Method invoked by the ChangeListener on the tabbed pane, in other words
4785 * when a different tabbed pane is selected by the user or programmatically.
4788 public void tabSelectionChanged(int index)
4792 alignPanel = alignPanels.get(index);
4793 viewport = alignPanel.av;
4794 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4795 setMenusFromViewport(viewport);
4799 * 'focus' any colour slider that is open to the selected viewport
4801 if (viewport.getConservationSelected())
4803 SliderPanel.setConservationSlider(alignPanel,
4804 viewport.getResidueShading(), alignPanel.getViewName());
4808 SliderPanel.hideConservationSlider();
4810 if (viewport.getAbovePIDThreshold())
4812 SliderPanel.setPIDSliderSource(alignPanel,
4813 viewport.getResidueShading(), alignPanel.getViewName());
4817 SliderPanel.hidePIDSlider();
4821 * If there is a frame linked to this one in a SplitPane, switch it to the
4822 * same view tab index. No infinite recursion of calls should happen, since
4823 * tabSelectionChanged() should not get invoked on setting the selected
4824 * index to an unchanged value. Guard against setting an invalid index
4825 * before the new view peer tab has been created.
4827 final AlignViewportI peer = viewport.getCodingComplement();
4830 AlignFrame linkedAlignFrame = ((AlignViewport) peer).getAlignPanel().alignFrame;
4831 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4833 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4839 * On right mouse click on view tab, prompt for and set new view name.
4842 public void tabbedPane_mousePressed(MouseEvent e)
4844 if (e.isPopupTrigger())
4846 String msg = MessageManager.getString("label.enter_view_name");
4847 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4848 JvOptionPane.QUESTION_MESSAGE);
4852 viewport.viewName = reply;
4853 // TODO warn if reply is in getExistingViewNames()?
4854 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4859 public AlignViewport getCurrentView()
4865 * Open the dialog for regex description parsing.
4868 protected void extractScores_actionPerformed(ActionEvent e)
4870 ParseProperties pp = new jalview.analysis.ParseProperties(
4871 viewport.getAlignment());
4872 // TODO: verify regex and introduce GUI dialog for version 2.5
4873 // if (pp.getScoresFromDescription("col", "score column ",
4874 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4876 if (pp.getScoresFromDescription("description column",
4877 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4879 buildSortByAnnotationScoresMenu();
4887 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4891 protected void showDbRefs_actionPerformed(ActionEvent e)
4893 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4899 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4903 protected void showNpFeats_actionPerformed(ActionEvent e)
4905 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4909 * find the viewport amongst the tabs in this alignment frame and close that
4914 public boolean closeView(AlignViewportI av)
4918 this.closeMenuItem_actionPerformed(false);
4921 Component[] comp = tabbedPane.getComponents();
4922 for (int i = 0; comp != null && i < comp.length; i++)
4924 if (comp[i] instanceof AlignmentPanel)
4926 if (((AlignmentPanel) comp[i]).av == av)
4929 closeView((AlignmentPanel) comp[i]);
4937 protected void build_fetchdbmenu(JMenu webService)
4939 // Temporary hack - DBRef Fetcher always top level ws entry.
4940 // TODO We probably want to store a sequence database checklist in
4941 // preferences and have checkboxes.. rather than individual sources selected
4943 final JMenu rfetch = new JMenu(
4944 MessageManager.getString("action.fetch_db_references"));
4945 rfetch.setToolTipText(MessageManager
4946 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4947 webService.add(rfetch);
4949 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4950 MessageManager.getString("option.trim_retrieved_seqs"));
4951 trimrs.setToolTipText(MessageManager
4952 .getString("label.trim_retrieved_sequences"));
4953 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
4954 trimrs.addActionListener(new ActionListener()
4957 public void actionPerformed(ActionEvent e)
4959 trimrs.setSelected(trimrs.isSelected());
4960 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
4961 Boolean.valueOf(trimrs.isSelected()).toString());
4965 JMenuItem fetchr = new JMenuItem(
4966 MessageManager.getString("label.standard_databases"));
4967 fetchr.setToolTipText(MessageManager
4968 .getString("label.fetch_embl_uniprot"));
4969 fetchr.addActionListener(new ActionListener()
4973 public void actionPerformed(ActionEvent e)
4975 new Thread(new Runnable()
4980 boolean isNucleotide = alignPanel.alignFrame.getViewport()
4981 .getAlignment().isNucleotide();
4982 DBRefFetcher dbRefFetcher = new DBRefFetcher(alignPanel.av
4983 .getSequenceSelection(), alignPanel.alignFrame, null,
4984 alignPanel.alignFrame.featureSettings, isNucleotide);
4985 dbRefFetcher.addListener(new FetchFinishedListenerI()
4988 public void finished()
4990 AlignFrame.this.setMenusForViewport();
4993 dbRefFetcher.fetchDBRefs(false);
5001 final AlignFrame me = this;
5002 new Thread(new Runnable()
5007 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5008 .getSequenceFetcherSingleton(me);
5009 javax.swing.SwingUtilities.invokeLater(new Runnable()
5014 String[] dbclasses = sf.getOrderedSupportedSources();
5015 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5016 // jalview.util.QuickSort.sort(otherdb, otherdb);
5017 List<DbSourceProxy> otherdb;
5018 JMenu dfetch = new JMenu();
5019 JMenu ifetch = new JMenu();
5020 JMenuItem fetchr = null;
5021 int comp = 0, icomp = 0, mcomp = 15;
5022 String mname = null;
5024 for (String dbclass : dbclasses)
5026 otherdb = sf.getSourceProxy(dbclass);
5027 // add a single entry for this class, or submenu allowing 'fetch
5029 if (otherdb == null || otherdb.size() < 1)
5033 // List<DbSourceProxy> dbs=otherdb;
5034 // otherdb=new ArrayList<DbSourceProxy>();
5035 // for (DbSourceProxy db:dbs)
5037 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5041 mname = "From " + dbclass;
5043 if (otherdb.size() == 1)
5045 final DbSourceProxy[] dassource = otherdb
5046 .toArray(new DbSourceProxy[0]);
5047 DbSourceProxy src = otherdb.get(0);
5048 fetchr = new JMenuItem(src.getDbSource());
5049 fetchr.addActionListener(new ActionListener()
5053 public void actionPerformed(ActionEvent e)
5055 new Thread(new Runnable()
5061 boolean isNucleotide = alignPanel.alignFrame
5062 .getViewport().getAlignment()
5064 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5065 alignPanel.av.getSequenceSelection(),
5066 alignPanel.alignFrame, dassource,
5067 alignPanel.alignFrame.featureSettings,
5070 .addListener(new FetchFinishedListenerI()
5073 public void finished()
5075 AlignFrame.this.setMenusForViewport();
5078 dbRefFetcher.fetchDBRefs(false);
5084 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5085 MessageManager.formatMessage(
5086 "label.fetch_retrieve_from",
5087 new Object[] { src.getDbName() })));
5093 final DbSourceProxy[] dassource = otherdb
5094 .toArray(new DbSourceProxy[0]);
5096 DbSourceProxy src = otherdb.get(0);
5097 fetchr = new JMenuItem(MessageManager.formatMessage(
5098 "label.fetch_all_param",
5099 new Object[] { src.getDbSource() }));
5100 fetchr.addActionListener(new ActionListener()
5103 public void actionPerformed(ActionEvent e)
5105 new Thread(new Runnable()
5111 boolean isNucleotide = alignPanel.alignFrame
5112 .getViewport().getAlignment()
5114 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5115 alignPanel.av.getSequenceSelection(),
5116 alignPanel.alignFrame, dassource,
5117 alignPanel.alignFrame.featureSettings,
5120 .addListener(new FetchFinishedListenerI()
5123 public void finished()
5125 AlignFrame.this.setMenusForViewport();
5128 dbRefFetcher.fetchDBRefs(false);
5134 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5135 MessageManager.formatMessage(
5136 "label.fetch_retrieve_from_all_sources",
5138 Integer.valueOf(otherdb.size())
5139 .toString(), src.getDbSource(),
5140 src.getDbName() })));
5143 // and then build the rest of the individual menus
5144 ifetch = new JMenu(MessageManager.formatMessage(
5145 "label.source_from_db_source",
5146 new Object[] { src.getDbSource() }));
5148 String imname = null;
5150 for (DbSourceProxy sproxy : otherdb)
5152 String dbname = sproxy.getDbName();
5153 String sname = dbname.length() > 5 ? dbname.substring(0,
5154 5) + "..." : dbname;
5155 String msname = dbname.length() > 10 ? dbname.substring(
5156 0, 10) + "..." : dbname;
5159 imname = MessageManager.formatMessage(
5160 "label.from_msname", new Object[] { sname });
5162 fetchr = new JMenuItem(msname);
5163 final DbSourceProxy[] dassrc = { sproxy };
5164 fetchr.addActionListener(new ActionListener()
5168 public void actionPerformed(ActionEvent e)
5170 new Thread(new Runnable()
5176 boolean isNucleotide = alignPanel.alignFrame
5177 .getViewport().getAlignment()
5179 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5180 alignPanel.av.getSequenceSelection(),
5181 alignPanel.alignFrame, dassrc,
5182 alignPanel.alignFrame.featureSettings,
5185 .addListener(new FetchFinishedListenerI()
5188 public void finished()
5190 AlignFrame.this.setMenusForViewport();
5193 dbRefFetcher.fetchDBRefs(false);
5199 fetchr.setToolTipText("<html>"
5200 + MessageManager.formatMessage(
5201 "label.fetch_retrieve_from", new Object[]
5205 if (++icomp >= mcomp || i == (otherdb.size()))
5207 ifetch.setText(MessageManager.formatMessage(
5208 "label.source_to_target", imname, sname));
5210 ifetch = new JMenu();
5218 if (comp >= mcomp || dbi >= (dbclasses.length))
5220 dfetch.setText(MessageManager.formatMessage(
5221 "label.source_to_target", mname, dbclass));
5223 dfetch = new JMenu();
5236 * Left justify the whole alignment.
5239 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5241 AlignmentI al = viewport.getAlignment();
5243 viewport.firePropertyChange("alignment", null, al);
5247 * Right justify the whole alignment.
5250 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5252 AlignmentI al = viewport.getAlignment();
5254 viewport.firePropertyChange("alignment", null, al);
5258 public void setShowSeqFeatures(boolean b)
5260 showSeqFeatures.setSelected(b);
5261 viewport.setShowSequenceFeatures(b);
5268 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5269 * awt.event.ActionEvent)
5272 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5274 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5275 alignPanel.paintAlignment(true);
5282 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5286 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5288 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5289 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5297 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5298 * .event.ActionEvent)
5301 protected void showGroupConservation_actionPerformed(ActionEvent e)
5303 viewport.setShowGroupConservation(showGroupConservation.getState());
5304 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5311 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5312 * .event.ActionEvent)
5315 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5317 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5318 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5325 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5326 * .event.ActionEvent)
5329 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5331 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5332 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5336 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5338 showSequenceLogo.setState(true);
5339 viewport.setShowSequenceLogo(true);
5340 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5341 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5345 protected void showInformationHistogram_actionPerformed(ActionEvent e)
5347 viewport.setShowInformationHistogram(
5348 showInformationHistogram.getState());
5349 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5353 protected void showHMMSequenceLogo_actionPerformed(ActionEvent e)
5355 viewport.setShowHMMSequenceLogo(showHMMSequenceLogo.getState());
5356 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5360 protected void normaliseHMMSequenceLogo_actionPerformed(ActionEvent e)
5362 showHMMSequenceLogo.setState(true);
5363 viewport.setShowHMMSequenceLogo(true);
5364 viewport.setNormaliseHMMSequenceLogo(normaliseSequenceLogo.getState());
5365 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5369 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5371 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5378 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5379 * .event.ActionEvent)
5382 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5384 if (avc.makeGroupsFromSelection())
5386 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5387 alignPanel.updateAnnotation();
5388 alignPanel.paintAlignment(true);
5392 public void clearAlignmentSeqRep()
5394 // TODO refactor alignmentseqrep to controller
5395 if (viewport.getAlignment().hasSeqrep())
5397 viewport.getAlignment().setSeqrep(null);
5398 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5399 alignPanel.updateAnnotation();
5400 alignPanel.paintAlignment(true);
5405 protected void createGroup_actionPerformed(ActionEvent e)
5407 if (avc.createGroup())
5409 alignPanel.alignmentChanged();
5414 protected void unGroup_actionPerformed(ActionEvent e)
5418 alignPanel.alignmentChanged();
5423 * make the given alignmentPanel the currently selected tab
5425 * @param alignmentPanel
5427 public void setDisplayedView(AlignmentPanel alignmentPanel)
5429 if (!viewport.getSequenceSetId().equals(
5430 alignmentPanel.av.getSequenceSetId()))
5434 .getString("error.implementation_error_cannot_show_view_alignment_frame"));
5436 if (tabbedPane != null
5437 && tabbedPane.getTabCount() > 0
5438 && alignPanels.indexOf(alignmentPanel) != tabbedPane
5439 .getSelectedIndex())
5441 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5446 * Action on selection of menu options to Show or Hide annotations.
5449 * @param forSequences
5450 * update sequence-related annotations
5451 * @param forAlignment
5452 * update non-sequence-related annotations
5455 protected void setAnnotationsVisibility(boolean visible,
5456 boolean forSequences, boolean forAlignment)
5458 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5459 .getAlignmentAnnotation();
5464 for (AlignmentAnnotation aa : anns)
5467 * don't display non-positional annotations on an alignment
5469 if (aa.annotations == null)
5473 boolean apply = (aa.sequenceRef == null && forAlignment)
5474 || (aa.sequenceRef != null && forSequences);
5477 aa.visible = visible;
5480 alignPanel.validateAnnotationDimensions(true);
5481 alignPanel.alignmentChanged();
5485 * Store selected annotation sort order for the view and repaint.
5488 protected void sortAnnotations_actionPerformed()
5490 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5492 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5493 alignPanel.paintAlignment(true);
5498 * @return alignment panels in this alignment frame
5500 public List<? extends AlignmentViewPanel> getAlignPanels()
5502 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5506 * Open a new alignment window, with the cDNA associated with this (protein)
5507 * alignment, aligned as is the protein.
5509 protected void viewAsCdna_actionPerformed()
5511 // TODO no longer a menu action - refactor as required
5512 final AlignmentI alignment = getViewport().getAlignment();
5513 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5514 if (mappings == null)
5518 List<SequenceI> cdnaSeqs = new ArrayList<>();
5519 for (SequenceI aaSeq : alignment.getSequences())
5521 for (AlignedCodonFrame acf : mappings)
5523 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5527 * There is a cDNA mapping for this protein sequence - add to new
5528 * alignment. It will share the same dataset sequence as other mapped
5529 * cDNA (no new mappings need to be created).
5531 final Sequence newSeq = new Sequence(dnaSeq);
5532 newSeq.setDatasetSequence(dnaSeq);
5533 cdnaSeqs.add(newSeq);
5537 if (cdnaSeqs.size() == 0)
5539 // show a warning dialog no mapped cDNA
5542 AlignmentI cdna = new Alignment(cdnaSeqs.toArray(new SequenceI[cdnaSeqs
5544 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5545 AlignFrame.DEFAULT_HEIGHT);
5546 cdna.alignAs(alignment);
5547 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5549 Desktop.addInternalFrame(alignFrame, newtitle,
5550 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
5554 * Set visibility of dna/protein complement view (available when shown in a
5560 protected void showComplement_actionPerformed(boolean show)
5562 SplitContainerI sf = getSplitViewContainer();
5565 sf.setComplementVisible(this, show);
5570 * Generate the reverse (optionally complemented) of the selected sequences,
5571 * and add them to the alignment
5574 protected void showReverse_actionPerformed(boolean complement)
5576 AlignmentI al = null;
5579 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5580 al = dna.reverseCdna(complement);
5581 viewport.addAlignment(al, "");
5582 addHistoryItem(new EditCommand(
5583 MessageManager.getString("label.add_sequences"),
5584 Action.PASTE, al.getSequencesArray(), 0, al.getWidth(),
5585 viewport.getAlignment()));
5586 } catch (Exception ex)
5588 System.err.println(ex.getMessage());
5594 * Try to run a script in the Groovy console, having first ensured that this
5595 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5596 * be targeted at this alignment.
5599 protected void runGroovy_actionPerformed()
5601 Jalview.setCurrentAlignFrame(this);
5602 groovy.ui.Console console = Desktop.getGroovyConsole();
5603 if (console != null)
5607 console.runScript();
5608 } catch (Exception ex)
5610 System.err.println((ex.toString()));
5612 .showInternalMessageDialog(Desktop.desktop, MessageManager
5613 .getString("label.couldnt_run_groovy_script"),
5615 .getString("label.groovy_support_failed"),
5616 JvOptionPane.ERROR_MESSAGE);
5621 System.err.println("Can't run Groovy script as console not found");
5626 * Hides columns containing (or not containing) a specified feature, provided
5627 * that would not leave all columns hidden
5629 * @param featureType
5630 * @param columnsContaining
5633 public boolean hideFeatureColumns(String featureType,
5634 boolean columnsContaining)
5636 boolean notForHiding = avc.markColumnsContainingFeatures(
5637 columnsContaining, false, false, featureType);
5640 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5641 false, featureType))
5643 getViewport().hideSelectedColumns();
5651 protected void selectHighlightedColumns_actionPerformed(
5652 ActionEvent actionEvent)
5654 // include key modifier check in case user selects from menu
5655 avc.markHighlightedColumns(
5656 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0,
5658 (actionEvent.getModifiers() & (ActionEvent.META_MASK | ActionEvent.CTRL_MASK)) != 0);
5662 * Rebuilds the Colour menu, including any user-defined colours which have
5663 * been loaded either on startup or during the session
5665 public void buildColourMenu()
5667 colourMenu.removeAll();
5669 colourMenu.add(applyToAllGroups);
5670 colourMenu.add(textColour);
5671 colourMenu.addSeparator();
5673 ColourMenuHelper.addMenuItems(colourMenu, this,
5674 viewport.getAlignment(), false);
5676 colourMenu.addSeparator();
5677 colourMenu.add(conservationMenuItem);
5678 colourMenu.add(modifyConservation);
5679 colourMenu.add(abovePIDThreshold);
5680 colourMenu.add(modifyPID);
5681 colourMenu.add(annotationColour);
5683 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5684 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5688 * Open a dialog (if not already open) that allows the user to select and
5689 * calculate PCA or Tree analysis
5691 protected void openTreePcaDialog()
5693 if (alignPanel.getCalculationDialog() == null)
5695 new CalculationChooser(AlignFrame.this);
5700 class PrintThread extends Thread
5704 public PrintThread(AlignmentPanel ap)
5709 static PageFormat pf;
5714 PrinterJob printJob = PrinterJob.getPrinterJob();
5718 printJob.setPrintable(ap, pf);
5722 printJob.setPrintable(ap);
5725 if (printJob.printDialog())
5730 } catch (Exception PrintException)
5732 PrintException.printStackTrace();