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();
1048 public void hmmAlign_actionPerformed(ActionEvent e)
1049 throws IOException, InterruptedException
1051 HMMERCommands.hmmAlign(this);
1052 alignPanel.repaint();
1056 public void hmmSearch_actionPerformed(ActionEvent e)
1059 alignPanel.repaint();
1063 public void reload_actionPerformed(ActionEvent e)
1065 if (fileName != null)
1067 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1068 // originating file's format
1069 // TODO: work out how to recover feature settings for correct view(s) when
1070 // file is reloaded.
1071 if (FileFormat.Jalview.equals(currentFileFormat))
1073 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1074 for (int i = 0; i < frames.length; i++)
1076 if (frames[i] instanceof AlignFrame && frames[i] != this
1077 && ((AlignFrame) frames[i]).fileName != null
1078 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1082 frames[i].setSelected(true);
1083 Desktop.instance.closeAssociatedWindows();
1084 } catch (java.beans.PropertyVetoException ex)
1090 Desktop.instance.closeAssociatedWindows();
1092 FileLoader loader = new FileLoader();
1093 DataSourceType protocol = fileName.startsWith("http:") ? DataSourceType.URL
1094 : DataSourceType.FILE;
1095 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1099 Rectangle bounds = this.getBounds();
1101 FileLoader loader = new FileLoader();
1102 DataSourceType protocol = fileName.startsWith("http:") ? DataSourceType.URL
1103 : DataSourceType.FILE;
1104 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1105 protocol, currentFileFormat);
1107 newframe.setBounds(bounds);
1108 if (featureSettings != null && featureSettings.isShowing())
1110 final Rectangle fspos = featureSettings.frame.getBounds();
1111 // TODO: need a 'show feature settings' function that takes bounds -
1112 // need to refactor Desktop.addFrame
1113 newframe.featureSettings_actionPerformed(null);
1114 final FeatureSettings nfs = newframe.featureSettings;
1115 SwingUtilities.invokeLater(new Runnable()
1120 nfs.frame.setBounds(fspos);
1123 this.featureSettings.close();
1124 this.featureSettings = null;
1126 this.closeMenuItem_actionPerformed(true);
1132 public void addFromText_actionPerformed(ActionEvent e)
1134 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport
1139 public void addFromURL_actionPerformed(ActionEvent e)
1141 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1145 public void save_actionPerformed(ActionEvent e)
1147 if (fileName == null || (currentFileFormat == null)
1148 || fileName.startsWith("http"))
1150 saveAs_actionPerformed(null);
1154 saveAlignment(fileName, currentFileFormat);
1165 public void saveAs_actionPerformed(ActionEvent e)
1167 String format = currentFileFormat == null ? null : currentFileFormat
1169 JalviewFileChooser chooser = JalviewFileChooser.forWrite(
1170 Cache.getProperty("LAST_DIRECTORY"), format);
1172 chooser.setFileView(new JalviewFileView());
1173 chooser.setDialogTitle(MessageManager
1174 .getString("label.save_alignment_to_file"));
1175 chooser.setToolTipText(MessageManager.getString("action.save"));
1177 int value = chooser.showSaveDialog(this);
1179 if (value == JalviewFileChooser.APPROVE_OPTION)
1181 currentFileFormat = chooser.getSelectedFormat();
1182 while (currentFileFormat == null)
1185 .showInternalMessageDialog(
1188 .getString("label.select_file_format_before_saving"),
1190 .getString("label.file_format_not_specified"),
1191 JvOptionPane.WARNING_MESSAGE);
1192 currentFileFormat = chooser.getSelectedFormat();
1193 value = chooser.showSaveDialog(this);
1194 if (value != JalviewFileChooser.APPROVE_OPTION)
1200 fileName = chooser.getSelectedFile().getPath();
1202 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1204 Cache.setProperty("LAST_DIRECTORY", fileName);
1205 saveAlignment(fileName, currentFileFormat);
1209 public boolean saveAlignment(String file, FileFormatI format)
1211 boolean success = true;
1213 if (FileFormat.Jalview.equals(format))
1215 String shortName = title;
1217 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1219 shortName = shortName.substring(shortName
1220 .lastIndexOf(java.io.File.separatorChar) + 1);
1223 success = new Jalview2XML().saveAlignment(this, file, shortName);
1225 statusBar.setText(MessageManager.formatMessage(
1226 "label.successfully_saved_to_file_in_format", new Object[] {
1227 fileName, format }));
1232 AlignmentExportData exportData = getAlignmentForExport(format,
1234 if (exportData.getSettings().isCancelled())
1238 FormatAdapter f = new FormatAdapter(alignPanel,
1239 exportData.getSettings());
1240 String output = f.formatSequences(
1242 exportData.getAlignment(), // class cast exceptions will
1243 // occur in the distant future
1244 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1245 f.getCacheSuffixDefault(format), viewport.getAlignment()
1246 .getHiddenColumns());
1256 PrintWriter out = new PrintWriter(new FileWriter(file));
1260 this.setTitle(file);
1261 statusBar.setText(MessageManager.formatMessage(
1262 "label.successfully_saved_to_file_in_format",
1263 new Object[] { fileName, format.getName() }));
1264 } catch (Exception ex)
1267 ex.printStackTrace();
1274 JvOptionPane.showInternalMessageDialog(this, MessageManager
1275 .formatMessage("label.couldnt_save_file",
1276 new Object[] { fileName }), MessageManager
1277 .getString("label.error_saving_file"),
1278 JvOptionPane.WARNING_MESSAGE);
1284 private void warningMessage(String warning, String title)
1286 if (new jalview.util.Platform().isHeadless())
1288 System.err.println("Warning: " + title + "\nWarning: " + warning);
1293 JvOptionPane.showInternalMessageDialog(this, warning, title,
1294 JvOptionPane.WARNING_MESSAGE);
1306 protected void outputText_actionPerformed(ActionEvent e)
1308 FileFormatI fileFormat = FileFormats.getInstance().forName(
1309 e.getActionCommand());
1310 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1312 if (exportData.getSettings().isCancelled())
1316 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1317 cap.setForInput(null);
1320 FileFormatI format = fileFormat;
1321 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1322 .formatSequences(format, exportData.getAlignment(),
1323 exportData.getOmitHidden(),
1325 .getStartEndPostions(), viewport
1326 .getAlignment().getHiddenColumns()));
1327 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1328 "label.alignment_output_command",
1329 new Object[] { e.getActionCommand() }), 600, 500);
1330 } catch (OutOfMemoryError oom)
1332 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1338 public static AlignmentExportData getAlignmentForExport(
1339 FileFormatI format, AlignViewportI viewport,
1340 AlignExportSettingI exportSettings)
1342 AlignmentI alignmentToExport = null;
1343 AlignExportSettingI settings = exportSettings;
1344 String[] omitHidden = null;
1346 HiddenSequences hiddenSeqs = viewport.getAlignment()
1347 .getHiddenSequences();
1349 alignmentToExport = viewport.getAlignment();
1351 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1352 if (settings == null)
1354 settings = new AlignExportSettings(hasHiddenSeqs,
1355 viewport.hasHiddenColumns(), format);
1357 // settings.isExportAnnotations();
1359 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1361 omitHidden = viewport.getViewAsString(false,
1362 settings.isExportHiddenSequences());
1365 int[] alignmentStartEnd = new int[2];
1366 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1368 alignmentToExport = hiddenSeqs.getFullAlignment();
1372 alignmentToExport = viewport.getAlignment();
1374 alignmentStartEnd = alignmentToExport
1375 .getVisibleStartAndEndIndex(viewport.getAlignment()
1377 .getHiddenRegions());
1378 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1379 omitHidden, alignmentStartEnd, settings);
1390 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1392 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1393 htmlSVG.exportHTML(null);
1397 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1399 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1400 bjs.exportHTML(null);
1403 public void createImageMap(File file, String image)
1405 alignPanel.makePNGImageMap(file, image);
1415 public void createPNG(File f)
1417 alignPanel.makePNG(f);
1427 public void createEPS(File f)
1429 alignPanel.makeEPS(f);
1433 public void createSVG(File f)
1435 alignPanel.makeSVG(f);
1439 public void pageSetup_actionPerformed(ActionEvent e)
1441 PrinterJob printJob = PrinterJob.getPrinterJob();
1442 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1452 public void printMenuItem_actionPerformed(ActionEvent e)
1454 // Putting in a thread avoids Swing painting problems
1455 PrintThread thread = new PrintThread(alignPanel);
1460 public void exportFeatures_actionPerformed(ActionEvent e)
1462 new AnnotationExporter().exportFeatures(alignPanel);
1466 public void exportAnnotations_actionPerformed(ActionEvent e)
1468 new AnnotationExporter().exportAnnotations(alignPanel);
1472 public void associatedData_actionPerformed(ActionEvent e)
1474 // Pick the tree file
1475 JalviewFileChooser chooser = new JalviewFileChooser(
1476 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1477 chooser.setFileView(new JalviewFileView());
1478 chooser.setDialogTitle(MessageManager
1479 .getString("label.load_jalview_annotations"));
1480 chooser.setToolTipText(MessageManager
1481 .getString("label.load_jalview_annotations"));
1483 int value = chooser.showOpenDialog(null);
1485 if (value == JalviewFileChooser.APPROVE_OPTION)
1487 String choice = chooser.getSelectedFile().getPath();
1488 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1489 loadJalviewDataFile(choice, null, null, null);
1495 * Close the current view or all views in the alignment frame. If the frame
1496 * only contains one view then the alignment will be removed from memory.
1498 * @param closeAllTabs
1501 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1503 if (alignPanels != null && alignPanels.size() < 2)
1505 closeAllTabs = true;
1510 if (alignPanels != null)
1514 if (this.isClosed())
1516 // really close all the windows - otherwise wait till
1517 // setClosed(true) is called
1518 for (int i = 0; i < alignPanels.size(); i++)
1520 AlignmentPanel ap = alignPanels.get(i);
1527 closeView(alignPanel);
1534 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1535 * be called recursively, with the frame now in 'closed' state
1537 this.setClosed(true);
1539 } catch (Exception ex)
1541 ex.printStackTrace();
1546 * Close the specified panel and close up tabs appropriately.
1548 * @param panelToClose
1550 public void closeView(AlignmentPanel panelToClose)
1552 int index = tabbedPane.getSelectedIndex();
1553 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1554 alignPanels.remove(panelToClose);
1555 panelToClose.closePanel();
1556 panelToClose = null;
1558 tabbedPane.removeTabAt(closedindex);
1559 tabbedPane.validate();
1561 if (index > closedindex || index == tabbedPane.getTabCount())
1563 // modify currently selected tab index if necessary.
1567 this.tabSelectionChanged(index);
1573 void updateEditMenuBar()
1576 if (viewport.getHistoryList().size() > 0)
1578 undoMenuItem.setEnabled(true);
1579 CommandI command = viewport.getHistoryList().peek();
1580 undoMenuItem.setText(MessageManager.formatMessage(
1581 "label.undo_command",
1582 new Object[] { command.getDescription() }));
1586 undoMenuItem.setEnabled(false);
1587 undoMenuItem.setText(MessageManager.getString("action.undo"));
1590 if (viewport.getRedoList().size() > 0)
1592 redoMenuItem.setEnabled(true);
1594 CommandI command = viewport.getRedoList().peek();
1595 redoMenuItem.setText(MessageManager.formatMessage(
1596 "label.redo_command",
1597 new Object[] { command.getDescription() }));
1601 redoMenuItem.setEnabled(false);
1602 redoMenuItem.setText(MessageManager.getString("action.redo"));
1607 public void addHistoryItem(CommandI command)
1609 if (command.getSize() > 0)
1611 viewport.addToHistoryList(command);
1612 viewport.clearRedoList();
1613 updateEditMenuBar();
1614 viewport.updateHiddenColumns();
1615 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1616 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1617 // viewport.getColumnSelection()
1618 // .getHiddenColumns().size() > 0);
1624 * @return alignment objects for all views
1626 AlignmentI[] getViewAlignments()
1628 if (alignPanels != null)
1630 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1632 for (AlignmentPanel ap : alignPanels)
1634 als[i++] = ap.av.getAlignment();
1638 if (viewport != null)
1640 return new AlignmentI[] { viewport.getAlignment() };
1652 protected void undoMenuItem_actionPerformed(ActionEvent e)
1654 if (viewport.getHistoryList().isEmpty())
1658 CommandI command = viewport.getHistoryList().pop();
1659 viewport.addToRedoList(command);
1660 command.undoCommand(getViewAlignments());
1662 AlignmentViewport originalSource = getOriginatingSource(command);
1663 updateEditMenuBar();
1665 if (originalSource != null)
1667 if (originalSource != viewport)
1670 .warn("Implementation worry: mismatch of viewport origin for undo");
1672 originalSource.updateHiddenColumns();
1673 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1675 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1676 // viewport.getColumnSelection()
1677 // .getHiddenColumns().size() > 0);
1678 originalSource.firePropertyChange("alignment", null, originalSource
1679 .getAlignment().getSequences());
1690 protected void redoMenuItem_actionPerformed(ActionEvent e)
1692 if (viewport.getRedoList().size() < 1)
1697 CommandI command = viewport.getRedoList().pop();
1698 viewport.addToHistoryList(command);
1699 command.doCommand(getViewAlignments());
1701 AlignmentViewport originalSource = getOriginatingSource(command);
1702 updateEditMenuBar();
1704 if (originalSource != null)
1707 if (originalSource != viewport)
1710 .warn("Implementation worry: mismatch of viewport origin for redo");
1712 originalSource.updateHiddenColumns();
1713 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1715 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1716 // viewport.getColumnSelection()
1717 // .getHiddenColumns().size() > 0);
1718 originalSource.firePropertyChange("alignment", null, originalSource
1719 .getAlignment().getSequences());
1723 AlignmentViewport getOriginatingSource(CommandI command)
1725 AlignmentViewport originalSource = null;
1726 // For sequence removal and addition, we need to fire
1727 // the property change event FROM the viewport where the
1728 // original alignment was altered
1729 AlignmentI al = null;
1730 if (command instanceof EditCommand)
1732 EditCommand editCommand = (EditCommand) command;
1733 al = editCommand.getAlignment();
1734 List<Component> comps = PaintRefresher.components.get(viewport
1735 .getSequenceSetId());
1737 for (Component comp : comps)
1739 if (comp instanceof AlignmentPanel)
1741 if (al == ((AlignmentPanel) comp).av.getAlignment())
1743 originalSource = ((AlignmentPanel) comp).av;
1750 if (originalSource == null)
1752 // The original view is closed, we must validate
1753 // the current view against the closed view first
1756 PaintRefresher.validateSequences(al, viewport.getAlignment());
1759 originalSource = viewport;
1762 return originalSource;
1771 public void moveSelectedSequences(boolean up)
1773 SequenceGroup sg = viewport.getSelectionGroup();
1779 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1780 viewport.getHiddenRepSequences(), up);
1781 alignPanel.paintAlignment(true);
1784 synchronized void slideSequences(boolean right, int size)
1786 List<SequenceI> sg = new ArrayList<>();
1787 if (viewport.cursorMode)
1789 sg.add(viewport.getAlignment().getSequenceAt(
1790 alignPanel.getSeqPanel().seqCanvas.cursorY));
1792 else if (viewport.getSelectionGroup() != null
1793 && viewport.getSelectionGroup().getSize() != viewport
1794 .getAlignment().getHeight())
1796 sg = viewport.getSelectionGroup().getSequences(
1797 viewport.getHiddenRepSequences());
1805 List<SequenceI> invertGroup = new ArrayList<>();
1807 for (SequenceI seq : viewport.getAlignment().getSequences())
1809 if (!sg.contains(seq))
1811 invertGroup.add(seq);
1815 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1817 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1818 for (int i = 0; i < invertGroup.size(); i++)
1820 seqs2[i] = invertGroup.get(i);
1823 SlideSequencesCommand ssc;
1826 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1827 size, viewport.getGapCharacter());
1831 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1832 size, viewport.getGapCharacter());
1835 int groupAdjustment = 0;
1836 if (ssc.getGapsInsertedBegin() && right)
1838 if (viewport.cursorMode)
1840 alignPanel.getSeqPanel().moveCursor(size, 0);
1844 groupAdjustment = size;
1847 else if (!ssc.getGapsInsertedBegin() && !right)
1849 if (viewport.cursorMode)
1851 alignPanel.getSeqPanel().moveCursor(-size, 0);
1855 groupAdjustment = -size;
1859 if (groupAdjustment != 0)
1861 viewport.getSelectionGroup().setStartRes(
1862 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1863 viewport.getSelectionGroup().setEndRes(
1864 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1868 * just extend the last slide command if compatible; but not if in
1869 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1871 boolean appendHistoryItem = false;
1872 Deque<CommandI> historyList = viewport.getHistoryList();
1873 boolean inSplitFrame = getSplitViewContainer() != null;
1874 if (!inSplitFrame && historyList != null && historyList.size() > 0
1875 && historyList.peek() instanceof SlideSequencesCommand)
1877 appendHistoryItem = ssc
1878 .appendSlideCommand((SlideSequencesCommand) historyList
1882 if (!appendHistoryItem)
1884 addHistoryItem(ssc);
1897 protected void copy_actionPerformed(ActionEvent e)
1900 if (viewport.getSelectionGroup() == null)
1904 // TODO: preserve the ordering of displayed alignment annotation in any
1905 // internal paste (particularly sequence associated annotation)
1906 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1907 String[] omitHidden = null;
1909 if (viewport.hasHiddenColumns())
1911 omitHidden = viewport.getViewAsString(true);
1914 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1915 seqs, omitHidden, null);
1917 StringSelection ss = new StringSelection(output);
1921 jalview.gui.Desktop.internalCopy = true;
1922 // Its really worth setting the clipboard contents
1923 // to empty before setting the large StringSelection!!
1924 Toolkit.getDefaultToolkit().getSystemClipboard()
1925 .setContents(new StringSelection(""), null);
1927 Toolkit.getDefaultToolkit().getSystemClipboard()
1928 .setContents(ss, Desktop.instance);
1929 } catch (OutOfMemoryError er)
1931 new OOMWarning("copying region", er);
1935 ArrayList<int[]> hiddenColumns = null;
1936 if (viewport.hasHiddenColumns())
1938 hiddenColumns = new ArrayList<>();
1939 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1940 .getSelectionGroup().getEndRes();
1941 for (int[] region : viewport.getAlignment().getHiddenColumns()
1942 .getHiddenRegions())
1944 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1946 hiddenColumns.add(new int[] { region[0] - hiddenOffset,
1947 region[1] - hiddenOffset });
1952 Desktop.jalviewClipboard = new Object[] { seqs,
1953 viewport.getAlignment().getDataset(), hiddenColumns };
1954 statusBar.setText(MessageManager.formatMessage(
1955 "label.copied_sequences_to_clipboard", new Object[] { Integer
1956 .valueOf(seqs.length).toString() }));
1966 protected void pasteNew_actionPerformed(ActionEvent e)
1978 protected void pasteThis_actionPerformed(ActionEvent e)
1984 * Paste contents of Jalview clipboard
1986 * @param newAlignment
1987 * true to paste to a new alignment, otherwise add to this.
1989 void paste(boolean newAlignment)
1991 boolean externalPaste = true;
1994 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1995 Transferable contents = c.getContents(this);
1997 if (contents == null)
2006 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2007 if (str.length() < 1)
2012 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2014 } catch (OutOfMemoryError er)
2016 new OOMWarning("Out of memory pasting sequences!!", er);
2020 SequenceI[] sequences;
2021 boolean annotationAdded = false;
2022 AlignmentI alignment = null;
2024 if (Desktop.jalviewClipboard != null)
2026 // The clipboard was filled from within Jalview, we must use the
2028 // And dataset from the copied alignment
2029 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2030 // be doubly sure that we create *new* sequence objects.
2031 sequences = new SequenceI[newseq.length];
2032 for (int i = 0; i < newseq.length; i++)
2034 sequences[i] = new Sequence(newseq[i]);
2036 alignment = new Alignment(sequences);
2037 externalPaste = false;
2041 // parse the clipboard as an alignment.
2042 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2044 sequences = alignment.getSequencesArray();
2048 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2054 if (Desktop.jalviewClipboard != null)
2056 // dataset is inherited
2057 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2061 // new dataset is constructed
2062 alignment.setDataset(null);
2064 alwidth = alignment.getWidth() + 1;
2068 AlignmentI pastedal = alignment; // preserve pasted alignment object
2069 // Add pasted sequences and dataset into existing alignment.
2070 alignment = viewport.getAlignment();
2071 alwidth = alignment.getWidth() + 1;
2072 // decide if we need to import sequences from an existing dataset
2073 boolean importDs = Desktop.jalviewClipboard != null
2074 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2075 // importDs==true instructs us to copy over new dataset sequences from
2076 // an existing alignment
2077 Vector newDs = (importDs) ? new Vector() : null; // used to create
2078 // minimum dataset set
2080 for (int i = 0; i < sequences.length; i++)
2084 newDs.addElement(null);
2086 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2088 if (importDs && ds != null)
2090 if (!newDs.contains(ds))
2092 newDs.setElementAt(ds, i);
2093 ds = new Sequence(ds);
2094 // update with new dataset sequence
2095 sequences[i].setDatasetSequence(ds);
2099 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2104 // copy and derive new dataset sequence
2105 sequences[i] = sequences[i].deriveSequence();
2106 alignment.getDataset().addSequence(
2107 sequences[i].getDatasetSequence());
2108 // TODO: avoid creation of duplicate dataset sequences with a
2109 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2111 alignment.addSequence(sequences[i]); // merges dataset
2115 newDs.clear(); // tidy up
2117 if (alignment.getAlignmentAnnotation() != null)
2119 for (AlignmentAnnotation alan : alignment
2120 .getAlignmentAnnotation())
2122 if (alan.graphGroup > fgroup)
2124 fgroup = alan.graphGroup;
2128 if (pastedal.getAlignmentAnnotation() != null)
2130 // Add any annotation attached to alignment.
2131 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2132 for (int i = 0; i < alann.length; i++)
2134 annotationAdded = true;
2135 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2137 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2138 if (newann.graphGroup > -1)
2140 if (newGraphGroups.size() <= newann.graphGroup
2141 || newGraphGroups.get(newann.graphGroup) == null)
2143 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2145 newGraphGroups.add(q, null);
2147 newGraphGroups.set(newann.graphGroup, new Integer(
2150 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2154 newann.padAnnotation(alwidth);
2155 alignment.addAnnotation(newann);
2165 addHistoryItem(new EditCommand(
2166 MessageManager.getString("label.add_sequences"),
2167 Action.PASTE, sequences, 0, alignment.getWidth(), alignment));
2169 // Add any annotations attached to sequences
2170 for (int i = 0; i < sequences.length; i++)
2172 if (sequences[i].getAnnotation() != null)
2174 AlignmentAnnotation newann;
2175 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2177 annotationAdded = true;
2178 newann = sequences[i].getAnnotation()[a];
2179 newann.adjustForAlignment();
2180 newann.padAnnotation(alwidth);
2181 if (newann.graphGroup > -1)
2183 if (newann.graphGroup > -1)
2185 if (newGraphGroups.size() <= newann.graphGroup
2186 || newGraphGroups.get(newann.graphGroup) == null)
2188 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2190 newGraphGroups.add(q, null);
2192 newGraphGroups.set(newann.graphGroup, new Integer(
2195 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2199 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2204 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2211 // propagate alignment changed.
2212 vpRanges.setEndSeq(alignment.getHeight());
2213 if (annotationAdded)
2215 // Duplicate sequence annotation in all views.
2216 AlignmentI[] alview = this.getViewAlignments();
2217 for (int i = 0; i < sequences.length; i++)
2219 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2224 for (int avnum = 0; avnum < alview.length; avnum++)
2226 if (alview[avnum] != alignment)
2228 // duplicate in a view other than the one with input focus
2229 int avwidth = alview[avnum].getWidth() + 1;
2230 // this relies on sann being preserved after we
2231 // modify the sequence's annotation array for each duplication
2232 for (int a = 0; a < sann.length; a++)
2234 AlignmentAnnotation newann = new AlignmentAnnotation(
2236 sequences[i].addAlignmentAnnotation(newann);
2237 newann.padAnnotation(avwidth);
2238 alview[avnum].addAnnotation(newann); // annotation was
2239 // duplicated earlier
2240 // TODO JAL-1145 graphGroups are not updated for sequence
2241 // annotation added to several views. This may cause
2243 alview[avnum].setAnnotationIndex(newann, a);
2248 buildSortByAnnotationScoresMenu();
2250 viewport.firePropertyChange("alignment", null,
2251 alignment.getSequences());
2252 if (alignPanels != null)
2254 for (AlignmentPanel ap : alignPanels)
2256 ap.validateAnnotationDimensions(false);
2261 alignPanel.validateAnnotationDimensions(false);
2267 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2269 String newtitle = new String("Copied sequences");
2271 if (Desktop.jalviewClipboard != null
2272 && Desktop.jalviewClipboard[2] != null)
2274 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2275 for (int[] region : hc)
2277 af.viewport.hideColumns(region[0], region[1]);
2281 // >>>This is a fix for the moment, until a better solution is
2283 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2285 alignPanel.getSeqPanel().seqCanvas
2286 .getFeatureRenderer());
2288 // TODO: maintain provenance of an alignment, rather than just make the
2289 // title a concatenation of operations.
2292 if (title.startsWith("Copied sequences"))
2298 newtitle = newtitle.concat("- from " + title);
2303 newtitle = new String("Pasted sequences");
2306 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2311 } catch (Exception ex)
2313 ex.printStackTrace();
2314 System.out.println("Exception whilst pasting: " + ex);
2315 // could be anything being pasted in here
2321 protected void expand_newalign(ActionEvent e)
2325 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2326 .getAlignment(), -1);
2327 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2329 String newtitle = new String("Flanking alignment");
2331 if (Desktop.jalviewClipboard != null
2332 && Desktop.jalviewClipboard[2] != null)
2334 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2335 for (int region[] : hc)
2337 af.viewport.hideColumns(region[0], region[1]);
2341 // >>>This is a fix for the moment, until a better solution is
2343 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2345 alignPanel.getSeqPanel().seqCanvas
2346 .getFeatureRenderer());
2348 // TODO: maintain provenance of an alignment, rather than just make the
2349 // title a concatenation of operations.
2351 if (title.startsWith("Copied sequences"))
2357 newtitle = newtitle.concat("- from " + title);
2361 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2363 } catch (Exception ex)
2365 ex.printStackTrace();
2366 System.out.println("Exception whilst pasting: " + ex);
2367 // could be anything being pasted in here
2368 } catch (OutOfMemoryError oom)
2370 new OOMWarning("Viewing flanking region of alignment", oom);
2381 protected void cut_actionPerformed(ActionEvent e)
2383 copy_actionPerformed(null);
2384 delete_actionPerformed(null);
2394 protected void delete_actionPerformed(ActionEvent evt)
2397 SequenceGroup sg = viewport.getSelectionGroup();
2404 * If the cut affects all sequences, warn, remove highlighted columns
2406 if (sg.getSize() == viewport.getAlignment().getHeight())
2408 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes()) + 1) == viewport
2409 .getAlignment().getWidth()) ? true : false;
2410 if (isEntireAlignWidth)
2412 int confirm = JvOptionPane.showConfirmDialog(this,
2413 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2414 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2415 JvOptionPane.OK_CANCEL_OPTION);
2417 if (confirm == JvOptionPane.CANCEL_OPTION
2418 || confirm == JvOptionPane.CLOSED_OPTION)
2423 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2424 sg.getEndRes() + 1);
2426 SequenceI[] cut = sg.getSequences()
2427 .toArray(new SequenceI[sg.getSize()]);
2429 addHistoryItem(new EditCommand(
2430 MessageManager.getString("label.cut_sequences"), Action.CUT,
2431 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2432 viewport.getAlignment()));
2434 viewport.setSelectionGroup(null);
2435 viewport.sendSelection();
2436 viewport.getAlignment().deleteGroup(sg);
2438 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2440 if (viewport.getAlignment().getHeight() < 1)
2444 this.setClosed(true);
2445 } catch (Exception ex)
2458 protected void deleteGroups_actionPerformed(ActionEvent e)
2460 if (avc.deleteGroups())
2462 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2463 alignPanel.updateAnnotation();
2464 alignPanel.paintAlignment(true);
2475 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2477 SequenceGroup sg = new SequenceGroup();
2479 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2481 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2484 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2485 viewport.setSelectionGroup(sg);
2486 viewport.sendSelection();
2487 // JAL-2034 - should delegate to
2488 // alignPanel to decide if overview needs
2490 alignPanel.paintAlignment(false);
2491 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2501 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2503 if (viewport.cursorMode)
2505 alignPanel.getSeqPanel().keyboardNo1 = null;
2506 alignPanel.getSeqPanel().keyboardNo2 = null;
2508 viewport.setSelectionGroup(null);
2509 viewport.getColumnSelection().clear();
2510 viewport.setSelectionGroup(null);
2511 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2512 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2513 // JAL-2034 - should delegate to
2514 // alignPanel to decide if overview needs
2516 alignPanel.paintAlignment(false);
2517 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2518 viewport.sendSelection();
2528 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2530 SequenceGroup sg = viewport.getSelectionGroup();
2534 selectAllSequenceMenuItem_actionPerformed(null);
2539 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2541 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2543 // JAL-2034 - should delegate to
2544 // alignPanel to decide if overview needs
2547 alignPanel.paintAlignment(true);
2548 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2549 viewport.sendSelection();
2553 public void invertColSel_actionPerformed(ActionEvent e)
2555 viewport.invertColumnSelection();
2556 alignPanel.paintAlignment(true);
2557 viewport.sendSelection();
2567 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2569 trimAlignment(true);
2579 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2581 trimAlignment(false);
2584 void trimAlignment(boolean trimLeft)
2586 ColumnSelection colSel = viewport.getColumnSelection();
2589 if (!colSel.isEmpty())
2593 column = colSel.getMin();
2597 column = colSel.getMax();
2601 if (viewport.getSelectionGroup() != null)
2603 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2604 viewport.getHiddenRepSequences());
2608 seqs = viewport.getAlignment().getSequencesArray();
2611 TrimRegionCommand trimRegion;
2614 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2615 column, viewport.getAlignment());
2616 vpRanges.setStartRes(0);
2620 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2621 column, viewport.getAlignment());
2624 statusBar.setText(MessageManager.formatMessage(
2625 "label.removed_columns",
2626 new String[] { Integer.valueOf(trimRegion.getSize())
2629 addHistoryItem(trimRegion);
2631 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2633 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2634 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2636 viewport.getAlignment().deleteGroup(sg);
2640 viewport.firePropertyChange("alignment", null, viewport
2641 .getAlignment().getSequences());
2652 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2654 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2657 if (viewport.getSelectionGroup() != null)
2659 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2660 viewport.getHiddenRepSequences());
2661 start = viewport.getSelectionGroup().getStartRes();
2662 end = viewport.getSelectionGroup().getEndRes();
2666 seqs = viewport.getAlignment().getSequencesArray();
2669 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2670 "Remove Gapped Columns", seqs, start, end,
2671 viewport.getAlignment());
2673 addHistoryItem(removeGapCols);
2675 statusBar.setText(MessageManager.formatMessage(
2676 "label.removed_empty_columns",
2677 new Object[] { Integer.valueOf(removeGapCols.getSize())
2680 // This is to maintain viewport position on first residue
2681 // of first sequence
2682 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2683 int startRes = seq.findPosition(vpRanges.getStartRes());
2684 // ShiftList shifts;
2685 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2686 // edit.alColumnChanges=shifts.getInverse();
2687 // if (viewport.hasHiddenColumns)
2688 // viewport.getColumnSelection().compensateForEdits(shifts);
2689 vpRanges.setStartRes(seq.findIndex(startRes) - 1);
2690 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2702 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2704 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2707 if (viewport.getSelectionGroup() != null)
2709 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2710 viewport.getHiddenRepSequences());
2711 start = viewport.getSelectionGroup().getStartRes();
2712 end = viewport.getSelectionGroup().getEndRes();
2716 seqs = viewport.getAlignment().getSequencesArray();
2719 // This is to maintain viewport position on first residue
2720 // of first sequence
2721 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2722 int startRes = seq.findPosition(vpRanges.getStartRes());
2724 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2725 viewport.getAlignment()));
2727 vpRanges.setStartRes(seq.findIndex(startRes) - 1);
2729 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2741 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2743 viewport.setPadGaps(padGapsMenuitem.isSelected());
2744 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2755 public void findMenuItem_actionPerformed(ActionEvent e)
2761 * Create a new view of the current alignment.
2764 public void newView_actionPerformed(ActionEvent e)
2766 newView(null, true);
2770 * Creates and shows a new view of the current alignment.
2773 * title of newly created view; if null, one will be generated
2774 * @param copyAnnotation
2775 * if true then duplicate all annnotation, groups and settings
2776 * @return new alignment panel, already displayed.
2778 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2781 * Create a new AlignmentPanel (with its own, new Viewport)
2783 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2785 if (!copyAnnotation)
2788 * remove all groups and annotation except for the automatic stuff
2790 newap.av.getAlignment().deleteAllGroups();
2791 newap.av.getAlignment().deleteAllAnnotations(false);
2794 newap.av.setGatherViewsHere(false);
2796 if (viewport.viewName == null)
2798 viewport.viewName = MessageManager
2799 .getString("label.view_name_original");
2803 * Views share the same edits undo and redo stacks
2805 newap.av.setHistoryList(viewport.getHistoryList());
2806 newap.av.setRedoList(viewport.getRedoList());
2809 * Views share the same mappings; need to deregister any new mappings
2810 * created by copyAlignPanel, and register the new reference to the shared
2813 newap.av.replaceMappings(viewport.getAlignment());
2816 * start up cDNA consensus (if applicable) now mappings are in place
2818 if (newap.av.initComplementConsensus())
2820 newap.refresh(true); // adjust layout of annotations
2823 newap.av.viewName = getNewViewName(viewTitle);
2825 addAlignmentPanel(newap, true);
2826 newap.alignmentChanged();
2828 if (alignPanels.size() == 2)
2830 viewport.setGatherViewsHere(true);
2832 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2837 * Make a new name for the view, ensuring it is unique within the current
2838 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2839 * these now use viewId. Unique view names are still desirable for usability.)
2844 protected String getNewViewName(String viewTitle)
2846 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2847 boolean addFirstIndex = false;
2848 if (viewTitle == null || viewTitle.trim().length() == 0)
2850 viewTitle = MessageManager.getString("action.view");
2851 addFirstIndex = true;
2855 index = 1;// we count from 1 if given a specific name
2857 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2859 List<Component> comps = PaintRefresher.components.get(viewport
2860 .getSequenceSetId());
2862 List<String> existingNames = getExistingViewNames(comps);
2864 while (existingNames.contains(newViewName))
2866 newViewName = viewTitle + " " + (++index);
2872 * Returns a list of distinct view names found in the given list of
2873 * components. View names are held on the viewport of an AlignmentPanel.
2878 protected List<String> getExistingViewNames(List<Component> comps)
2880 List<String> existingNames = new ArrayList<>();
2881 for (Component comp : comps)
2883 if (comp instanceof AlignmentPanel)
2885 AlignmentPanel ap = (AlignmentPanel) comp;
2886 if (!existingNames.contains(ap.av.viewName))
2888 existingNames.add(ap.av.viewName);
2892 return existingNames;
2896 * Explode tabbed views into separate windows.
2899 public void expandViews_actionPerformed(ActionEvent e)
2901 Desktop.explodeViews(this);
2905 * Gather views in separate windows back into a tabbed presentation.
2908 public void gatherViews_actionPerformed(ActionEvent e)
2910 Desktop.instance.gatherViews(this);
2920 public void font_actionPerformed(ActionEvent e)
2922 new FontChooser(alignPanel);
2932 protected void seqLimit_actionPerformed(ActionEvent e)
2934 viewport.setShowJVSuffix(seqLimits.isSelected());
2936 alignPanel.getIdPanel().getIdCanvas()
2937 .setPreferredSize(alignPanel.calculateIdWidth());
2938 alignPanel.paintAlignment(true);
2942 public void idRightAlign_actionPerformed(ActionEvent e)
2944 viewport.setRightAlignIds(idRightAlign.isSelected());
2945 alignPanel.paintAlignment(true);
2949 public void centreColumnLabels_actionPerformed(ActionEvent e)
2951 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2952 alignPanel.paintAlignment(true);
2958 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2961 protected void followHighlight_actionPerformed()
2964 * Set the 'follow' flag on the Viewport (and scroll to position if now
2967 final boolean state = this.followHighlightMenuItem.getState();
2968 viewport.setFollowHighlight(state);
2971 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2982 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2984 viewport.setColourText(colourTextMenuItem.isSelected());
2985 alignPanel.paintAlignment(true);
2995 public void wrapMenuItem_actionPerformed(ActionEvent e)
2997 scaleAbove.setVisible(wrapMenuItem.isSelected());
2998 scaleLeft.setVisible(wrapMenuItem.isSelected());
2999 scaleRight.setVisible(wrapMenuItem.isSelected());
3000 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3001 alignPanel.updateLayout();
3005 public void showAllSeqs_actionPerformed(ActionEvent e)
3007 viewport.showAllHiddenSeqs();
3011 public void showAllColumns_actionPerformed(ActionEvent e)
3013 viewport.showAllHiddenColumns();
3015 viewport.sendSelection();
3019 public void hideSelSequences_actionPerformed(ActionEvent e)
3021 viewport.hideAllSelectedSeqs();
3022 // alignPanel.paintAlignment(true);
3026 * called by key handler and the hide all/show all menu items
3031 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3034 boolean hide = false;
3035 SequenceGroup sg = viewport.getSelectionGroup();
3036 if (!toggleSeqs && !toggleCols)
3038 // Hide everything by the current selection - this is a hack - we do the
3039 // invert and then hide
3040 // first check that there will be visible columns after the invert.
3041 if (viewport.hasSelectedColumns()
3042 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
3045 // now invert the sequence set, if required - empty selection implies
3046 // that no hiding is required.
3049 invertSequenceMenuItem_actionPerformed(null);
3050 sg = viewport.getSelectionGroup();
3054 viewport.expandColSelection(sg, true);
3055 // finally invert the column selection and get the new sequence
3057 invertColSel_actionPerformed(null);
3064 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3066 hideSelSequences_actionPerformed(null);
3069 else if (!(toggleCols && viewport.hasSelectedColumns()))
3071 showAllSeqs_actionPerformed(null);
3077 if (viewport.hasSelectedColumns())
3079 hideSelColumns_actionPerformed(null);
3082 viewport.setSelectionGroup(sg);
3087 showAllColumns_actionPerformed(null);
3096 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3097 * event.ActionEvent)
3100 public void hideAllButSelection_actionPerformed(ActionEvent e)
3102 toggleHiddenRegions(false, false);
3103 viewport.sendSelection();
3110 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3114 public void hideAllSelection_actionPerformed(ActionEvent e)
3116 SequenceGroup sg = viewport.getSelectionGroup();
3117 viewport.expandColSelection(sg, false);
3118 viewport.hideAllSelectedSeqs();
3119 viewport.hideSelectedColumns();
3120 alignPanel.paintAlignment(true);
3121 viewport.sendSelection();
3128 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3132 public void showAllhidden_actionPerformed(ActionEvent e)
3134 viewport.showAllHiddenColumns();
3135 viewport.showAllHiddenSeqs();
3136 alignPanel.paintAlignment(true);
3137 viewport.sendSelection();
3141 public void hideSelColumns_actionPerformed(ActionEvent e)
3143 viewport.hideSelectedColumns();
3144 alignPanel.paintAlignment(true);
3145 viewport.sendSelection();
3149 public void hiddenMarkers_actionPerformed(ActionEvent e)
3151 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3162 protected void scaleAbove_actionPerformed(ActionEvent e)
3164 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3165 alignPanel.paintAlignment(true);
3175 protected void scaleLeft_actionPerformed(ActionEvent e)
3177 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3178 alignPanel.paintAlignment(true);
3188 protected void scaleRight_actionPerformed(ActionEvent e)
3190 viewport.setScaleRightWrapped(scaleRight.isSelected());
3191 alignPanel.paintAlignment(true);
3201 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3203 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3204 alignPanel.paintAlignment(true);
3214 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3216 viewport.setShowText(viewTextMenuItem.isSelected());
3217 alignPanel.paintAlignment(true);
3227 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3229 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3230 alignPanel.paintAlignment(true);
3233 public FeatureSettings featureSettings;
3236 public FeatureSettingsControllerI getFeatureSettingsUI()
3238 return featureSettings;
3242 public void featureSettings_actionPerformed(ActionEvent e)
3244 if (featureSettings != null)
3246 featureSettings.close();
3247 featureSettings = null;
3249 if (!showSeqFeatures.isSelected())
3251 // make sure features are actually displayed
3252 showSeqFeatures.setSelected(true);
3253 showSeqFeatures_actionPerformed(null);
3255 featureSettings = new FeatureSettings(this);
3259 * Set or clear 'Show Sequence Features'
3265 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3267 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3268 alignPanel.paintAlignment(true);
3269 if (alignPanel.getOverviewPanel() != null)
3271 alignPanel.getOverviewPanel().updateOverviewImage();
3276 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3277 * the annotations panel as a whole.
3279 * The options to show/hide all annotations should be enabled when the panel
3280 * is shown, and disabled when the panel is hidden.
3285 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3287 final boolean setVisible = annotationPanelMenuItem.isSelected();
3288 viewport.setShowAnnotation(setVisible);
3289 this.showAllSeqAnnotations.setEnabled(setVisible);
3290 this.hideAllSeqAnnotations.setEnabled(setVisible);
3291 this.showAllAlAnnotations.setEnabled(setVisible);
3292 this.hideAllAlAnnotations.setEnabled(setVisible);
3293 alignPanel.updateLayout();
3297 public void alignmentProperties()
3299 JEditorPane editPane = new JEditorPane("text/html", "");
3300 editPane.setEditable(false);
3301 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3303 editPane.setText(MessageManager.formatMessage("label.html_content",
3304 new Object[] { contents.toString() }));
3305 JInternalFrame frame = new JInternalFrame();
3306 frame.getContentPane().add(new JScrollPane(editPane));
3308 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3309 "label.alignment_properties", new Object[] { getTitle() }),
3320 public void overviewMenuItem_actionPerformed(ActionEvent e)
3322 if (alignPanel.overviewPanel != null)
3327 JInternalFrame frame = new JInternalFrame();
3328 OverviewPanel overview = new OverviewPanel(alignPanel);
3329 frame.setContentPane(overview);
3330 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3331 "label.overview_params", new Object[] { this.getTitle() }),
3332 true, frame.getWidth(), frame.getHeight(), true, true);
3334 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3335 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3338 public void internalFrameClosed(
3339 javax.swing.event.InternalFrameEvent evt)
3341 alignPanel.setOverviewPanel(null);
3345 alignPanel.setOverviewPanel(overview);
3349 public void textColour_actionPerformed()
3351 new TextColourChooser().chooseColour(alignPanel, null);
3355 * public void covariationColour_actionPerformed() {
3357 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3361 public void annotationColour_actionPerformed()
3363 new AnnotationColourChooser(viewport, alignPanel);
3367 public void annotationColumn_actionPerformed(ActionEvent e)
3369 new AnnotationColumnChooser(viewport, alignPanel);
3373 * Action on the user checking or unchecking the option to apply the selected
3374 * colour scheme to all groups. If unchecked, groups may have their own
3375 * independent colour schemes.
3380 public void applyToAllGroups_actionPerformed(boolean selected)
3382 viewport.setColourAppliesToAllGroups(selected);
3386 * Action on user selecting a colour from the colour menu
3389 * the name (not the menu item label!) of the colour scheme
3392 public void changeColour_actionPerformed(String name)
3395 * 'User Defined' opens a panel to configure or load a
3396 * user-defined colour scheme
3398 if (ResidueColourScheme.USER_DEFINED.equals(name))
3400 new UserDefinedColours(alignPanel);
3405 * otherwise set the chosen colour scheme (or null for 'None')
3407 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3408 viewport.getAlignment(), viewport.getHiddenRepSequences());
3413 * Actions on setting or changing the alignment colour scheme
3418 public void changeColour(ColourSchemeI cs)
3420 // TODO: pull up to controller method
3421 ColourMenuHelper.setColourSelected(colourMenu, cs);
3423 viewport.setGlobalColourScheme(cs);
3425 alignPanel.paintAlignment(true);
3429 * Show the PID threshold slider panel
3432 protected void modifyPID_actionPerformed()
3434 SliderPanel.setPIDSliderSource(alignPanel,
3435 viewport.getResidueShading(), alignPanel.getViewName());
3436 SliderPanel.showPIDSlider();
3440 * Show the Conservation slider panel
3443 protected void modifyConservation_actionPerformed()
3445 SliderPanel.setConservationSlider(alignPanel,
3446 viewport.getResidueShading(), alignPanel.getViewName());
3447 SliderPanel.showConservationSlider();
3451 * Action on selecting or deselecting (Colour) By Conservation
3454 public void conservationMenuItem_actionPerformed(boolean selected)
3456 modifyConservation.setEnabled(selected);
3457 viewport.setConservationSelected(selected);
3458 viewport.getResidueShading().setConservationApplied(selected);
3460 changeColour(viewport.getGlobalColourScheme());
3463 modifyConservation_actionPerformed();
3467 SliderPanel.hideConservationSlider();
3472 * Action on selecting or deselecting (Colour) Above PID Threshold
3475 public void abovePIDThreshold_actionPerformed(boolean selected)
3477 modifyPID.setEnabled(selected);
3478 viewport.setAbovePIDThreshold(selected);
3481 viewport.getResidueShading().setThreshold(0,
3482 viewport.isIgnoreGapsConsensus());
3485 changeColour(viewport.getGlobalColourScheme());
3488 modifyPID_actionPerformed();
3492 SliderPanel.hidePIDSlider();
3503 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3505 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3506 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3507 .getAlignment().getSequenceAt(0));
3508 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3509 viewport.getAlignment()));
3510 alignPanel.paintAlignment(true);
3520 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3522 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3523 AlignmentSorter.sortByID(viewport.getAlignment());
3524 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3525 viewport.getAlignment()));
3526 alignPanel.paintAlignment(true);
3536 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3538 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3539 AlignmentSorter.sortByLength(viewport.getAlignment());
3540 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3541 viewport.getAlignment()));
3542 alignPanel.paintAlignment(true);
3552 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3554 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3555 AlignmentSorter.sortByGroup(viewport.getAlignment());
3556 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3557 viewport.getAlignment()));
3559 alignPanel.paintAlignment(true);
3569 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3571 new RedundancyPanel(alignPanel, this);
3581 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3583 if ((viewport.getSelectionGroup() == null)
3584 || (viewport.getSelectionGroup().getSize() < 2))
3586 JvOptionPane.showInternalMessageDialog(this, MessageManager
3587 .getString("label.you_must_select_least_two_sequences"),
3588 MessageManager.getString("label.invalid_selection"),
3589 JvOptionPane.WARNING_MESSAGE);
3593 JInternalFrame frame = new JInternalFrame();
3594 frame.setContentPane(new PairwiseAlignPanel(viewport));
3595 Desktop.addInternalFrame(frame,
3596 MessageManager.getString("action.pairwise_alignment"), 600,
3602 public void autoCalculate_actionPerformed(ActionEvent e)
3604 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3605 if (viewport.autoCalculateConsensus)
3607 viewport.firePropertyChange("alignment", null, viewport
3608 .getAlignment().getSequences());
3613 public void sortByTreeOption_actionPerformed(ActionEvent e)
3615 viewport.sortByTree = sortByTree.isSelected();
3619 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3621 viewport.followSelection = listenToViewSelections.isSelected();
3625 * Constructs a tree panel and adds it to the desktop
3628 * tree type (NJ or AV)
3630 * name of score model used to compute the tree
3632 * parameters for the distance or similarity calculation
3634 void newTreePanel(String type, String modelName, SimilarityParamsI options)
3636 String frameTitle = "";
3639 boolean onSelection = false;
3640 if (viewport.getSelectionGroup() != null
3641 && viewport.getSelectionGroup().getSize() > 0)
3643 SequenceGroup sg = viewport.getSelectionGroup();
3645 /* Decide if the selection is a column region */
3646 for (SequenceI _s : sg.getSequences())
3648 if (_s.getLength() < sg.getEndRes())
3654 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3656 .getString("label.sequences_selection_not_aligned"),
3657 JvOptionPane.WARNING_MESSAGE);
3666 if (viewport.getAlignment().getHeight() < 2)
3672 tp = new TreePanel(alignPanel, type, modelName, options);
3673 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3675 frameTitle += " from ";
3677 if (viewport.viewName != null)
3679 frameTitle += viewport.viewName + " of ";
3682 frameTitle += this.title;
3684 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3695 public void addSortByOrderMenuItem(String title,
3696 final AlignmentOrder order)
3698 final JMenuItem item = new JMenuItem(MessageManager.formatMessage(
3699 "action.by_title_param", new Object[] { title }));
3701 item.addActionListener(new java.awt.event.ActionListener()
3704 public void actionPerformed(ActionEvent e)
3706 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3708 // TODO: JBPNote - have to map order entries to curent SequenceI
3710 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3712 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
3715 alignPanel.paintAlignment(true);
3721 * Add a new sort by annotation score menu item
3724 * the menu to add the option to
3726 * the label used to retrieve scores for each sequence on the
3729 public void addSortByAnnotScoreMenuItem(JMenu sort,
3730 final String scoreLabel)
3732 final JMenuItem item = new JMenuItem(scoreLabel);
3734 item.addActionListener(new java.awt.event.ActionListener()
3737 public void actionPerformed(ActionEvent e)
3739 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3740 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3741 viewport.getAlignment());// ,viewport.getSelectionGroup());
3742 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3743 viewport.getAlignment()));
3744 alignPanel.paintAlignment(true);
3750 * last hash for alignment's annotation array - used to minimise cost of
3753 protected int _annotationScoreVectorHash;
3756 * search the alignment and rebuild the sort by annotation score submenu the
3757 * last alignment annotation vector hash is stored to minimize cost of
3758 * rebuilding in subsequence calls.
3762 public void buildSortByAnnotationScoresMenu()
3764 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3769 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
3771 sortByAnnotScore.removeAll();
3772 // almost certainly a quicker way to do this - but we keep it simple
3773 Hashtable scoreSorts = new Hashtable();
3774 AlignmentAnnotation aann[];
3775 for (SequenceI sqa : viewport.getAlignment().getSequences())
3777 aann = sqa.getAnnotation();
3778 for (int i = 0; aann != null && i < aann.length; i++)
3780 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3782 scoreSorts.put(aann[i].label, aann[i].label);
3786 Enumeration labels = scoreSorts.keys();
3787 while (labels.hasMoreElements())
3789 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3790 (String) labels.nextElement());
3792 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3795 _annotationScoreVectorHash = viewport.getAlignment()
3796 .getAlignmentAnnotation().hashCode();
3801 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3802 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3803 * call. Listeners are added to remove the menu item when the treePanel is
3804 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3808 public void buildTreeSortMenu()
3810 sortByTreeMenu.removeAll();
3812 List<Component> comps = PaintRefresher.components.get(viewport
3813 .getSequenceSetId());
3814 List<TreePanel> treePanels = new ArrayList<>();
3815 for (Component comp : comps)
3817 if (comp instanceof TreePanel)
3819 treePanels.add((TreePanel) comp);
3823 if (treePanels.size() < 1)
3825 sortByTreeMenu.setVisible(false);
3829 sortByTreeMenu.setVisible(true);
3831 for (final TreePanel tp : treePanels)
3833 final JMenuItem item = new JMenuItem(tp.getTitle());
3834 item.addActionListener(new java.awt.event.ActionListener()
3837 public void actionPerformed(ActionEvent e)
3839 tp.sortByTree_actionPerformed();
3840 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3845 sortByTreeMenu.add(item);
3849 public boolean sortBy(AlignmentOrder alorder, String undoname)
3851 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3852 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3853 if (undoname != null)
3855 addHistoryItem(new OrderCommand(undoname, oldOrder,
3856 viewport.getAlignment()));
3858 alignPanel.paintAlignment(true);
3863 * Work out whether the whole set of sequences or just the selected set will
3864 * be submitted for multiple alignment.
3867 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3869 // Now, check we have enough sequences
3870 AlignmentView msa = null;
3872 if ((viewport.getSelectionGroup() != null)
3873 && (viewport.getSelectionGroup().getSize() > 1))
3875 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3876 // some common interface!
3878 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3879 * SequenceI[sz = seqs.getSize(false)];
3881 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3882 * seqs.getSequenceAt(i); }
3884 msa = viewport.getAlignmentView(true);
3886 else if (viewport.getSelectionGroup() != null
3887 && viewport.getSelectionGroup().getSize() == 1)
3889 int option = JvOptionPane.showConfirmDialog(this,
3890 MessageManager.getString("warn.oneseq_msainput_selection"),
3891 MessageManager.getString("label.invalid_selection"),
3892 JvOptionPane.OK_CANCEL_OPTION);
3893 if (option == JvOptionPane.OK_OPTION)
3895 msa = viewport.getAlignmentView(false);
3900 msa = viewport.getAlignmentView(false);
3906 * Decides what is submitted to a secondary structure prediction service: the
3907 * first sequence in the alignment, or in the current selection, or, if the
3908 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3909 * region or the whole alignment. (where the first sequence in the set is the
3910 * one that the prediction will be for).
3912 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3914 AlignmentView seqs = null;
3916 if ((viewport.getSelectionGroup() != null)
3917 && (viewport.getSelectionGroup().getSize() > 0))
3919 seqs = viewport.getAlignmentView(true);
3923 seqs = viewport.getAlignmentView(false);
3925 // limit sequences - JBPNote in future - could spawn multiple prediction
3927 // TODO: viewport.getAlignment().isAligned is a global state - the local
3928 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3929 if (!viewport.getAlignment().isAligned(false))
3931 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3932 // TODO: if seqs.getSequences().length>1 then should really have warned
3946 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3948 // Pick the tree file
3949 JalviewFileChooser chooser = new JalviewFileChooser(
3950 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3951 chooser.setFileView(new JalviewFileView());
3952 chooser.setDialogTitle(MessageManager
3953 .getString("label.select_newick_like_tree_file"));
3954 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
3956 int value = chooser.showOpenDialog(null);
3958 if (value == JalviewFileChooser.APPROVE_OPTION)
3960 String filePath = chooser.getSelectedFile().getPath();
3961 Cache.setProperty("LAST_DIRECTORY", filePath);
3962 NewickFile fin = null;
3965 fin = new NewickFile(filePath, DataSourceType.FILE);
3966 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
3967 } catch (Exception ex)
3974 .getString("label.problem_reading_tree_file"),
3975 JvOptionPane.WARNING_MESSAGE);
3976 ex.printStackTrace();
3978 if (fin != null && fin.hasWarningMessage())
3980 JvOptionPane.showMessageDialog(Desktop.desktop, fin
3981 .getWarningMessage(), MessageManager
3982 .getString("label.possible_problem_with_tree_file"),
3983 JvOptionPane.WARNING_MESSAGE);
3988 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
3990 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
3993 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
3994 int h, int x, int y)
3996 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4000 * Add a treeviewer for the tree extracted from a Newick file object to the
4001 * current alignment view
4008 * Associated alignment input data (or null)
4017 * @return TreePanel handle
4019 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4020 AlignmentView input, int w, int h, int x, int y)
4022 TreePanel tp = null;
4028 if (nf.getTree() != null)
4030 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4036 tp.setLocation(x, y);
4039 Desktop.addInternalFrame(tp, treeTitle, w, h);
4041 } catch (Exception ex)
4043 ex.printStackTrace();
4049 private boolean buildingMenu = false;
4052 * Generates menu items and listener event actions for web service clients
4055 public void BuildWebServiceMenu()
4057 while (buildingMenu)
4061 System.err.println("Waiting for building menu to finish.");
4063 } catch (Exception e)
4067 final AlignFrame me = this;
4068 buildingMenu = true;
4069 new Thread(new Runnable()
4074 final List<JMenuItem> legacyItems = new ArrayList<>();
4077 // System.err.println("Building ws menu again "
4078 // + Thread.currentThread());
4079 // TODO: add support for context dependent disabling of services based
4081 // alignment and current selection
4082 // TODO: add additional serviceHandle parameter to specify abstract
4084 // class independently of AbstractName
4085 // TODO: add in rediscovery GUI function to restart discoverer
4086 // TODO: group services by location as well as function and/or
4088 // object broker mechanism.
4089 final Vector<JMenu> wsmenu = new Vector<>();
4090 final IProgressIndicator af = me;
4093 * do not i18n these strings - they are hard-coded in class
4094 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4095 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4097 final JMenu msawsmenu = new JMenu("Alignment");
4098 final JMenu secstrmenu = new JMenu(
4099 "Secondary Structure Prediction");
4100 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4101 final JMenu analymenu = new JMenu("Analysis");
4102 final JMenu dismenu = new JMenu("Protein Disorder");
4103 // JAL-940 - only show secondary structure prediction services from
4104 // the legacy server
4105 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4107 Discoverer.services != null && (Discoverer.services.size() > 0))
4109 // TODO: refactor to allow list of AbstractName/Handler bindings to
4111 // stored or retrieved from elsewhere
4112 // No MSAWS used any more:
4113 // Vector msaws = null; // (Vector)
4114 // Discoverer.services.get("MsaWS");
4115 Vector secstrpr = (Vector) Discoverer.services
4117 if (secstrpr != null)
4119 // Add any secondary structure prediction services
4120 for (int i = 0, j = secstrpr.size(); i < j; i++)
4122 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4124 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4125 .getServiceClient(sh);
4126 int p = secstrmenu.getItemCount();
4127 impl.attachWSMenuEntry(secstrmenu, me);
4128 int q = secstrmenu.getItemCount();
4129 for (int litm = p; litm < q; litm++)
4131 legacyItems.add(secstrmenu.getItem(litm));
4137 // Add all submenus in the order they should appear on the web
4139 wsmenu.add(msawsmenu);
4140 wsmenu.add(secstrmenu);
4141 wsmenu.add(dismenu);
4142 wsmenu.add(analymenu);
4143 // No search services yet
4144 // wsmenu.add(seqsrchmenu);
4146 javax.swing.SwingUtilities.invokeLater(new Runnable()
4153 webService.removeAll();
4154 // first, add discovered services onto the webservices menu
4155 if (wsmenu.size() > 0)
4157 for (int i = 0, j = wsmenu.size(); i < j; i++)
4159 webService.add(wsmenu.get(i));
4164 webService.add(me.webServiceNoServices);
4166 // TODO: move into separate menu builder class.
4167 boolean new_sspred = false;
4168 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4170 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4171 if (jws2servs != null)
4173 if (jws2servs.hasServices())
4175 jws2servs.attachWSMenuEntry(webService, me);
4176 for (Jws2Instance sv : jws2servs.getServices())
4178 if (sv.description.toLowerCase().contains("jpred"))
4180 for (JMenuItem jmi : legacyItems)
4182 jmi.setVisible(false);
4188 if (jws2servs.isRunning())
4190 JMenuItem tm = new JMenuItem(
4191 "Still discovering JABA Services");
4192 tm.setEnabled(false);
4197 build_urlServiceMenu(me.webService);
4198 build_fetchdbmenu(webService);
4199 for (JMenu item : wsmenu)
4201 if (item.getItemCount() == 0)
4203 item.setEnabled(false);
4207 item.setEnabled(true);
4210 } catch (Exception e)
4213 .debug("Exception during web service menu building process.",
4218 } catch (Exception e)
4221 buildingMenu = false;
4228 * construct any groupURL type service menu entries.
4232 private void build_urlServiceMenu(JMenu webService)
4234 // TODO: remove this code when 2.7 is released
4235 // DEBUG - alignmentView
4237 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4238 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4240 * @Override public void actionPerformed(ActionEvent e) {
4241 * jalview.datamodel.AlignmentView
4242 * .testSelectionViews(af.viewport.getAlignment(),
4243 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4245 * }); webService.add(testAlView);
4247 // TODO: refactor to RestClient discoverer and merge menu entries for
4248 // rest-style services with other types of analysis/calculation service
4249 // SHmmr test client - still being implemented.
4250 // DEBUG - alignmentView
4252 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4255 client.attachWSMenuEntry(
4256 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4262 * Searches the alignment sequences for xRefs and builds the Show
4263 * Cross-References menu (formerly called Show Products), with database
4264 * sources for which cross-references are found (protein sources for a
4265 * nucleotide alignment and vice versa)
4267 * @return true if Show Cross-references menu should be enabled
4269 public boolean canShowProducts()
4271 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4272 AlignmentI dataset = viewport.getAlignment().getDataset();
4274 showProducts.removeAll();
4275 final boolean dna = viewport.getAlignment().isNucleotide();
4277 if (seqs == null || seqs.length == 0)
4279 // nothing to see here.
4283 boolean showp = false;
4286 List<String> ptypes = new CrossRef(seqs, dataset)
4287 .findXrefSourcesForSequences(dna);
4289 for (final String source : ptypes)
4292 final AlignFrame af = this;
4293 JMenuItem xtype = new JMenuItem(source);
4294 xtype.addActionListener(new ActionListener()
4297 public void actionPerformed(ActionEvent e)
4299 showProductsFor(af.viewport.getSequenceSelection(), dna, source);
4302 showProducts.add(xtype);
4304 showProducts.setVisible(showp);
4305 showProducts.setEnabled(showp);
4306 } catch (Exception e)
4309 .warn("canShowProducts threw an exception - please report to help@jalview.org",
4317 * Finds and displays cross-references for the selected sequences (protein
4318 * products for nucleotide sequences, dna coding sequences for peptides).
4321 * the sequences to show cross-references for
4323 * true if from a nucleotide alignment (so showing proteins)
4325 * the database to show cross-references for
4327 protected void showProductsFor(final SequenceI[] sel,
4328 final boolean _odna, final String source)
4330 new Thread(CrossRefAction.showProductsFor(sel, _odna, source, this))
4335 * Construct and display a new frame containing the translation of this
4336 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4339 public void showTranslation_actionPerformed(ActionEvent e)
4341 AlignmentI al = null;
4344 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4346 al = dna.translateCdna();
4347 } catch (Exception ex)
4349 jalview.bin.Cache.log.error(
4350 "Exception during translation. Please report this !", ex);
4351 final String msg = MessageManager
4352 .getString("label.error_when_translating_sequences_submit_bug_report");
4353 final String errorTitle = MessageManager
4354 .getString("label.implementation_error")
4355 + MessageManager.getString("label.translation_failed");
4356 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4357 JvOptionPane.ERROR_MESSAGE);
4360 if (al == null || al.getHeight() == 0)
4362 final String msg = MessageManager
4363 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4364 final String errorTitle = MessageManager
4365 .getString("label.translation_failed");
4366 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4367 JvOptionPane.WARNING_MESSAGE);
4371 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4372 af.setFileFormat(this.currentFileFormat);
4373 final String newTitle = MessageManager.formatMessage(
4374 "label.translation_of_params",
4375 new Object[] { this.getTitle() });
4376 af.setTitle(newTitle);
4377 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4379 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4380 viewport.openSplitFrame(af, new Alignment(seqs));
4384 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4391 * Set the file format
4395 public void setFileFormat(FileFormatI format)
4397 this.currentFileFormat = format;
4401 * Try to load a features file onto the alignment.
4404 * contents or path to retrieve file
4406 * access mode of file (see jalview.io.AlignFile)
4407 * @return true if features file was parsed correctly.
4409 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4411 return avc.parseFeaturesFile(file, sourceType,
4412 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4417 public void refreshFeatureUI(boolean enableIfNecessary)
4419 // note - currently this is only still here rather than in the controller
4420 // because of the featureSettings hard reference that is yet to be
4422 if (enableIfNecessary)
4424 viewport.setShowSequenceFeatures(true);
4425 showSeqFeatures.setSelected(true);
4431 public void dragEnter(DropTargetDragEvent evt)
4436 public void dragExit(DropTargetEvent evt)
4441 public void dragOver(DropTargetDragEvent evt)
4446 public void dropActionChanged(DropTargetDragEvent evt)
4451 public void drop(DropTargetDropEvent evt)
4453 // JAL-1552 - acceptDrop required before getTransferable call for
4454 // Java's Transferable for native dnd
4455 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4456 Transferable t = evt.getTransferable();
4457 List<String> files = new ArrayList<>();
4458 List<DataSourceType> protocols = new ArrayList<>();
4462 Desktop.transferFromDropTarget(files, protocols, evt, t);
4463 } catch (Exception e)
4465 e.printStackTrace();
4471 // check to see if any of these files have names matching sequences in
4473 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4474 .getAlignment().getSequencesArray());
4476 * Object[] { String,SequenceI}
4478 ArrayList<Object[]> filesmatched = new ArrayList<>();
4479 ArrayList<String> filesnotmatched = new ArrayList<>();
4480 for (int i = 0; i < files.size(); i++)
4482 String file = files.get(i).toString();
4484 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4485 if (protocol == DataSourceType.FILE)
4487 File fl = new File(file);
4488 pdbfn = fl.getName();
4490 else if (protocol == DataSourceType.URL)
4492 URL url = new URL(file);
4493 pdbfn = url.getFile();
4495 if (pdbfn.length() > 0)
4497 // attempt to find a match in the alignment
4498 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4499 int l = 0, c = pdbfn.indexOf(".");
4500 while (mtch == null && c != -1)
4505 } while ((c = pdbfn.indexOf(".", l)) > l);
4508 pdbfn = pdbfn.substring(0, l);
4510 mtch = idm.findAllIdMatches(pdbfn);
4514 FileFormatI type = null;
4517 type = new IdentifyFile().identify(file, protocol);
4518 } catch (Exception ex)
4522 if (type != null && type.isStructureFile())
4524 filesmatched.add(new Object[] { file, protocol, mtch });
4528 // File wasn't named like one of the sequences or wasn't a PDB file.
4529 filesnotmatched.add(file);
4533 if (filesmatched.size() > 0)
4535 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4541 "label.automatically_associate_structure_files_with_sequences_same_name",
4542 new Object[] { Integer
4548 .getString("label.automatically_associate_structure_files_by_name"),
4549 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION)
4552 for (Object[] fm : filesmatched)
4554 // try and associate
4555 // TODO: may want to set a standard ID naming formalism for
4556 // associating PDB files which have no IDs.
4557 for (SequenceI toassoc : (SequenceI[]) fm[2])
4559 PDBEntry pe = new AssociatePdbFileWithSeq()
4560 .associatePdbWithSeq((String) fm[0],
4561 (DataSourceType) fm[1], toassoc, false,
4565 System.err.println("Associated file : "
4566 + ((String) fm[0]) + " with "
4567 + toassoc.getDisplayId(true));
4571 alignPanel.paintAlignment(true);
4575 if (filesnotmatched.size() > 0)
4578 && (Cache.getDefault(
4579 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JvOptionPane
4585 "label.ignore_unmatched_dropped_files_info",
4586 new Object[] { Integer
4593 .getString("label.ignore_unmatched_dropped_files"),
4594 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4598 for (String fn : filesnotmatched)
4600 loadJalviewDataFile(fn, null, null, null);
4604 } catch (Exception ex)
4606 ex.printStackTrace();
4612 * Attempt to load a "dropped" file or URL string, by testing in turn for
4614 * <li>an Annotation file</li>
4615 * <li>a JNet file</li>
4616 * <li>a features file</li>
4617 * <li>else try to interpret as an alignment file</li>
4621 * either a filename or a URL string.
4623 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4624 FileFormatI format, SequenceI assocSeq)
4628 if (sourceType == null)
4630 sourceType = FormatAdapter.checkProtocol(file);
4632 // if the file isn't identified, or not positively identified as some
4633 // other filetype (PFAM is default unidentified alignment file type) then
4634 // try to parse as annotation.
4635 boolean isAnnotation = (format == null || FileFormat.Pfam
4636 .equals(format)) ? new AnnotationFile()
4637 .annotateAlignmentView(viewport, file, sourceType) : false;
4641 // first see if its a T-COFFEE score file
4642 TCoffeeScoreFile tcf = null;
4645 tcf = new TCoffeeScoreFile(file, sourceType);
4648 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4651 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
4652 isAnnotation = true;
4654 .setText(MessageManager
4655 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
4659 // some problem - if no warning its probable that the ID matching
4660 // process didn't work
4664 tcf.getWarningMessage() == null ? MessageManager
4665 .getString("label.check_file_matches_sequence_ids_alignment")
4666 : tcf.getWarningMessage(),
4668 .getString("label.problem_reading_tcoffee_score_file"),
4669 JvOptionPane.WARNING_MESSAGE);
4676 } catch (Exception x)
4679 .debug("Exception when processing data source as T-COFFEE score file",
4685 // try to see if its a JNet 'concise' style annotation file *before*
4687 // try to parse it as a features file
4690 format = new IdentifyFile().identify(file, sourceType);
4692 if (FileFormat.ScoreMatrix == format)
4694 ScoreMatrixFile sm = new ScoreMatrixFile(new FileParse(file,
4697 // todo: i18n this message
4699 .setText(MessageManager.formatMessage(
4700 "label.successfully_loaded_matrix",
4701 sm.getMatrixName()));
4703 else if (FileFormat.HMMER3.equals(format))
4705 HMMFile hmmFile = new HMMFile(new FileParse(file, sourceType)); // TODO
4712 HiddenMarkovModel hmm = hmmFile.getHMM();
4714 hmm.mapToReferenceAnnotation(this);
4717 AlignmentAnnotation annotation = hmm.createAnnotation(
4718 getViewport().getAlignment().getWidth());
4719 getViewport().getAlignment().addAnnotation(annotation);
4720 hmm.initPlaceholder(this);
4721 isAnnotation = true;
4722 alignPanel.repaint();
4725 else if (FileFormat.Jnet.equals(format))
4727 JPredFile predictions = new JPredFile(file, sourceType);
4728 new JnetAnnotationMaker();
4729 JnetAnnotationMaker.add_annotation(predictions,
4730 viewport.getAlignment(), 0, false);
4731 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
4732 viewport.getAlignment().setSeqrep(repseq);
4733 HiddenColumns cs = new HiddenColumns();
4734 cs.hideInsertionsFor(repseq);
4735 viewport.getAlignment().setHiddenColumns(cs);
4736 isAnnotation = true;
4738 // else if (IdentifyFile.FeaturesFile.equals(format))
4739 else if (FileFormat.Features.equals(format))
4741 if (parseFeaturesFile(file, sourceType))
4743 alignPanel.paintAlignment(true);
4748 new FileLoader().LoadFile(viewport, file, sourceType, format);
4754 alignPanel.adjustAnnotationHeight();
4755 viewport.updateSequenceIdColours();
4756 buildSortByAnnotationScoresMenu();
4757 alignPanel.paintAlignment(true);
4759 } catch (Exception ex)
4761 ex.printStackTrace();
4762 } catch (OutOfMemoryError oom)
4767 } catch (Exception x)
4772 + (sourceType != null ? (sourceType == DataSourceType.PASTE ? "from clipboard."
4773 : "using " + sourceType + " from " + file)
4775 + (format != null ? "(parsing as '" + format
4776 + "' file)" : ""), oom, Desktop.desktop);
4781 * Method invoked by the ChangeListener on the tabbed pane, in other words
4782 * when a different tabbed pane is selected by the user or programmatically.
4785 public void tabSelectionChanged(int index)
4789 alignPanel = alignPanels.get(index);
4790 viewport = alignPanel.av;
4791 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4792 setMenusFromViewport(viewport);
4796 * 'focus' any colour slider that is open to the selected viewport
4798 if (viewport.getConservationSelected())
4800 SliderPanel.setConservationSlider(alignPanel,
4801 viewport.getResidueShading(), alignPanel.getViewName());
4805 SliderPanel.hideConservationSlider();
4807 if (viewport.getAbovePIDThreshold())
4809 SliderPanel.setPIDSliderSource(alignPanel,
4810 viewport.getResidueShading(), alignPanel.getViewName());
4814 SliderPanel.hidePIDSlider();
4818 * If there is a frame linked to this one in a SplitPane, switch it to the
4819 * same view tab index. No infinite recursion of calls should happen, since
4820 * tabSelectionChanged() should not get invoked on setting the selected
4821 * index to an unchanged value. Guard against setting an invalid index
4822 * before the new view peer tab has been created.
4824 final AlignViewportI peer = viewport.getCodingComplement();
4827 AlignFrame linkedAlignFrame = ((AlignViewport) peer).getAlignPanel().alignFrame;
4828 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4830 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4836 * On right mouse click on view tab, prompt for and set new view name.
4839 public void tabbedPane_mousePressed(MouseEvent e)
4841 if (e.isPopupTrigger())
4843 String msg = MessageManager.getString("label.enter_view_name");
4844 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4845 JvOptionPane.QUESTION_MESSAGE);
4849 viewport.viewName = reply;
4850 // TODO warn if reply is in getExistingViewNames()?
4851 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4856 public AlignViewport getCurrentView()
4862 * Open the dialog for regex description parsing.
4865 protected void extractScores_actionPerformed(ActionEvent e)
4867 ParseProperties pp = new jalview.analysis.ParseProperties(
4868 viewport.getAlignment());
4869 // TODO: verify regex and introduce GUI dialog for version 2.5
4870 // if (pp.getScoresFromDescription("col", "score column ",
4871 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4873 if (pp.getScoresFromDescription("description column",
4874 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4876 buildSortByAnnotationScoresMenu();
4884 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4888 protected void showDbRefs_actionPerformed(ActionEvent e)
4890 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4896 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4900 protected void showNpFeats_actionPerformed(ActionEvent e)
4902 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4906 * find the viewport amongst the tabs in this alignment frame and close that
4911 public boolean closeView(AlignViewportI av)
4915 this.closeMenuItem_actionPerformed(false);
4918 Component[] comp = tabbedPane.getComponents();
4919 for (int i = 0; comp != null && i < comp.length; i++)
4921 if (comp[i] instanceof AlignmentPanel)
4923 if (((AlignmentPanel) comp[i]).av == av)
4926 closeView((AlignmentPanel) comp[i]);
4934 protected void build_fetchdbmenu(JMenu webService)
4936 // Temporary hack - DBRef Fetcher always top level ws entry.
4937 // TODO We probably want to store a sequence database checklist in
4938 // preferences and have checkboxes.. rather than individual sources selected
4940 final JMenu rfetch = new JMenu(
4941 MessageManager.getString("action.fetch_db_references"));
4942 rfetch.setToolTipText(MessageManager
4943 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4944 webService.add(rfetch);
4946 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4947 MessageManager.getString("option.trim_retrieved_seqs"));
4948 trimrs.setToolTipText(MessageManager
4949 .getString("label.trim_retrieved_sequences"));
4950 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
4951 trimrs.addActionListener(new ActionListener()
4954 public void actionPerformed(ActionEvent e)
4956 trimrs.setSelected(trimrs.isSelected());
4957 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
4958 Boolean.valueOf(trimrs.isSelected()).toString());
4962 JMenuItem fetchr = new JMenuItem(
4963 MessageManager.getString("label.standard_databases"));
4964 fetchr.setToolTipText(MessageManager
4965 .getString("label.fetch_embl_uniprot"));
4966 fetchr.addActionListener(new ActionListener()
4970 public void actionPerformed(ActionEvent e)
4972 new Thread(new Runnable()
4977 boolean isNucleotide = alignPanel.alignFrame.getViewport()
4978 .getAlignment().isNucleotide();
4979 DBRefFetcher dbRefFetcher = new DBRefFetcher(alignPanel.av
4980 .getSequenceSelection(), alignPanel.alignFrame, null,
4981 alignPanel.alignFrame.featureSettings, isNucleotide);
4982 dbRefFetcher.addListener(new FetchFinishedListenerI()
4985 public void finished()
4987 AlignFrame.this.setMenusForViewport();
4990 dbRefFetcher.fetchDBRefs(false);
4998 final AlignFrame me = this;
4999 new Thread(new Runnable()
5004 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5005 .getSequenceFetcherSingleton(me);
5006 javax.swing.SwingUtilities.invokeLater(new Runnable()
5011 String[] dbclasses = sf.getOrderedSupportedSources();
5012 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5013 // jalview.util.QuickSort.sort(otherdb, otherdb);
5014 List<DbSourceProxy> otherdb;
5015 JMenu dfetch = new JMenu();
5016 JMenu ifetch = new JMenu();
5017 JMenuItem fetchr = null;
5018 int comp = 0, icomp = 0, mcomp = 15;
5019 String mname = null;
5021 for (String dbclass : dbclasses)
5023 otherdb = sf.getSourceProxy(dbclass);
5024 // add a single entry for this class, or submenu allowing 'fetch
5026 if (otherdb == null || otherdb.size() < 1)
5030 // List<DbSourceProxy> dbs=otherdb;
5031 // otherdb=new ArrayList<DbSourceProxy>();
5032 // for (DbSourceProxy db:dbs)
5034 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5038 mname = "From " + dbclass;
5040 if (otherdb.size() == 1)
5042 final DbSourceProxy[] dassource = otherdb
5043 .toArray(new DbSourceProxy[0]);
5044 DbSourceProxy src = otherdb.get(0);
5045 fetchr = new JMenuItem(src.getDbSource());
5046 fetchr.addActionListener(new ActionListener()
5050 public void actionPerformed(ActionEvent e)
5052 new Thread(new Runnable()
5058 boolean isNucleotide = alignPanel.alignFrame
5059 .getViewport().getAlignment()
5061 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5062 alignPanel.av.getSequenceSelection(),
5063 alignPanel.alignFrame, dassource,
5064 alignPanel.alignFrame.featureSettings,
5067 .addListener(new FetchFinishedListenerI()
5070 public void finished()
5072 AlignFrame.this.setMenusForViewport();
5075 dbRefFetcher.fetchDBRefs(false);
5081 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5082 MessageManager.formatMessage(
5083 "label.fetch_retrieve_from",
5084 new Object[] { src.getDbName() })));
5090 final DbSourceProxy[] dassource = otherdb
5091 .toArray(new DbSourceProxy[0]);
5093 DbSourceProxy src = otherdb.get(0);
5094 fetchr = new JMenuItem(MessageManager.formatMessage(
5095 "label.fetch_all_param",
5096 new Object[] { src.getDbSource() }));
5097 fetchr.addActionListener(new ActionListener()
5100 public void actionPerformed(ActionEvent e)
5102 new Thread(new Runnable()
5108 boolean isNucleotide = alignPanel.alignFrame
5109 .getViewport().getAlignment()
5111 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5112 alignPanel.av.getSequenceSelection(),
5113 alignPanel.alignFrame, dassource,
5114 alignPanel.alignFrame.featureSettings,
5117 .addListener(new FetchFinishedListenerI()
5120 public void finished()
5122 AlignFrame.this.setMenusForViewport();
5125 dbRefFetcher.fetchDBRefs(false);
5131 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5132 MessageManager.formatMessage(
5133 "label.fetch_retrieve_from_all_sources",
5135 Integer.valueOf(otherdb.size())
5136 .toString(), src.getDbSource(),
5137 src.getDbName() })));
5140 // and then build the rest of the individual menus
5141 ifetch = new JMenu(MessageManager.formatMessage(
5142 "label.source_from_db_source",
5143 new Object[] { src.getDbSource() }));
5145 String imname = null;
5147 for (DbSourceProxy sproxy : otherdb)
5149 String dbname = sproxy.getDbName();
5150 String sname = dbname.length() > 5 ? dbname.substring(0,
5151 5) + "..." : dbname;
5152 String msname = dbname.length() > 10 ? dbname.substring(
5153 0, 10) + "..." : dbname;
5156 imname = MessageManager.formatMessage(
5157 "label.from_msname", new Object[] { sname });
5159 fetchr = new JMenuItem(msname);
5160 final DbSourceProxy[] dassrc = { sproxy };
5161 fetchr.addActionListener(new ActionListener()
5165 public void actionPerformed(ActionEvent e)
5167 new Thread(new Runnable()
5173 boolean isNucleotide = alignPanel.alignFrame
5174 .getViewport().getAlignment()
5176 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5177 alignPanel.av.getSequenceSelection(),
5178 alignPanel.alignFrame, dassrc,
5179 alignPanel.alignFrame.featureSettings,
5182 .addListener(new FetchFinishedListenerI()
5185 public void finished()
5187 AlignFrame.this.setMenusForViewport();
5190 dbRefFetcher.fetchDBRefs(false);
5196 fetchr.setToolTipText("<html>"
5197 + MessageManager.formatMessage(
5198 "label.fetch_retrieve_from", new Object[]
5202 if (++icomp >= mcomp || i == (otherdb.size()))
5204 ifetch.setText(MessageManager.formatMessage(
5205 "label.source_to_target", imname, sname));
5207 ifetch = new JMenu();
5215 if (comp >= mcomp || dbi >= (dbclasses.length))
5217 dfetch.setText(MessageManager.formatMessage(
5218 "label.source_to_target", mname, dbclass));
5220 dfetch = new JMenu();
5233 * Left justify the whole alignment.
5236 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5238 AlignmentI al = viewport.getAlignment();
5240 viewport.firePropertyChange("alignment", null, al);
5244 * Right justify the whole alignment.
5247 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5249 AlignmentI al = viewport.getAlignment();
5251 viewport.firePropertyChange("alignment", null, al);
5255 public void setShowSeqFeatures(boolean b)
5257 showSeqFeatures.setSelected(b);
5258 viewport.setShowSequenceFeatures(b);
5265 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5266 * awt.event.ActionEvent)
5269 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5271 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5272 alignPanel.paintAlignment(true);
5279 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5283 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5285 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5286 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5294 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5295 * .event.ActionEvent)
5298 protected void showGroupConservation_actionPerformed(ActionEvent e)
5300 viewport.setShowGroupConservation(showGroupConservation.getState());
5301 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5308 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5309 * .event.ActionEvent)
5312 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5314 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5315 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5322 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5323 * .event.ActionEvent)
5326 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5328 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5329 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5333 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5335 showSequenceLogo.setState(true);
5336 viewport.setShowSequenceLogo(true);
5337 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5338 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5342 protected void showInformationHistogram_actionPerformed(ActionEvent e)
5344 viewport.setShowInformationHistogram(
5345 showInformationHistogram.getState());
5346 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5350 protected void showHMMSequenceLogo_actionPerformed(ActionEvent e)
5352 viewport.setShowHMMSequenceLogo(showHMMSequenceLogo.getState());
5353 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5357 protected void normaliseHMMSequenceLogo_actionPerformed(ActionEvent e)
5359 showHMMSequenceLogo.setState(true);
5360 viewport.setShowHMMSequenceLogo(true);
5361 viewport.setNormaliseHMMSequenceLogo(normaliseSequenceLogo.getState());
5362 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5366 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5368 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5375 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5376 * .event.ActionEvent)
5379 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5381 if (avc.makeGroupsFromSelection())
5383 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5384 alignPanel.updateAnnotation();
5385 alignPanel.paintAlignment(true);
5389 public void clearAlignmentSeqRep()
5391 // TODO refactor alignmentseqrep to controller
5392 if (viewport.getAlignment().hasSeqrep())
5394 viewport.getAlignment().setSeqrep(null);
5395 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5396 alignPanel.updateAnnotation();
5397 alignPanel.paintAlignment(true);
5402 protected void createGroup_actionPerformed(ActionEvent e)
5404 if (avc.createGroup())
5406 alignPanel.alignmentChanged();
5411 protected void unGroup_actionPerformed(ActionEvent e)
5415 alignPanel.alignmentChanged();
5420 * make the given alignmentPanel the currently selected tab
5422 * @param alignmentPanel
5424 public void setDisplayedView(AlignmentPanel alignmentPanel)
5426 if (!viewport.getSequenceSetId().equals(
5427 alignmentPanel.av.getSequenceSetId()))
5431 .getString("error.implementation_error_cannot_show_view_alignment_frame"));
5433 if (tabbedPane != null
5434 && tabbedPane.getTabCount() > 0
5435 && alignPanels.indexOf(alignmentPanel) != tabbedPane
5436 .getSelectedIndex())
5438 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5443 * Action on selection of menu options to Show or Hide annotations.
5446 * @param forSequences
5447 * update sequence-related annotations
5448 * @param forAlignment
5449 * update non-sequence-related annotations
5452 protected void setAnnotationsVisibility(boolean visible,
5453 boolean forSequences, boolean forAlignment)
5455 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5456 .getAlignmentAnnotation();
5461 for (AlignmentAnnotation aa : anns)
5464 * don't display non-positional annotations on an alignment
5466 if (aa.annotations == null)
5470 boolean apply = (aa.sequenceRef == null && forAlignment)
5471 || (aa.sequenceRef != null && forSequences);
5474 aa.visible = visible;
5477 alignPanel.validateAnnotationDimensions(true);
5478 alignPanel.alignmentChanged();
5482 * Store selected annotation sort order for the view and repaint.
5485 protected void sortAnnotations_actionPerformed()
5487 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5489 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5490 alignPanel.paintAlignment(true);
5495 * @return alignment panels in this alignment frame
5497 public List<? extends AlignmentViewPanel> getAlignPanels()
5499 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5503 * Open a new alignment window, with the cDNA associated with this (protein)
5504 * alignment, aligned as is the protein.
5506 protected void viewAsCdna_actionPerformed()
5508 // TODO no longer a menu action - refactor as required
5509 final AlignmentI alignment = getViewport().getAlignment();
5510 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5511 if (mappings == null)
5515 List<SequenceI> cdnaSeqs = new ArrayList<>();
5516 for (SequenceI aaSeq : alignment.getSequences())
5518 for (AlignedCodonFrame acf : mappings)
5520 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5524 * There is a cDNA mapping for this protein sequence - add to new
5525 * alignment. It will share the same dataset sequence as other mapped
5526 * cDNA (no new mappings need to be created).
5528 final Sequence newSeq = new Sequence(dnaSeq);
5529 newSeq.setDatasetSequence(dnaSeq);
5530 cdnaSeqs.add(newSeq);
5534 if (cdnaSeqs.size() == 0)
5536 // show a warning dialog no mapped cDNA
5539 AlignmentI cdna = new Alignment(cdnaSeqs.toArray(new SequenceI[cdnaSeqs
5541 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5542 AlignFrame.DEFAULT_HEIGHT);
5543 cdna.alignAs(alignment);
5544 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5546 Desktop.addInternalFrame(alignFrame, newtitle,
5547 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
5551 * Set visibility of dna/protein complement view (available when shown in a
5557 protected void showComplement_actionPerformed(boolean show)
5559 SplitContainerI sf = getSplitViewContainer();
5562 sf.setComplementVisible(this, show);
5567 * Generate the reverse (optionally complemented) of the selected sequences,
5568 * and add them to the alignment
5571 protected void showReverse_actionPerformed(boolean complement)
5573 AlignmentI al = null;
5576 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5577 al = dna.reverseCdna(complement);
5578 viewport.addAlignment(al, "");
5579 addHistoryItem(new EditCommand(
5580 MessageManager.getString("label.add_sequences"),
5581 Action.PASTE, al.getSequencesArray(), 0, al.getWidth(),
5582 viewport.getAlignment()));
5583 } catch (Exception ex)
5585 System.err.println(ex.getMessage());
5591 * Try to run a script in the Groovy console, having first ensured that this
5592 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5593 * be targeted at this alignment.
5596 protected void runGroovy_actionPerformed()
5598 Jalview.setCurrentAlignFrame(this);
5599 groovy.ui.Console console = Desktop.getGroovyConsole();
5600 if (console != null)
5604 console.runScript();
5605 } catch (Exception ex)
5607 System.err.println((ex.toString()));
5609 .showInternalMessageDialog(Desktop.desktop, MessageManager
5610 .getString("label.couldnt_run_groovy_script"),
5612 .getString("label.groovy_support_failed"),
5613 JvOptionPane.ERROR_MESSAGE);
5618 System.err.println("Can't run Groovy script as console not found");
5623 * Hides columns containing (or not containing) a specified feature, provided
5624 * that would not leave all columns hidden
5626 * @param featureType
5627 * @param columnsContaining
5630 public boolean hideFeatureColumns(String featureType,
5631 boolean columnsContaining)
5633 boolean notForHiding = avc.markColumnsContainingFeatures(
5634 columnsContaining, false, false, featureType);
5637 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5638 false, featureType))
5640 getViewport().hideSelectedColumns();
5648 protected void selectHighlightedColumns_actionPerformed(
5649 ActionEvent actionEvent)
5651 // include key modifier check in case user selects from menu
5652 avc.markHighlightedColumns(
5653 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0,
5655 (actionEvent.getModifiers() & (ActionEvent.META_MASK | ActionEvent.CTRL_MASK)) != 0);
5659 * Rebuilds the Colour menu, including any user-defined colours which have
5660 * been loaded either on startup or during the session
5662 public void buildColourMenu()
5664 colourMenu.removeAll();
5666 colourMenu.add(applyToAllGroups);
5667 colourMenu.add(textColour);
5668 colourMenu.addSeparator();
5670 ColourMenuHelper.addMenuItems(colourMenu, this,
5671 viewport.getAlignment(), false);
5673 colourMenu.addSeparator();
5674 colourMenu.add(conservationMenuItem);
5675 colourMenu.add(modifyConservation);
5676 colourMenu.add(abovePIDThreshold);
5677 colourMenu.add(modifyPID);
5678 colourMenu.add(annotationColour);
5680 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5681 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5685 * Open a dialog (if not already open) that allows the user to select and
5686 * calculate PCA or Tree analysis
5688 protected void openTreePcaDialog()
5690 if (alignPanel.getCalculationDialog() == null)
5692 new CalculationChooser(AlignFrame.this);
5697 class PrintThread extends Thread
5701 public PrintThread(AlignmentPanel ap)
5706 static PageFormat pf;
5711 PrinterJob printJob = PrinterJob.getPrinterJob();
5715 printJob.setPrintable(ap, pf);
5719 printJob.setPrintable(ap);
5722 if (printJob.printDialog())
5727 } catch (Exception PrintException)
5729 PrintException.printStackTrace();