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.HMMAlignThread;
67 import jalview.hmmer.HMMBuildThread;
68 import jalview.io.AlignmentProperties;
69 import jalview.io.AnnotationFile;
70 import jalview.io.BioJsHTMLOutput;
71 import jalview.io.DataSourceType;
72 import jalview.io.FileFormat;
73 import jalview.io.FileFormatI;
74 import jalview.io.FileFormats;
75 import jalview.io.FileLoader;
76 import jalview.io.FileParse;
77 import jalview.io.FormatAdapter;
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.JOptionPane;
149 import javax.swing.JScrollPane;
150 import javax.swing.SwingUtilities;
156 * @version $Revision$
158 public class AlignFrame extends GAlignFrame implements DropTargetListener,
159 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
162 Map<String, Float> distribution = new HashMap<>(); // temporary
164 public static final int DEFAULT_WIDTH = 700;
166 public static final int DEFAULT_HEIGHT = 500;
168 boolean autoAlignNewSequences;
172 * The currently displayed panel (selected tabbed view if more than one)
174 public AlignmentPanel alignPanel;
176 AlignViewport viewport;
178 ViewportRanges vpRanges;
180 public AlignViewControllerI avc;
183 * The selected HMM for this align frame
185 HiddenMarkovModel selectedHMM = null;
187 List<AlignmentPanel> alignPanels = new ArrayList<>();
190 * Last format used to load or save alignments in this window
192 FileFormatI currentFileFormat = null;
195 * Current filename for this alignment
197 String fileName = null;
201 * Creates a new AlignFrame object with specific width and height.
207 public AlignFrame(AlignmentI al, int width, int height)
209 this(al, null, width, height);
213 * Creates a new AlignFrame object with specific width, height and
219 * @param sequenceSetId
221 public AlignFrame(AlignmentI al, int width, int height,
222 String sequenceSetId)
224 this(al, null, width, height, sequenceSetId);
228 * Creates a new AlignFrame object with specific width, height and
234 * @param sequenceSetId
237 public AlignFrame(AlignmentI al, int width, int height,
238 String sequenceSetId, String viewId)
240 this(al, null, width, height, sequenceSetId, viewId);
244 * new alignment window with hidden columns
248 * @param hiddenColumns
249 * ColumnSelection or null
251 * Width of alignment frame
255 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns,
256 int width, int height)
258 this(al, hiddenColumns, width, height, null);
262 * Create alignment frame for al with hiddenColumns, a specific width and
263 * height, and specific sequenceId
266 * @param hiddenColumns
269 * @param sequenceSetId
272 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns,
273 int width, int height, String sequenceSetId)
275 this(al, hiddenColumns, width, height, sequenceSetId, null);
279 * Create alignment frame for al with hiddenColumns, a specific width and
280 * height, and specific sequenceId
283 * @param hiddenColumns
286 * @param sequenceSetId
291 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns,
292 int width, int height, String sequenceSetId, String viewId)
294 setSize(width, height);
296 if (al.getDataset() == null)
301 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
303 alignPanel = new AlignmentPanel(this, viewport);
305 addAlignmentPanel(alignPanel, true);
309 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
310 HiddenColumns hiddenColumns, int width, int height)
312 setSize(width, height);
314 if (al.getDataset() == null)
319 viewport = new AlignViewport(al, hiddenColumns);
321 if (hiddenSeqs != null && hiddenSeqs.length > 0)
323 viewport.hideSequence(hiddenSeqs);
325 alignPanel = new AlignmentPanel(this, viewport);
326 addAlignmentPanel(alignPanel, true);
331 * Make a new AlignFrame from existing alignmentPanels
338 public AlignFrame(AlignmentPanel ap)
342 addAlignmentPanel(ap, false);
347 * initalise the alignframe from the underlying viewport data and the
352 if (!Jalview.isHeadlessMode())
354 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
357 vpRanges = viewport.getRanges();
358 avc = new jalview.controller.AlignViewController(this, viewport,
360 if (viewport.getAlignmentConservationAnnotation() == null)
362 // BLOSUM62Colour.setEnabled(false);
363 conservationMenuItem.setEnabled(false);
364 modifyConservation.setEnabled(false);
365 // PIDColour.setEnabled(false);
366 // abovePIDThreshold.setEnabled(false);
367 // modifyPID.setEnabled(false);
370 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
373 if (sortby.equals("Id"))
375 sortIDMenuItem_actionPerformed(null);
377 else if (sortby.equals("Pairwise Identity"))
379 sortPairwiseMenuItem_actionPerformed(null);
383 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
385 setMenusFromViewport(viewport);
386 buildSortByAnnotationScoresMenu();
387 calculateTree.addActionListener(new ActionListener()
391 public void actionPerformed(ActionEvent e)
399 if (Desktop.desktop != null)
401 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
402 addServiceListeners();
406 if (viewport.getWrapAlignment())
408 wrapMenuItem_actionPerformed(null);
411 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
413 this.overviewMenuItem_actionPerformed(null);
418 final List<AlignmentPanel> selviews = new ArrayList<>();
419 final List<AlignmentPanel> origview = new ArrayList<>();
420 final String menuLabel = MessageManager
421 .getString("label.copy_format_from");
422 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
423 new ViewSetProvider()
427 public AlignmentPanel[] getAllAlignmentPanels()
430 origview.add(alignPanel);
431 // make an array of all alignment panels except for this one
432 List<AlignmentPanel> aps = new ArrayList<>(
433 Arrays.asList(Desktop.getAlignmentPanels(null)));
434 aps.remove(AlignFrame.this.alignPanel);
435 return aps.toArray(new AlignmentPanel[aps.size()]);
437 }, selviews, new ItemListener()
441 public void itemStateChanged(ItemEvent e)
443 if (origview.size() > 0)
445 final AlignmentPanel ap = origview.get(0);
448 * Copy the ViewStyle of the selected panel to 'this one'.
449 * Don't change value of 'scaleProteinAsCdna' unless copying
452 ViewStyleI vs = selviews.get(0).getAlignViewport()
454 boolean fromSplitFrame = selviews.get(0)
455 .getAlignViewport().getCodingComplement() != null;
458 vs.setScaleProteinAsCdna(ap.getAlignViewport()
459 .getViewStyle().isScaleProteinAsCdna());
461 ap.getAlignViewport().setViewStyle(vs);
464 * Also rescale ViewStyle of SplitFrame complement if there is
465 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
466 * the whole ViewStyle (allow cDNA protein to have different
469 AlignViewportI complement = ap.getAlignViewport()
470 .getCodingComplement();
471 if (complement != null && vs.isScaleProteinAsCdna())
473 AlignFrame af = Desktop.getAlignFrameFor(complement);
474 ((SplitFrame) af.getSplitViewContainer())
476 af.setMenusForViewport();
480 ap.setSelected(true);
481 ap.alignFrame.setMenusForViewport();
486 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
487 .indexOf("devel") > -1
488 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
489 .indexOf("test") > -1)
491 formatMenu.add(vsel);
493 addFocusListener(new FocusAdapter()
496 public void focusGained(FocusEvent e)
498 Jalview.setCurrentAlignFrame(AlignFrame.this);
505 * Adds all menu items to the HMMER menu
507 private void buildHMMERMenu()
509 hmmerMenu.removeAll();
511 hmmerMenu.add(hmmAlign);
512 hmmerMenu.add(hmmBuild);
513 hmmerMenu.add(hmmSearch);
517 * Change the filename and format for the alignment, and enable the 'reload'
518 * button functionality.
525 public void setFileName(String file, FileFormatI format)
528 setFileFormat(format);
529 reload.setEnabled(true);
533 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
536 void addKeyListener()
538 addKeyListener(new KeyAdapter()
541 public void keyPressed(KeyEvent evt)
543 if (viewport.cursorMode
544 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
545 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
546 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
547 && Character.isDigit(evt.getKeyChar()))
549 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
552 switch (evt.getKeyCode())
555 case 27: // escape key
556 deselectAllSequenceMenuItem_actionPerformed(null);
560 case KeyEvent.VK_DOWN:
561 if (evt.isAltDown() || !viewport.cursorMode)
563 moveSelectedSequences(false);
565 if (viewport.cursorMode)
567 alignPanel.getSeqPanel().moveCursor(0, 1);
572 if (evt.isAltDown() || !viewport.cursorMode)
574 moveSelectedSequences(true);
576 if (viewport.cursorMode)
578 alignPanel.getSeqPanel().moveCursor(0, -1);
583 case KeyEvent.VK_LEFT:
584 if (evt.isAltDown() || !viewport.cursorMode)
586 slideSequences(false, alignPanel.getSeqPanel().getKeyboardNo1());
590 alignPanel.getSeqPanel().moveCursor(-1, 0);
595 case KeyEvent.VK_RIGHT:
596 if (evt.isAltDown() || !viewport.cursorMode)
598 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
602 alignPanel.getSeqPanel().moveCursor(1, 0);
606 case KeyEvent.VK_SPACE:
607 if (viewport.cursorMode)
609 alignPanel.getSeqPanel().insertGapAtCursor(
610 evt.isControlDown() || evt.isShiftDown()
615 // case KeyEvent.VK_A:
616 // if (viewport.cursorMode)
618 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
619 // //System.out.println("A");
623 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
624 * System.out.println("closing bracket"); } break;
626 case KeyEvent.VK_DELETE:
627 case KeyEvent.VK_BACK_SPACE:
628 if (!viewport.cursorMode)
630 cut_actionPerformed(null);
634 alignPanel.getSeqPanel().deleteGapAtCursor(
635 evt.isControlDown() || evt.isShiftDown()
642 if (viewport.cursorMode)
644 alignPanel.getSeqPanel().setCursorRow();
648 if (viewport.cursorMode && !evt.isControlDown())
650 alignPanel.getSeqPanel().setCursorColumn();
654 if (viewport.cursorMode)
656 alignPanel.getSeqPanel().setCursorPosition();
660 case KeyEvent.VK_ENTER:
661 case KeyEvent.VK_COMMA:
662 if (viewport.cursorMode)
664 alignPanel.getSeqPanel().setCursorRowAndColumn();
669 if (viewport.cursorMode)
671 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
675 if (viewport.cursorMode)
677 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
682 viewport.cursorMode = !viewport.cursorMode;
683 statusBar.setText(MessageManager.formatMessage(
684 "label.keyboard_editing_mode",
685 new String[] { (viewport.cursorMode ? "on" : "off") }));
686 if (viewport.cursorMode)
688 alignPanel.getSeqPanel().seqCanvas.cursorX = vpRanges
690 alignPanel.getSeqPanel().seqCanvas.cursorY = vpRanges
693 alignPanel.getSeqPanel().seqCanvas.repaint();
699 Help.showHelpWindow();
700 } catch (Exception ex)
702 ex.printStackTrace();
707 boolean toggleSeqs = !evt.isControlDown();
708 boolean toggleCols = !evt.isShiftDown();
709 toggleHiddenRegions(toggleSeqs, toggleCols);
714 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
715 boolean modifyExisting = true; // always modify, don't clear
716 // evt.isShiftDown();
717 boolean invertHighlighted = evt.isAltDown();
718 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
722 case KeyEvent.VK_PAGE_UP:
723 if (viewport.getWrapAlignment())
725 vpRanges.scrollUp(true);
732 case KeyEvent.VK_PAGE_DOWN:
733 if (viewport.getWrapAlignment())
735 vpRanges.scrollUp(false);
746 public void keyReleased(KeyEvent evt)
748 switch (evt.getKeyCode())
750 case KeyEvent.VK_LEFT:
751 if (evt.isAltDown() || !viewport.cursorMode)
753 viewport.firePropertyChange("alignment", null, viewport
754 .getAlignment().getSequences());
758 case KeyEvent.VK_RIGHT:
759 if (evt.isAltDown() || !viewport.cursorMode)
761 viewport.firePropertyChange("alignment", null, viewport
762 .getAlignment().getSequences());
770 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
772 ap.alignFrame = this;
773 avc = new jalview.controller.AlignViewController(this, viewport,
778 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
780 int aSize = alignPanels.size();
782 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
784 if (aSize == 1 && ap.av.viewName == null)
786 this.getContentPane().add(ap, BorderLayout.CENTER);
792 setInitialTabVisible();
795 expandViews.setEnabled(true);
796 gatherViews.setEnabled(true);
797 tabbedPane.addTab(ap.av.viewName, ap);
799 ap.setVisible(false);
804 if (ap.av.isPadGaps())
806 ap.av.getAlignment().padGaps();
808 ap.av.updateConservation(ap);
809 ap.av.updateConsensus(ap);
810 ap.av.updateStrucConsensus(ap);
811 ap.av.updateInformation(ap);
815 public void setInitialTabVisible()
817 expandViews.setEnabled(true);
818 gatherViews.setEnabled(true);
819 tabbedPane.setVisible(true);
820 AlignmentPanel first = alignPanels.get(0);
821 tabbedPane.addTab(first.av.viewName, first);
822 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
825 public AlignViewport getViewport()
830 /* Set up intrinsic listeners for dynamically generated GUI bits. */
831 private void addServiceListeners()
833 final java.beans.PropertyChangeListener thisListener;
834 Desktop.instance.addJalviewPropertyChangeListener("services",
835 thisListener = new java.beans.PropertyChangeListener()
838 public void propertyChange(PropertyChangeEvent evt)
840 // // System.out.println("Discoverer property change.");
841 // if (evt.getPropertyName().equals("services"))
843 SwingUtilities.invokeLater(new Runnable()
850 .println("Rebuild WS Menu for service change");
851 BuildWebServiceMenu();
858 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
861 public void internalFrameClosed(
862 javax.swing.event.InternalFrameEvent evt)
864 // System.out.println("deregistering discoverer listener");
865 Desktop.instance.removeJalviewPropertyChangeListener("services",
867 closeMenuItem_actionPerformed(true);
870 // Finally, build the menu once to get current service state
871 new Thread(new Runnable()
876 BuildWebServiceMenu();
882 * Configure menu items that vary according to whether the alignment is
883 * nucleotide or protein
885 public void setGUINucleotide()
887 AlignmentI al = getViewport().getAlignment();
888 boolean nucleotide = al.isNucleotide();
890 showTranslation.setVisible(nucleotide);
891 showReverse.setVisible(nucleotide);
892 showReverseComplement.setVisible(nucleotide);
893 conservationMenuItem.setEnabled(!nucleotide);
894 modifyConservation.setEnabled(!nucleotide
895 && conservationMenuItem.isSelected());
896 showGroupConservation.setEnabled(!nucleotide);
898 showComplementMenuItem.setText(nucleotide ? MessageManager
899 .getString("label.protein") : MessageManager
900 .getString("label.nucleotide"));
904 * set up menus for the current viewport. This may be called after any
905 * operation that affects the data in the current view (selection changed,
906 * etc) to update the menus to reflect the new state.
909 public void setMenusForViewport()
911 setMenusFromViewport(viewport);
915 * Need to call this method when tabs are selected for multiple views, or when
916 * loading from Jalview2XML.java
921 void setMenusFromViewport(AlignViewport av)
923 padGapsMenuitem.setSelected(av.isPadGaps());
924 colourTextMenuItem.setSelected(av.isShowColourText());
925 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
926 modifyPID.setEnabled(abovePIDThreshold.isSelected());
927 conservationMenuItem.setSelected(av.getConservationSelected());
928 modifyConservation.setEnabled(conservationMenuItem.isSelected());
929 seqLimits.setSelected(av.getShowJVSuffix());
930 idRightAlign.setSelected(av.isRightAlignIds());
931 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
932 renderGapsMenuItem.setSelected(av.isRenderGaps());
933 wrapMenuItem.setSelected(av.getWrapAlignment());
934 scaleAbove.setVisible(av.getWrapAlignment());
935 scaleLeft.setVisible(av.getWrapAlignment());
936 scaleRight.setVisible(av.getWrapAlignment());
937 annotationPanelMenuItem.setState(av.isShowAnnotation());
939 * Show/hide annotations only enabled if annotation panel is shown
941 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
942 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
943 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
944 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
945 viewBoxesMenuItem.setSelected(av.getShowBoxes());
946 viewTextMenuItem.setSelected(av.getShowText());
947 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
948 showGroupConsensus.setSelected(av.isShowGroupConsensus());
949 showGroupConservation.setSelected(av.isShowGroupConservation());
950 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
951 showSequenceLogo.setSelected(av.isShowSequenceLogo());
952 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
953 showInformationHistogram.setSelected(av.isShowInformationHistogram());
954 showHMMSequenceLogo.setSelected(av.isShowHMMSequenceLogo());
955 normaliseHMMSequenceLogo.setSelected(av.isNormaliseHMMSequenceLogo());
957 ColourMenuHelper.setColourSelected(colourMenu,
958 av.getGlobalColourScheme());
960 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
961 hiddenMarkers.setState(av.getShowHiddenMarkers());
962 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
963 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
964 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
965 autoCalculate.setSelected(av.autoCalculateConsensus);
966 sortByTree.setSelected(av.sortByTree);
967 listenToViewSelections.setSelected(av.followSelection);
969 showProducts.setEnabled(canShowProducts());
970 setGroovyEnabled(Desktop.getGroovyConsole() != null);
976 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
980 public void setGroovyEnabled(boolean b)
982 runGroovy.setEnabled(b);
985 private IProgressIndicator progressBar;
990 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
993 public void setProgressBar(String message, long id)
995 progressBar.setProgressBar(message, id);
999 public void registerHandler(final long id,
1000 final IProgressIndicatorHandler handler)
1002 progressBar.registerHandler(id, handler);
1007 * @return true if any progress bars are still active
1010 public boolean operationInProgress()
1012 return progressBar.operationInProgress();
1016 public void setStatus(String text)
1018 statusBar.setText(text);
1022 * Added so Castor Mapping file can obtain Jalview Version
1024 public String getVersion()
1026 return jalview.bin.Cache.getProperty("VERSION");
1029 public FeatureRenderer getFeatureRenderer()
1031 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1035 public void fetchSequence_actionPerformed(ActionEvent e)
1037 new jalview.gui.SequenceFetcher(this);
1041 public void addFromFile_actionPerformed(ActionEvent e)
1043 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1047 public void hmmBuild_actionPerformed(ActionEvent e)
1048 throws IOException, InterruptedException
1050 new Thread(new HMMBuildThread(this)).start();
1051 alignPanel.repaint();
1056 public void hmmAlign_actionPerformed(ActionEvent e)
1057 throws IOException, InterruptedException
1059 new Thread(new HMMAlignThread(this, true)).start();
1060 alignPanel.repaint();
1064 public void changeHMMERLocation_actionPerformed(ActionEvent e)
1066 String location = JOptionPane.showInputDialog(
1067 MessageManager.getString("label.enter_location"));
1068 Cache.setProperty(Preferences.HMMER_PATH, location);
1072 public void autoAlignSeqs_actionPerformed(boolean autoAlignSeqs)
1074 autoAlignNewSequences = autoAlignSeqs;
1075 alignPanel.repaint();
1079 public void hmmSearch_actionPerformed(ActionEvent e)
1081 alignPanel.repaint();
1085 public void reload_actionPerformed(ActionEvent e)
1087 if (fileName != null)
1089 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1090 // originating file's format
1091 // TODO: work out how to recover feature settings for correct view(s) when
1092 // file is reloaded.
1093 if (FileFormat.Jalview.equals(currentFileFormat))
1095 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1096 for (int i = 0; i < frames.length; i++)
1098 if (frames[i] instanceof AlignFrame && frames[i] != this
1099 && ((AlignFrame) frames[i]).fileName != null
1100 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1104 frames[i].setSelected(true);
1105 Desktop.instance.closeAssociatedWindows();
1106 } catch (java.beans.PropertyVetoException ex)
1112 Desktop.instance.closeAssociatedWindows();
1114 FileLoader loader = new FileLoader();
1115 DataSourceType protocol = fileName.startsWith("http:") ? DataSourceType.URL
1116 : DataSourceType.FILE;
1117 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1121 Rectangle bounds = this.getBounds();
1123 FileLoader loader = new FileLoader();
1124 DataSourceType protocol = fileName.startsWith("http:") ? DataSourceType.URL
1125 : DataSourceType.FILE;
1126 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1127 protocol, currentFileFormat);
1129 newframe.setBounds(bounds);
1130 if (featureSettings != null && featureSettings.isShowing())
1132 final Rectangle fspos = featureSettings.frame.getBounds();
1133 // TODO: need a 'show feature settings' function that takes bounds -
1134 // need to refactor Desktop.addFrame
1135 newframe.featureSettings_actionPerformed(null);
1136 final FeatureSettings nfs = newframe.featureSettings;
1137 SwingUtilities.invokeLater(new Runnable()
1142 nfs.frame.setBounds(fspos);
1145 this.featureSettings.close();
1146 this.featureSettings = null;
1148 this.closeMenuItem_actionPerformed(true);
1154 public void addFromText_actionPerformed(ActionEvent e)
1156 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport
1161 public void addFromURL_actionPerformed(ActionEvent e)
1163 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1167 public void save_actionPerformed(ActionEvent e)
1169 if (fileName == null || (currentFileFormat == null)
1170 || fileName.startsWith("http"))
1172 saveAs_actionPerformed(null);
1176 saveAlignment(fileName, currentFileFormat);
1187 public void saveAs_actionPerformed(ActionEvent e)
1189 String format = currentFileFormat == null ? null : currentFileFormat
1191 JalviewFileChooser chooser = JalviewFileChooser.forWrite(
1192 Cache.getProperty("LAST_DIRECTORY"), format);
1194 chooser.setFileView(new JalviewFileView());
1195 chooser.setDialogTitle(MessageManager
1196 .getString("label.save_alignment_to_file"));
1197 chooser.setToolTipText(MessageManager.getString("action.save"));
1199 int value = chooser.showSaveDialog(this);
1201 if (value == JalviewFileChooser.APPROVE_OPTION)
1203 currentFileFormat = chooser.getSelectedFormat();
1204 while (currentFileFormat == null)
1207 .showInternalMessageDialog(
1210 .getString("label.select_file_format_before_saving"),
1212 .getString("label.file_format_not_specified"),
1213 JvOptionPane.WARNING_MESSAGE);
1214 currentFileFormat = chooser.getSelectedFormat();
1215 value = chooser.showSaveDialog(this);
1216 if (value != JalviewFileChooser.APPROVE_OPTION)
1222 fileName = chooser.getSelectedFile().getPath();
1224 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1226 Cache.setProperty("LAST_DIRECTORY", fileName);
1227 saveAlignment(fileName, currentFileFormat);
1231 public boolean saveAlignment(String file, FileFormatI format)
1233 boolean success = true;
1235 if (FileFormat.Jalview.equals(format))
1237 String shortName = title;
1239 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1241 shortName = shortName.substring(shortName
1242 .lastIndexOf(java.io.File.separatorChar) + 1);
1245 success = new Jalview2XML().saveAlignment(this, file, shortName);
1247 statusBar.setText(MessageManager.formatMessage(
1248 "label.successfully_saved_to_file_in_format", new Object[] {
1249 fileName, format }));
1254 AlignmentExportData exportData = getAlignmentForExport(format,
1256 if (exportData.getSettings().isCancelled())
1260 FormatAdapter f = new FormatAdapter(alignPanel,
1261 exportData.getSettings());
1262 String output = f.formatSequences(
1264 exportData.getAlignment(), // class cast exceptions will
1265 // occur in the distant future
1266 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1267 f.getCacheSuffixDefault(format), viewport.getAlignment()
1268 .getHiddenColumns());
1278 PrintWriter out = new PrintWriter(new FileWriter(file));
1282 this.setTitle(file);
1283 statusBar.setText(MessageManager.formatMessage(
1284 "label.successfully_saved_to_file_in_format",
1285 new Object[] { fileName, format.getName() }));
1286 } catch (Exception ex)
1289 ex.printStackTrace();
1296 JvOptionPane.showInternalMessageDialog(this, MessageManager
1297 .formatMessage("label.couldnt_save_file",
1298 new Object[] { fileName }), MessageManager
1299 .getString("label.error_saving_file"),
1300 JvOptionPane.WARNING_MESSAGE);
1306 private void warningMessage(String warning, String title)
1308 if (new jalview.util.Platform().isHeadless())
1310 System.err.println("Warning: " + title + "\nWarning: " + warning);
1315 JvOptionPane.showInternalMessageDialog(this, warning, title,
1316 JvOptionPane.WARNING_MESSAGE);
1328 protected void outputText_actionPerformed(ActionEvent e)
1330 FileFormatI fileFormat = FileFormats.getInstance().forName(
1331 e.getActionCommand());
1332 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1334 if (exportData.getSettings().isCancelled())
1338 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1339 cap.setForInput(null);
1342 FileFormatI format = fileFormat;
1343 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1344 .formatSequences(format, exportData.getAlignment(),
1345 exportData.getOmitHidden(),
1347 .getStartEndPostions(), viewport
1348 .getAlignment().getHiddenColumns()));
1349 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1350 "label.alignment_output_command",
1351 new Object[] { e.getActionCommand() }), 600, 500);
1352 } catch (OutOfMemoryError oom)
1354 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1360 public static AlignmentExportData getAlignmentForExport(
1361 FileFormatI format, AlignViewportI viewport,
1362 AlignExportSettingI exportSettings)
1364 AlignmentI alignmentToExport = null;
1365 AlignExportSettingI settings = exportSettings;
1366 String[] omitHidden = null;
1368 HiddenSequences hiddenSeqs = viewport.getAlignment()
1369 .getHiddenSequences();
1371 alignmentToExport = viewport.getAlignment();
1373 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1374 if (settings == null)
1376 settings = new AlignExportSettings(hasHiddenSeqs,
1377 viewport.hasHiddenColumns(), format);
1379 // settings.isExportAnnotations();
1381 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1383 omitHidden = viewport.getViewAsString(false,
1384 settings.isExportHiddenSequences());
1387 int[] alignmentStartEnd = new int[2];
1388 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1390 alignmentToExport = hiddenSeqs.getFullAlignment();
1394 alignmentToExport = viewport.getAlignment();
1396 alignmentStartEnd = alignmentToExport
1397 .getVisibleStartAndEndIndex(viewport.getAlignment()
1399 .getHiddenRegions());
1400 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1401 omitHidden, alignmentStartEnd, settings);
1412 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1414 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1415 htmlSVG.exportHTML(null);
1419 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1421 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1422 bjs.exportHTML(null);
1425 public void createImageMap(File file, String image)
1427 alignPanel.makePNGImageMap(file, image);
1437 public void createPNG(File f)
1439 alignPanel.makePNG(f);
1449 public void createEPS(File f)
1451 alignPanel.makeEPS(f);
1455 public void createSVG(File f)
1457 alignPanel.makeSVG(f);
1461 public void pageSetup_actionPerformed(ActionEvent e)
1463 PrinterJob printJob = PrinterJob.getPrinterJob();
1464 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1474 public void printMenuItem_actionPerformed(ActionEvent e)
1476 // Putting in a thread avoids Swing painting problems
1477 PrintThread thread = new PrintThread(alignPanel);
1482 public void exportFeatures_actionPerformed(ActionEvent e)
1484 new AnnotationExporter().exportFeatures(alignPanel);
1488 public void exportAnnotations_actionPerformed(ActionEvent e)
1490 new AnnotationExporter().exportAnnotations(alignPanel);
1494 public void associatedData_actionPerformed(ActionEvent e)
1495 throws IOException, InterruptedException
1497 // Pick the tree file
1498 JalviewFileChooser chooser = new JalviewFileChooser(
1499 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1500 chooser.setFileView(new JalviewFileView());
1501 chooser.setDialogTitle(MessageManager
1502 .getString("label.load_jalview_annotations"));
1503 chooser.setToolTipText(MessageManager
1504 .getString("label.load_jalview_annotations"));
1506 int value = chooser.showOpenDialog(null);
1508 if (value == JalviewFileChooser.APPROVE_OPTION)
1510 String choice = chooser.getSelectedFile().getPath();
1511 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1512 loadJalviewDataFile(choice, null, null, null);
1518 * Close the current view or all views in the alignment frame. If the frame
1519 * only contains one view then the alignment will be removed from memory.
1521 * @param closeAllTabs
1524 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1526 if (alignPanels != null && alignPanels.size() < 2)
1528 closeAllTabs = true;
1533 if (alignPanels != null)
1537 if (this.isClosed())
1539 // really close all the windows - otherwise wait till
1540 // setClosed(true) is called
1541 for (int i = 0; i < alignPanels.size(); i++)
1543 AlignmentPanel ap = alignPanels.get(i);
1550 closeView(alignPanel);
1557 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1558 * be called recursively, with the frame now in 'closed' state
1560 this.setClosed(true);
1562 } catch (Exception ex)
1564 ex.printStackTrace();
1569 * Close the specified panel and close up tabs appropriately.
1571 * @param panelToClose
1573 public void closeView(AlignmentPanel panelToClose)
1575 int index = tabbedPane.getSelectedIndex();
1576 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1577 alignPanels.remove(panelToClose);
1578 panelToClose.closePanel();
1579 panelToClose = null;
1581 tabbedPane.removeTabAt(closedindex);
1582 tabbedPane.validate();
1584 if (index > closedindex || index == tabbedPane.getTabCount())
1586 // modify currently selected tab index if necessary.
1590 this.tabSelectionChanged(index);
1596 void updateEditMenuBar()
1599 if (viewport.getHistoryList().size() > 0)
1601 undoMenuItem.setEnabled(true);
1602 CommandI command = viewport.getHistoryList().peek();
1603 undoMenuItem.setText(MessageManager.formatMessage(
1604 "label.undo_command",
1605 new Object[] { command.getDescription() }));
1609 undoMenuItem.setEnabled(false);
1610 undoMenuItem.setText(MessageManager.getString("action.undo"));
1613 if (viewport.getRedoList().size() > 0)
1615 redoMenuItem.setEnabled(true);
1617 CommandI command = viewport.getRedoList().peek();
1618 redoMenuItem.setText(MessageManager.formatMessage(
1619 "label.redo_command",
1620 new Object[] { command.getDescription() }));
1624 redoMenuItem.setEnabled(false);
1625 redoMenuItem.setText(MessageManager.getString("action.redo"));
1630 public void addHistoryItem(CommandI command)
1632 if (command.getSize() > 0)
1634 viewport.addToHistoryList(command);
1635 viewport.clearRedoList();
1636 updateEditMenuBar();
1637 viewport.updateHiddenColumns();
1638 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1639 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1640 // viewport.getColumnSelection()
1641 // .getHiddenColumns().size() > 0);
1647 * @return alignment objects for all views
1649 AlignmentI[] getViewAlignments()
1651 if (alignPanels != null)
1653 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1655 for (AlignmentPanel ap : alignPanels)
1657 als[i++] = ap.av.getAlignment();
1661 if (viewport != null)
1663 return new AlignmentI[] { viewport.getAlignment() };
1675 protected void undoMenuItem_actionPerformed(ActionEvent e)
1677 if (viewport.getHistoryList().isEmpty())
1681 CommandI command = viewport.getHistoryList().pop();
1682 viewport.addToRedoList(command);
1683 command.undoCommand(getViewAlignments());
1685 AlignmentViewport originalSource = getOriginatingSource(command);
1686 updateEditMenuBar();
1688 if (originalSource != null)
1690 if (originalSource != viewport)
1693 .warn("Implementation worry: mismatch of viewport origin for undo");
1695 originalSource.updateHiddenColumns();
1696 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1698 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1699 // viewport.getColumnSelection()
1700 // .getHiddenColumns().size() > 0);
1701 originalSource.firePropertyChange("alignment", null, originalSource
1702 .getAlignment().getSequences());
1713 protected void redoMenuItem_actionPerformed(ActionEvent e)
1715 if (viewport.getRedoList().size() < 1)
1720 CommandI command = viewport.getRedoList().pop();
1721 viewport.addToHistoryList(command);
1722 command.doCommand(getViewAlignments());
1724 AlignmentViewport originalSource = getOriginatingSource(command);
1725 updateEditMenuBar();
1727 if (originalSource != null)
1730 if (originalSource != viewport)
1733 .warn("Implementation worry: mismatch of viewport origin for redo");
1735 originalSource.updateHiddenColumns();
1736 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1738 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1739 // viewport.getColumnSelection()
1740 // .getHiddenColumns().size() > 0);
1741 originalSource.firePropertyChange("alignment", null, originalSource
1742 .getAlignment().getSequences());
1746 AlignmentViewport getOriginatingSource(CommandI command)
1748 AlignmentViewport originalSource = null;
1749 // For sequence removal and addition, we need to fire
1750 // the property change event FROM the viewport where the
1751 // original alignment was altered
1752 AlignmentI al = null;
1753 if (command instanceof EditCommand)
1755 EditCommand editCommand = (EditCommand) command;
1756 al = editCommand.getAlignment();
1757 List<Component> comps = PaintRefresher.components.get(viewport
1758 .getSequenceSetId());
1760 for (Component comp : comps)
1762 if (comp instanceof AlignmentPanel)
1764 if (al == ((AlignmentPanel) comp).av.getAlignment())
1766 originalSource = ((AlignmentPanel) comp).av;
1773 if (originalSource == null)
1775 // The original view is closed, we must validate
1776 // the current view against the closed view first
1779 PaintRefresher.validateSequences(al, viewport.getAlignment());
1782 originalSource = viewport;
1785 return originalSource;
1794 public void moveSelectedSequences(boolean up)
1796 SequenceGroup sg = viewport.getSelectionGroup();
1802 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1803 viewport.getHiddenRepSequences(), up);
1804 alignPanel.paintAlignment(true);
1807 synchronized void slideSequences(boolean right, int size)
1809 List<SequenceI> sg = new ArrayList<>();
1810 if (viewport.cursorMode)
1812 sg.add(viewport.getAlignment().getSequenceAt(
1813 alignPanel.getSeqPanel().seqCanvas.cursorY));
1815 else if (viewport.getSelectionGroup() != null
1816 && viewport.getSelectionGroup().getSize() != viewport
1817 .getAlignment().getHeight())
1819 sg = viewport.getSelectionGroup().getSequences(
1820 viewport.getHiddenRepSequences());
1828 List<SequenceI> invertGroup = new ArrayList<>();
1830 for (SequenceI seq : viewport.getAlignment().getSequences())
1832 if (!sg.contains(seq))
1834 invertGroup.add(seq);
1838 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1840 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1841 for (int i = 0; i < invertGroup.size(); i++)
1843 seqs2[i] = invertGroup.get(i);
1846 SlideSequencesCommand ssc;
1849 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1850 size, viewport.getGapCharacter());
1854 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1855 size, viewport.getGapCharacter());
1858 int groupAdjustment = 0;
1859 if (ssc.getGapsInsertedBegin() && right)
1861 if (viewport.cursorMode)
1863 alignPanel.getSeqPanel().moveCursor(size, 0);
1867 groupAdjustment = size;
1870 else if (!ssc.getGapsInsertedBegin() && !right)
1872 if (viewport.cursorMode)
1874 alignPanel.getSeqPanel().moveCursor(-size, 0);
1878 groupAdjustment = -size;
1882 if (groupAdjustment != 0)
1884 viewport.getSelectionGroup().setStartRes(
1885 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1886 viewport.getSelectionGroup().setEndRes(
1887 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1891 * just extend the last slide command if compatible; but not if in
1892 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1894 boolean appendHistoryItem = false;
1895 Deque<CommandI> historyList = viewport.getHistoryList();
1896 boolean inSplitFrame = getSplitViewContainer() != null;
1897 if (!inSplitFrame && historyList != null && historyList.size() > 0
1898 && historyList.peek() instanceof SlideSequencesCommand)
1900 appendHistoryItem = ssc
1901 .appendSlideCommand((SlideSequencesCommand) historyList
1905 if (!appendHistoryItem)
1907 addHistoryItem(ssc);
1920 protected void copy_actionPerformed(ActionEvent e)
1923 if (viewport.getSelectionGroup() == null)
1927 // TODO: preserve the ordering of displayed alignment annotation in any
1928 // internal paste (particularly sequence associated annotation)
1929 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1930 String[] omitHidden = null;
1932 if (viewport.hasHiddenColumns())
1934 omitHidden = viewport.getViewAsString(true);
1937 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1938 seqs, omitHidden, null);
1940 StringSelection ss = new StringSelection(output);
1944 jalview.gui.Desktop.internalCopy = true;
1945 // Its really worth setting the clipboard contents
1946 // to empty before setting the large StringSelection!!
1947 Toolkit.getDefaultToolkit().getSystemClipboard()
1948 .setContents(new StringSelection(""), null);
1950 Toolkit.getDefaultToolkit().getSystemClipboard()
1951 .setContents(ss, Desktop.instance);
1952 } catch (OutOfMemoryError er)
1954 new OOMWarning("copying region", er);
1958 ArrayList<int[]> hiddenColumns = null;
1959 if (viewport.hasHiddenColumns())
1961 hiddenColumns = new ArrayList<>();
1962 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1963 .getSelectionGroup().getEndRes();
1964 for (int[] region : viewport.getAlignment().getHiddenColumns()
1965 .getHiddenRegions())
1967 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1969 hiddenColumns.add(new int[] { region[0] - hiddenOffset,
1970 region[1] - hiddenOffset });
1975 Desktop.jalviewClipboard = new Object[] { seqs,
1976 viewport.getAlignment().getDataset(), hiddenColumns };
1977 statusBar.setText(MessageManager.formatMessage(
1978 "label.copied_sequences_to_clipboard", new Object[] { Integer
1979 .valueOf(seqs.length).toString() }));
1987 * @throws InterruptedException
1988 * @throws IOException
1991 protected void pasteNew_actionPerformed(ActionEvent e)
1992 throws IOException, InterruptedException
2002 * @throws InterruptedException
2003 * @throws IOException
2006 protected void pasteThis_actionPerformed(ActionEvent e)
2007 throws IOException, InterruptedException
2013 * Paste contents of Jalview clipboard
2015 * @param newAlignment
2016 * true to paste to a new alignment, otherwise add to this.
2017 * @throws InterruptedException
2018 * @throws IOException
2020 void paste(boolean newAlignment) throws IOException, InterruptedException
2022 boolean externalPaste = true;
2025 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2026 Transferable contents = c.getContents(this);
2028 if (contents == null)
2037 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2038 if (str.length() < 1)
2043 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2045 } catch (OutOfMemoryError er)
2047 new OOMWarning("Out of memory pasting sequences!!", er);
2051 SequenceI[] sequences;
2052 boolean annotationAdded = false;
2053 AlignmentI alignment = null;
2055 if (Desktop.jalviewClipboard != null)
2057 // The clipboard was filled from within Jalview, we must use the
2059 // And dataset from the copied alignment
2060 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2061 // be doubly sure that we create *new* sequence objects.
2062 sequences = new SequenceI[newseq.length];
2063 for (int i = 0; i < newseq.length; i++)
2065 sequences[i] = new Sequence(newseq[i]);
2067 alignment = new Alignment(sequences);
2068 externalPaste = false;
2072 // parse the clipboard as an alignment.
2073 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2075 sequences = alignment.getSequencesArray();
2079 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2085 if (Desktop.jalviewClipboard != null)
2087 // dataset is inherited
2088 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2092 // new dataset is constructed
2093 alignment.setDataset(null);
2095 alwidth = alignment.getWidth() + 1;
2099 AlignmentI pastedal = alignment; // preserve pasted alignment object
2100 // Add pasted sequences and dataset into existing alignment.
2101 alignment = viewport.getAlignment();
2102 alwidth = alignment.getWidth() + 1;
2103 // decide if we need to import sequences from an existing dataset
2104 boolean importDs = Desktop.jalviewClipboard != null
2105 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2106 // importDs==true instructs us to copy over new dataset sequences from
2107 // an existing alignment
2108 Vector newDs = (importDs) ? new Vector() : null; // used to create
2109 // minimum dataset set
2111 for (int i = 0; i < sequences.length; i++)
2115 newDs.addElement(null);
2117 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2119 if (importDs && ds != null)
2121 if (!newDs.contains(ds))
2123 newDs.setElementAt(ds, i);
2124 ds = new Sequence(ds);
2125 // update with new dataset sequence
2126 sequences[i].setDatasetSequence(ds);
2130 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2135 // copy and derive new dataset sequence
2136 sequences[i] = sequences[i].deriveSequence();
2137 alignment.getDataset().addSequence(
2138 sequences[i].getDatasetSequence());
2139 // TODO: avoid creation of duplicate dataset sequences with a
2140 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2142 alignment.addSequence(sequences[i]); // merges dataset
2146 newDs.clear(); // tidy up
2148 if (alignment.getAlignmentAnnotation() != null)
2150 for (AlignmentAnnotation alan : alignment
2151 .getAlignmentAnnotation())
2153 if (alan.graphGroup > fgroup)
2155 fgroup = alan.graphGroup;
2159 if (pastedal.getAlignmentAnnotation() != null)
2161 // Add any annotation attached to alignment.
2162 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2163 for (int i = 0; i < alann.length; i++)
2165 annotationAdded = true;
2166 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2168 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2169 if (newann.graphGroup > -1)
2171 if (newGraphGroups.size() <= newann.graphGroup
2172 || newGraphGroups.get(newann.graphGroup) == null)
2174 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2176 newGraphGroups.add(q, null);
2178 newGraphGroups.set(newann.graphGroup, new Integer(
2181 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2185 newann.padAnnotation(alwidth);
2186 alignment.addAnnotation(newann);
2196 addHistoryItem(new EditCommand(
2197 MessageManager.getString("label.add_sequences"),
2198 Action.PASTE, sequences, 0, alignment.getWidth(), alignment));
2200 // Add any annotations attached to sequences
2201 for (int i = 0; i < sequences.length; i++)
2203 if (sequences[i].getAnnotation() != null)
2205 AlignmentAnnotation newann;
2206 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2208 annotationAdded = true;
2209 newann = sequences[i].getAnnotation()[a];
2210 newann.adjustForAlignment();
2211 newann.padAnnotation(alwidth);
2212 if (newann.graphGroup > -1)
2214 if (newann.graphGroup > -1)
2216 if (newGraphGroups.size() <= newann.graphGroup
2217 || newGraphGroups.get(newann.graphGroup) == null)
2219 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2221 newGraphGroups.add(q, null);
2223 newGraphGroups.set(newann.graphGroup, new Integer(
2226 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2230 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2235 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2242 // propagate alignment changed.
2243 vpRanges.setEndSeq(alignment.getHeight());
2244 if (annotationAdded)
2246 // Duplicate sequence annotation in all views.
2247 AlignmentI[] alview = this.getViewAlignments();
2248 for (int i = 0; i < sequences.length; i++)
2250 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2255 for (int avnum = 0; avnum < alview.length; avnum++)
2257 if (alview[avnum] != alignment)
2259 // duplicate in a view other than the one with input focus
2260 int avwidth = alview[avnum].getWidth() + 1;
2261 // this relies on sann being preserved after we
2262 // modify the sequence's annotation array for each duplication
2263 for (int a = 0; a < sann.length; a++)
2265 AlignmentAnnotation newann = new AlignmentAnnotation(
2267 sequences[i].addAlignmentAnnotation(newann);
2268 newann.padAnnotation(avwidth);
2269 alview[avnum].addAnnotation(newann); // annotation was
2270 // duplicated earlier
2271 // TODO JAL-1145 graphGroups are not updated for sequence
2272 // annotation added to several views. This may cause
2274 alview[avnum].setAnnotationIndex(newann, a);
2279 buildSortByAnnotationScoresMenu();
2281 viewport.firePropertyChange("alignment", null,
2282 alignment.getSequences());
2283 if (alignPanels != null)
2285 for (AlignmentPanel ap : alignPanels)
2287 ap.validateAnnotationDimensions(false);
2292 alignPanel.validateAnnotationDimensions(false);
2298 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2300 String newtitle = new String("Copied sequences");
2302 if (Desktop.jalviewClipboard != null
2303 && Desktop.jalviewClipboard[2] != null)
2305 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2306 for (int[] region : hc)
2308 af.viewport.hideColumns(region[0], region[1]);
2312 // >>>This is a fix for the moment, until a better solution is
2314 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2316 alignPanel.getSeqPanel().seqCanvas
2317 .getFeatureRenderer());
2319 // TODO: maintain provenance of an alignment, rather than just make the
2320 // title a concatenation of operations.
2323 if (title.startsWith("Copied sequences"))
2329 newtitle = newtitle.concat("- from " + title);
2334 newtitle = new String("Pasted sequences");
2337 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2342 } catch (Exception ex)
2344 ex.printStackTrace();
2345 System.out.println("Exception whilst pasting: " + ex);
2346 // could be anything being pasted in here
2351 protected void expand_newalign(ActionEvent e)
2355 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2356 .getAlignment(), -1);
2357 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2359 String newtitle = new String("Flanking alignment");
2361 if (Desktop.jalviewClipboard != null
2362 && Desktop.jalviewClipboard[2] != null)
2364 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2365 for (int region[] : hc)
2367 af.viewport.hideColumns(region[0], region[1]);
2371 // >>>This is a fix for the moment, until a better solution is
2373 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2375 alignPanel.getSeqPanel().seqCanvas
2376 .getFeatureRenderer());
2378 // TODO: maintain provenance of an alignment, rather than just make the
2379 // title a concatenation of operations.
2381 if (title.startsWith("Copied sequences"))
2387 newtitle = newtitle.concat("- from " + title);
2391 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2393 } catch (Exception ex)
2395 ex.printStackTrace();
2396 System.out.println("Exception whilst pasting: " + ex);
2397 // could be anything being pasted in here
2398 } catch (OutOfMemoryError oom)
2400 new OOMWarning("Viewing flanking region of alignment", oom);
2411 protected void cut_actionPerformed(ActionEvent e)
2413 copy_actionPerformed(null);
2414 delete_actionPerformed(null);
2424 protected void delete_actionPerformed(ActionEvent evt)
2427 SequenceGroup sg = viewport.getSelectionGroup();
2434 * If the cut affects all sequences, warn, remove highlighted columns
2436 if (sg.getSize() == viewport.getAlignment().getHeight())
2438 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes()) + 1) == viewport
2439 .getAlignment().getWidth()) ? true : false;
2440 if (isEntireAlignWidth)
2442 int confirm = JvOptionPane.showConfirmDialog(this,
2443 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2444 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2445 JvOptionPane.OK_CANCEL_OPTION);
2447 if (confirm == JvOptionPane.CANCEL_OPTION
2448 || confirm == JvOptionPane.CLOSED_OPTION)
2453 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2454 sg.getEndRes() + 1);
2456 SequenceI[] cut = sg.getSequences()
2457 .toArray(new SequenceI[sg.getSize()]);
2459 addHistoryItem(new EditCommand(
2460 MessageManager.getString("label.cut_sequences"), Action.CUT,
2461 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2462 viewport.getAlignment()));
2464 viewport.setSelectionGroup(null);
2465 viewport.sendSelection();
2466 viewport.getAlignment().deleteGroup(sg);
2468 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2470 if (viewport.getAlignment().getHeight() < 1)
2474 this.setClosed(true);
2475 } catch (Exception ex)
2488 protected void deleteGroups_actionPerformed(ActionEvent e)
2490 if (avc.deleteGroups())
2492 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2493 alignPanel.updateAnnotation();
2494 alignPanel.paintAlignment(true);
2505 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2507 SequenceGroup sg = new SequenceGroup();
2509 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2511 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2514 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2515 viewport.setSelectionGroup(sg);
2516 viewport.sendSelection();
2517 // JAL-2034 - should delegate to
2518 // alignPanel to decide if overview needs
2520 alignPanel.paintAlignment(false);
2521 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2531 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2533 if (viewport.cursorMode)
2535 alignPanel.getSeqPanel().keyboardNo1 = null;
2536 alignPanel.getSeqPanel().keyboardNo2 = null;
2538 viewport.setSelectionGroup(null);
2539 viewport.getColumnSelection().clear();
2540 viewport.setSelectionGroup(null);
2541 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2542 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2543 // JAL-2034 - should delegate to
2544 // alignPanel to decide if overview needs
2546 alignPanel.paintAlignment(false);
2547 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2548 viewport.sendSelection();
2558 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2560 SequenceGroup sg = viewport.getSelectionGroup();
2564 selectAllSequenceMenuItem_actionPerformed(null);
2569 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2571 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2573 // JAL-2034 - should delegate to
2574 // alignPanel to decide if overview needs
2577 alignPanel.paintAlignment(true);
2578 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2579 viewport.sendSelection();
2583 public void invertColSel_actionPerformed(ActionEvent e)
2585 viewport.invertColumnSelection();
2586 alignPanel.paintAlignment(true);
2587 viewport.sendSelection();
2597 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2599 trimAlignment(true);
2609 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2611 trimAlignment(false);
2614 void trimAlignment(boolean trimLeft)
2616 ColumnSelection colSel = viewport.getColumnSelection();
2619 if (!colSel.isEmpty())
2623 column = colSel.getMin();
2627 column = colSel.getMax();
2631 if (viewport.getSelectionGroup() != null)
2633 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2634 viewport.getHiddenRepSequences());
2638 seqs = viewport.getAlignment().getSequencesArray();
2641 TrimRegionCommand trimRegion;
2644 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2645 column, viewport.getAlignment());
2646 vpRanges.setStartRes(0);
2650 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2651 column, viewport.getAlignment());
2654 statusBar.setText(MessageManager.formatMessage(
2655 "label.removed_columns",
2656 new String[] { Integer.valueOf(trimRegion.getSize())
2659 addHistoryItem(trimRegion);
2661 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2663 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2664 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2666 viewport.getAlignment().deleteGroup(sg);
2670 viewport.firePropertyChange("alignment", null, viewport
2671 .getAlignment().getSequences());
2682 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2684 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2687 if (viewport.getSelectionGroup() != null)
2689 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2690 viewport.getHiddenRepSequences());
2691 start = viewport.getSelectionGroup().getStartRes();
2692 end = viewport.getSelectionGroup().getEndRes();
2696 seqs = viewport.getAlignment().getSequencesArray();
2699 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2700 "Remove Gapped Columns", seqs, start, end,
2701 viewport.getAlignment());
2703 addHistoryItem(removeGapCols);
2705 statusBar.setText(MessageManager.formatMessage(
2706 "label.removed_empty_columns",
2707 new Object[] { Integer.valueOf(removeGapCols.getSize())
2710 // This is to maintain viewport position on first residue
2711 // of first sequence
2712 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2713 int startRes = seq.findPosition(vpRanges.getStartRes());
2714 // ShiftList shifts;
2715 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2716 // edit.alColumnChanges=shifts.getInverse();
2717 // if (viewport.hasHiddenColumns)
2718 // viewport.getColumnSelection().compensateForEdits(shifts);
2719 vpRanges.setStartRes(seq.findIndex(startRes) - 1);
2720 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2732 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2734 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2737 if (viewport.getSelectionGroup() != null)
2739 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2740 viewport.getHiddenRepSequences());
2741 start = viewport.getSelectionGroup().getStartRes();
2742 end = viewport.getSelectionGroup().getEndRes();
2746 seqs = viewport.getAlignment().getSequencesArray();
2749 // This is to maintain viewport position on first residue
2750 // of first sequence
2751 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2752 int startRes = seq.findPosition(vpRanges.getStartRes());
2754 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2755 viewport.getAlignment()));
2757 vpRanges.setStartRes(seq.findIndex(startRes) - 1);
2759 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2771 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2773 viewport.setPadGaps(padGapsMenuitem.isSelected());
2774 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2785 public void findMenuItem_actionPerformed(ActionEvent e)
2791 * Create a new view of the current alignment.
2794 public void newView_actionPerformed(ActionEvent e)
2796 newView(null, true);
2800 * Creates and shows a new view of the current alignment.
2803 * title of newly created view; if null, one will be generated
2804 * @param copyAnnotation
2805 * if true then duplicate all annnotation, groups and settings
2806 * @return new alignment panel, already displayed.
2808 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2811 * Create a new AlignmentPanel (with its own, new Viewport)
2813 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2815 if (!copyAnnotation)
2818 * remove all groups and annotation except for the automatic stuff
2820 newap.av.getAlignment().deleteAllGroups();
2821 newap.av.getAlignment().deleteAllAnnotations(false);
2824 newap.av.setGatherViewsHere(false);
2826 if (viewport.viewName == null)
2828 viewport.viewName = MessageManager
2829 .getString("label.view_name_original");
2833 * Views share the same edits undo and redo stacks
2835 newap.av.setHistoryList(viewport.getHistoryList());
2836 newap.av.setRedoList(viewport.getRedoList());
2839 * Views share the same mappings; need to deregister any new mappings
2840 * created by copyAlignPanel, and register the new reference to the shared
2843 newap.av.replaceMappings(viewport.getAlignment());
2846 * start up cDNA consensus (if applicable) now mappings are in place
2848 if (newap.av.initComplementConsensus())
2850 newap.refresh(true); // adjust layout of annotations
2853 newap.av.viewName = getNewViewName(viewTitle);
2855 addAlignmentPanel(newap, true);
2856 newap.alignmentChanged();
2858 if (alignPanels.size() == 2)
2860 viewport.setGatherViewsHere(true);
2862 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2867 * Make a new name for the view, ensuring it is unique within the current
2868 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2869 * these now use viewId. Unique view names are still desirable for usability.)
2874 protected String getNewViewName(String viewTitle)
2876 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2877 boolean addFirstIndex = false;
2878 if (viewTitle == null || viewTitle.trim().length() == 0)
2880 viewTitle = MessageManager.getString("action.view");
2881 addFirstIndex = true;
2885 index = 1;// we count from 1 if given a specific name
2887 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2889 List<Component> comps = PaintRefresher.components.get(viewport
2890 .getSequenceSetId());
2892 List<String> existingNames = getExistingViewNames(comps);
2894 while (existingNames.contains(newViewName))
2896 newViewName = viewTitle + " " + (++index);
2902 * Returns a list of distinct view names found in the given list of
2903 * components. View names are held on the viewport of an AlignmentPanel.
2908 protected List<String> getExistingViewNames(List<Component> comps)
2910 List<String> existingNames = new ArrayList<>();
2911 for (Component comp : comps)
2913 if (comp instanceof AlignmentPanel)
2915 AlignmentPanel ap = (AlignmentPanel) comp;
2916 if (!existingNames.contains(ap.av.viewName))
2918 existingNames.add(ap.av.viewName);
2922 return existingNames;
2926 * Explode tabbed views into separate windows.
2929 public void expandViews_actionPerformed(ActionEvent e)
2931 Desktop.explodeViews(this);
2935 * Gather views in separate windows back into a tabbed presentation.
2938 public void gatherViews_actionPerformed(ActionEvent e)
2940 Desktop.instance.gatherViews(this);
2950 public void font_actionPerformed(ActionEvent e)
2952 new FontChooser(alignPanel);
2962 protected void seqLimit_actionPerformed(ActionEvent e)
2964 viewport.setShowJVSuffix(seqLimits.isSelected());
2966 alignPanel.getIdPanel().getIdCanvas()
2967 .setPreferredSize(alignPanel.calculateIdWidth());
2968 alignPanel.paintAlignment(true);
2972 public void idRightAlign_actionPerformed(ActionEvent e)
2974 viewport.setRightAlignIds(idRightAlign.isSelected());
2975 alignPanel.paintAlignment(true);
2979 public void centreColumnLabels_actionPerformed(ActionEvent e)
2981 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2982 alignPanel.paintAlignment(true);
2988 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2991 protected void followHighlight_actionPerformed()
2994 * Set the 'follow' flag on the Viewport (and scroll to position if now
2997 final boolean state = this.followHighlightMenuItem.getState();
2998 viewport.setFollowHighlight(state);
3001 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
3012 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3014 viewport.setColourText(colourTextMenuItem.isSelected());
3015 alignPanel.paintAlignment(true);
3025 public void wrapMenuItem_actionPerformed(ActionEvent e)
3027 scaleAbove.setVisible(wrapMenuItem.isSelected());
3028 scaleLeft.setVisible(wrapMenuItem.isSelected());
3029 scaleRight.setVisible(wrapMenuItem.isSelected());
3030 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3031 alignPanel.updateLayout();
3035 public void showAllSeqs_actionPerformed(ActionEvent e)
3037 viewport.showAllHiddenSeqs();
3041 public void showAllColumns_actionPerformed(ActionEvent e)
3043 viewport.showAllHiddenColumns();
3045 viewport.sendSelection();
3049 public void hideSelSequences_actionPerformed(ActionEvent e)
3051 viewport.hideAllSelectedSeqs();
3052 // alignPanel.paintAlignment(true);
3056 * called by key handler and the hide all/show all menu items
3061 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3064 boolean hide = false;
3065 SequenceGroup sg = viewport.getSelectionGroup();
3066 if (!toggleSeqs && !toggleCols)
3068 // Hide everything by the current selection - this is a hack - we do the
3069 // invert and then hide
3070 // first check that there will be visible columns after the invert.
3071 if (viewport.hasSelectedColumns()
3072 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
3075 // now invert the sequence set, if required - empty selection implies
3076 // that no hiding is required.
3079 invertSequenceMenuItem_actionPerformed(null);
3080 sg = viewport.getSelectionGroup();
3084 viewport.expandColSelection(sg, true);
3085 // finally invert the column selection and get the new sequence
3087 invertColSel_actionPerformed(null);
3094 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3096 hideSelSequences_actionPerformed(null);
3099 else if (!(toggleCols && viewport.hasSelectedColumns()))
3101 showAllSeqs_actionPerformed(null);
3107 if (viewport.hasSelectedColumns())
3109 hideSelColumns_actionPerformed(null);
3112 viewport.setSelectionGroup(sg);
3117 showAllColumns_actionPerformed(null);
3126 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3127 * event.ActionEvent)
3130 public void hideAllButSelection_actionPerformed(ActionEvent e)
3132 toggleHiddenRegions(false, false);
3133 viewport.sendSelection();
3140 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3144 public void hideAllSelection_actionPerformed(ActionEvent e)
3146 SequenceGroup sg = viewport.getSelectionGroup();
3147 viewport.expandColSelection(sg, false);
3148 viewport.hideAllSelectedSeqs();
3149 viewport.hideSelectedColumns();
3150 alignPanel.paintAlignment(true);
3151 viewport.sendSelection();
3158 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3162 public void showAllhidden_actionPerformed(ActionEvent e)
3164 viewport.showAllHiddenColumns();
3165 viewport.showAllHiddenSeqs();
3166 alignPanel.paintAlignment(true);
3167 viewport.sendSelection();
3171 public void hideSelColumns_actionPerformed(ActionEvent e)
3173 viewport.hideSelectedColumns();
3174 alignPanel.paintAlignment(true);
3175 viewport.sendSelection();
3179 public void hiddenMarkers_actionPerformed(ActionEvent e)
3181 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3192 protected void scaleAbove_actionPerformed(ActionEvent e)
3194 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3195 alignPanel.paintAlignment(true);
3205 protected void scaleLeft_actionPerformed(ActionEvent e)
3207 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3208 alignPanel.paintAlignment(true);
3218 protected void scaleRight_actionPerformed(ActionEvent e)
3220 viewport.setScaleRightWrapped(scaleRight.isSelected());
3221 alignPanel.paintAlignment(true);
3231 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3233 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3234 alignPanel.paintAlignment(true);
3244 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3246 viewport.setShowText(viewTextMenuItem.isSelected());
3247 alignPanel.paintAlignment(true);
3257 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3259 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3260 alignPanel.paintAlignment(true);
3263 public FeatureSettings featureSettings;
3266 public FeatureSettingsControllerI getFeatureSettingsUI()
3268 return featureSettings;
3272 public void featureSettings_actionPerformed(ActionEvent e)
3274 if (featureSettings != null)
3276 featureSettings.close();
3277 featureSettings = null;
3279 if (!showSeqFeatures.isSelected())
3281 // make sure features are actually displayed
3282 showSeqFeatures.setSelected(true);
3283 showSeqFeatures_actionPerformed(null);
3285 featureSettings = new FeatureSettings(this);
3289 * Set or clear 'Show Sequence Features'
3295 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3297 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3298 alignPanel.paintAlignment(true);
3299 if (alignPanel.getOverviewPanel() != null)
3301 alignPanel.getOverviewPanel().updateOverviewImage();
3306 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3307 * the annotations panel as a whole.
3309 * The options to show/hide all annotations should be enabled when the panel
3310 * is shown, and disabled when the panel is hidden.
3315 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3317 final boolean setVisible = annotationPanelMenuItem.isSelected();
3318 viewport.setShowAnnotation(setVisible);
3319 this.showAllSeqAnnotations.setEnabled(setVisible);
3320 this.hideAllSeqAnnotations.setEnabled(setVisible);
3321 this.showAllAlAnnotations.setEnabled(setVisible);
3322 this.hideAllAlAnnotations.setEnabled(setVisible);
3323 alignPanel.updateLayout();
3327 public void alignmentProperties()
3329 JEditorPane editPane = new JEditorPane("text/html", "");
3330 editPane.setEditable(false);
3331 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3333 editPane.setText(MessageManager.formatMessage("label.html_content",
3334 new Object[] { contents.toString() }));
3335 JInternalFrame frame = new JInternalFrame();
3336 frame.getContentPane().add(new JScrollPane(editPane));
3338 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3339 "label.alignment_properties", new Object[] { getTitle() }),
3350 public void overviewMenuItem_actionPerformed(ActionEvent e)
3352 if (alignPanel.overviewPanel != null)
3357 JInternalFrame frame = new JInternalFrame();
3358 OverviewPanel overview = new OverviewPanel(alignPanel);
3359 frame.setContentPane(overview);
3360 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3361 "label.overview_params", new Object[] { this.getTitle() }),
3362 true, frame.getWidth(), frame.getHeight(), true, true);
3364 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3365 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3368 public void internalFrameClosed(
3369 javax.swing.event.InternalFrameEvent evt)
3371 alignPanel.setOverviewPanel(null);
3375 alignPanel.setOverviewPanel(overview);
3379 public void textColour_actionPerformed()
3381 new TextColourChooser().chooseColour(alignPanel, null);
3385 * public void covariationColour_actionPerformed() {
3387 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3391 public void annotationColour_actionPerformed()
3393 new AnnotationColourChooser(viewport, alignPanel);
3397 public void annotationColumn_actionPerformed(ActionEvent e)
3399 new AnnotationColumnChooser(viewport, alignPanel);
3403 * Action on the user checking or unchecking the option to apply the selected
3404 * colour scheme to all groups. If unchecked, groups may have their own
3405 * independent colour schemes.
3410 public void applyToAllGroups_actionPerformed(boolean selected)
3412 viewport.setColourAppliesToAllGroups(selected);
3416 * Action on user selecting a colour from the colour menu
3419 * the name (not the menu item label!) of the colour scheme
3422 public void changeColour_actionPerformed(String name)
3425 * 'User Defined' opens a panel to configure or load a
3426 * user-defined colour scheme
3428 if (ResidueColourScheme.USER_DEFINED.equals(name))
3430 new UserDefinedColours(alignPanel);
3435 * otherwise set the chosen colour scheme (or null for 'None')
3437 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3438 viewport.getAlignment(), viewport.getHiddenRepSequences());
3443 * Actions on setting or changing the alignment colour scheme
3448 public void changeColour(ColourSchemeI cs)
3450 // TODO: pull up to controller method
3451 ColourMenuHelper.setColourSelected(colourMenu, cs);
3453 viewport.setGlobalColourScheme(cs);
3455 alignPanel.paintAlignment(true);
3459 * Show the PID threshold slider panel
3462 protected void modifyPID_actionPerformed()
3464 SliderPanel.setPIDSliderSource(alignPanel,
3465 viewport.getResidueShading(), alignPanel.getViewName());
3466 SliderPanel.showPIDSlider();
3470 * Show the Conservation slider panel
3473 protected void modifyConservation_actionPerformed()
3475 SliderPanel.setConservationSlider(alignPanel,
3476 viewport.getResidueShading(), alignPanel.getViewName());
3477 SliderPanel.showConservationSlider();
3481 * Action on selecting or deselecting (Colour) By Conservation
3484 public void conservationMenuItem_actionPerformed(boolean selected)
3486 modifyConservation.setEnabled(selected);
3487 viewport.setConservationSelected(selected);
3488 viewport.getResidueShading().setConservationApplied(selected);
3490 changeColour(viewport.getGlobalColourScheme());
3493 modifyConservation_actionPerformed();
3497 SliderPanel.hideConservationSlider();
3502 * Action on selecting or deselecting (Colour) Above PID Threshold
3505 public void abovePIDThreshold_actionPerformed(boolean selected)
3507 modifyPID.setEnabled(selected);
3508 viewport.setAbovePIDThreshold(selected);
3511 viewport.getResidueShading().setThreshold(0,
3512 viewport.isIgnoreGapsConsensus());
3515 changeColour(viewport.getGlobalColourScheme());
3518 modifyPID_actionPerformed();
3522 SliderPanel.hidePIDSlider();
3533 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3535 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3536 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3537 .getAlignment().getSequenceAt(0));
3538 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3539 viewport.getAlignment()));
3540 alignPanel.paintAlignment(true);
3550 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3552 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3553 AlignmentSorter.sortByID(viewport.getAlignment());
3554 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3555 viewport.getAlignment()));
3556 alignPanel.paintAlignment(true);
3566 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3568 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3569 AlignmentSorter.sortByLength(viewport.getAlignment());
3570 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3571 viewport.getAlignment()));
3572 alignPanel.paintAlignment(true);
3582 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3584 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3585 AlignmentSorter.sortByGroup(viewport.getAlignment());
3586 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3587 viewport.getAlignment()));
3589 alignPanel.paintAlignment(true);
3599 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3601 new RedundancyPanel(alignPanel, this);
3611 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3613 if ((viewport.getSelectionGroup() == null)
3614 || (viewport.getSelectionGroup().getSize() < 2))
3616 JvOptionPane.showInternalMessageDialog(this, MessageManager
3617 .getString("label.you_must_select_least_two_sequences"),
3618 MessageManager.getString("label.invalid_selection"),
3619 JvOptionPane.WARNING_MESSAGE);
3623 JInternalFrame frame = new JInternalFrame();
3624 frame.setContentPane(new PairwiseAlignPanel(viewport));
3625 Desktop.addInternalFrame(frame,
3626 MessageManager.getString("action.pairwise_alignment"), 600,
3632 public void autoCalculate_actionPerformed(ActionEvent e)
3634 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3635 if (viewport.autoCalculateConsensus)
3637 viewport.firePropertyChange("alignment", null, viewport
3638 .getAlignment().getSequences());
3643 public void sortByTreeOption_actionPerformed(ActionEvent e)
3645 viewport.sortByTree = sortByTree.isSelected();
3649 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3651 viewport.followSelection = listenToViewSelections.isSelected();
3655 * Constructs a tree panel and adds it to the desktop
3658 * tree type (NJ or AV)
3660 * name of score model used to compute the tree
3662 * parameters for the distance or similarity calculation
3664 void newTreePanel(String type, String modelName, SimilarityParamsI options)
3666 String frameTitle = "";
3669 boolean onSelection = false;
3670 if (viewport.getSelectionGroup() != null
3671 && viewport.getSelectionGroup().getSize() > 0)
3673 SequenceGroup sg = viewport.getSelectionGroup();
3675 /* Decide if the selection is a column region */
3676 for (SequenceI _s : sg.getSequences())
3678 if (_s.getLength() < sg.getEndRes())
3684 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3686 .getString("label.sequences_selection_not_aligned"),
3687 JvOptionPane.WARNING_MESSAGE);
3696 if (viewport.getAlignment().getHeight() < 2)
3702 tp = new TreePanel(alignPanel, type, modelName, options);
3703 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3705 frameTitle += " from ";
3707 if (viewport.viewName != null)
3709 frameTitle += viewport.viewName + " of ";
3712 frameTitle += this.title;
3714 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3725 public void addSortByOrderMenuItem(String title,
3726 final AlignmentOrder order)
3728 final JMenuItem item = new JMenuItem(MessageManager.formatMessage(
3729 "action.by_title_param", new Object[] { title }));
3731 item.addActionListener(new java.awt.event.ActionListener()
3734 public void actionPerformed(ActionEvent e)
3736 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3738 // TODO: JBPNote - have to map order entries to curent SequenceI
3740 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3742 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
3745 alignPanel.paintAlignment(true);
3751 * Add a new sort by annotation score menu item
3754 * the menu to add the option to
3756 * the label used to retrieve scores for each sequence on the
3759 public void addSortByAnnotScoreMenuItem(JMenu sort,
3760 final String scoreLabel)
3762 final JMenuItem item = new JMenuItem(scoreLabel);
3764 item.addActionListener(new java.awt.event.ActionListener()
3767 public void actionPerformed(ActionEvent e)
3769 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3770 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3771 viewport.getAlignment());// ,viewport.getSelectionGroup());
3772 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3773 viewport.getAlignment()));
3774 alignPanel.paintAlignment(true);
3780 * last hash for alignment's annotation array - used to minimise cost of
3783 protected int _annotationScoreVectorHash;
3786 * search the alignment and rebuild the sort by annotation score submenu the
3787 * last alignment annotation vector hash is stored to minimize cost of
3788 * rebuilding in subsequence calls.
3792 public void buildSortByAnnotationScoresMenu()
3794 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3799 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
3801 sortByAnnotScore.removeAll();
3802 // almost certainly a quicker way to do this - but we keep it simple
3803 Hashtable scoreSorts = new Hashtable();
3804 AlignmentAnnotation aann[];
3805 for (SequenceI sqa : viewport.getAlignment().getSequences())
3807 aann = sqa.getAnnotation();
3808 for (int i = 0; aann != null && i < aann.length; i++)
3810 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3812 scoreSorts.put(aann[i].label, aann[i].label);
3816 Enumeration labels = scoreSorts.keys();
3817 while (labels.hasMoreElements())
3819 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3820 (String) labels.nextElement());
3822 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3825 _annotationScoreVectorHash = viewport.getAlignment()
3826 .getAlignmentAnnotation().hashCode();
3831 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3832 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3833 * call. Listeners are added to remove the menu item when the treePanel is
3834 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3838 public void buildTreeSortMenu()
3840 sortByTreeMenu.removeAll();
3842 List<Component> comps = PaintRefresher.components.get(viewport
3843 .getSequenceSetId());
3844 List<TreePanel> treePanels = new ArrayList<>();
3845 for (Component comp : comps)
3847 if (comp instanceof TreePanel)
3849 treePanels.add((TreePanel) comp);
3853 if (treePanels.size() < 1)
3855 sortByTreeMenu.setVisible(false);
3859 sortByTreeMenu.setVisible(true);
3861 for (final TreePanel tp : treePanels)
3863 final JMenuItem item = new JMenuItem(tp.getTitle());
3864 item.addActionListener(new java.awt.event.ActionListener()
3867 public void actionPerformed(ActionEvent e)
3869 tp.sortByTree_actionPerformed();
3870 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3875 sortByTreeMenu.add(item);
3879 public boolean sortBy(AlignmentOrder alorder, String undoname)
3881 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3882 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3883 if (undoname != null)
3885 addHistoryItem(new OrderCommand(undoname, oldOrder,
3886 viewport.getAlignment()));
3888 alignPanel.paintAlignment(true);
3893 * Work out whether the whole set of sequences or just the selected set will
3894 * be submitted for multiple alignment.
3897 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3899 // Now, check we have enough sequences
3900 AlignmentView msa = null;
3902 if ((viewport.getSelectionGroup() != null)
3903 && (viewport.getSelectionGroup().getSize() > 1))
3905 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3906 // some common interface!
3908 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3909 * SequenceI[sz = seqs.getSize(false)];
3911 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3912 * seqs.getSequenceAt(i); }
3914 msa = viewport.getAlignmentView(true);
3916 else if (viewport.getSelectionGroup() != null
3917 && viewport.getSelectionGroup().getSize() == 1)
3919 int option = JvOptionPane.showConfirmDialog(this,
3920 MessageManager.getString("warn.oneseq_msainput_selection"),
3921 MessageManager.getString("label.invalid_selection"),
3922 JvOptionPane.OK_CANCEL_OPTION);
3923 if (option == JvOptionPane.OK_OPTION)
3925 msa = viewport.getAlignmentView(false);
3930 msa = viewport.getAlignmentView(false);
3936 * Decides what is submitted to a secondary structure prediction service: the
3937 * first sequence in the alignment, or in the current selection, or, if the
3938 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3939 * region or the whole alignment. (where the first sequence in the set is the
3940 * one that the prediction will be for).
3942 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3944 AlignmentView seqs = null;
3946 if ((viewport.getSelectionGroup() != null)
3947 && (viewport.getSelectionGroup().getSize() > 0))
3949 seqs = viewport.getAlignmentView(true);
3953 seqs = viewport.getAlignmentView(false);
3955 // limit sequences - JBPNote in future - could spawn multiple prediction
3957 // TODO: viewport.getAlignment().isAligned is a global state - the local
3958 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3959 if (!viewport.getAlignment().isAligned(false))
3961 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3962 // TODO: if seqs.getSequences().length>1 then should really have warned
3976 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3978 // Pick the tree file
3979 JalviewFileChooser chooser = new JalviewFileChooser(
3980 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3981 chooser.setFileView(new JalviewFileView());
3982 chooser.setDialogTitle(MessageManager
3983 .getString("label.select_newick_like_tree_file"));
3984 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
3986 int value = chooser.showOpenDialog(null);
3988 if (value == JalviewFileChooser.APPROVE_OPTION)
3990 String filePath = chooser.getSelectedFile().getPath();
3991 Cache.setProperty("LAST_DIRECTORY", filePath);
3992 NewickFile fin = null;
3995 fin = new NewickFile(filePath, DataSourceType.FILE);
3996 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
3997 } catch (Exception ex)
4004 .getString("label.problem_reading_tree_file"),
4005 JvOptionPane.WARNING_MESSAGE);
4006 ex.printStackTrace();
4008 if (fin != null && fin.hasWarningMessage())
4010 JvOptionPane.showMessageDialog(Desktop.desktop, fin
4011 .getWarningMessage(), MessageManager
4012 .getString("label.possible_problem_with_tree_file"),
4013 JvOptionPane.WARNING_MESSAGE);
4018 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4020 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4023 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4024 int h, int x, int y)
4026 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4030 * Add a treeviewer for the tree extracted from a Newick file object to the
4031 * current alignment view
4038 * Associated alignment input data (or null)
4047 * @return TreePanel handle
4049 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4050 AlignmentView input, int w, int h, int x, int y)
4052 TreePanel tp = null;
4058 if (nf.getTree() != null)
4060 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4066 tp.setLocation(x, y);
4069 Desktop.addInternalFrame(tp, treeTitle, w, h);
4071 } catch (Exception ex)
4073 ex.printStackTrace();
4079 private boolean buildingMenu = false;
4082 * Generates menu items and listener event actions for web service clients
4085 public void BuildWebServiceMenu()
4087 while (buildingMenu)
4091 System.err.println("Waiting for building menu to finish.");
4093 } catch (Exception e)
4097 final AlignFrame me = this;
4098 buildingMenu = true;
4099 new Thread(new Runnable()
4104 final List<JMenuItem> legacyItems = new ArrayList<>();
4107 // System.err.println("Building ws menu again "
4108 // + Thread.currentThread());
4109 // TODO: add support for context dependent disabling of services based
4111 // alignment and current selection
4112 // TODO: add additional serviceHandle parameter to specify abstract
4114 // class independently of AbstractName
4115 // TODO: add in rediscovery GUI function to restart discoverer
4116 // TODO: group services by location as well as function and/or
4118 // object broker mechanism.
4119 final Vector<JMenu> wsmenu = new Vector<>();
4120 final IProgressIndicator af = me;
4123 * do not i18n these strings - they are hard-coded in class
4124 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4125 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4127 final JMenu msawsmenu = new JMenu("Alignment");
4128 final JMenu secstrmenu = new JMenu(
4129 "Secondary Structure Prediction");
4130 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4131 final JMenu analymenu = new JMenu("Analysis");
4132 final JMenu dismenu = new JMenu("Protein Disorder");
4133 // JAL-940 - only show secondary structure prediction services from
4134 // the legacy server
4135 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4137 Discoverer.services != null && (Discoverer.services.size() > 0))
4139 // TODO: refactor to allow list of AbstractName/Handler bindings to
4141 // stored or retrieved from elsewhere
4142 // No MSAWS used any more:
4143 // Vector msaws = null; // (Vector)
4144 // Discoverer.services.get("MsaWS");
4145 Vector secstrpr = (Vector) Discoverer.services
4147 if (secstrpr != null)
4149 // Add any secondary structure prediction services
4150 for (int i = 0, j = secstrpr.size(); i < j; i++)
4152 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4154 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4155 .getServiceClient(sh);
4156 int p = secstrmenu.getItemCount();
4157 impl.attachWSMenuEntry(secstrmenu, me);
4158 int q = secstrmenu.getItemCount();
4159 for (int litm = p; litm < q; litm++)
4161 legacyItems.add(secstrmenu.getItem(litm));
4167 // Add all submenus in the order they should appear on the web
4169 wsmenu.add(msawsmenu);
4170 wsmenu.add(secstrmenu);
4171 wsmenu.add(dismenu);
4172 wsmenu.add(analymenu);
4173 // No search services yet
4174 // wsmenu.add(seqsrchmenu);
4176 javax.swing.SwingUtilities.invokeLater(new Runnable()
4183 webService.removeAll();
4184 // first, add discovered services onto the webservices menu
4185 if (wsmenu.size() > 0)
4187 for (int i = 0, j = wsmenu.size(); i < j; i++)
4189 webService.add(wsmenu.get(i));
4194 webService.add(me.webServiceNoServices);
4196 // TODO: move into separate menu builder class.
4197 boolean new_sspred = false;
4198 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4200 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4201 if (jws2servs != null)
4203 if (jws2servs.hasServices())
4205 jws2servs.attachWSMenuEntry(webService, me);
4206 for (Jws2Instance sv : jws2servs.getServices())
4208 if (sv.description.toLowerCase().contains("jpred"))
4210 for (JMenuItem jmi : legacyItems)
4212 jmi.setVisible(false);
4218 if (jws2servs.isRunning())
4220 JMenuItem tm = new JMenuItem(
4221 "Still discovering JABA Services");
4222 tm.setEnabled(false);
4227 build_urlServiceMenu(me.webService);
4228 build_fetchdbmenu(webService);
4229 for (JMenu item : wsmenu)
4231 if (item.getItemCount() == 0)
4233 item.setEnabled(false);
4237 item.setEnabled(true);
4240 } catch (Exception e)
4243 .debug("Exception during web service menu building process.",
4248 } catch (Exception e)
4251 buildingMenu = false;
4258 * construct any groupURL type service menu entries.
4262 private void build_urlServiceMenu(JMenu webService)
4264 // TODO: remove this code when 2.7 is released
4265 // DEBUG - alignmentView
4267 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4268 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4270 * @Override public void actionPerformed(ActionEvent e) {
4271 * jalview.datamodel.AlignmentView
4272 * .testSelectionViews(af.viewport.getAlignment(),
4273 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4275 * }); webService.add(testAlView);
4277 // TODO: refactor to RestClient discoverer and merge menu entries for
4278 // rest-style services with other types of analysis/calculation service
4279 // SHmmr test client - still being implemented.
4280 // DEBUG - alignmentView
4282 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4285 client.attachWSMenuEntry(
4286 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4292 * Searches the alignment sequences for xRefs and builds the Show
4293 * Cross-References menu (formerly called Show Products), with database
4294 * sources for which cross-references are found (protein sources for a
4295 * nucleotide alignment and vice versa)
4297 * @return true if Show Cross-references menu should be enabled
4299 public boolean canShowProducts()
4301 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4302 AlignmentI dataset = viewport.getAlignment().getDataset();
4304 showProducts.removeAll();
4305 final boolean dna = viewport.getAlignment().isNucleotide();
4307 if (seqs == null || seqs.length == 0)
4309 // nothing to see here.
4313 boolean showp = false;
4316 List<String> ptypes = new CrossRef(seqs, dataset)
4317 .findXrefSourcesForSequences(dna);
4319 for (final String source : ptypes)
4322 final AlignFrame af = this;
4323 JMenuItem xtype = new JMenuItem(source);
4324 xtype.addActionListener(new ActionListener()
4327 public void actionPerformed(ActionEvent e)
4329 showProductsFor(af.viewport.getSequenceSelection(), dna, source);
4332 showProducts.add(xtype);
4334 showProducts.setVisible(showp);
4335 showProducts.setEnabled(showp);
4336 } catch (Exception e)
4339 .warn("canShowProducts threw an exception - please report to help@jalview.org",
4347 * Finds and displays cross-references for the selected sequences (protein
4348 * products for nucleotide sequences, dna coding sequences for peptides).
4351 * the sequences to show cross-references for
4353 * true if from a nucleotide alignment (so showing proteins)
4355 * the database to show cross-references for
4357 protected void showProductsFor(final SequenceI[] sel,
4358 final boolean _odna, final String source)
4360 new Thread(CrossRefAction.showProductsFor(sel, _odna, source, this))
4365 * Construct and display a new frame containing the translation of this
4366 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4369 public void showTranslation_actionPerformed(ActionEvent e)
4371 AlignmentI al = null;
4374 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4376 al = dna.translateCdna();
4377 } catch (Exception ex)
4379 jalview.bin.Cache.log.error(
4380 "Exception during translation. Please report this !", ex);
4381 final String msg = MessageManager
4382 .getString("label.error_when_translating_sequences_submit_bug_report");
4383 final String errorTitle = MessageManager
4384 .getString("label.implementation_error")
4385 + MessageManager.getString("label.translation_failed");
4386 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4387 JvOptionPane.ERROR_MESSAGE);
4390 if (al == null || al.getHeight() == 0)
4392 final String msg = MessageManager
4393 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4394 final String errorTitle = MessageManager
4395 .getString("label.translation_failed");
4396 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4397 JvOptionPane.WARNING_MESSAGE);
4401 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4402 af.setFileFormat(this.currentFileFormat);
4403 final String newTitle = MessageManager.formatMessage(
4404 "label.translation_of_params",
4405 new Object[] { this.getTitle() });
4406 af.setTitle(newTitle);
4407 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4409 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4410 viewport.openSplitFrame(af, new Alignment(seqs));
4414 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4421 * Set the file format
4425 public void setFileFormat(FileFormatI format)
4427 this.currentFileFormat = format;
4431 * Try to load a features file onto the alignment.
4434 * contents or path to retrieve file
4436 * access mode of file (see jalview.io.AlignFile)
4437 * @return true if features file was parsed correctly.
4439 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4441 return avc.parseFeaturesFile(file, sourceType,
4442 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4447 public void refreshFeatureUI(boolean enableIfNecessary)
4449 // note - currently this is only still here rather than in the controller
4450 // because of the featureSettings hard reference that is yet to be
4452 if (enableIfNecessary)
4454 viewport.setShowSequenceFeatures(true);
4455 showSeqFeatures.setSelected(true);
4461 public void dragEnter(DropTargetDragEvent evt)
4466 public void dragExit(DropTargetEvent evt)
4471 public void dragOver(DropTargetDragEvent evt)
4476 public void dropActionChanged(DropTargetDragEvent evt)
4481 public void drop(DropTargetDropEvent evt)
4483 // JAL-1552 - acceptDrop required before getTransferable call for
4484 // Java's Transferable for native dnd
4485 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4486 Transferable t = evt.getTransferable();
4487 List<String> files = new ArrayList<>();
4488 List<DataSourceType> protocols = new ArrayList<>();
4492 Desktop.transferFromDropTarget(files, protocols, evt, t);
4493 } catch (Exception e)
4495 e.printStackTrace();
4501 // check to see if any of these files have names matching sequences in
4503 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4504 .getAlignment().getSequencesArray());
4506 * Object[] { String,SequenceI}
4508 ArrayList<Object[]> filesmatched = new ArrayList<>();
4509 ArrayList<String> filesnotmatched = new ArrayList<>();
4510 for (int i = 0; i < files.size(); i++)
4512 String file = files.get(i).toString();
4514 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4515 if (protocol == DataSourceType.FILE)
4517 File fl = new File(file);
4518 pdbfn = fl.getName();
4520 else if (protocol == DataSourceType.URL)
4522 URL url = new URL(file);
4523 pdbfn = url.getFile();
4525 if (pdbfn.length() > 0)
4527 // attempt to find a match in the alignment
4528 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4529 int l = 0, c = pdbfn.indexOf(".");
4530 while (mtch == null && c != -1)
4535 } while ((c = pdbfn.indexOf(".", l)) > l);
4538 pdbfn = pdbfn.substring(0, l);
4540 mtch = idm.findAllIdMatches(pdbfn);
4544 FileFormatI type = null;
4547 type = new IdentifyFile().identify(file, protocol);
4548 } catch (Exception ex)
4552 if (type != null && type.isStructureFile())
4554 filesmatched.add(new Object[] { file, protocol, mtch });
4558 // File wasn't named like one of the sequences or wasn't a PDB file.
4559 filesnotmatched.add(file);
4563 if (filesmatched.size() > 0)
4565 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4571 "label.automatically_associate_structure_files_with_sequences_same_name",
4572 new Object[] { Integer
4578 .getString("label.automatically_associate_structure_files_by_name"),
4579 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION)
4582 for (Object[] fm : filesmatched)
4584 // try and associate
4585 // TODO: may want to set a standard ID naming formalism for
4586 // associating PDB files which have no IDs.
4587 for (SequenceI toassoc : (SequenceI[]) fm[2])
4589 PDBEntry pe = new AssociatePdbFileWithSeq()
4590 .associatePdbWithSeq((String) fm[0],
4591 (DataSourceType) fm[1], toassoc, false,
4595 System.err.println("Associated file : "
4596 + ((String) fm[0]) + " with "
4597 + toassoc.getDisplayId(true));
4601 alignPanel.paintAlignment(true);
4605 if (filesnotmatched.size() > 0)
4608 && (Cache.getDefault(
4609 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JvOptionPane
4615 "label.ignore_unmatched_dropped_files_info",
4616 new Object[] { Integer
4623 .getString("label.ignore_unmatched_dropped_files"),
4624 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4628 for (String fn : filesnotmatched)
4630 loadJalviewDataFile(fn, null, null, null);
4634 } catch (Exception ex)
4636 ex.printStackTrace();
4642 * Attempt to load a "dropped" file or URL string, by testing in turn for
4644 * <li>an Annotation file</li>
4645 * <li>a JNet file</li>
4646 * <li>a features file</li>
4647 * <li>else try to interpret as an alignment file</li>
4651 * either a filename or a URL string.
4652 * @throws InterruptedException
4653 * @throws IOException
4655 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4656 FileFormatI format, SequenceI assocSeq)
4660 if (sourceType == null)
4662 sourceType = FormatAdapter.checkProtocol(file);
4664 // if the file isn't identified, or not positively identified as some
4665 // other filetype (PFAM is default unidentified alignment file type) then
4666 // try to parse as annotation.
4667 boolean isAnnotation = (format == null || FileFormat.Pfam
4668 .equals(format)) ? new AnnotationFile()
4669 .annotateAlignmentView(viewport, file, sourceType) : false;
4673 // first see if its a T-COFFEE score file
4674 TCoffeeScoreFile tcf = null;
4677 tcf = new TCoffeeScoreFile(file, sourceType);
4680 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4683 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
4684 isAnnotation = true;
4686 .setText(MessageManager
4687 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
4691 // some problem - if no warning its probable that the ID matching
4692 // process didn't work
4696 tcf.getWarningMessage() == null ? MessageManager
4697 .getString("label.check_file_matches_sequence_ids_alignment")
4698 : tcf.getWarningMessage(),
4700 .getString("label.problem_reading_tcoffee_score_file"),
4701 JvOptionPane.WARNING_MESSAGE);
4708 } catch (Exception x)
4711 .debug("Exception when processing data source as T-COFFEE score file",
4717 // try to see if its a JNet 'concise' style annotation file *before*
4719 // try to parse it as a features file
4722 format = new IdentifyFile().identify(file, sourceType);
4724 if (FileFormat.ScoreMatrix == format)
4726 ScoreMatrixFile sm = new ScoreMatrixFile(new FileParse(file,
4729 // todo: i18n this message
4731 .setText(MessageManager.formatMessage(
4732 "label.successfully_loaded_matrix",
4733 sm.getMatrixName()));
4735 else if (FileFormat.Jnet.equals(format))
4737 JPredFile predictions = new JPredFile(file, sourceType);
4738 new JnetAnnotationMaker();
4739 JnetAnnotationMaker.add_annotation(predictions,
4740 viewport.getAlignment(), 0, false);
4741 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
4742 viewport.getAlignment().setSeqrep(repseq);
4743 HiddenColumns cs = new HiddenColumns();
4744 cs.hideInsertionsFor(repseq);
4745 viewport.getAlignment().setHiddenColumns(cs);
4746 isAnnotation = true;
4748 // else if (IdentifyFile.FeaturesFile.equals(format))
4749 else if (FileFormat.Features.equals(format))
4751 if (parseFeaturesFile(file, sourceType))
4753 alignPanel.paintAlignment(true);
4758 new FileLoader().LoadFile(viewport, file, sourceType, format);
4764 alignPanel.adjustAnnotationHeight();
4765 viewport.updateSequenceIdColours();
4766 buildSortByAnnotationScoresMenu();
4767 alignPanel.paintAlignment(true);
4769 } catch (Exception ex)
4771 ex.printStackTrace();
4772 } catch (OutOfMemoryError oom)
4777 } catch (Exception x)
4782 + (sourceType != null ? (sourceType == DataSourceType.PASTE ? "from clipboard."
4783 : "using " + sourceType + " from " + file)
4785 + (format != null ? "(parsing as '" + format
4786 + "' file)" : ""), oom, Desktop.desktop);
4791 * Method invoked by the ChangeListener on the tabbed pane, in other words
4792 * when a different tabbed pane is selected by the user or programmatically.
4795 public void tabSelectionChanged(int index)
4799 alignPanel = alignPanels.get(index);
4800 viewport = alignPanel.av;
4801 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4802 setMenusFromViewport(viewport);
4806 * 'focus' any colour slider that is open to the selected viewport
4808 if (viewport.getConservationSelected())
4810 SliderPanel.setConservationSlider(alignPanel,
4811 viewport.getResidueShading(), alignPanel.getViewName());
4815 SliderPanel.hideConservationSlider();
4817 if (viewport.getAbovePIDThreshold())
4819 SliderPanel.setPIDSliderSource(alignPanel,
4820 viewport.getResidueShading(), alignPanel.getViewName());
4824 SliderPanel.hidePIDSlider();
4828 * If there is a frame linked to this one in a SplitPane, switch it to the
4829 * same view tab index. No infinite recursion of calls should happen, since
4830 * tabSelectionChanged() should not get invoked on setting the selected
4831 * index to an unchanged value. Guard against setting an invalid index
4832 * before the new view peer tab has been created.
4834 final AlignViewportI peer = viewport.getCodingComplement();
4837 AlignFrame linkedAlignFrame = ((AlignViewport) peer).getAlignPanel().alignFrame;
4838 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4840 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4846 * On right mouse click on view tab, prompt for and set new view name.
4849 public void tabbedPane_mousePressed(MouseEvent e)
4851 if (e.isPopupTrigger())
4853 String msg = MessageManager.getString("label.enter_view_name");
4854 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4855 JvOptionPane.QUESTION_MESSAGE);
4859 viewport.viewName = reply;
4860 // TODO warn if reply is in getExistingViewNames()?
4861 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4866 public AlignViewport getCurrentView()
4872 * Open the dialog for regex description parsing.
4875 protected void extractScores_actionPerformed(ActionEvent e)
4877 ParseProperties pp = new jalview.analysis.ParseProperties(
4878 viewport.getAlignment());
4879 // TODO: verify regex and introduce GUI dialog for version 2.5
4880 // if (pp.getScoresFromDescription("col", "score column ",
4881 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4883 if (pp.getScoresFromDescription("description column",
4884 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4886 buildSortByAnnotationScoresMenu();
4894 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4898 protected void showDbRefs_actionPerformed(ActionEvent e)
4900 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4906 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4910 protected void showNpFeats_actionPerformed(ActionEvent e)
4912 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4916 * find the viewport amongst the tabs in this alignment frame and close that
4921 public boolean closeView(AlignViewportI av)
4925 this.closeMenuItem_actionPerformed(false);
4928 Component[] comp = tabbedPane.getComponents();
4929 for (int i = 0; comp != null && i < comp.length; i++)
4931 if (comp[i] instanceof AlignmentPanel)
4933 if (((AlignmentPanel) comp[i]).av == av)
4936 closeView((AlignmentPanel) comp[i]);
4944 protected void build_fetchdbmenu(JMenu webService)
4946 // Temporary hack - DBRef Fetcher always top level ws entry.
4947 // TODO We probably want to store a sequence database checklist in
4948 // preferences and have checkboxes.. rather than individual sources selected
4950 final JMenu rfetch = new JMenu(
4951 MessageManager.getString("action.fetch_db_references"));
4952 rfetch.setToolTipText(MessageManager
4953 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4954 webService.add(rfetch);
4956 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4957 MessageManager.getString("option.trim_retrieved_seqs"));
4958 trimrs.setToolTipText(MessageManager
4959 .getString("label.trim_retrieved_sequences"));
4960 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
4961 trimrs.addActionListener(new ActionListener()
4964 public void actionPerformed(ActionEvent e)
4966 trimrs.setSelected(trimrs.isSelected());
4967 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
4968 Boolean.valueOf(trimrs.isSelected()).toString());
4972 JMenuItem fetchr = new JMenuItem(
4973 MessageManager.getString("label.standard_databases"));
4974 fetchr.setToolTipText(MessageManager
4975 .getString("label.fetch_embl_uniprot"));
4976 fetchr.addActionListener(new ActionListener()
4980 public void actionPerformed(ActionEvent e)
4982 new Thread(new Runnable()
4987 boolean isNucleotide = alignPanel.alignFrame.getViewport()
4988 .getAlignment().isNucleotide();
4989 DBRefFetcher dbRefFetcher = new DBRefFetcher(alignPanel.av
4990 .getSequenceSelection(), alignPanel.alignFrame, null,
4991 alignPanel.alignFrame.featureSettings, isNucleotide);
4992 dbRefFetcher.addListener(new FetchFinishedListenerI()
4995 public void finished()
4997 AlignFrame.this.setMenusForViewport();
5000 dbRefFetcher.fetchDBRefs(false);
5008 final AlignFrame me = this;
5009 new Thread(new Runnable()
5014 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5015 .getSequenceFetcherSingleton(me);
5016 javax.swing.SwingUtilities.invokeLater(new Runnable()
5021 String[] dbclasses = sf.getOrderedSupportedSources();
5022 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5023 // jalview.util.QuickSort.sort(otherdb, otherdb);
5024 List<DbSourceProxy> otherdb;
5025 JMenu dfetch = new JMenu();
5026 JMenu ifetch = new JMenu();
5027 JMenuItem fetchr = null;
5028 int comp = 0, icomp = 0, mcomp = 15;
5029 String mname = null;
5031 for (String dbclass : dbclasses)
5033 otherdb = sf.getSourceProxy(dbclass);
5034 // add a single entry for this class, or submenu allowing 'fetch
5036 if (otherdb == null || otherdb.size() < 1)
5040 // List<DbSourceProxy> dbs=otherdb;
5041 // otherdb=new ArrayList<DbSourceProxy>();
5042 // for (DbSourceProxy db:dbs)
5044 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5048 mname = "From " + dbclass;
5050 if (otherdb.size() == 1)
5052 final DbSourceProxy[] dassource = otherdb
5053 .toArray(new DbSourceProxy[0]);
5054 DbSourceProxy src = otherdb.get(0);
5055 fetchr = new JMenuItem(src.getDbSource());
5056 fetchr.addActionListener(new ActionListener()
5060 public void actionPerformed(ActionEvent e)
5062 new Thread(new Runnable()
5068 boolean isNucleotide = alignPanel.alignFrame
5069 .getViewport().getAlignment()
5071 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5072 alignPanel.av.getSequenceSelection(),
5073 alignPanel.alignFrame, dassource,
5074 alignPanel.alignFrame.featureSettings,
5077 .addListener(new FetchFinishedListenerI()
5080 public void finished()
5082 AlignFrame.this.setMenusForViewport();
5085 dbRefFetcher.fetchDBRefs(false);
5091 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5092 MessageManager.formatMessage(
5093 "label.fetch_retrieve_from",
5094 new Object[] { src.getDbName() })));
5100 final DbSourceProxy[] dassource = otherdb
5101 .toArray(new DbSourceProxy[0]);
5103 DbSourceProxy src = otherdb.get(0);
5104 fetchr = new JMenuItem(MessageManager.formatMessage(
5105 "label.fetch_all_param",
5106 new Object[] { src.getDbSource() }));
5107 fetchr.addActionListener(new ActionListener()
5110 public void actionPerformed(ActionEvent e)
5112 new Thread(new Runnable()
5118 boolean isNucleotide = alignPanel.alignFrame
5119 .getViewport().getAlignment()
5121 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5122 alignPanel.av.getSequenceSelection(),
5123 alignPanel.alignFrame, dassource,
5124 alignPanel.alignFrame.featureSettings,
5127 .addListener(new FetchFinishedListenerI()
5130 public void finished()
5132 AlignFrame.this.setMenusForViewport();
5135 dbRefFetcher.fetchDBRefs(false);
5141 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5142 MessageManager.formatMessage(
5143 "label.fetch_retrieve_from_all_sources",
5145 Integer.valueOf(otherdb.size())
5146 .toString(), src.getDbSource(),
5147 src.getDbName() })));
5150 // and then build the rest of the individual menus
5151 ifetch = new JMenu(MessageManager.formatMessage(
5152 "label.source_from_db_source",
5153 new Object[] { src.getDbSource() }));
5155 String imname = null;
5157 for (DbSourceProxy sproxy : otherdb)
5159 String dbname = sproxy.getDbName();
5160 String sname = dbname.length() > 5 ? dbname.substring(0,
5161 5) + "..." : dbname;
5162 String msname = dbname.length() > 10 ? dbname.substring(
5163 0, 10) + "..." : dbname;
5166 imname = MessageManager.formatMessage(
5167 "label.from_msname", new Object[] { sname });
5169 fetchr = new JMenuItem(msname);
5170 final DbSourceProxy[] dassrc = { sproxy };
5171 fetchr.addActionListener(new ActionListener()
5175 public void actionPerformed(ActionEvent e)
5177 new Thread(new Runnable()
5183 boolean isNucleotide = alignPanel.alignFrame
5184 .getViewport().getAlignment()
5186 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5187 alignPanel.av.getSequenceSelection(),
5188 alignPanel.alignFrame, dassrc,
5189 alignPanel.alignFrame.featureSettings,
5192 .addListener(new FetchFinishedListenerI()
5195 public void finished()
5197 AlignFrame.this.setMenusForViewport();
5200 dbRefFetcher.fetchDBRefs(false);
5206 fetchr.setToolTipText("<html>"
5207 + MessageManager.formatMessage(
5208 "label.fetch_retrieve_from", new Object[]
5212 if (++icomp >= mcomp || i == (otherdb.size()))
5214 ifetch.setText(MessageManager.formatMessage(
5215 "label.source_to_target", imname, sname));
5217 ifetch = new JMenu();
5225 if (comp >= mcomp || dbi >= (dbclasses.length))
5227 dfetch.setText(MessageManager.formatMessage(
5228 "label.source_to_target", mname, dbclass));
5230 dfetch = new JMenu();
5243 * Left justify the whole alignment.
5246 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5248 AlignmentI al = viewport.getAlignment();
5250 viewport.firePropertyChange("alignment", null, al);
5254 * Right justify the whole alignment.
5257 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5259 AlignmentI al = viewport.getAlignment();
5261 viewport.firePropertyChange("alignment", null, al);
5265 public void setShowSeqFeatures(boolean b)
5267 showSeqFeatures.setSelected(b);
5268 viewport.setShowSequenceFeatures(b);
5275 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5276 * awt.event.ActionEvent)
5279 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5281 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5282 alignPanel.paintAlignment(true);
5289 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5293 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5295 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5296 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5304 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5305 * .event.ActionEvent)
5308 protected void showGroupConservation_actionPerformed(ActionEvent e)
5310 viewport.setShowGroupConservation(showGroupConservation.getState());
5311 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5318 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5319 * .event.ActionEvent)
5322 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5324 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5325 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5332 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5333 * .event.ActionEvent)
5336 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5338 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5339 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5343 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5345 showSequenceLogo.setState(true);
5346 viewport.setShowSequenceLogo(true);
5347 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5348 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5352 protected void showInformationHistogram_actionPerformed(ActionEvent e)
5354 viewport.setShowInformationHistogram(
5355 showInformationHistogram.getState());
5356 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5360 protected void showHMMSequenceLogo_actionPerformed(ActionEvent e)
5362 viewport.setShowHMMSequenceLogo(showHMMSequenceLogo.getState());
5363 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5367 protected void normaliseHMMSequenceLogo_actionPerformed(ActionEvent e)
5369 showHMMSequenceLogo.setState(true);
5370 viewport.setShowHMMSequenceLogo(true);
5371 viewport.setNormaliseHMMSequenceLogo(normaliseSequenceLogo.getState());
5372 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5376 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5378 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5385 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5386 * .event.ActionEvent)
5389 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5391 if (avc.makeGroupsFromSelection())
5393 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5394 alignPanel.updateAnnotation();
5395 alignPanel.paintAlignment(true);
5399 public void clearAlignmentSeqRep()
5401 // TODO refactor alignmentseqrep to controller
5402 if (viewport.getAlignment().hasSeqrep())
5404 viewport.getAlignment().setSeqrep(null);
5405 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5406 alignPanel.updateAnnotation();
5407 alignPanel.paintAlignment(true);
5412 protected void createGroup_actionPerformed(ActionEvent e)
5414 if (avc.createGroup())
5416 alignPanel.alignmentChanged();
5421 protected void unGroup_actionPerformed(ActionEvent e)
5425 alignPanel.alignmentChanged();
5430 * make the given alignmentPanel the currently selected tab
5432 * @param alignmentPanel
5434 public void setDisplayedView(AlignmentPanel alignmentPanel)
5436 if (!viewport.getSequenceSetId().equals(
5437 alignmentPanel.av.getSequenceSetId()))
5441 .getString("error.implementation_error_cannot_show_view_alignment_frame"));
5443 if (tabbedPane != null
5444 && tabbedPane.getTabCount() > 0
5445 && alignPanels.indexOf(alignmentPanel) != tabbedPane
5446 .getSelectedIndex())
5448 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5453 * Action on selection of menu options to Show or Hide annotations.
5456 * @param forSequences
5457 * update sequence-related annotations
5458 * @param forAlignment
5459 * update non-sequence-related annotations
5462 protected void setAnnotationsVisibility(boolean visible,
5463 boolean forSequences, boolean forAlignment)
5465 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5466 .getAlignmentAnnotation();
5471 for (AlignmentAnnotation aa : anns)
5474 * don't display non-positional annotations on an alignment
5476 if (aa.annotations == null)
5480 boolean apply = (aa.sequenceRef == null && forAlignment)
5481 || (aa.sequenceRef != null && forSequences);
5484 aa.visible = visible;
5487 alignPanel.validateAnnotationDimensions(true);
5488 alignPanel.alignmentChanged();
5492 * Store selected annotation sort order for the view and repaint.
5495 protected void sortAnnotations_actionPerformed()
5497 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5499 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5500 alignPanel.paintAlignment(true);
5505 * @return alignment panels in this alignment frame
5507 public List<? extends AlignmentViewPanel> getAlignPanels()
5509 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5513 * Open a new alignment window, with the cDNA associated with this (protein)
5514 * alignment, aligned as is the protein.
5516 protected void viewAsCdna_actionPerformed()
5518 // TODO no longer a menu action - refactor as required
5519 final AlignmentI alignment = getViewport().getAlignment();
5520 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5521 if (mappings == null)
5525 List<SequenceI> cdnaSeqs = new ArrayList<>();
5526 for (SequenceI aaSeq : alignment.getSequences())
5528 for (AlignedCodonFrame acf : mappings)
5530 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5534 * There is a cDNA mapping for this protein sequence - add to new
5535 * alignment. It will share the same dataset sequence as other mapped
5536 * cDNA (no new mappings need to be created).
5538 final Sequence newSeq = new Sequence(dnaSeq);
5539 newSeq.setDatasetSequence(dnaSeq);
5540 cdnaSeqs.add(newSeq);
5544 if (cdnaSeqs.size() == 0)
5546 // show a warning dialog no mapped cDNA
5549 AlignmentI cdna = new Alignment(cdnaSeqs.toArray(new SequenceI[cdnaSeqs
5551 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5552 AlignFrame.DEFAULT_HEIGHT);
5553 cdna.alignAs(alignment);
5554 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5556 Desktop.addInternalFrame(alignFrame, newtitle,
5557 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
5561 * Set visibility of dna/protein complement view (available when shown in a
5567 protected void showComplement_actionPerformed(boolean show)
5569 SplitContainerI sf = getSplitViewContainer();
5572 sf.setComplementVisible(this, show);
5577 * Generate the reverse (optionally complemented) of the selected sequences,
5578 * and add them to the alignment
5581 protected void showReverse_actionPerformed(boolean complement)
5583 AlignmentI al = null;
5586 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5587 al = dna.reverseCdna(complement);
5588 viewport.addAlignment(al, "");
5589 addHistoryItem(new EditCommand(
5590 MessageManager.getString("label.add_sequences"),
5591 Action.PASTE, al.getSequencesArray(), 0, al.getWidth(),
5592 viewport.getAlignment()));
5593 } catch (Exception ex)
5595 System.err.println(ex.getMessage());
5601 * Try to run a script in the Groovy console, having first ensured that this
5602 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5603 * be targeted at this alignment.
5606 protected void runGroovy_actionPerformed()
5608 Jalview.setCurrentAlignFrame(this);
5609 groovy.ui.Console console = Desktop.getGroovyConsole();
5610 if (console != null)
5614 console.runScript();
5615 } catch (Exception ex)
5617 System.err.println((ex.toString()));
5619 .showInternalMessageDialog(Desktop.desktop, MessageManager
5620 .getString("label.couldnt_run_groovy_script"),
5622 .getString("label.groovy_support_failed"),
5623 JvOptionPane.ERROR_MESSAGE);
5628 System.err.println("Can't run Groovy script as console not found");
5633 * Hides columns containing (or not containing) a specified feature, provided
5634 * that would not leave all columns hidden
5636 * @param featureType
5637 * @param columnsContaining
5640 public boolean hideFeatureColumns(String featureType,
5641 boolean columnsContaining)
5643 boolean notForHiding = avc.markColumnsContainingFeatures(
5644 columnsContaining, false, false, featureType);
5647 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5648 false, featureType))
5650 getViewport().hideSelectedColumns();
5658 protected void selectHighlightedColumns_actionPerformed(
5659 ActionEvent actionEvent)
5661 // include key modifier check in case user selects from menu
5662 avc.markHighlightedColumns(
5663 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0,
5665 (actionEvent.getModifiers() & (ActionEvent.META_MASK | ActionEvent.CTRL_MASK)) != 0);
5669 * Rebuilds the Colour menu, including any user-defined colours which have
5670 * been loaded either on startup or during the session
5672 public void buildColourMenu()
5674 colourMenu.removeAll();
5676 colourMenu.add(applyToAllGroups);
5677 colourMenu.add(textColour);
5678 colourMenu.addSeparator();
5680 ColourMenuHelper.addMenuItems(colourMenu, this,
5681 viewport.getAlignment(), false);
5683 colourMenu.addSeparator();
5684 colourMenu.add(conservationMenuItem);
5685 colourMenu.add(modifyConservation);
5686 colourMenu.add(abovePIDThreshold);
5687 colourMenu.add(modifyPID);
5688 colourMenu.add(annotationColour);
5690 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5691 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5695 * Open a dialog (if not already open) that allows the user to select and
5696 * calculate PCA or Tree analysis
5698 protected void openTreePcaDialog()
5700 if (alignPanel.getCalculationDialog() == null)
5702 new CalculationChooser(AlignFrame.this);
5707 * Sets the status of the HMMER menu
5711 public void updateHMMERStatus(boolean status)
5713 hmmerMenu.setEnabled(status);
5717 * Returns the selected hidden Markov model.
5721 public HiddenMarkovModel getSelectedHMM()
5727 * Sets the selected hidden Markov model
5729 * @param selectedHMM
5731 public void setSelectedHMM(HiddenMarkovModel selectedHMM)
5733 this.selectedHMM = selectedHMM;
5734 hmmAlign.setText(MessageManager.getString("label.hmmalign") + " to "
5735 + selectedHMM.getName() + "_HMM");
5736 hmmSearch.setText(MessageManager.getString("label.hmmsearch") + " with "
5737 + selectedHMM.getName() + "_HMM");
5741 public void hmmerMenu_actionPerformed(ActionEvent e)
5743 SequenceGroup grp = getViewport().getSelectionGroup();
5746 hmmBuild.setText(MessageManager.getString("label.hmmbuild") + " from "
5751 hmmBuild.setText(MessageManager.getString("label.hmmbuild")
5752 + " from Alignment");
5758 class PrintThread extends Thread
5762 public PrintThread(AlignmentPanel ap)
5767 static PageFormat pf;
5772 PrinterJob printJob = PrinterJob.getPrinterJob();
5776 printJob.setPrintable(ap, pf);
5780 printJob.setPrintable(ap);
5783 if (printJob.printDialog())
5788 } catch (Exception PrintException)
5790 PrintException.printStackTrace();