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.ws.DBRefFetcher;
96 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
97 import jalview.ws.jws1.Discoverer;
98 import jalview.ws.jws2.Jws2Discoverer;
99 import jalview.ws.jws2.jabaws2.Jws2Instance;
100 import jalview.ws.seqfetcher.DbSourceProxy;
102 import java.awt.BorderLayout;
103 import java.awt.Component;
104 import java.awt.Rectangle;
105 import java.awt.Toolkit;
106 import java.awt.datatransfer.Clipboard;
107 import java.awt.datatransfer.DataFlavor;
108 import java.awt.datatransfer.StringSelection;
109 import java.awt.datatransfer.Transferable;
110 import java.awt.dnd.DnDConstants;
111 import java.awt.dnd.DropTargetDragEvent;
112 import java.awt.dnd.DropTargetDropEvent;
113 import java.awt.dnd.DropTargetEvent;
114 import java.awt.dnd.DropTargetListener;
115 import java.awt.event.ActionEvent;
116 import java.awt.event.ActionListener;
117 import java.awt.event.FocusAdapter;
118 import java.awt.event.FocusEvent;
119 import java.awt.event.ItemEvent;
120 import java.awt.event.ItemListener;
121 import java.awt.event.KeyAdapter;
122 import java.awt.event.KeyEvent;
123 import java.awt.event.MouseEvent;
124 import java.awt.print.PageFormat;
125 import java.awt.print.PrinterJob;
126 import java.beans.PropertyChangeEvent;
128 import java.io.FileWriter;
129 import java.io.IOException;
130 import java.io.PrintWriter;
132 import java.util.ArrayList;
133 import java.util.Arrays;
134 import java.util.Deque;
135 import java.util.Enumeration;
136 import java.util.HashMap;
137 import java.util.Hashtable;
138 import java.util.List;
139 import java.util.Map;
140 import java.util.Vector;
142 import javax.swing.JCheckBoxMenuItem;
143 import javax.swing.JEditorPane;
144 import javax.swing.JInternalFrame;
145 import javax.swing.JLayeredPane;
146 import javax.swing.JMenu;
147 import javax.swing.JMenuItem;
148 import javax.swing.JScrollPane;
149 import javax.swing.SwingUtilities;
155 * @version $Revision$
157 public class AlignFrame extends GAlignFrame implements DropTargetListener,
158 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
161 Map<String, Float> distribution = new HashMap<>(); // temporary
163 public static final int DEFAULT_WIDTH = 700;
165 public static final int DEFAULT_HEIGHT = 500;
168 * The currently displayed panel (selected tabbed view if more than one)
170 public AlignmentPanel alignPanel;
172 AlignViewport viewport;
174 ViewportRanges vpRanges;
176 public AlignViewControllerI avc;
178 List<AlignmentPanel> alignPanels = new ArrayList<>();
181 * Last format used to load or save alignments in this window
183 FileFormatI currentFileFormat = null;
186 * Current filename for this alignment
188 String fileName = null;
192 * Creates a new AlignFrame object with specific width and height.
198 public AlignFrame(AlignmentI al, int width, int height)
200 this(al, null, width, height);
204 * Creates a new AlignFrame object with specific width, height and
210 * @param sequenceSetId
212 public AlignFrame(AlignmentI al, int width, int height,
213 String sequenceSetId)
215 this(al, null, width, height, sequenceSetId);
219 * Creates a new AlignFrame object with specific width, height and
225 * @param sequenceSetId
228 public AlignFrame(AlignmentI al, int width, int height,
229 String sequenceSetId, String viewId)
231 this(al, null, width, height, sequenceSetId, viewId);
235 * new alignment window with hidden columns
239 * @param hiddenColumns
240 * ColumnSelection or null
242 * Width of alignment frame
246 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns,
247 int width, int height)
249 this(al, hiddenColumns, width, height, null);
253 * Create alignment frame for al with hiddenColumns, a specific width and
254 * height, and specific sequenceId
257 * @param hiddenColumns
260 * @param sequenceSetId
263 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns,
264 int width, int height, String sequenceSetId)
266 this(al, hiddenColumns, width, height, sequenceSetId, null);
270 * Create alignment frame for al with hiddenColumns, a specific width and
271 * height, and specific sequenceId
274 * @param hiddenColumns
277 * @param sequenceSetId
282 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns,
283 int width, int height, String sequenceSetId, String viewId)
285 setSize(width, height);
287 if (al.getDataset() == null)
292 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
294 alignPanel = new AlignmentPanel(this, viewport);
296 addAlignmentPanel(alignPanel, true);
300 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
301 HiddenColumns hiddenColumns, int width, int height)
303 setSize(width, height);
305 if (al.getDataset() == null)
310 viewport = new AlignViewport(al, hiddenColumns);
312 if (hiddenSeqs != null && hiddenSeqs.length > 0)
314 viewport.hideSequence(hiddenSeqs);
316 alignPanel = new AlignmentPanel(this, viewport);
317 addAlignmentPanel(alignPanel, true);
322 * Make a new AlignFrame from existing alignmentPanels
329 public AlignFrame(AlignmentPanel ap)
333 addAlignmentPanel(ap, false);
338 * initalise the alignframe from the underlying viewport data and the
343 if (!Jalview.isHeadlessMode())
345 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
348 vpRanges = viewport.getRanges();
349 avc = new jalview.controller.AlignViewController(this, viewport,
351 if (viewport.getAlignmentConservationAnnotation() == null)
353 // BLOSUM62Colour.setEnabled(false);
354 conservationMenuItem.setEnabled(false);
355 modifyConservation.setEnabled(false);
356 // PIDColour.setEnabled(false);
357 // abovePIDThreshold.setEnabled(false);
358 // modifyPID.setEnabled(false);
361 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
364 if (sortby.equals("Id"))
366 sortIDMenuItem_actionPerformed(null);
368 else if (sortby.equals("Pairwise Identity"))
370 sortPairwiseMenuItem_actionPerformed(null);
374 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
376 setMenusFromViewport(viewport);
377 buildSortByAnnotationScoresMenu();
378 calculateTree.addActionListener(new ActionListener()
382 public void actionPerformed(ActionEvent e)
390 if (Desktop.desktop != null)
392 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
393 addServiceListeners();
397 if (viewport.getWrapAlignment())
399 wrapMenuItem_actionPerformed(null);
402 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
404 this.overviewMenuItem_actionPerformed(null);
409 final List<AlignmentPanel> selviews = new ArrayList<>();
410 final List<AlignmentPanel> origview = new ArrayList<>();
411 final String menuLabel = MessageManager
412 .getString("label.copy_format_from");
413 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
414 new ViewSetProvider()
418 public AlignmentPanel[] getAllAlignmentPanels()
421 origview.add(alignPanel);
422 // make an array of all alignment panels except for this one
423 List<AlignmentPanel> aps = new ArrayList<>(
424 Arrays.asList(Desktop.getAlignmentPanels(null)));
425 aps.remove(AlignFrame.this.alignPanel);
426 return aps.toArray(new AlignmentPanel[aps.size()]);
428 }, selviews, new ItemListener()
432 public void itemStateChanged(ItemEvent e)
434 if (origview.size() > 0)
436 final AlignmentPanel ap = origview.get(0);
439 * Copy the ViewStyle of the selected panel to 'this one'.
440 * Don't change value of 'scaleProteinAsCdna' unless copying
443 ViewStyleI vs = selviews.get(0).getAlignViewport()
445 boolean fromSplitFrame = selviews.get(0)
446 .getAlignViewport().getCodingComplement() != null;
449 vs.setScaleProteinAsCdna(ap.getAlignViewport()
450 .getViewStyle().isScaleProteinAsCdna());
452 ap.getAlignViewport().setViewStyle(vs);
455 * Also rescale ViewStyle of SplitFrame complement if there is
456 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
457 * the whole ViewStyle (allow cDNA protein to have different
460 AlignViewportI complement = ap.getAlignViewport()
461 .getCodingComplement();
462 if (complement != null && vs.isScaleProteinAsCdna())
464 AlignFrame af = Desktop.getAlignFrameFor(complement);
465 ((SplitFrame) af.getSplitViewContainer())
467 af.setMenusForViewport();
471 ap.setSelected(true);
472 ap.alignFrame.setMenusForViewport();
477 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
478 .indexOf("devel") > -1
479 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
480 .indexOf("test") > -1)
482 formatMenu.add(vsel);
484 addFocusListener(new FocusAdapter()
487 public void focusGained(FocusEvent e)
489 Jalview.setCurrentAlignFrame(AlignFrame.this);
495 private void buildHMMERMenu()
497 hmmerMenu.removeAll();
499 hmmerMenu.add(autoAlignSeqs);
500 hmmerMenu.addSeparator();
502 hmmerMenu.add(hmmAlign);
503 hmmerMenu.add(hmmBuild);
504 hmmerMenu.add(hmmSearch);
509 * Change the filename and format for the alignment, and enable the 'reload'
510 * button functionality.
517 public void setFileName(String file, FileFormatI format)
520 setFileFormat(format);
521 reload.setEnabled(true);
525 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
528 void addKeyListener()
530 addKeyListener(new KeyAdapter()
533 public void keyPressed(KeyEvent evt)
535 if (viewport.cursorMode
536 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
537 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
538 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
539 && Character.isDigit(evt.getKeyChar()))
541 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
544 switch (evt.getKeyCode())
547 case 27: // escape key
548 deselectAllSequenceMenuItem_actionPerformed(null);
552 case KeyEvent.VK_DOWN:
553 if (evt.isAltDown() || !viewport.cursorMode)
555 moveSelectedSequences(false);
557 if (viewport.cursorMode)
559 alignPanel.getSeqPanel().moveCursor(0, 1);
564 if (evt.isAltDown() || !viewport.cursorMode)
566 moveSelectedSequences(true);
568 if (viewport.cursorMode)
570 alignPanel.getSeqPanel().moveCursor(0, -1);
575 case KeyEvent.VK_LEFT:
576 if (evt.isAltDown() || !viewport.cursorMode)
578 slideSequences(false, alignPanel.getSeqPanel().getKeyboardNo1());
582 alignPanel.getSeqPanel().moveCursor(-1, 0);
587 case KeyEvent.VK_RIGHT:
588 if (evt.isAltDown() || !viewport.cursorMode)
590 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
594 alignPanel.getSeqPanel().moveCursor(1, 0);
598 case KeyEvent.VK_SPACE:
599 if (viewport.cursorMode)
601 alignPanel.getSeqPanel().insertGapAtCursor(
602 evt.isControlDown() || evt.isShiftDown()
607 // case KeyEvent.VK_A:
608 // if (viewport.cursorMode)
610 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
611 // //System.out.println("A");
615 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
616 * System.out.println("closing bracket"); } break;
618 case KeyEvent.VK_DELETE:
619 case KeyEvent.VK_BACK_SPACE:
620 if (!viewport.cursorMode)
622 cut_actionPerformed(null);
626 alignPanel.getSeqPanel().deleteGapAtCursor(
627 evt.isControlDown() || evt.isShiftDown()
634 if (viewport.cursorMode)
636 alignPanel.getSeqPanel().setCursorRow();
640 if (viewport.cursorMode && !evt.isControlDown())
642 alignPanel.getSeqPanel().setCursorColumn();
646 if (viewport.cursorMode)
648 alignPanel.getSeqPanel().setCursorPosition();
652 case KeyEvent.VK_ENTER:
653 case KeyEvent.VK_COMMA:
654 if (viewport.cursorMode)
656 alignPanel.getSeqPanel().setCursorRowAndColumn();
661 if (viewport.cursorMode)
663 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
667 if (viewport.cursorMode)
669 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
674 viewport.cursorMode = !viewport.cursorMode;
675 statusBar.setText(MessageManager.formatMessage(
676 "label.keyboard_editing_mode",
677 new String[] { (viewport.cursorMode ? "on" : "off") }));
678 if (viewport.cursorMode)
680 alignPanel.getSeqPanel().seqCanvas.cursorX = vpRanges
682 alignPanel.getSeqPanel().seqCanvas.cursorY = vpRanges
685 alignPanel.getSeqPanel().seqCanvas.repaint();
691 Help.showHelpWindow();
692 } catch (Exception ex)
694 ex.printStackTrace();
699 boolean toggleSeqs = !evt.isControlDown();
700 boolean toggleCols = !evt.isShiftDown();
701 toggleHiddenRegions(toggleSeqs, toggleCols);
706 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
707 boolean modifyExisting = true; // always modify, don't clear
708 // evt.isShiftDown();
709 boolean invertHighlighted = evt.isAltDown();
710 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
714 case KeyEvent.VK_PAGE_UP:
715 if (viewport.getWrapAlignment())
717 vpRanges.scrollUp(true);
724 case KeyEvent.VK_PAGE_DOWN:
725 if (viewport.getWrapAlignment())
727 vpRanges.scrollUp(false);
738 public void keyReleased(KeyEvent evt)
740 switch (evt.getKeyCode())
742 case KeyEvent.VK_LEFT:
743 if (evt.isAltDown() || !viewport.cursorMode)
745 viewport.firePropertyChange("alignment", null, viewport
746 .getAlignment().getSequences());
750 case KeyEvent.VK_RIGHT:
751 if (evt.isAltDown() || !viewport.cursorMode)
753 viewport.firePropertyChange("alignment", null, viewport
754 .getAlignment().getSequences());
762 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
764 ap.alignFrame = this;
765 avc = new jalview.controller.AlignViewController(this, viewport,
770 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
772 int aSize = alignPanels.size();
774 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
776 if (aSize == 1 && ap.av.viewName == null)
778 this.getContentPane().add(ap, BorderLayout.CENTER);
784 setInitialTabVisible();
787 expandViews.setEnabled(true);
788 gatherViews.setEnabled(true);
789 tabbedPane.addTab(ap.av.viewName, ap);
791 ap.setVisible(false);
796 if (ap.av.isPadGaps())
798 ap.av.getAlignment().padGaps();
800 ap.av.updateConservation(ap);
801 ap.av.updateConsensus(ap);
802 ap.av.updateStrucConsensus(ap);
806 public void setInitialTabVisible()
808 expandViews.setEnabled(true);
809 gatherViews.setEnabled(true);
810 tabbedPane.setVisible(true);
811 AlignmentPanel first = alignPanels.get(0);
812 tabbedPane.addTab(first.av.viewName, first);
813 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
816 public AlignViewport getViewport()
821 /* Set up intrinsic listeners for dynamically generated GUI bits. */
822 private void addServiceListeners()
824 final java.beans.PropertyChangeListener thisListener;
825 Desktop.instance.addJalviewPropertyChangeListener("services",
826 thisListener = new java.beans.PropertyChangeListener()
829 public void propertyChange(PropertyChangeEvent evt)
831 // // System.out.println("Discoverer property change.");
832 // if (evt.getPropertyName().equals("services"))
834 SwingUtilities.invokeLater(new Runnable()
841 .println("Rebuild WS Menu for service change");
842 BuildWebServiceMenu();
849 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
852 public void internalFrameClosed(
853 javax.swing.event.InternalFrameEvent evt)
855 // System.out.println("deregistering discoverer listener");
856 Desktop.instance.removeJalviewPropertyChangeListener("services",
858 closeMenuItem_actionPerformed(true);
861 // Finally, build the menu once to get current service state
862 new Thread(new Runnable()
867 BuildWebServiceMenu();
873 * Configure menu items that vary according to whether the alignment is
874 * nucleotide or protein
876 public void setGUINucleotide()
878 AlignmentI al = getViewport().getAlignment();
879 boolean nucleotide = al.isNucleotide();
881 showTranslation.setVisible(nucleotide);
882 showReverse.setVisible(nucleotide);
883 showReverseComplement.setVisible(nucleotide);
884 conservationMenuItem.setEnabled(!nucleotide);
885 modifyConservation.setEnabled(!nucleotide
886 && conservationMenuItem.isSelected());
887 showGroupConservation.setEnabled(!nucleotide);
889 showComplementMenuItem.setText(nucleotide ? MessageManager
890 .getString("label.protein") : MessageManager
891 .getString("label.nucleotide"));
895 * set up menus for the current viewport. This may be called after any
896 * operation that affects the data in the current view (selection changed,
897 * etc) to update the menus to reflect the new state.
900 public void setMenusForViewport()
902 setMenusFromViewport(viewport);
906 * Need to call this method when tabs are selected for multiple views, or when
907 * loading from Jalview2XML.java
912 void setMenusFromViewport(AlignViewport av)
914 padGapsMenuitem.setSelected(av.isPadGaps());
915 colourTextMenuItem.setSelected(av.isShowColourText());
916 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
917 modifyPID.setEnabled(abovePIDThreshold.isSelected());
918 conservationMenuItem.setSelected(av.getConservationSelected());
919 modifyConservation.setEnabled(conservationMenuItem.isSelected());
920 seqLimits.setSelected(av.getShowJVSuffix());
921 idRightAlign.setSelected(av.isRightAlignIds());
922 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
923 renderGapsMenuItem.setSelected(av.isRenderGaps());
924 wrapMenuItem.setSelected(av.getWrapAlignment());
925 scaleAbove.setVisible(av.getWrapAlignment());
926 scaleLeft.setVisible(av.getWrapAlignment());
927 scaleRight.setVisible(av.getWrapAlignment());
928 annotationPanelMenuItem.setState(av.isShowAnnotation());
930 * Show/hide annotations only enabled if annotation panel is shown
932 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
933 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
934 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
935 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
936 viewBoxesMenuItem.setSelected(av.getShowBoxes());
937 viewTextMenuItem.setSelected(av.getShowText());
938 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
939 showGroupConsensus.setSelected(av.isShowGroupConsensus());
940 showGroupConservation.setSelected(av.isShowGroupConservation());
941 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
942 showSequenceLogo.setSelected(av.isShowSequenceLogo());
943 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
944 showInformationHistogram.setSelected(av.isShowInformationHistogram());
945 showHMMSequenceLogo.setSelected(av.isShowHMMSequenceLogo());
946 normaliseHMMSequenceLogo.setSelected(av.isNormaliseHMMSequenceLogo());
948 ColourMenuHelper.setColourSelected(colourMenu,
949 av.getGlobalColourScheme());
951 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
952 hiddenMarkers.setState(av.getShowHiddenMarkers());
953 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
954 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
955 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
956 autoCalculate.setSelected(av.autoCalculateConsensus);
957 sortByTree.setSelected(av.sortByTree);
958 listenToViewSelections.setSelected(av.followSelection);
960 showProducts.setEnabled(canShowProducts());
961 setGroovyEnabled(Desktop.getGroovyConsole() != null);
967 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
971 public void setGroovyEnabled(boolean b)
973 runGroovy.setEnabled(b);
976 private IProgressIndicator progressBar;
981 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
984 public void setProgressBar(String message, long id)
986 progressBar.setProgressBar(message, id);
990 public void registerHandler(final long id,
991 final IProgressIndicatorHandler handler)
993 progressBar.registerHandler(id, handler);
998 * @return true if any progress bars are still active
1001 public boolean operationInProgress()
1003 return progressBar.operationInProgress();
1007 public void setStatus(String text)
1009 statusBar.setText(text);
1013 * Added so Castor Mapping file can obtain Jalview Version
1015 public String getVersion()
1017 return jalview.bin.Cache.getProperty("VERSION");
1020 public FeatureRenderer getFeatureRenderer()
1022 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1026 public void fetchSequence_actionPerformed(ActionEvent e)
1028 new jalview.gui.SequenceFetcher(this);
1032 public void addFromFile_actionPerformed(ActionEvent e)
1034 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1038 public void hmmBuild_actionPerformed(ActionEvent e)
1039 throws IOException, InterruptedException
1042 HMMERCommands.hmmBuild(this);
1043 alignPanel.repaint();
1047 public void hmmAlign_actionPerformed(ActionEvent e)
1050 alignPanel.repaint();
1054 public void hmmSearch_actionPerformed(ActionEvent e)
1057 alignPanel.repaint();
1061 public void reload_actionPerformed(ActionEvent e)
1063 if (fileName != null)
1065 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1066 // originating file's format
1067 // TODO: work out how to recover feature settings for correct view(s) when
1068 // file is reloaded.
1069 if (FileFormat.Jalview.equals(currentFileFormat))
1071 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1072 for (int i = 0; i < frames.length; i++)
1074 if (frames[i] instanceof AlignFrame && frames[i] != this
1075 && ((AlignFrame) frames[i]).fileName != null
1076 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1080 frames[i].setSelected(true);
1081 Desktop.instance.closeAssociatedWindows();
1082 } catch (java.beans.PropertyVetoException ex)
1088 Desktop.instance.closeAssociatedWindows();
1090 FileLoader loader = new FileLoader();
1091 DataSourceType protocol = fileName.startsWith("http:") ? DataSourceType.URL
1092 : DataSourceType.FILE;
1093 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1097 Rectangle bounds = this.getBounds();
1099 FileLoader loader = new FileLoader();
1100 DataSourceType protocol = fileName.startsWith("http:") ? DataSourceType.URL
1101 : DataSourceType.FILE;
1102 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1103 protocol, currentFileFormat);
1105 newframe.setBounds(bounds);
1106 if (featureSettings != null && featureSettings.isShowing())
1108 final Rectangle fspos = featureSettings.frame.getBounds();
1109 // TODO: need a 'show feature settings' function that takes bounds -
1110 // need to refactor Desktop.addFrame
1111 newframe.featureSettings_actionPerformed(null);
1112 final FeatureSettings nfs = newframe.featureSettings;
1113 SwingUtilities.invokeLater(new Runnable()
1118 nfs.frame.setBounds(fspos);
1121 this.featureSettings.close();
1122 this.featureSettings = null;
1124 this.closeMenuItem_actionPerformed(true);
1130 public void addFromText_actionPerformed(ActionEvent e)
1132 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport
1137 public void addFromURL_actionPerformed(ActionEvent e)
1139 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1143 public void save_actionPerformed(ActionEvent e)
1145 if (fileName == null || (currentFileFormat == null)
1146 || fileName.startsWith("http"))
1148 saveAs_actionPerformed(null);
1152 saveAlignment(fileName, currentFileFormat);
1163 public void saveAs_actionPerformed(ActionEvent e)
1165 String format = currentFileFormat == null ? null : currentFileFormat
1167 JalviewFileChooser chooser = JalviewFileChooser.forWrite(
1168 Cache.getProperty("LAST_DIRECTORY"), format);
1170 chooser.setFileView(new JalviewFileView());
1171 chooser.setDialogTitle(MessageManager
1172 .getString("label.save_alignment_to_file"));
1173 chooser.setToolTipText(MessageManager.getString("action.save"));
1175 int value = chooser.showSaveDialog(this);
1177 if (value == JalviewFileChooser.APPROVE_OPTION)
1179 currentFileFormat = chooser.getSelectedFormat();
1180 while (currentFileFormat == null)
1183 .showInternalMessageDialog(
1186 .getString("label.select_file_format_before_saving"),
1188 .getString("label.file_format_not_specified"),
1189 JvOptionPane.WARNING_MESSAGE);
1190 currentFileFormat = chooser.getSelectedFormat();
1191 value = chooser.showSaveDialog(this);
1192 if (value != JalviewFileChooser.APPROVE_OPTION)
1198 fileName = chooser.getSelectedFile().getPath();
1200 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1202 Cache.setProperty("LAST_DIRECTORY", fileName);
1203 saveAlignment(fileName, currentFileFormat);
1207 public boolean saveAlignment(String file, FileFormatI format)
1209 boolean success = true;
1211 if (FileFormat.Jalview.equals(format))
1213 String shortName = title;
1215 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1217 shortName = shortName.substring(shortName
1218 .lastIndexOf(java.io.File.separatorChar) + 1);
1221 success = new Jalview2XML().saveAlignment(this, file, shortName);
1223 statusBar.setText(MessageManager.formatMessage(
1224 "label.successfully_saved_to_file_in_format", new Object[] {
1225 fileName, format }));
1230 AlignmentExportData exportData = getAlignmentForExport(format,
1232 if (exportData.getSettings().isCancelled())
1236 FormatAdapter f = new FormatAdapter(alignPanel,
1237 exportData.getSettings());
1238 String output = f.formatSequences(
1240 exportData.getAlignment(), // class cast exceptions will
1241 // occur in the distant future
1242 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1243 f.getCacheSuffixDefault(format), viewport.getAlignment()
1244 .getHiddenColumns());
1254 PrintWriter out = new PrintWriter(new FileWriter(file));
1258 this.setTitle(file);
1259 statusBar.setText(MessageManager.formatMessage(
1260 "label.successfully_saved_to_file_in_format",
1261 new Object[] { fileName, format.getName() }));
1262 } catch (Exception ex)
1265 ex.printStackTrace();
1272 JvOptionPane.showInternalMessageDialog(this, MessageManager
1273 .formatMessage("label.couldnt_save_file",
1274 new Object[] { fileName }), MessageManager
1275 .getString("label.error_saving_file"),
1276 JvOptionPane.WARNING_MESSAGE);
1282 private void warningMessage(String warning, String title)
1284 if (new jalview.util.Platform().isHeadless())
1286 System.err.println("Warning: " + title + "\nWarning: " + warning);
1291 JvOptionPane.showInternalMessageDialog(this, warning, title,
1292 JvOptionPane.WARNING_MESSAGE);
1304 protected void outputText_actionPerformed(ActionEvent e)
1306 FileFormatI fileFormat = FileFormats.getInstance().forName(
1307 e.getActionCommand());
1308 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1310 if (exportData.getSettings().isCancelled())
1314 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1315 cap.setForInput(null);
1318 FileFormatI format = fileFormat;
1319 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1320 .formatSequences(format, exportData.getAlignment(),
1321 exportData.getOmitHidden(),
1323 .getStartEndPostions(), viewport
1324 .getAlignment().getHiddenColumns()));
1325 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1326 "label.alignment_output_command",
1327 new Object[] { e.getActionCommand() }), 600, 500);
1328 } catch (OutOfMemoryError oom)
1330 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1336 public static AlignmentExportData getAlignmentForExport(
1337 FileFormatI format, AlignViewportI viewport,
1338 AlignExportSettingI exportSettings)
1340 AlignmentI alignmentToExport = null;
1341 AlignExportSettingI settings = exportSettings;
1342 String[] omitHidden = null;
1344 HiddenSequences hiddenSeqs = viewport.getAlignment()
1345 .getHiddenSequences();
1347 alignmentToExport = viewport.getAlignment();
1349 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1350 if (settings == null)
1352 settings = new AlignExportSettings(hasHiddenSeqs,
1353 viewport.hasHiddenColumns(), format);
1355 // settings.isExportAnnotations();
1357 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1359 omitHidden = viewport.getViewAsString(false,
1360 settings.isExportHiddenSequences());
1363 int[] alignmentStartEnd = new int[2];
1364 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1366 alignmentToExport = hiddenSeqs.getFullAlignment();
1370 alignmentToExport = viewport.getAlignment();
1372 alignmentStartEnd = alignmentToExport
1373 .getVisibleStartAndEndIndex(viewport.getAlignment()
1375 .getHiddenRegions());
1376 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1377 omitHidden, alignmentStartEnd, settings);
1388 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1390 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1391 htmlSVG.exportHTML(null);
1395 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1397 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1398 bjs.exportHTML(null);
1401 public void createImageMap(File file, String image)
1403 alignPanel.makePNGImageMap(file, image);
1413 public void createPNG(File f)
1415 alignPanel.makePNG(f);
1425 public void createEPS(File f)
1427 alignPanel.makeEPS(f);
1431 public void createSVG(File f)
1433 alignPanel.makeSVG(f);
1437 public void pageSetup_actionPerformed(ActionEvent e)
1439 PrinterJob printJob = PrinterJob.getPrinterJob();
1440 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1450 public void printMenuItem_actionPerformed(ActionEvent e)
1452 // Putting in a thread avoids Swing painting problems
1453 PrintThread thread = new PrintThread(alignPanel);
1458 public void exportFeatures_actionPerformed(ActionEvent e)
1460 new AnnotationExporter().exportFeatures(alignPanel);
1464 public void exportAnnotations_actionPerformed(ActionEvent e)
1466 new AnnotationExporter().exportAnnotations(alignPanel);
1470 public void associatedData_actionPerformed(ActionEvent e)
1472 // Pick the tree file
1473 JalviewFileChooser chooser = new JalviewFileChooser(
1474 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1475 chooser.setFileView(new JalviewFileView());
1476 chooser.setDialogTitle(MessageManager
1477 .getString("label.load_jalview_annotations"));
1478 chooser.setToolTipText(MessageManager
1479 .getString("label.load_jalview_annotations"));
1481 int value = chooser.showOpenDialog(null);
1483 if (value == JalviewFileChooser.APPROVE_OPTION)
1485 String choice = chooser.getSelectedFile().getPath();
1486 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1487 loadJalviewDataFile(choice, null, null, null);
1493 * Close the current view or all views in the alignment frame. If the frame
1494 * only contains one view then the alignment will be removed from memory.
1496 * @param closeAllTabs
1499 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1501 if (alignPanels != null && alignPanels.size() < 2)
1503 closeAllTabs = true;
1508 if (alignPanels != null)
1512 if (this.isClosed())
1514 // really close all the windows - otherwise wait till
1515 // setClosed(true) is called
1516 for (int i = 0; i < alignPanels.size(); i++)
1518 AlignmentPanel ap = alignPanels.get(i);
1525 closeView(alignPanel);
1532 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1533 * be called recursively, with the frame now in 'closed' state
1535 this.setClosed(true);
1537 } catch (Exception ex)
1539 ex.printStackTrace();
1544 * Close the specified panel and close up tabs appropriately.
1546 * @param panelToClose
1548 public void closeView(AlignmentPanel panelToClose)
1550 int index = tabbedPane.getSelectedIndex();
1551 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1552 alignPanels.remove(panelToClose);
1553 panelToClose.closePanel();
1554 panelToClose = null;
1556 tabbedPane.removeTabAt(closedindex);
1557 tabbedPane.validate();
1559 if (index > closedindex || index == tabbedPane.getTabCount())
1561 // modify currently selected tab index if necessary.
1565 this.tabSelectionChanged(index);
1571 void updateEditMenuBar()
1574 if (viewport.getHistoryList().size() > 0)
1576 undoMenuItem.setEnabled(true);
1577 CommandI command = viewport.getHistoryList().peek();
1578 undoMenuItem.setText(MessageManager.formatMessage(
1579 "label.undo_command",
1580 new Object[] { command.getDescription() }));
1584 undoMenuItem.setEnabled(false);
1585 undoMenuItem.setText(MessageManager.getString("action.undo"));
1588 if (viewport.getRedoList().size() > 0)
1590 redoMenuItem.setEnabled(true);
1592 CommandI command = viewport.getRedoList().peek();
1593 redoMenuItem.setText(MessageManager.formatMessage(
1594 "label.redo_command",
1595 new Object[] { command.getDescription() }));
1599 redoMenuItem.setEnabled(false);
1600 redoMenuItem.setText(MessageManager.getString("action.redo"));
1605 public void addHistoryItem(CommandI command)
1607 if (command.getSize() > 0)
1609 viewport.addToHistoryList(command);
1610 viewport.clearRedoList();
1611 updateEditMenuBar();
1612 viewport.updateHiddenColumns();
1613 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1614 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1615 // viewport.getColumnSelection()
1616 // .getHiddenColumns().size() > 0);
1622 * @return alignment objects for all views
1624 AlignmentI[] getViewAlignments()
1626 if (alignPanels != null)
1628 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1630 for (AlignmentPanel ap : alignPanels)
1632 als[i++] = ap.av.getAlignment();
1636 if (viewport != null)
1638 return new AlignmentI[] { viewport.getAlignment() };
1650 protected void undoMenuItem_actionPerformed(ActionEvent e)
1652 if (viewport.getHistoryList().isEmpty())
1656 CommandI command = viewport.getHistoryList().pop();
1657 viewport.addToRedoList(command);
1658 command.undoCommand(getViewAlignments());
1660 AlignmentViewport originalSource = getOriginatingSource(command);
1661 updateEditMenuBar();
1663 if (originalSource != null)
1665 if (originalSource != viewport)
1668 .warn("Implementation worry: mismatch of viewport origin for undo");
1670 originalSource.updateHiddenColumns();
1671 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1673 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1674 // viewport.getColumnSelection()
1675 // .getHiddenColumns().size() > 0);
1676 originalSource.firePropertyChange("alignment", null, originalSource
1677 .getAlignment().getSequences());
1688 protected void redoMenuItem_actionPerformed(ActionEvent e)
1690 if (viewport.getRedoList().size() < 1)
1695 CommandI command = viewport.getRedoList().pop();
1696 viewport.addToHistoryList(command);
1697 command.doCommand(getViewAlignments());
1699 AlignmentViewport originalSource = getOriginatingSource(command);
1700 updateEditMenuBar();
1702 if (originalSource != null)
1705 if (originalSource != viewport)
1708 .warn("Implementation worry: mismatch of viewport origin for redo");
1710 originalSource.updateHiddenColumns();
1711 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1713 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1714 // viewport.getColumnSelection()
1715 // .getHiddenColumns().size() > 0);
1716 originalSource.firePropertyChange("alignment", null, originalSource
1717 .getAlignment().getSequences());
1721 AlignmentViewport getOriginatingSource(CommandI command)
1723 AlignmentViewport originalSource = null;
1724 // For sequence removal and addition, we need to fire
1725 // the property change event FROM the viewport where the
1726 // original alignment was altered
1727 AlignmentI al = null;
1728 if (command instanceof EditCommand)
1730 EditCommand editCommand = (EditCommand) command;
1731 al = editCommand.getAlignment();
1732 List<Component> comps = PaintRefresher.components.get(viewport
1733 .getSequenceSetId());
1735 for (Component comp : comps)
1737 if (comp instanceof AlignmentPanel)
1739 if (al == ((AlignmentPanel) comp).av.getAlignment())
1741 originalSource = ((AlignmentPanel) comp).av;
1748 if (originalSource == null)
1750 // The original view is closed, we must validate
1751 // the current view against the closed view first
1754 PaintRefresher.validateSequences(al, viewport.getAlignment());
1757 originalSource = viewport;
1760 return originalSource;
1769 public void moveSelectedSequences(boolean up)
1771 SequenceGroup sg = viewport.getSelectionGroup();
1777 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1778 viewport.getHiddenRepSequences(), up);
1779 alignPanel.paintAlignment(true);
1782 synchronized void slideSequences(boolean right, int size)
1784 List<SequenceI> sg = new ArrayList<>();
1785 if (viewport.cursorMode)
1787 sg.add(viewport.getAlignment().getSequenceAt(
1788 alignPanel.getSeqPanel().seqCanvas.cursorY));
1790 else if (viewport.getSelectionGroup() != null
1791 && viewport.getSelectionGroup().getSize() != viewport
1792 .getAlignment().getHeight())
1794 sg = viewport.getSelectionGroup().getSequences(
1795 viewport.getHiddenRepSequences());
1803 List<SequenceI> invertGroup = new ArrayList<>();
1805 for (SequenceI seq : viewport.getAlignment().getSequences())
1807 if (!sg.contains(seq))
1809 invertGroup.add(seq);
1813 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1815 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1816 for (int i = 0; i < invertGroup.size(); i++)
1818 seqs2[i] = invertGroup.get(i);
1821 SlideSequencesCommand ssc;
1824 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1825 size, viewport.getGapCharacter());
1829 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1830 size, viewport.getGapCharacter());
1833 int groupAdjustment = 0;
1834 if (ssc.getGapsInsertedBegin() && right)
1836 if (viewport.cursorMode)
1838 alignPanel.getSeqPanel().moveCursor(size, 0);
1842 groupAdjustment = size;
1845 else if (!ssc.getGapsInsertedBegin() && !right)
1847 if (viewport.cursorMode)
1849 alignPanel.getSeqPanel().moveCursor(-size, 0);
1853 groupAdjustment = -size;
1857 if (groupAdjustment != 0)
1859 viewport.getSelectionGroup().setStartRes(
1860 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1861 viewport.getSelectionGroup().setEndRes(
1862 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1866 * just extend the last slide command if compatible; but not if in
1867 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1869 boolean appendHistoryItem = false;
1870 Deque<CommandI> historyList = viewport.getHistoryList();
1871 boolean inSplitFrame = getSplitViewContainer() != null;
1872 if (!inSplitFrame && historyList != null && historyList.size() > 0
1873 && historyList.peek() instanceof SlideSequencesCommand)
1875 appendHistoryItem = ssc
1876 .appendSlideCommand((SlideSequencesCommand) historyList
1880 if (!appendHistoryItem)
1882 addHistoryItem(ssc);
1895 protected void copy_actionPerformed(ActionEvent e)
1898 if (viewport.getSelectionGroup() == null)
1902 // TODO: preserve the ordering of displayed alignment annotation in any
1903 // internal paste (particularly sequence associated annotation)
1904 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1905 String[] omitHidden = null;
1907 if (viewport.hasHiddenColumns())
1909 omitHidden = viewport.getViewAsString(true);
1912 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1913 seqs, omitHidden, null);
1915 StringSelection ss = new StringSelection(output);
1919 jalview.gui.Desktop.internalCopy = true;
1920 // Its really worth setting the clipboard contents
1921 // to empty before setting the large StringSelection!!
1922 Toolkit.getDefaultToolkit().getSystemClipboard()
1923 .setContents(new StringSelection(""), null);
1925 Toolkit.getDefaultToolkit().getSystemClipboard()
1926 .setContents(ss, Desktop.instance);
1927 } catch (OutOfMemoryError er)
1929 new OOMWarning("copying region", er);
1933 ArrayList<int[]> hiddenColumns = null;
1934 if (viewport.hasHiddenColumns())
1936 hiddenColumns = new ArrayList<>();
1937 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1938 .getSelectionGroup().getEndRes();
1939 for (int[] region : viewport.getAlignment().getHiddenColumns()
1940 .getHiddenRegions())
1942 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1944 hiddenColumns.add(new int[] { region[0] - hiddenOffset,
1945 region[1] - hiddenOffset });
1950 Desktop.jalviewClipboard = new Object[] { seqs,
1951 viewport.getAlignment().getDataset(), hiddenColumns };
1952 statusBar.setText(MessageManager.formatMessage(
1953 "label.copied_sequences_to_clipboard", new Object[] { Integer
1954 .valueOf(seqs.length).toString() }));
1964 protected void pasteNew_actionPerformed(ActionEvent e)
1976 protected void pasteThis_actionPerformed(ActionEvent e)
1982 * Paste contents of Jalview clipboard
1984 * @param newAlignment
1985 * true to paste to a new alignment, otherwise add to this.
1987 void paste(boolean newAlignment)
1989 boolean externalPaste = true;
1992 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1993 Transferable contents = c.getContents(this);
1995 if (contents == null)
2004 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2005 if (str.length() < 1)
2010 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2012 } catch (OutOfMemoryError er)
2014 new OOMWarning("Out of memory pasting sequences!!", er);
2018 SequenceI[] sequences;
2019 boolean annotationAdded = false;
2020 AlignmentI alignment = null;
2022 if (Desktop.jalviewClipboard != null)
2024 // The clipboard was filled from within Jalview, we must use the
2026 // And dataset from the copied alignment
2027 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2028 // be doubly sure that we create *new* sequence objects.
2029 sequences = new SequenceI[newseq.length];
2030 for (int i = 0; i < newseq.length; i++)
2032 sequences[i] = new Sequence(newseq[i]);
2034 alignment = new Alignment(sequences);
2035 externalPaste = false;
2039 // parse the clipboard as an alignment.
2040 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2042 sequences = alignment.getSequencesArray();
2046 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2052 if (Desktop.jalviewClipboard != null)
2054 // dataset is inherited
2055 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2059 // new dataset is constructed
2060 alignment.setDataset(null);
2062 alwidth = alignment.getWidth() + 1;
2066 AlignmentI pastedal = alignment; // preserve pasted alignment object
2067 // Add pasted sequences and dataset into existing alignment.
2068 alignment = viewport.getAlignment();
2069 alwidth = alignment.getWidth() + 1;
2070 // decide if we need to import sequences from an existing dataset
2071 boolean importDs = Desktop.jalviewClipboard != null
2072 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2073 // importDs==true instructs us to copy over new dataset sequences from
2074 // an existing alignment
2075 Vector newDs = (importDs) ? new Vector() : null; // used to create
2076 // minimum dataset set
2078 for (int i = 0; i < sequences.length; i++)
2082 newDs.addElement(null);
2084 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2086 if (importDs && ds != null)
2088 if (!newDs.contains(ds))
2090 newDs.setElementAt(ds, i);
2091 ds = new Sequence(ds);
2092 // update with new dataset sequence
2093 sequences[i].setDatasetSequence(ds);
2097 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2102 // copy and derive new dataset sequence
2103 sequences[i] = sequences[i].deriveSequence();
2104 alignment.getDataset().addSequence(
2105 sequences[i].getDatasetSequence());
2106 // TODO: avoid creation of duplicate dataset sequences with a
2107 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2109 alignment.addSequence(sequences[i]); // merges dataset
2113 newDs.clear(); // tidy up
2115 if (alignment.getAlignmentAnnotation() != null)
2117 for (AlignmentAnnotation alan : alignment
2118 .getAlignmentAnnotation())
2120 if (alan.graphGroup > fgroup)
2122 fgroup = alan.graphGroup;
2126 if (pastedal.getAlignmentAnnotation() != null)
2128 // Add any annotation attached to alignment.
2129 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2130 for (int i = 0; i < alann.length; i++)
2132 annotationAdded = true;
2133 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2135 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2136 if (newann.graphGroup > -1)
2138 if (newGraphGroups.size() <= newann.graphGroup
2139 || newGraphGroups.get(newann.graphGroup) == null)
2141 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2143 newGraphGroups.add(q, null);
2145 newGraphGroups.set(newann.graphGroup, new Integer(
2148 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2152 newann.padAnnotation(alwidth);
2153 alignment.addAnnotation(newann);
2163 addHistoryItem(new EditCommand(
2164 MessageManager.getString("label.add_sequences"),
2165 Action.PASTE, sequences, 0, alignment.getWidth(), alignment));
2167 // Add any annotations attached to sequences
2168 for (int i = 0; i < sequences.length; i++)
2170 if (sequences[i].getAnnotation() != null)
2172 AlignmentAnnotation newann;
2173 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2175 annotationAdded = true;
2176 newann = sequences[i].getAnnotation()[a];
2177 newann.adjustForAlignment();
2178 newann.padAnnotation(alwidth);
2179 if (newann.graphGroup > -1)
2181 if (newann.graphGroup > -1)
2183 if (newGraphGroups.size() <= newann.graphGroup
2184 || newGraphGroups.get(newann.graphGroup) == null)
2186 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2188 newGraphGroups.add(q, null);
2190 newGraphGroups.set(newann.graphGroup, new Integer(
2193 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2197 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2202 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2209 // propagate alignment changed.
2210 vpRanges.setEndSeq(alignment.getHeight());
2211 if (annotationAdded)
2213 // Duplicate sequence annotation in all views.
2214 AlignmentI[] alview = this.getViewAlignments();
2215 for (int i = 0; i < sequences.length; i++)
2217 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2222 for (int avnum = 0; avnum < alview.length; avnum++)
2224 if (alview[avnum] != alignment)
2226 // duplicate in a view other than the one with input focus
2227 int avwidth = alview[avnum].getWidth() + 1;
2228 // this relies on sann being preserved after we
2229 // modify the sequence's annotation array for each duplication
2230 for (int a = 0; a < sann.length; a++)
2232 AlignmentAnnotation newann = new AlignmentAnnotation(
2234 sequences[i].addAlignmentAnnotation(newann);
2235 newann.padAnnotation(avwidth);
2236 alview[avnum].addAnnotation(newann); // annotation was
2237 // duplicated earlier
2238 // TODO JAL-1145 graphGroups are not updated for sequence
2239 // annotation added to several views. This may cause
2241 alview[avnum].setAnnotationIndex(newann, a);
2246 buildSortByAnnotationScoresMenu();
2248 viewport.firePropertyChange("alignment", null,
2249 alignment.getSequences());
2250 if (alignPanels != null)
2252 for (AlignmentPanel ap : alignPanels)
2254 ap.validateAnnotationDimensions(false);
2259 alignPanel.validateAnnotationDimensions(false);
2265 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2267 String newtitle = new String("Copied sequences");
2269 if (Desktop.jalviewClipboard != null
2270 && Desktop.jalviewClipboard[2] != null)
2272 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2273 for (int[] region : hc)
2275 af.viewport.hideColumns(region[0], region[1]);
2279 // >>>This is a fix for the moment, until a better solution is
2281 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2283 alignPanel.getSeqPanel().seqCanvas
2284 .getFeatureRenderer());
2286 // TODO: maintain provenance of an alignment, rather than just make the
2287 // title a concatenation of operations.
2290 if (title.startsWith("Copied sequences"))
2296 newtitle = newtitle.concat("- from " + title);
2301 newtitle = new String("Pasted sequences");
2304 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2309 } catch (Exception ex)
2311 ex.printStackTrace();
2312 System.out.println("Exception whilst pasting: " + ex);
2313 // could be anything being pasted in here
2319 protected void expand_newalign(ActionEvent e)
2323 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2324 .getAlignment(), -1);
2325 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2327 String newtitle = new String("Flanking alignment");
2329 if (Desktop.jalviewClipboard != null
2330 && Desktop.jalviewClipboard[2] != null)
2332 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2333 for (int region[] : hc)
2335 af.viewport.hideColumns(region[0], region[1]);
2339 // >>>This is a fix for the moment, until a better solution is
2341 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2343 alignPanel.getSeqPanel().seqCanvas
2344 .getFeatureRenderer());
2346 // TODO: maintain provenance of an alignment, rather than just make the
2347 // title a concatenation of operations.
2349 if (title.startsWith("Copied sequences"))
2355 newtitle = newtitle.concat("- from " + title);
2359 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2361 } catch (Exception ex)
2363 ex.printStackTrace();
2364 System.out.println("Exception whilst pasting: " + ex);
2365 // could be anything being pasted in here
2366 } catch (OutOfMemoryError oom)
2368 new OOMWarning("Viewing flanking region of alignment", oom);
2379 protected void cut_actionPerformed(ActionEvent e)
2381 copy_actionPerformed(null);
2382 delete_actionPerformed(null);
2392 protected void delete_actionPerformed(ActionEvent evt)
2395 SequenceGroup sg = viewport.getSelectionGroup();
2402 * If the cut affects all sequences, warn, remove highlighted columns
2404 if (sg.getSize() == viewport.getAlignment().getHeight())
2406 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes()) + 1) == viewport
2407 .getAlignment().getWidth()) ? true : false;
2408 if (isEntireAlignWidth)
2410 int confirm = JvOptionPane.showConfirmDialog(this,
2411 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2412 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2413 JvOptionPane.OK_CANCEL_OPTION);
2415 if (confirm == JvOptionPane.CANCEL_OPTION
2416 || confirm == JvOptionPane.CLOSED_OPTION)
2421 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2422 sg.getEndRes() + 1);
2424 SequenceI[] cut = sg.getSequences()
2425 .toArray(new SequenceI[sg.getSize()]);
2427 addHistoryItem(new EditCommand(
2428 MessageManager.getString("label.cut_sequences"), Action.CUT,
2429 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2430 viewport.getAlignment()));
2432 viewport.setSelectionGroup(null);
2433 viewport.sendSelection();
2434 viewport.getAlignment().deleteGroup(sg);
2436 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2438 if (viewport.getAlignment().getHeight() < 1)
2442 this.setClosed(true);
2443 } catch (Exception ex)
2456 protected void deleteGroups_actionPerformed(ActionEvent e)
2458 if (avc.deleteGroups())
2460 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2461 alignPanel.updateAnnotation();
2462 alignPanel.paintAlignment(true);
2473 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2475 SequenceGroup sg = new SequenceGroup();
2477 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2479 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2482 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2483 viewport.setSelectionGroup(sg);
2484 viewport.sendSelection();
2485 // JAL-2034 - should delegate to
2486 // alignPanel to decide if overview needs
2488 alignPanel.paintAlignment(false);
2489 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2499 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2501 if (viewport.cursorMode)
2503 alignPanel.getSeqPanel().keyboardNo1 = null;
2504 alignPanel.getSeqPanel().keyboardNo2 = null;
2506 viewport.setSelectionGroup(null);
2507 viewport.getColumnSelection().clear();
2508 viewport.setSelectionGroup(null);
2509 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2510 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2511 // JAL-2034 - should delegate to
2512 // alignPanel to decide if overview needs
2514 alignPanel.paintAlignment(false);
2515 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2516 viewport.sendSelection();
2526 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2528 SequenceGroup sg = viewport.getSelectionGroup();
2532 selectAllSequenceMenuItem_actionPerformed(null);
2537 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2539 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2541 // JAL-2034 - should delegate to
2542 // alignPanel to decide if overview needs
2545 alignPanel.paintAlignment(true);
2546 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2547 viewport.sendSelection();
2551 public void invertColSel_actionPerformed(ActionEvent e)
2553 viewport.invertColumnSelection();
2554 alignPanel.paintAlignment(true);
2555 viewport.sendSelection();
2565 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2567 trimAlignment(true);
2577 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2579 trimAlignment(false);
2582 void trimAlignment(boolean trimLeft)
2584 ColumnSelection colSel = viewport.getColumnSelection();
2587 if (!colSel.isEmpty())
2591 column = colSel.getMin();
2595 column = colSel.getMax();
2599 if (viewport.getSelectionGroup() != null)
2601 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2602 viewport.getHiddenRepSequences());
2606 seqs = viewport.getAlignment().getSequencesArray();
2609 TrimRegionCommand trimRegion;
2612 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2613 column, viewport.getAlignment());
2614 vpRanges.setStartRes(0);
2618 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2619 column, viewport.getAlignment());
2622 statusBar.setText(MessageManager.formatMessage(
2623 "label.removed_columns",
2624 new String[] { Integer.valueOf(trimRegion.getSize())
2627 addHistoryItem(trimRegion);
2629 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2631 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2632 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2634 viewport.getAlignment().deleteGroup(sg);
2638 viewport.firePropertyChange("alignment", null, viewport
2639 .getAlignment().getSequences());
2650 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2652 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2655 if (viewport.getSelectionGroup() != null)
2657 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2658 viewport.getHiddenRepSequences());
2659 start = viewport.getSelectionGroup().getStartRes();
2660 end = viewport.getSelectionGroup().getEndRes();
2664 seqs = viewport.getAlignment().getSequencesArray();
2667 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2668 "Remove Gapped Columns", seqs, start, end,
2669 viewport.getAlignment());
2671 addHistoryItem(removeGapCols);
2673 statusBar.setText(MessageManager.formatMessage(
2674 "label.removed_empty_columns",
2675 new Object[] { Integer.valueOf(removeGapCols.getSize())
2678 // This is to maintain viewport position on first residue
2679 // of first sequence
2680 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2681 int startRes = seq.findPosition(vpRanges.getStartRes());
2682 // ShiftList shifts;
2683 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2684 // edit.alColumnChanges=shifts.getInverse();
2685 // if (viewport.hasHiddenColumns)
2686 // viewport.getColumnSelection().compensateForEdits(shifts);
2687 vpRanges.setStartRes(seq.findIndex(startRes) - 1);
2688 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2700 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2702 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2705 if (viewport.getSelectionGroup() != null)
2707 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2708 viewport.getHiddenRepSequences());
2709 start = viewport.getSelectionGroup().getStartRes();
2710 end = viewport.getSelectionGroup().getEndRes();
2714 seqs = viewport.getAlignment().getSequencesArray();
2717 // This is to maintain viewport position on first residue
2718 // of first sequence
2719 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2720 int startRes = seq.findPosition(vpRanges.getStartRes());
2722 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2723 viewport.getAlignment()));
2725 vpRanges.setStartRes(seq.findIndex(startRes) - 1);
2727 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2739 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2741 viewport.setPadGaps(padGapsMenuitem.isSelected());
2742 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2753 public void findMenuItem_actionPerformed(ActionEvent e)
2759 * Create a new view of the current alignment.
2762 public void newView_actionPerformed(ActionEvent e)
2764 newView(null, true);
2768 * Creates and shows a new view of the current alignment.
2771 * title of newly created view; if null, one will be generated
2772 * @param copyAnnotation
2773 * if true then duplicate all annnotation, groups and settings
2774 * @return new alignment panel, already displayed.
2776 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2779 * Create a new AlignmentPanel (with its own, new Viewport)
2781 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2783 if (!copyAnnotation)
2786 * remove all groups and annotation except for the automatic stuff
2788 newap.av.getAlignment().deleteAllGroups();
2789 newap.av.getAlignment().deleteAllAnnotations(false);
2792 newap.av.setGatherViewsHere(false);
2794 if (viewport.viewName == null)
2796 viewport.viewName = MessageManager
2797 .getString("label.view_name_original");
2801 * Views share the same edits undo and redo stacks
2803 newap.av.setHistoryList(viewport.getHistoryList());
2804 newap.av.setRedoList(viewport.getRedoList());
2807 * Views share the same mappings; need to deregister any new mappings
2808 * created by copyAlignPanel, and register the new reference to the shared
2811 newap.av.replaceMappings(viewport.getAlignment());
2814 * start up cDNA consensus (if applicable) now mappings are in place
2816 if (newap.av.initComplementConsensus())
2818 newap.refresh(true); // adjust layout of annotations
2821 newap.av.viewName = getNewViewName(viewTitle);
2823 addAlignmentPanel(newap, true);
2824 newap.alignmentChanged();
2826 if (alignPanels.size() == 2)
2828 viewport.setGatherViewsHere(true);
2830 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2835 * Make a new name for the view, ensuring it is unique within the current
2836 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2837 * these now use viewId. Unique view names are still desirable for usability.)
2842 protected String getNewViewName(String viewTitle)
2844 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2845 boolean addFirstIndex = false;
2846 if (viewTitle == null || viewTitle.trim().length() == 0)
2848 viewTitle = MessageManager.getString("action.view");
2849 addFirstIndex = true;
2853 index = 1;// we count from 1 if given a specific name
2855 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2857 List<Component> comps = PaintRefresher.components.get(viewport
2858 .getSequenceSetId());
2860 List<String> existingNames = getExistingViewNames(comps);
2862 while (existingNames.contains(newViewName))
2864 newViewName = viewTitle + " " + (++index);
2870 * Returns a list of distinct view names found in the given list of
2871 * components. View names are held on the viewport of an AlignmentPanel.
2876 protected List<String> getExistingViewNames(List<Component> comps)
2878 List<String> existingNames = new ArrayList<>();
2879 for (Component comp : comps)
2881 if (comp instanceof AlignmentPanel)
2883 AlignmentPanel ap = (AlignmentPanel) comp;
2884 if (!existingNames.contains(ap.av.viewName))
2886 existingNames.add(ap.av.viewName);
2890 return existingNames;
2894 * Explode tabbed views into separate windows.
2897 public void expandViews_actionPerformed(ActionEvent e)
2899 Desktop.explodeViews(this);
2903 * Gather views in separate windows back into a tabbed presentation.
2906 public void gatherViews_actionPerformed(ActionEvent e)
2908 Desktop.instance.gatherViews(this);
2918 public void font_actionPerformed(ActionEvent e)
2920 new FontChooser(alignPanel);
2930 protected void seqLimit_actionPerformed(ActionEvent e)
2932 viewport.setShowJVSuffix(seqLimits.isSelected());
2934 alignPanel.getIdPanel().getIdCanvas()
2935 .setPreferredSize(alignPanel.calculateIdWidth());
2936 alignPanel.paintAlignment(true);
2940 public void idRightAlign_actionPerformed(ActionEvent e)
2942 viewport.setRightAlignIds(idRightAlign.isSelected());
2943 alignPanel.paintAlignment(true);
2947 public void centreColumnLabels_actionPerformed(ActionEvent e)
2949 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2950 alignPanel.paintAlignment(true);
2956 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2959 protected void followHighlight_actionPerformed()
2962 * Set the 'follow' flag on the Viewport (and scroll to position if now
2965 final boolean state = this.followHighlightMenuItem.getState();
2966 viewport.setFollowHighlight(state);
2969 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2980 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2982 viewport.setColourText(colourTextMenuItem.isSelected());
2983 alignPanel.paintAlignment(true);
2993 public void wrapMenuItem_actionPerformed(ActionEvent e)
2995 scaleAbove.setVisible(wrapMenuItem.isSelected());
2996 scaleLeft.setVisible(wrapMenuItem.isSelected());
2997 scaleRight.setVisible(wrapMenuItem.isSelected());
2998 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2999 alignPanel.updateLayout();
3003 public void showAllSeqs_actionPerformed(ActionEvent e)
3005 viewport.showAllHiddenSeqs();
3009 public void showAllColumns_actionPerformed(ActionEvent e)
3011 viewport.showAllHiddenColumns();
3013 viewport.sendSelection();
3017 public void hideSelSequences_actionPerformed(ActionEvent e)
3019 viewport.hideAllSelectedSeqs();
3020 // alignPanel.paintAlignment(true);
3024 * called by key handler and the hide all/show all menu items
3029 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3032 boolean hide = false;
3033 SequenceGroup sg = viewport.getSelectionGroup();
3034 if (!toggleSeqs && !toggleCols)
3036 // Hide everything by the current selection - this is a hack - we do the
3037 // invert and then hide
3038 // first check that there will be visible columns after the invert.
3039 if (viewport.hasSelectedColumns()
3040 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
3043 // now invert the sequence set, if required - empty selection implies
3044 // that no hiding is required.
3047 invertSequenceMenuItem_actionPerformed(null);
3048 sg = viewport.getSelectionGroup();
3052 viewport.expandColSelection(sg, true);
3053 // finally invert the column selection and get the new sequence
3055 invertColSel_actionPerformed(null);
3062 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3064 hideSelSequences_actionPerformed(null);
3067 else if (!(toggleCols && viewport.hasSelectedColumns()))
3069 showAllSeqs_actionPerformed(null);
3075 if (viewport.hasSelectedColumns())
3077 hideSelColumns_actionPerformed(null);
3080 viewport.setSelectionGroup(sg);
3085 showAllColumns_actionPerformed(null);
3094 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3095 * event.ActionEvent)
3098 public void hideAllButSelection_actionPerformed(ActionEvent e)
3100 toggleHiddenRegions(false, false);
3101 viewport.sendSelection();
3108 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3112 public void hideAllSelection_actionPerformed(ActionEvent e)
3114 SequenceGroup sg = viewport.getSelectionGroup();
3115 viewport.expandColSelection(sg, false);
3116 viewport.hideAllSelectedSeqs();
3117 viewport.hideSelectedColumns();
3118 alignPanel.paintAlignment(true);
3119 viewport.sendSelection();
3126 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3130 public void showAllhidden_actionPerformed(ActionEvent e)
3132 viewport.showAllHiddenColumns();
3133 viewport.showAllHiddenSeqs();
3134 alignPanel.paintAlignment(true);
3135 viewport.sendSelection();
3139 public void hideSelColumns_actionPerformed(ActionEvent e)
3141 viewport.hideSelectedColumns();
3142 alignPanel.paintAlignment(true);
3143 viewport.sendSelection();
3147 public void hiddenMarkers_actionPerformed(ActionEvent e)
3149 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3160 protected void scaleAbove_actionPerformed(ActionEvent e)
3162 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3163 alignPanel.paintAlignment(true);
3173 protected void scaleLeft_actionPerformed(ActionEvent e)
3175 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3176 alignPanel.paintAlignment(true);
3186 protected void scaleRight_actionPerformed(ActionEvent e)
3188 viewport.setScaleRightWrapped(scaleRight.isSelected());
3189 alignPanel.paintAlignment(true);
3199 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3201 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3202 alignPanel.paintAlignment(true);
3212 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3214 viewport.setShowText(viewTextMenuItem.isSelected());
3215 alignPanel.paintAlignment(true);
3225 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3227 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3228 alignPanel.paintAlignment(true);
3231 public FeatureSettings featureSettings;
3234 public FeatureSettingsControllerI getFeatureSettingsUI()
3236 return featureSettings;
3240 public void featureSettings_actionPerformed(ActionEvent e)
3242 if (featureSettings != null)
3244 featureSettings.close();
3245 featureSettings = null;
3247 if (!showSeqFeatures.isSelected())
3249 // make sure features are actually displayed
3250 showSeqFeatures.setSelected(true);
3251 showSeqFeatures_actionPerformed(null);
3253 featureSettings = new FeatureSettings(this);
3257 * Set or clear 'Show Sequence Features'
3263 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3265 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3266 alignPanel.paintAlignment(true);
3267 if (alignPanel.getOverviewPanel() != null)
3269 alignPanel.getOverviewPanel().updateOverviewImage();
3274 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3275 * the annotations panel as a whole.
3277 * The options to show/hide all annotations should be enabled when the panel
3278 * is shown, and disabled when the panel is hidden.
3283 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3285 final boolean setVisible = annotationPanelMenuItem.isSelected();
3286 viewport.setShowAnnotation(setVisible);
3287 this.showAllSeqAnnotations.setEnabled(setVisible);
3288 this.hideAllSeqAnnotations.setEnabled(setVisible);
3289 this.showAllAlAnnotations.setEnabled(setVisible);
3290 this.hideAllAlAnnotations.setEnabled(setVisible);
3291 alignPanel.updateLayout();
3295 public void alignmentProperties()
3297 JEditorPane editPane = new JEditorPane("text/html", "");
3298 editPane.setEditable(false);
3299 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3301 editPane.setText(MessageManager.formatMessage("label.html_content",
3302 new Object[] { contents.toString() }));
3303 JInternalFrame frame = new JInternalFrame();
3304 frame.getContentPane().add(new JScrollPane(editPane));
3306 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3307 "label.alignment_properties", new Object[] { getTitle() }),
3318 public void overviewMenuItem_actionPerformed(ActionEvent e)
3320 if (alignPanel.overviewPanel != null)
3325 JInternalFrame frame = new JInternalFrame();
3326 OverviewPanel overview = new OverviewPanel(alignPanel);
3327 frame.setContentPane(overview);
3328 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3329 "label.overview_params", new Object[] { this.getTitle() }),
3330 true, frame.getWidth(), frame.getHeight(), true, true);
3332 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3333 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3336 public void internalFrameClosed(
3337 javax.swing.event.InternalFrameEvent evt)
3339 alignPanel.setOverviewPanel(null);
3343 alignPanel.setOverviewPanel(overview);
3347 public void textColour_actionPerformed()
3349 new TextColourChooser().chooseColour(alignPanel, null);
3353 * public void covariationColour_actionPerformed() {
3355 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3359 public void annotationColour_actionPerformed()
3361 new AnnotationColourChooser(viewport, alignPanel);
3365 public void annotationColumn_actionPerformed(ActionEvent e)
3367 new AnnotationColumnChooser(viewport, alignPanel);
3371 * Action on the user checking or unchecking the option to apply the selected
3372 * colour scheme to all groups. If unchecked, groups may have their own
3373 * independent colour schemes.
3378 public void applyToAllGroups_actionPerformed(boolean selected)
3380 viewport.setColourAppliesToAllGroups(selected);
3384 * Action on user selecting a colour from the colour menu
3387 * the name (not the menu item label!) of the colour scheme
3390 public void changeColour_actionPerformed(String name)
3393 * 'User Defined' opens a panel to configure or load a
3394 * user-defined colour scheme
3396 if (ResidueColourScheme.USER_DEFINED.equals(name))
3398 new UserDefinedColours(alignPanel);
3403 * otherwise set the chosen colour scheme (or null for 'None')
3405 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3406 viewport.getAlignment(), viewport.getHiddenRepSequences());
3411 * Actions on setting or changing the alignment colour scheme
3416 public void changeColour(ColourSchemeI cs)
3418 // TODO: pull up to controller method
3419 ColourMenuHelper.setColourSelected(colourMenu, cs);
3421 viewport.setGlobalColourScheme(cs);
3423 alignPanel.paintAlignment(true);
3427 * Show the PID threshold slider panel
3430 protected void modifyPID_actionPerformed()
3432 SliderPanel.setPIDSliderSource(alignPanel,
3433 viewport.getResidueShading(), alignPanel.getViewName());
3434 SliderPanel.showPIDSlider();
3438 * Show the Conservation slider panel
3441 protected void modifyConservation_actionPerformed()
3443 SliderPanel.setConservationSlider(alignPanel,
3444 viewport.getResidueShading(), alignPanel.getViewName());
3445 SliderPanel.showConservationSlider();
3449 * Action on selecting or deselecting (Colour) By Conservation
3452 public void conservationMenuItem_actionPerformed(boolean selected)
3454 modifyConservation.setEnabled(selected);
3455 viewport.setConservationSelected(selected);
3456 viewport.getResidueShading().setConservationApplied(selected);
3458 changeColour(viewport.getGlobalColourScheme());
3461 modifyConservation_actionPerformed();
3465 SliderPanel.hideConservationSlider();
3470 * Action on selecting or deselecting (Colour) Above PID Threshold
3473 public void abovePIDThreshold_actionPerformed(boolean selected)
3475 modifyPID.setEnabled(selected);
3476 viewport.setAbovePIDThreshold(selected);
3479 viewport.getResidueShading().setThreshold(0,
3480 viewport.isIgnoreGapsConsensus());
3483 changeColour(viewport.getGlobalColourScheme());
3486 modifyPID_actionPerformed();
3490 SliderPanel.hidePIDSlider();
3501 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3503 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3504 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3505 .getAlignment().getSequenceAt(0));
3506 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3507 viewport.getAlignment()));
3508 alignPanel.paintAlignment(true);
3518 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3520 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3521 AlignmentSorter.sortByID(viewport.getAlignment());
3522 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3523 viewport.getAlignment()));
3524 alignPanel.paintAlignment(true);
3534 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3536 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3537 AlignmentSorter.sortByLength(viewport.getAlignment());
3538 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3539 viewport.getAlignment()));
3540 alignPanel.paintAlignment(true);
3550 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3552 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3553 AlignmentSorter.sortByGroup(viewport.getAlignment());
3554 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3555 viewport.getAlignment()));
3557 alignPanel.paintAlignment(true);
3567 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3569 new RedundancyPanel(alignPanel, this);
3579 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3581 if ((viewport.getSelectionGroup() == null)
3582 || (viewport.getSelectionGroup().getSize() < 2))
3584 JvOptionPane.showInternalMessageDialog(this, MessageManager
3585 .getString("label.you_must_select_least_two_sequences"),
3586 MessageManager.getString("label.invalid_selection"),
3587 JvOptionPane.WARNING_MESSAGE);
3591 JInternalFrame frame = new JInternalFrame();
3592 frame.setContentPane(new PairwiseAlignPanel(viewport));
3593 Desktop.addInternalFrame(frame,
3594 MessageManager.getString("action.pairwise_alignment"), 600,
3600 public void autoCalculate_actionPerformed(ActionEvent e)
3602 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3603 if (viewport.autoCalculateConsensus)
3605 viewport.firePropertyChange("alignment", null, viewport
3606 .getAlignment().getSequences());
3611 public void sortByTreeOption_actionPerformed(ActionEvent e)
3613 viewport.sortByTree = sortByTree.isSelected();
3617 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3619 viewport.followSelection = listenToViewSelections.isSelected();
3623 * Constructs a tree panel and adds it to the desktop
3626 * tree type (NJ or AV)
3628 * name of score model used to compute the tree
3630 * parameters for the distance or similarity calculation
3632 void newTreePanel(String type, String modelName, SimilarityParamsI options)
3634 String frameTitle = "";
3637 boolean onSelection = false;
3638 if (viewport.getSelectionGroup() != null
3639 && viewport.getSelectionGroup().getSize() > 0)
3641 SequenceGroup sg = viewport.getSelectionGroup();
3643 /* Decide if the selection is a column region */
3644 for (SequenceI _s : sg.getSequences())
3646 if (_s.getLength() < sg.getEndRes())
3652 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3654 .getString("label.sequences_selection_not_aligned"),
3655 JvOptionPane.WARNING_MESSAGE);
3664 if (viewport.getAlignment().getHeight() < 2)
3670 tp = new TreePanel(alignPanel, type, modelName, options);
3671 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3673 frameTitle += " from ";
3675 if (viewport.viewName != null)
3677 frameTitle += viewport.viewName + " of ";
3680 frameTitle += this.title;
3682 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3693 public void addSortByOrderMenuItem(String title,
3694 final AlignmentOrder order)
3696 final JMenuItem item = new JMenuItem(MessageManager.formatMessage(
3697 "action.by_title_param", new Object[] { title }));
3699 item.addActionListener(new java.awt.event.ActionListener()
3702 public void actionPerformed(ActionEvent e)
3704 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3706 // TODO: JBPNote - have to map order entries to curent SequenceI
3708 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3710 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
3713 alignPanel.paintAlignment(true);
3719 * Add a new sort by annotation score menu item
3722 * the menu to add the option to
3724 * the label used to retrieve scores for each sequence on the
3727 public void addSortByAnnotScoreMenuItem(JMenu sort,
3728 final String scoreLabel)
3730 final JMenuItem item = new JMenuItem(scoreLabel);
3732 item.addActionListener(new java.awt.event.ActionListener()
3735 public void actionPerformed(ActionEvent e)
3737 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3738 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3739 viewport.getAlignment());// ,viewport.getSelectionGroup());
3740 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3741 viewport.getAlignment()));
3742 alignPanel.paintAlignment(true);
3748 * last hash for alignment's annotation array - used to minimise cost of
3751 protected int _annotationScoreVectorHash;
3754 * search the alignment and rebuild the sort by annotation score submenu the
3755 * last alignment annotation vector hash is stored to minimize cost of
3756 * rebuilding in subsequence calls.
3760 public void buildSortByAnnotationScoresMenu()
3762 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3767 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
3769 sortByAnnotScore.removeAll();
3770 // almost certainly a quicker way to do this - but we keep it simple
3771 Hashtable scoreSorts = new Hashtable();
3772 AlignmentAnnotation aann[];
3773 for (SequenceI sqa : viewport.getAlignment().getSequences())
3775 aann = sqa.getAnnotation();
3776 for (int i = 0; aann != null && i < aann.length; i++)
3778 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3780 scoreSorts.put(aann[i].label, aann[i].label);
3784 Enumeration labels = scoreSorts.keys();
3785 while (labels.hasMoreElements())
3787 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3788 (String) labels.nextElement());
3790 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3793 _annotationScoreVectorHash = viewport.getAlignment()
3794 .getAlignmentAnnotation().hashCode();
3799 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3800 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3801 * call. Listeners are added to remove the menu item when the treePanel is
3802 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3806 public void buildTreeSortMenu()
3808 sortByTreeMenu.removeAll();
3810 List<Component> comps = PaintRefresher.components.get(viewport
3811 .getSequenceSetId());
3812 List<TreePanel> treePanels = new ArrayList<>();
3813 for (Component comp : comps)
3815 if (comp instanceof TreePanel)
3817 treePanels.add((TreePanel) comp);
3821 if (treePanels.size() < 1)
3823 sortByTreeMenu.setVisible(false);
3827 sortByTreeMenu.setVisible(true);
3829 for (final TreePanel tp : treePanels)
3831 final JMenuItem item = new JMenuItem(tp.getTitle());
3832 item.addActionListener(new java.awt.event.ActionListener()
3835 public void actionPerformed(ActionEvent e)
3837 tp.sortByTree_actionPerformed();
3838 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3843 sortByTreeMenu.add(item);
3847 public boolean sortBy(AlignmentOrder alorder, String undoname)
3849 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3850 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3851 if (undoname != null)
3853 addHistoryItem(new OrderCommand(undoname, oldOrder,
3854 viewport.getAlignment()));
3856 alignPanel.paintAlignment(true);
3861 * Work out whether the whole set of sequences or just the selected set will
3862 * be submitted for multiple alignment.
3865 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3867 // Now, check we have enough sequences
3868 AlignmentView msa = null;
3870 if ((viewport.getSelectionGroup() != null)
3871 && (viewport.getSelectionGroup().getSize() > 1))
3873 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3874 // some common interface!
3876 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3877 * SequenceI[sz = seqs.getSize(false)];
3879 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3880 * seqs.getSequenceAt(i); }
3882 msa = viewport.getAlignmentView(true);
3884 else if (viewport.getSelectionGroup() != null
3885 && viewport.getSelectionGroup().getSize() == 1)
3887 int option = JvOptionPane.showConfirmDialog(this,
3888 MessageManager.getString("warn.oneseq_msainput_selection"),
3889 MessageManager.getString("label.invalid_selection"),
3890 JvOptionPane.OK_CANCEL_OPTION);
3891 if (option == JvOptionPane.OK_OPTION)
3893 msa = viewport.getAlignmentView(false);
3898 msa = viewport.getAlignmentView(false);
3904 * Decides what is submitted to a secondary structure prediction service: the
3905 * first sequence in the alignment, or in the current selection, or, if the
3906 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3907 * region or the whole alignment. (where the first sequence in the set is the
3908 * one that the prediction will be for).
3910 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3912 AlignmentView seqs = null;
3914 if ((viewport.getSelectionGroup() != null)
3915 && (viewport.getSelectionGroup().getSize() > 0))
3917 seqs = viewport.getAlignmentView(true);
3921 seqs = viewport.getAlignmentView(false);
3923 // limit sequences - JBPNote in future - could spawn multiple prediction
3925 // TODO: viewport.getAlignment().isAligned is a global state - the local
3926 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3927 if (!viewport.getAlignment().isAligned(false))
3929 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3930 // TODO: if seqs.getSequences().length>1 then should really have warned
3944 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3946 // Pick the tree file
3947 JalviewFileChooser chooser = new JalviewFileChooser(
3948 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3949 chooser.setFileView(new JalviewFileView());
3950 chooser.setDialogTitle(MessageManager
3951 .getString("label.select_newick_like_tree_file"));
3952 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
3954 int value = chooser.showOpenDialog(null);
3956 if (value == JalviewFileChooser.APPROVE_OPTION)
3958 String filePath = chooser.getSelectedFile().getPath();
3959 Cache.setProperty("LAST_DIRECTORY", filePath);
3960 NewickFile fin = null;
3963 fin = new NewickFile(filePath, DataSourceType.FILE);
3964 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
3965 } catch (Exception ex)
3972 .getString("label.problem_reading_tree_file"),
3973 JvOptionPane.WARNING_MESSAGE);
3974 ex.printStackTrace();
3976 if (fin != null && fin.hasWarningMessage())
3978 JvOptionPane.showMessageDialog(Desktop.desktop, fin
3979 .getWarningMessage(), MessageManager
3980 .getString("label.possible_problem_with_tree_file"),
3981 JvOptionPane.WARNING_MESSAGE);
3986 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
3988 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
3991 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
3992 int h, int x, int y)
3994 return showNewickTree(nf, treeTitle, null, w, h, x, y);
3998 * Add a treeviewer for the tree extracted from a Newick file object to the
3999 * current alignment view
4006 * Associated alignment input data (or null)
4015 * @return TreePanel handle
4017 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4018 AlignmentView input, int w, int h, int x, int y)
4020 TreePanel tp = null;
4026 if (nf.getTree() != null)
4028 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4034 tp.setLocation(x, y);
4037 Desktop.addInternalFrame(tp, treeTitle, w, h);
4039 } catch (Exception ex)
4041 ex.printStackTrace();
4047 private boolean buildingMenu = false;
4050 * Generates menu items and listener event actions for web service clients
4053 public void BuildWebServiceMenu()
4055 while (buildingMenu)
4059 System.err.println("Waiting for building menu to finish.");
4061 } catch (Exception e)
4065 final AlignFrame me = this;
4066 buildingMenu = true;
4067 new Thread(new Runnable()
4072 final List<JMenuItem> legacyItems = new ArrayList<>();
4075 // System.err.println("Building ws menu again "
4076 // + Thread.currentThread());
4077 // TODO: add support for context dependent disabling of services based
4079 // alignment and current selection
4080 // TODO: add additional serviceHandle parameter to specify abstract
4082 // class independently of AbstractName
4083 // TODO: add in rediscovery GUI function to restart discoverer
4084 // TODO: group services by location as well as function and/or
4086 // object broker mechanism.
4087 final Vector<JMenu> wsmenu = new Vector<>();
4088 final IProgressIndicator af = me;
4091 * do not i18n these strings - they are hard-coded in class
4092 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4093 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4095 final JMenu msawsmenu = new JMenu("Alignment");
4096 final JMenu secstrmenu = new JMenu(
4097 "Secondary Structure Prediction");
4098 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4099 final JMenu analymenu = new JMenu("Analysis");
4100 final JMenu dismenu = new JMenu("Protein Disorder");
4101 // JAL-940 - only show secondary structure prediction services from
4102 // the legacy server
4103 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4105 Discoverer.services != null && (Discoverer.services.size() > 0))
4107 // TODO: refactor to allow list of AbstractName/Handler bindings to
4109 // stored or retrieved from elsewhere
4110 // No MSAWS used any more:
4111 // Vector msaws = null; // (Vector)
4112 // Discoverer.services.get("MsaWS");
4113 Vector secstrpr = (Vector) Discoverer.services
4115 if (secstrpr != null)
4117 // Add any secondary structure prediction services
4118 for (int i = 0, j = secstrpr.size(); i < j; i++)
4120 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4122 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4123 .getServiceClient(sh);
4124 int p = secstrmenu.getItemCount();
4125 impl.attachWSMenuEntry(secstrmenu, me);
4126 int q = secstrmenu.getItemCount();
4127 for (int litm = p; litm < q; litm++)
4129 legacyItems.add(secstrmenu.getItem(litm));
4135 // Add all submenus in the order they should appear on the web
4137 wsmenu.add(msawsmenu);
4138 wsmenu.add(secstrmenu);
4139 wsmenu.add(dismenu);
4140 wsmenu.add(analymenu);
4141 // No search services yet
4142 // wsmenu.add(seqsrchmenu);
4144 javax.swing.SwingUtilities.invokeLater(new Runnable()
4151 webService.removeAll();
4152 // first, add discovered services onto the webservices menu
4153 if (wsmenu.size() > 0)
4155 for (int i = 0, j = wsmenu.size(); i < j; i++)
4157 webService.add(wsmenu.get(i));
4162 webService.add(me.webServiceNoServices);
4164 // TODO: move into separate menu builder class.
4165 boolean new_sspred = false;
4166 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4168 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4169 if (jws2servs != null)
4171 if (jws2servs.hasServices())
4173 jws2servs.attachWSMenuEntry(webService, me);
4174 for (Jws2Instance sv : jws2servs.getServices())
4176 if (sv.description.toLowerCase().contains("jpred"))
4178 for (JMenuItem jmi : legacyItems)
4180 jmi.setVisible(false);
4186 if (jws2servs.isRunning())
4188 JMenuItem tm = new JMenuItem(
4189 "Still discovering JABA Services");
4190 tm.setEnabled(false);
4195 build_urlServiceMenu(me.webService);
4196 build_fetchdbmenu(webService);
4197 for (JMenu item : wsmenu)
4199 if (item.getItemCount() == 0)
4201 item.setEnabled(false);
4205 item.setEnabled(true);
4208 } catch (Exception e)
4211 .debug("Exception during web service menu building process.",
4216 } catch (Exception e)
4219 buildingMenu = false;
4226 * construct any groupURL type service menu entries.
4230 private void build_urlServiceMenu(JMenu webService)
4232 // TODO: remove this code when 2.7 is released
4233 // DEBUG - alignmentView
4235 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4236 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4238 * @Override public void actionPerformed(ActionEvent e) {
4239 * jalview.datamodel.AlignmentView
4240 * .testSelectionViews(af.viewport.getAlignment(),
4241 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4243 * }); webService.add(testAlView);
4245 // TODO: refactor to RestClient discoverer and merge menu entries for
4246 // rest-style services with other types of analysis/calculation service
4247 // SHmmr test client - still being implemented.
4248 // DEBUG - alignmentView
4250 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4253 client.attachWSMenuEntry(
4254 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4260 * Searches the alignment sequences for xRefs and builds the Show
4261 * Cross-References menu (formerly called Show Products), with database
4262 * sources for which cross-references are found (protein sources for a
4263 * nucleotide alignment and vice versa)
4265 * @return true if Show Cross-references menu should be enabled
4267 public boolean canShowProducts()
4269 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4270 AlignmentI dataset = viewport.getAlignment().getDataset();
4272 showProducts.removeAll();
4273 final boolean dna = viewport.getAlignment().isNucleotide();
4275 if (seqs == null || seqs.length == 0)
4277 // nothing to see here.
4281 boolean showp = false;
4284 List<String> ptypes = new CrossRef(seqs, dataset)
4285 .findXrefSourcesForSequences(dna);
4287 for (final String source : ptypes)
4290 final AlignFrame af = this;
4291 JMenuItem xtype = new JMenuItem(source);
4292 xtype.addActionListener(new ActionListener()
4295 public void actionPerformed(ActionEvent e)
4297 showProductsFor(af.viewport.getSequenceSelection(), dna, source);
4300 showProducts.add(xtype);
4302 showProducts.setVisible(showp);
4303 showProducts.setEnabled(showp);
4304 } catch (Exception e)
4307 .warn("canShowProducts threw an exception - please report to help@jalview.org",
4315 * Finds and displays cross-references for the selected sequences (protein
4316 * products for nucleotide sequences, dna coding sequences for peptides).
4319 * the sequences to show cross-references for
4321 * true if from a nucleotide alignment (so showing proteins)
4323 * the database to show cross-references for
4325 protected void showProductsFor(final SequenceI[] sel,
4326 final boolean _odna, final String source)
4328 new Thread(CrossRefAction.showProductsFor(sel, _odna, source, this))
4333 * Construct and display a new frame containing the translation of this
4334 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4337 public void showTranslation_actionPerformed(ActionEvent e)
4339 AlignmentI al = null;
4342 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4344 al = dna.translateCdna();
4345 } catch (Exception ex)
4347 jalview.bin.Cache.log.error(
4348 "Exception during translation. Please report this !", ex);
4349 final String msg = MessageManager
4350 .getString("label.error_when_translating_sequences_submit_bug_report");
4351 final String errorTitle = MessageManager
4352 .getString("label.implementation_error")
4353 + MessageManager.getString("label.translation_failed");
4354 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4355 JvOptionPane.ERROR_MESSAGE);
4358 if (al == null || al.getHeight() == 0)
4360 final String msg = MessageManager
4361 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4362 final String errorTitle = MessageManager
4363 .getString("label.translation_failed");
4364 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4365 JvOptionPane.WARNING_MESSAGE);
4369 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4370 af.setFileFormat(this.currentFileFormat);
4371 final String newTitle = MessageManager.formatMessage(
4372 "label.translation_of_params",
4373 new Object[] { this.getTitle() });
4374 af.setTitle(newTitle);
4375 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4377 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4378 viewport.openSplitFrame(af, new Alignment(seqs));
4382 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4389 * Set the file format
4393 public void setFileFormat(FileFormatI format)
4395 this.currentFileFormat = format;
4399 * Try to load a features file onto the alignment.
4402 * contents or path to retrieve file
4404 * access mode of file (see jalview.io.AlignFile)
4405 * @return true if features file was parsed correctly.
4407 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4409 return avc.parseFeaturesFile(file, sourceType,
4410 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4415 public void refreshFeatureUI(boolean enableIfNecessary)
4417 // note - currently this is only still here rather than in the controller
4418 // because of the featureSettings hard reference that is yet to be
4420 if (enableIfNecessary)
4422 viewport.setShowSequenceFeatures(true);
4423 showSeqFeatures.setSelected(true);
4429 public void dragEnter(DropTargetDragEvent evt)
4434 public void dragExit(DropTargetEvent evt)
4439 public void dragOver(DropTargetDragEvent evt)
4444 public void dropActionChanged(DropTargetDragEvent evt)
4449 public void drop(DropTargetDropEvent evt)
4451 // JAL-1552 - acceptDrop required before getTransferable call for
4452 // Java's Transferable for native dnd
4453 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4454 Transferable t = evt.getTransferable();
4455 List<String> files = new ArrayList<>();
4456 List<DataSourceType> protocols = new ArrayList<>();
4460 Desktop.transferFromDropTarget(files, protocols, evt, t);
4461 } catch (Exception e)
4463 e.printStackTrace();
4469 // check to see if any of these files have names matching sequences in
4471 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4472 .getAlignment().getSequencesArray());
4474 * Object[] { String,SequenceI}
4476 ArrayList<Object[]> filesmatched = new ArrayList<>();
4477 ArrayList<String> filesnotmatched = new ArrayList<>();
4478 for (int i = 0; i < files.size(); i++)
4480 String file = files.get(i).toString();
4482 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4483 if (protocol == DataSourceType.FILE)
4485 File fl = new File(file);
4486 pdbfn = fl.getName();
4488 else if (protocol == DataSourceType.URL)
4490 URL url = new URL(file);
4491 pdbfn = url.getFile();
4493 if (pdbfn.length() > 0)
4495 // attempt to find a match in the alignment
4496 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4497 int l = 0, c = pdbfn.indexOf(".");
4498 while (mtch == null && c != -1)
4503 } while ((c = pdbfn.indexOf(".", l)) > l);
4506 pdbfn = pdbfn.substring(0, l);
4508 mtch = idm.findAllIdMatches(pdbfn);
4512 FileFormatI type = null;
4515 type = new IdentifyFile().identify(file, protocol);
4516 } catch (Exception ex)
4520 if (type != null && type.isStructureFile())
4522 filesmatched.add(new Object[] { file, protocol, mtch });
4526 // File wasn't named like one of the sequences or wasn't a PDB file.
4527 filesnotmatched.add(file);
4531 if (filesmatched.size() > 0)
4533 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4539 "label.automatically_associate_structure_files_with_sequences_same_name",
4540 new Object[] { Integer
4546 .getString("label.automatically_associate_structure_files_by_name"),
4547 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION)
4550 for (Object[] fm : filesmatched)
4552 // try and associate
4553 // TODO: may want to set a standard ID naming formalism for
4554 // associating PDB files which have no IDs.
4555 for (SequenceI toassoc : (SequenceI[]) fm[2])
4557 PDBEntry pe = new AssociatePdbFileWithSeq()
4558 .associatePdbWithSeq((String) fm[0],
4559 (DataSourceType) fm[1], toassoc, false,
4563 System.err.println("Associated file : "
4564 + ((String) fm[0]) + " with "
4565 + toassoc.getDisplayId(true));
4569 alignPanel.paintAlignment(true);
4573 if (filesnotmatched.size() > 0)
4576 && (Cache.getDefault(
4577 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JvOptionPane
4583 "label.ignore_unmatched_dropped_files_info",
4584 new Object[] { Integer
4591 .getString("label.ignore_unmatched_dropped_files"),
4592 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4596 for (String fn : filesnotmatched)
4598 loadJalviewDataFile(fn, null, null, null);
4602 } catch (Exception ex)
4604 ex.printStackTrace();
4610 * Attempt to load a "dropped" file or URL string, by testing in turn for
4612 * <li>an Annotation file</li>
4613 * <li>a JNet file</li>
4614 * <li>a features file</li>
4615 * <li>else try to interpret as an alignment file</li>
4619 * either a filename or a URL string.
4621 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4622 FileFormatI format, SequenceI assocSeq)
4626 if (sourceType == null)
4628 sourceType = FormatAdapter.checkProtocol(file);
4630 // if the file isn't identified, or not positively identified as some
4631 // other filetype (PFAM is default unidentified alignment file type) then
4632 // try to parse as annotation.
4633 boolean isAnnotation = (format == null || FileFormat.Pfam
4634 .equals(format)) ? new AnnotationFile()
4635 .annotateAlignmentView(viewport, file, sourceType) : false;
4639 // first see if its a T-COFFEE score file
4640 TCoffeeScoreFile tcf = null;
4643 tcf = new TCoffeeScoreFile(file, sourceType);
4646 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4649 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
4650 isAnnotation = true;
4652 .setText(MessageManager
4653 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
4657 // some problem - if no warning its probable that the ID matching
4658 // process didn't work
4662 tcf.getWarningMessage() == null ? MessageManager
4663 .getString("label.check_file_matches_sequence_ids_alignment")
4664 : tcf.getWarningMessage(),
4666 .getString("label.problem_reading_tcoffee_score_file"),
4667 JvOptionPane.WARNING_MESSAGE);
4674 } catch (Exception x)
4677 .debug("Exception when processing data source as T-COFFEE score file",
4683 // try to see if its a JNet 'concise' style annotation file *before*
4685 // try to parse it as a features file
4688 format = new IdentifyFile().identify(file, sourceType);
4690 if (FileFormat.ScoreMatrix == format)
4692 ScoreMatrixFile sm = new ScoreMatrixFile(new FileParse(file,
4695 // todo: i18n this message
4697 .setText(MessageManager.formatMessage(
4698 "label.successfully_loaded_matrix",
4699 sm.getMatrixName()));
4701 else if (FileFormat.HMMER3.equals(format))
4703 HMMFile hmmFile = new HMMFile(new FileParse(file, sourceType)); // TODO
4710 HiddenMarkovModel hmm = hmmFile.getHMM();
4711 AlignmentAnnotation annotArray[] = getViewport().getAlignment()
4712 .getAlignmentAnnotation();
4714 AlignmentAnnotation reference = null;
4715 for (AlignmentAnnotation annot : annotArray)
4717 if (annot.label.contains("Reference"))
4723 if (reference != null)
4725 hmm.mapToReferenceAnnotation(reference);
4728 AlignmentAnnotation annotation = hmm.createAnnotation(
4729 getViewport().getAlignment().getWidth());
4730 getViewport().getAlignment().addAnnotation(annotation);
4731 AlignmentI newAlignment = hmm
4732 .initPlaceholder(getViewport().getAlignment());
4733 getViewport().setAlignment(newAlignment);
4734 isAnnotation = true;
4735 alignPanel.repaint();
4738 else if (FileFormat.Jnet.equals(format))
4740 JPredFile predictions = new JPredFile(file, sourceType);
4741 new JnetAnnotationMaker();
4742 JnetAnnotationMaker.add_annotation(predictions,
4743 viewport.getAlignment(), 0, false);
4744 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
4745 viewport.getAlignment().setSeqrep(repseq);
4746 HiddenColumns cs = new HiddenColumns();
4747 cs.hideInsertionsFor(repseq);
4748 viewport.getAlignment().setHiddenColumns(cs);
4749 isAnnotation = true;
4751 // else if (IdentifyFile.FeaturesFile.equals(format))
4752 else if (FileFormat.Features.equals(format))
4754 if (parseFeaturesFile(file, sourceType))
4756 alignPanel.paintAlignment(true);
4761 new FileLoader().LoadFile(viewport, file, sourceType, format);
4768 alignPanel.adjustAnnotationHeight();
4769 viewport.updateSequenceIdColours();
4770 buildSortByAnnotationScoresMenu();
4771 alignPanel.paintAlignment(true);
4773 } catch (Exception ex)
4775 ex.printStackTrace();
4776 } catch (OutOfMemoryError oom)
4781 } catch (Exception x)
4786 + (sourceType != null ? (sourceType == DataSourceType.PASTE ? "from clipboard."
4787 : "using " + sourceType + " from " + file)
4789 + (format != null ? "(parsing as '" + format
4790 + "' file)" : ""), oom, Desktop.desktop);
4795 * Method invoked by the ChangeListener on the tabbed pane, in other words
4796 * when a different tabbed pane is selected by the user or programmatically.
4799 public void tabSelectionChanged(int index)
4803 alignPanel = alignPanels.get(index);
4804 viewport = alignPanel.av;
4805 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4806 setMenusFromViewport(viewport);
4810 * 'focus' any colour slider that is open to the selected viewport
4812 if (viewport.getConservationSelected())
4814 SliderPanel.setConservationSlider(alignPanel,
4815 viewport.getResidueShading(), alignPanel.getViewName());
4819 SliderPanel.hideConservationSlider();
4821 if (viewport.getAbovePIDThreshold())
4823 SliderPanel.setPIDSliderSource(alignPanel,
4824 viewport.getResidueShading(), alignPanel.getViewName());
4828 SliderPanel.hidePIDSlider();
4832 * If there is a frame linked to this one in a SplitPane, switch it to the
4833 * same view tab index. No infinite recursion of calls should happen, since
4834 * tabSelectionChanged() should not get invoked on setting the selected
4835 * index to an unchanged value. Guard against setting an invalid index
4836 * before the new view peer tab has been created.
4838 final AlignViewportI peer = viewport.getCodingComplement();
4841 AlignFrame linkedAlignFrame = ((AlignViewport) peer).getAlignPanel().alignFrame;
4842 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4844 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4850 * On right mouse click on view tab, prompt for and set new view name.
4853 public void tabbedPane_mousePressed(MouseEvent e)
4855 if (e.isPopupTrigger())
4857 String msg = MessageManager.getString("label.enter_view_name");
4858 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4859 JvOptionPane.QUESTION_MESSAGE);
4863 viewport.viewName = reply;
4864 // TODO warn if reply is in getExistingViewNames()?
4865 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4870 public AlignViewport getCurrentView()
4876 * Open the dialog for regex description parsing.
4879 protected void extractScores_actionPerformed(ActionEvent e)
4881 ParseProperties pp = new jalview.analysis.ParseProperties(
4882 viewport.getAlignment());
4883 // TODO: verify regex and introduce GUI dialog for version 2.5
4884 // if (pp.getScoresFromDescription("col", "score column ",
4885 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4887 if (pp.getScoresFromDescription("description column",
4888 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4890 buildSortByAnnotationScoresMenu();
4898 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4902 protected void showDbRefs_actionPerformed(ActionEvent e)
4904 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4910 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4914 protected void showNpFeats_actionPerformed(ActionEvent e)
4916 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4920 * find the viewport amongst the tabs in this alignment frame and close that
4925 public boolean closeView(AlignViewportI av)
4929 this.closeMenuItem_actionPerformed(false);
4932 Component[] comp = tabbedPane.getComponents();
4933 for (int i = 0; comp != null && i < comp.length; i++)
4935 if (comp[i] instanceof AlignmentPanel)
4937 if (((AlignmentPanel) comp[i]).av == av)
4940 closeView((AlignmentPanel) comp[i]);
4948 protected void build_fetchdbmenu(JMenu webService)
4950 // Temporary hack - DBRef Fetcher always top level ws entry.
4951 // TODO We probably want to store a sequence database checklist in
4952 // preferences and have checkboxes.. rather than individual sources selected
4954 final JMenu rfetch = new JMenu(
4955 MessageManager.getString("action.fetch_db_references"));
4956 rfetch.setToolTipText(MessageManager
4957 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4958 webService.add(rfetch);
4960 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4961 MessageManager.getString("option.trim_retrieved_seqs"));
4962 trimrs.setToolTipText(MessageManager
4963 .getString("label.trim_retrieved_sequences"));
4964 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
4965 trimrs.addActionListener(new ActionListener()
4968 public void actionPerformed(ActionEvent e)
4970 trimrs.setSelected(trimrs.isSelected());
4971 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
4972 Boolean.valueOf(trimrs.isSelected()).toString());
4976 JMenuItem fetchr = new JMenuItem(
4977 MessageManager.getString("label.standard_databases"));
4978 fetchr.setToolTipText(MessageManager
4979 .getString("label.fetch_embl_uniprot"));
4980 fetchr.addActionListener(new ActionListener()
4984 public void actionPerformed(ActionEvent e)
4986 new Thread(new Runnable()
4991 boolean isNucleotide = alignPanel.alignFrame.getViewport()
4992 .getAlignment().isNucleotide();
4993 DBRefFetcher dbRefFetcher = new DBRefFetcher(alignPanel.av
4994 .getSequenceSelection(), alignPanel.alignFrame, null,
4995 alignPanel.alignFrame.featureSettings, isNucleotide);
4996 dbRefFetcher.addListener(new FetchFinishedListenerI()
4999 public void finished()
5001 AlignFrame.this.setMenusForViewport();
5004 dbRefFetcher.fetchDBRefs(false);
5012 final AlignFrame me = this;
5013 new Thread(new Runnable()
5018 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5019 .getSequenceFetcherSingleton(me);
5020 javax.swing.SwingUtilities.invokeLater(new Runnable()
5025 String[] dbclasses = sf.getOrderedSupportedSources();
5026 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5027 // jalview.util.QuickSort.sort(otherdb, otherdb);
5028 List<DbSourceProxy> otherdb;
5029 JMenu dfetch = new JMenu();
5030 JMenu ifetch = new JMenu();
5031 JMenuItem fetchr = null;
5032 int comp = 0, icomp = 0, mcomp = 15;
5033 String mname = null;
5035 for (String dbclass : dbclasses)
5037 otherdb = sf.getSourceProxy(dbclass);
5038 // add a single entry for this class, or submenu allowing 'fetch
5040 if (otherdb == null || otherdb.size() < 1)
5044 // List<DbSourceProxy> dbs=otherdb;
5045 // otherdb=new ArrayList<DbSourceProxy>();
5046 // for (DbSourceProxy db:dbs)
5048 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5052 mname = "From " + dbclass;
5054 if (otherdb.size() == 1)
5056 final DbSourceProxy[] dassource = otherdb
5057 .toArray(new DbSourceProxy[0]);
5058 DbSourceProxy src = otherdb.get(0);
5059 fetchr = new JMenuItem(src.getDbSource());
5060 fetchr.addActionListener(new ActionListener()
5064 public void actionPerformed(ActionEvent e)
5066 new Thread(new Runnable()
5072 boolean isNucleotide = alignPanel.alignFrame
5073 .getViewport().getAlignment()
5075 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5076 alignPanel.av.getSequenceSelection(),
5077 alignPanel.alignFrame, dassource,
5078 alignPanel.alignFrame.featureSettings,
5081 .addListener(new FetchFinishedListenerI()
5084 public void finished()
5086 AlignFrame.this.setMenusForViewport();
5089 dbRefFetcher.fetchDBRefs(false);
5095 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5096 MessageManager.formatMessage(
5097 "label.fetch_retrieve_from",
5098 new Object[] { src.getDbName() })));
5104 final DbSourceProxy[] dassource = otherdb
5105 .toArray(new DbSourceProxy[0]);
5107 DbSourceProxy src = otherdb.get(0);
5108 fetchr = new JMenuItem(MessageManager.formatMessage(
5109 "label.fetch_all_param",
5110 new Object[] { src.getDbSource() }));
5111 fetchr.addActionListener(new ActionListener()
5114 public void actionPerformed(ActionEvent e)
5116 new Thread(new Runnable()
5122 boolean isNucleotide = alignPanel.alignFrame
5123 .getViewport().getAlignment()
5125 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5126 alignPanel.av.getSequenceSelection(),
5127 alignPanel.alignFrame, dassource,
5128 alignPanel.alignFrame.featureSettings,
5131 .addListener(new FetchFinishedListenerI()
5134 public void finished()
5136 AlignFrame.this.setMenusForViewport();
5139 dbRefFetcher.fetchDBRefs(false);
5145 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5146 MessageManager.formatMessage(
5147 "label.fetch_retrieve_from_all_sources",
5149 Integer.valueOf(otherdb.size())
5150 .toString(), src.getDbSource(),
5151 src.getDbName() })));
5154 // and then build the rest of the individual menus
5155 ifetch = new JMenu(MessageManager.formatMessage(
5156 "label.source_from_db_source",
5157 new Object[] { src.getDbSource() }));
5159 String imname = null;
5161 for (DbSourceProxy sproxy : otherdb)
5163 String dbname = sproxy.getDbName();
5164 String sname = dbname.length() > 5 ? dbname.substring(0,
5165 5) + "..." : dbname;
5166 String msname = dbname.length() > 10 ? dbname.substring(
5167 0, 10) + "..." : dbname;
5170 imname = MessageManager.formatMessage(
5171 "label.from_msname", new Object[] { sname });
5173 fetchr = new JMenuItem(msname);
5174 final DbSourceProxy[] dassrc = { sproxy };
5175 fetchr.addActionListener(new ActionListener()
5179 public void actionPerformed(ActionEvent e)
5181 new Thread(new Runnable()
5187 boolean isNucleotide = alignPanel.alignFrame
5188 .getViewport().getAlignment()
5190 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5191 alignPanel.av.getSequenceSelection(),
5192 alignPanel.alignFrame, dassrc,
5193 alignPanel.alignFrame.featureSettings,
5196 .addListener(new FetchFinishedListenerI()
5199 public void finished()
5201 AlignFrame.this.setMenusForViewport();
5204 dbRefFetcher.fetchDBRefs(false);
5210 fetchr.setToolTipText("<html>"
5211 + MessageManager.formatMessage(
5212 "label.fetch_retrieve_from", new Object[]
5216 if (++icomp >= mcomp || i == (otherdb.size()))
5218 ifetch.setText(MessageManager.formatMessage(
5219 "label.source_to_target", imname, sname));
5221 ifetch = new JMenu();
5229 if (comp >= mcomp || dbi >= (dbclasses.length))
5231 dfetch.setText(MessageManager.formatMessage(
5232 "label.source_to_target", mname, dbclass));
5234 dfetch = new JMenu();
5247 * Left justify the whole alignment.
5250 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5252 AlignmentI al = viewport.getAlignment();
5254 viewport.firePropertyChange("alignment", null, al);
5258 * Right justify the whole alignment.
5261 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5263 AlignmentI al = viewport.getAlignment();
5265 viewport.firePropertyChange("alignment", null, al);
5269 public void setShowSeqFeatures(boolean b)
5271 showSeqFeatures.setSelected(b);
5272 viewport.setShowSequenceFeatures(b);
5279 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5280 * awt.event.ActionEvent)
5283 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5285 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5286 alignPanel.paintAlignment(true);
5293 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5297 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5299 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5300 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5308 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5309 * .event.ActionEvent)
5312 protected void showGroupConservation_actionPerformed(ActionEvent e)
5314 viewport.setShowGroupConservation(showGroupConservation.getState());
5315 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5322 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5323 * .event.ActionEvent)
5326 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5328 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5329 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5336 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5337 * .event.ActionEvent)
5340 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5342 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5343 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5347 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5349 showSequenceLogo.setState(true);
5350 viewport.setShowSequenceLogo(true);
5351 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5352 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5356 protected void showInformationHistogram_actionPerformed(ActionEvent e)
5358 viewport.setShowInformationHistogram(
5359 showInformationHistogram.getState());
5360 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5364 protected void showHMMSequenceLogo_actionPerformed(ActionEvent e)
5366 viewport.setShowHMMSequenceLogo(showHMMSequenceLogo.getState());
5367 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5371 protected void normaliseHMMSequenceLogo_actionPerformed(ActionEvent e)
5373 showHMMSequenceLogo.setState(true);
5374 viewport.setShowHMMSequenceLogo(true);
5375 viewport.setNormaliseHMMSequenceLogo(normaliseSequenceLogo.getState());
5376 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5380 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5382 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5389 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5390 * .event.ActionEvent)
5393 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5395 if (avc.makeGroupsFromSelection())
5397 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5398 alignPanel.updateAnnotation();
5399 alignPanel.paintAlignment(true);
5403 public void clearAlignmentSeqRep()
5405 // TODO refactor alignmentseqrep to controller
5406 if (viewport.getAlignment().hasSeqrep())
5408 viewport.getAlignment().setSeqrep(null);
5409 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5410 alignPanel.updateAnnotation();
5411 alignPanel.paintAlignment(true);
5416 protected void createGroup_actionPerformed(ActionEvent e)
5418 if (avc.createGroup())
5420 alignPanel.alignmentChanged();
5425 protected void unGroup_actionPerformed(ActionEvent e)
5429 alignPanel.alignmentChanged();
5434 * make the given alignmentPanel the currently selected tab
5436 * @param alignmentPanel
5438 public void setDisplayedView(AlignmentPanel alignmentPanel)
5440 if (!viewport.getSequenceSetId().equals(
5441 alignmentPanel.av.getSequenceSetId()))
5445 .getString("error.implementation_error_cannot_show_view_alignment_frame"));
5447 if (tabbedPane != null
5448 && tabbedPane.getTabCount() > 0
5449 && alignPanels.indexOf(alignmentPanel) != tabbedPane
5450 .getSelectedIndex())
5452 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5457 * Action on selection of menu options to Show or Hide annotations.
5460 * @param forSequences
5461 * update sequence-related annotations
5462 * @param forAlignment
5463 * update non-sequence-related annotations
5466 protected void setAnnotationsVisibility(boolean visible,
5467 boolean forSequences, boolean forAlignment)
5469 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5470 .getAlignmentAnnotation();
5475 for (AlignmentAnnotation aa : anns)
5478 * don't display non-positional annotations on an alignment
5480 if (aa.annotations == null)
5484 boolean apply = (aa.sequenceRef == null && forAlignment)
5485 || (aa.sequenceRef != null && forSequences);
5488 aa.visible = visible;
5491 alignPanel.validateAnnotationDimensions(true);
5492 alignPanel.alignmentChanged();
5496 * Store selected annotation sort order for the view and repaint.
5499 protected void sortAnnotations_actionPerformed()
5501 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5503 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5504 alignPanel.paintAlignment(true);
5509 * @return alignment panels in this alignment frame
5511 public List<? extends AlignmentViewPanel> getAlignPanels()
5513 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5517 * Open a new alignment window, with the cDNA associated with this (protein)
5518 * alignment, aligned as is the protein.
5520 protected void viewAsCdna_actionPerformed()
5522 // TODO no longer a menu action - refactor as required
5523 final AlignmentI alignment = getViewport().getAlignment();
5524 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5525 if (mappings == null)
5529 List<SequenceI> cdnaSeqs = new ArrayList<>();
5530 for (SequenceI aaSeq : alignment.getSequences())
5532 for (AlignedCodonFrame acf : mappings)
5534 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5538 * There is a cDNA mapping for this protein sequence - add to new
5539 * alignment. It will share the same dataset sequence as other mapped
5540 * cDNA (no new mappings need to be created).
5542 final Sequence newSeq = new Sequence(dnaSeq);
5543 newSeq.setDatasetSequence(dnaSeq);
5544 cdnaSeqs.add(newSeq);
5548 if (cdnaSeqs.size() == 0)
5550 // show a warning dialog no mapped cDNA
5553 AlignmentI cdna = new Alignment(cdnaSeqs.toArray(new SequenceI[cdnaSeqs
5555 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5556 AlignFrame.DEFAULT_HEIGHT);
5557 cdna.alignAs(alignment);
5558 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5560 Desktop.addInternalFrame(alignFrame, newtitle,
5561 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
5565 * Set visibility of dna/protein complement view (available when shown in a
5571 protected void showComplement_actionPerformed(boolean show)
5573 SplitContainerI sf = getSplitViewContainer();
5576 sf.setComplementVisible(this, show);
5581 * Generate the reverse (optionally complemented) of the selected sequences,
5582 * and add them to the alignment
5585 protected void showReverse_actionPerformed(boolean complement)
5587 AlignmentI al = null;
5590 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5591 al = dna.reverseCdna(complement);
5592 viewport.addAlignment(al, "");
5593 addHistoryItem(new EditCommand(
5594 MessageManager.getString("label.add_sequences"),
5595 Action.PASTE, al.getSequencesArray(), 0, al.getWidth(),
5596 viewport.getAlignment()));
5597 } catch (Exception ex)
5599 System.err.println(ex.getMessage());
5605 * Try to run a script in the Groovy console, having first ensured that this
5606 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5607 * be targeted at this alignment.
5610 protected void runGroovy_actionPerformed()
5612 Jalview.setCurrentAlignFrame(this);
5613 groovy.ui.Console console = Desktop.getGroovyConsole();
5614 if (console != null)
5618 console.runScript();
5619 } catch (Exception ex)
5621 System.err.println((ex.toString()));
5623 .showInternalMessageDialog(Desktop.desktop, MessageManager
5624 .getString("label.couldnt_run_groovy_script"),
5626 .getString("label.groovy_support_failed"),
5627 JvOptionPane.ERROR_MESSAGE);
5632 System.err.println("Can't run Groovy script as console not found");
5637 * Hides columns containing (or not containing) a specified feature, provided
5638 * that would not leave all columns hidden
5640 * @param featureType
5641 * @param columnsContaining
5644 public boolean hideFeatureColumns(String featureType,
5645 boolean columnsContaining)
5647 boolean notForHiding = avc.markColumnsContainingFeatures(
5648 columnsContaining, false, false, featureType);
5651 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5652 false, featureType))
5654 getViewport().hideSelectedColumns();
5662 protected void selectHighlightedColumns_actionPerformed(
5663 ActionEvent actionEvent)
5665 // include key modifier check in case user selects from menu
5666 avc.markHighlightedColumns(
5667 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0,
5669 (actionEvent.getModifiers() & (ActionEvent.META_MASK | ActionEvent.CTRL_MASK)) != 0);
5673 * Rebuilds the Colour menu, including any user-defined colours which have
5674 * been loaded either on startup or during the session
5676 public void buildColourMenu()
5678 colourMenu.removeAll();
5680 colourMenu.add(applyToAllGroups);
5681 colourMenu.add(textColour);
5682 colourMenu.addSeparator();
5684 ColourMenuHelper.addMenuItems(colourMenu, this,
5685 viewport.getAlignment(), false);
5687 colourMenu.addSeparator();
5688 colourMenu.add(conservationMenuItem);
5689 colourMenu.add(modifyConservation);
5690 colourMenu.add(abovePIDThreshold);
5691 colourMenu.add(modifyPID);
5692 colourMenu.add(annotationColour);
5694 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5695 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5699 * Open a dialog (if not already open) that allows the user to select and
5700 * calculate PCA or Tree analysis
5702 protected void openTreePcaDialog()
5704 if (alignPanel.getCalculationDialog() == null)
5706 new CalculationChooser(AlignFrame.this);
5711 class PrintThread extends Thread
5715 public PrintThread(AlignmentPanel ap)
5720 static PageFormat pf;
5725 PrinterJob printJob = PrinterJob.getPrinterJob();
5729 printJob.setPrintable(ap, pf);
5733 printJob.setPrintable(ap);
5736 if (printJob.printDialog())
5741 } catch (Exception PrintException)
5743 PrintException.printStackTrace();