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;
182 * The selected HMM for this align frame
184 HiddenMarkovModel selectedHMM = null;
186 List<AlignmentPanel> alignPanels = new ArrayList<>();
189 * Last format used to load or save alignments in this window
191 FileFormatI currentFileFormat = null;
194 * Current filename for this alignment
196 String fileName = null;
200 * Creates a new AlignFrame object with specific width and height.
206 public AlignFrame(AlignmentI al, int width, int height)
208 this(al, null, width, height);
212 * Creates a new AlignFrame object with specific width, height and
218 * @param sequenceSetId
220 public AlignFrame(AlignmentI al, int width, int height,
221 String sequenceSetId)
223 this(al, null, width, height, sequenceSetId);
227 * Creates a new AlignFrame object with specific width, height and
233 * @param sequenceSetId
236 public AlignFrame(AlignmentI al, int width, int height,
237 String sequenceSetId, String viewId)
239 this(al, null, width, height, sequenceSetId, viewId);
243 * new alignment window with hidden columns
247 * @param hiddenColumns
248 * ColumnSelection or null
250 * Width of alignment frame
254 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
257 this(al, hiddenColumns, width, height, null);
261 * Create alignment frame for al with hiddenColumns, a specific width and
262 * height, and specific sequenceId
265 * @param hiddenColumns
268 * @param sequenceSetId
271 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
272 int height, String sequenceSetId)
274 this(al, hiddenColumns, width, height, sequenceSetId, null);
278 * Create alignment frame for al with hiddenColumns, a specific width and
279 * height, and specific sequenceId
282 * @param hiddenColumns
285 * @param sequenceSetId
290 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
291 int height, String sequenceSetId, String viewId)
293 setSize(width, height);
295 if (al.getDataset() == null)
300 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
302 alignPanel = new AlignmentPanel(this, viewport);
304 addAlignmentPanel(alignPanel, true);
308 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
309 HiddenColumns hiddenColumns, int width, int height)
311 setSize(width, height);
313 if (al.getDataset() == null)
318 viewport = new AlignViewport(al, hiddenColumns);
320 if (hiddenSeqs != null && hiddenSeqs.length > 0)
322 viewport.hideSequence(hiddenSeqs);
324 alignPanel = new AlignmentPanel(this, viewport);
325 addAlignmentPanel(alignPanel, true);
330 * Make a new AlignFrame from existing alignmentPanels
337 public AlignFrame(AlignmentPanel ap)
341 addAlignmentPanel(ap, false);
346 * initalise the alignframe from the underlying viewport data and the
351 if (!Jalview.isHeadlessMode())
353 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
356 vpRanges = viewport.getRanges();
357 avc = new jalview.controller.AlignViewController(this, viewport,
359 if (viewport.getAlignmentConservationAnnotation() == null)
361 // BLOSUM62Colour.setEnabled(false);
362 conservationMenuItem.setEnabled(false);
363 modifyConservation.setEnabled(false);
364 // PIDColour.setEnabled(false);
365 // abovePIDThreshold.setEnabled(false);
366 // modifyPID.setEnabled(false);
369 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
372 if (sortby.equals("Id"))
374 sortIDMenuItem_actionPerformed(null);
376 else if (sortby.equals("Pairwise Identity"))
378 sortPairwiseMenuItem_actionPerformed(null);
382 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
384 setMenusFromViewport(viewport);
385 buildSortByAnnotationScoresMenu();
386 calculateTree.addActionListener(new ActionListener()
390 public void actionPerformed(ActionEvent e)
398 if (Desktop.desktop != null)
400 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
401 addServiceListeners();
405 if (viewport.getWrapAlignment())
407 wrapMenuItem_actionPerformed(null);
410 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
412 this.overviewMenuItem_actionPerformed(null);
417 final List<AlignmentPanel> selviews = new ArrayList<>();
418 final List<AlignmentPanel> origview = new ArrayList<>();
419 final String menuLabel = MessageManager
420 .getString("label.copy_format_from");
421 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
422 new ViewSetProvider()
426 public AlignmentPanel[] getAllAlignmentPanels()
429 origview.add(alignPanel);
430 // make an array of all alignment panels except for this one
431 List<AlignmentPanel> aps = new ArrayList<>(
432 Arrays.asList(Desktop.getAlignmentPanels(null)));
433 aps.remove(AlignFrame.this.alignPanel);
434 return aps.toArray(new AlignmentPanel[aps.size()]);
436 }, selviews, new ItemListener()
440 public void itemStateChanged(ItemEvent e)
442 if (origview.size() > 0)
444 final AlignmentPanel ap = origview.get(0);
447 * Copy the ViewStyle of the selected panel to 'this one'.
448 * Don't change value of 'scaleProteinAsCdna' unless copying
451 ViewStyleI vs = selviews.get(0).getAlignViewport()
453 boolean fromSplitFrame = selviews.get(0)
454 .getAlignViewport().getCodingComplement() != null;
457 vs.setScaleProteinAsCdna(ap.getAlignViewport()
458 .getViewStyle().isScaleProteinAsCdna());
460 ap.getAlignViewport().setViewStyle(vs);
463 * Also rescale ViewStyle of SplitFrame complement if there is
464 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
465 * the whole ViewStyle (allow cDNA protein to have different
468 AlignViewportI complement = ap.getAlignViewport()
469 .getCodingComplement();
470 if (complement != null && vs.isScaleProteinAsCdna())
472 AlignFrame af = Desktop.getAlignFrameFor(complement);
473 ((SplitFrame) af.getSplitViewContainer())
475 af.setMenusForViewport();
479 ap.setSelected(true);
480 ap.alignFrame.setMenusForViewport();
485 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
486 .indexOf("devel") > -1
487 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
488 .indexOf("test") > -1)
490 formatMenu.add(vsel);
492 addFocusListener(new FocusAdapter()
495 public void focusGained(FocusEvent e)
497 Jalview.setCurrentAlignFrame(AlignFrame.this);
504 * Adds all menu items to the HMMER menu
506 private void buildHMMERMenu()
508 hmmerMenu.removeAll();
510 hmmerMenu.add(hmmAlign);
511 hmmerMenu.add(hmmBuild);
512 hmmerMenu.add(hmmSearch);
516 * Change the filename and format for the alignment, and enable the 'reload'
517 * button functionality.
524 public void setFileName(String file, FileFormatI format)
527 setFileFormat(format);
528 reload.setEnabled(true);
532 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
535 void addKeyListener()
537 addKeyListener(new KeyAdapter()
540 public void keyPressed(KeyEvent evt)
542 if (viewport.cursorMode
543 && ((evt.getKeyCode() >= KeyEvent.VK_0
544 && evt.getKeyCode() <= KeyEvent.VK_9)
545 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
546 && evt.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,
587 alignPanel.getSeqPanel().getKeyboardNo1());
591 alignPanel.getSeqPanel().moveCursor(-1, 0);
596 case KeyEvent.VK_RIGHT:
597 if (evt.isAltDown() || !viewport.cursorMode)
599 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
603 alignPanel.getSeqPanel().moveCursor(1, 0);
607 case KeyEvent.VK_SPACE:
608 if (viewport.cursorMode)
610 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
611 || evt.isShiftDown() || evt.isAltDown());
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(evt.isControlDown()
635 || evt.isShiftDown() || evt.isAltDown());
641 if (viewport.cursorMode)
643 alignPanel.getSeqPanel().setCursorRow();
647 if (viewport.cursorMode && !evt.isControlDown())
649 alignPanel.getSeqPanel().setCursorColumn();
653 if (viewport.cursorMode)
655 alignPanel.getSeqPanel().setCursorPosition();
659 case KeyEvent.VK_ENTER:
660 case KeyEvent.VK_COMMA:
661 if (viewport.cursorMode)
663 alignPanel.getSeqPanel().setCursorRowAndColumn();
668 if (viewport.cursorMode)
670 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
674 if (viewport.cursorMode)
676 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
681 viewport.cursorMode = !viewport.cursorMode;
682 statusBar.setText(MessageManager
683 .formatMessage("label.keyboard_editing_mode", new String[]
684 { (viewport.cursorMode ? "on" : "off") }));
685 if (viewport.cursorMode)
687 alignPanel.getSeqPanel().seqCanvas.cursorX = vpRanges
689 alignPanel.getSeqPanel().seqCanvas.cursorY = vpRanges
692 alignPanel.getSeqPanel().seqCanvas.repaint();
698 Help.showHelpWindow();
699 } catch (Exception ex)
701 ex.printStackTrace();
706 boolean toggleSeqs = !evt.isControlDown();
707 boolean toggleCols = !evt.isShiftDown();
708 toggleHiddenRegions(toggleSeqs, toggleCols);
713 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
714 boolean modifyExisting = true; // always modify, don't clear
715 // evt.isShiftDown();
716 boolean invertHighlighted = evt.isAltDown();
717 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
721 case KeyEvent.VK_PAGE_UP:
724 case KeyEvent.VK_PAGE_DOWN:
731 public void keyReleased(KeyEvent evt)
733 switch (evt.getKeyCode())
735 case KeyEvent.VK_LEFT:
736 if (evt.isAltDown() || !viewport.cursorMode)
738 viewport.firePropertyChange("alignment", null,
739 viewport.getAlignment().getSequences());
743 case KeyEvent.VK_RIGHT:
744 if (evt.isAltDown() || !viewport.cursorMode)
746 viewport.firePropertyChange("alignment", null,
747 viewport.getAlignment().getSequences());
755 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
757 ap.alignFrame = this;
758 avc = new jalview.controller.AlignViewController(this, viewport,
763 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
765 int aSize = alignPanels.size();
767 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
769 if (aSize == 1 && ap.av.viewName == null)
771 this.getContentPane().add(ap, BorderLayout.CENTER);
777 setInitialTabVisible();
780 expandViews.setEnabled(true);
781 gatherViews.setEnabled(true);
782 tabbedPane.addTab(ap.av.viewName, ap);
784 ap.setVisible(false);
789 if (ap.av.isPadGaps())
791 ap.av.getAlignment().padGaps();
793 ap.av.updateConservation(ap);
794 ap.av.updateConsensus(ap);
795 ap.av.updateStrucConsensus(ap);
796 ap.av.updateInformation(ap);
800 public void setInitialTabVisible()
802 expandViews.setEnabled(true);
803 gatherViews.setEnabled(true);
804 tabbedPane.setVisible(true);
805 AlignmentPanel first = alignPanels.get(0);
806 tabbedPane.addTab(first.av.viewName, first);
807 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
810 public AlignViewport getViewport()
815 /* Set up intrinsic listeners for dynamically generated GUI bits. */
816 private void addServiceListeners()
818 final java.beans.PropertyChangeListener thisListener;
819 Desktop.instance.addJalviewPropertyChangeListener("services",
820 thisListener = new java.beans.PropertyChangeListener()
823 public void propertyChange(PropertyChangeEvent evt)
825 // // System.out.println("Discoverer property change.");
826 // if (evt.getPropertyName().equals("services"))
828 SwingUtilities.invokeLater(new Runnable()
835 "Rebuild WS Menu for service change");
836 BuildWebServiceMenu();
843 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
846 public void internalFrameClosed(
847 javax.swing.event.InternalFrameEvent evt)
849 // System.out.println("deregistering discoverer listener");
850 Desktop.instance.removeJalviewPropertyChangeListener("services",
852 closeMenuItem_actionPerformed(true);
855 // Finally, build the menu once to get current service state
856 new Thread(new Runnable()
861 BuildWebServiceMenu();
867 * Configure menu items that vary according to whether the alignment is
868 * nucleotide or protein
870 public void setGUINucleotide()
872 AlignmentI al = getViewport().getAlignment();
873 boolean nucleotide = al.isNucleotide();
875 showTranslation.setVisible(nucleotide);
876 showReverse.setVisible(nucleotide);
877 showReverseComplement.setVisible(nucleotide);
878 conservationMenuItem.setEnabled(!nucleotide);
880 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
881 showGroupConservation.setEnabled(!nucleotide);
883 showComplementMenuItem
884 .setText(nucleotide ? MessageManager.getString("label.protein")
885 : MessageManager.getString("label.nucleotide"));
889 * set up menus for the current viewport. This may be called after any
890 * operation that affects the data in the current view (selection changed,
891 * etc) to update the menus to reflect the new state.
894 public void setMenusForViewport()
896 setMenusFromViewport(viewport);
900 * Need to call this method when tabs are selected for multiple views, or when
901 * loading from Jalview2XML.java
906 void setMenusFromViewport(AlignViewport av)
908 padGapsMenuitem.setSelected(av.isPadGaps());
909 colourTextMenuItem.setSelected(av.isShowColourText());
910 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
911 modifyPID.setEnabled(abovePIDThreshold.isSelected());
912 conservationMenuItem.setSelected(av.getConservationSelected());
913 modifyConservation.setEnabled(conservationMenuItem.isSelected());
914 seqLimits.setSelected(av.getShowJVSuffix());
915 idRightAlign.setSelected(av.isRightAlignIds());
916 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
917 renderGapsMenuItem.setSelected(av.isRenderGaps());
918 wrapMenuItem.setSelected(av.getWrapAlignment());
919 scaleAbove.setVisible(av.getWrapAlignment());
920 scaleLeft.setVisible(av.getWrapAlignment());
921 scaleRight.setVisible(av.getWrapAlignment());
922 annotationPanelMenuItem.setState(av.isShowAnnotation());
924 * Show/hide annotations only enabled if annotation panel is shown
926 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
927 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
928 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
929 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
930 viewBoxesMenuItem.setSelected(av.getShowBoxes());
931 viewTextMenuItem.setSelected(av.getShowText());
932 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
933 showGroupConsensus.setSelected(av.isShowGroupConsensus());
934 showGroupConservation.setSelected(av.isShowGroupConservation());
935 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
936 showSequenceLogo.setSelected(av.isShowSequenceLogo());
937 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
938 showInformationHistogram.setSelected(av.isShowInformationHistogram());
939 showHMMSequenceLogo.setSelected(av.isShowHMMSequenceLogo());
940 normaliseHMMSequenceLogo.setSelected(av.isNormaliseHMMSequenceLogo());
942 ColourMenuHelper.setColourSelected(colourMenu,
943 av.getGlobalColourScheme());
945 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
946 hiddenMarkers.setState(av.getShowHiddenMarkers());
947 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
948 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
949 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
950 autoCalculate.setSelected(av.autoCalculateConsensus);
951 sortByTree.setSelected(av.sortByTree);
952 listenToViewSelections.setSelected(av.followSelection);
954 showProducts.setEnabled(canShowProducts());
955 setGroovyEnabled(Desktop.getGroovyConsole() != null);
961 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
965 public void setGroovyEnabled(boolean b)
967 runGroovy.setEnabled(b);
970 private IProgressIndicator progressBar;
975 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
978 public void setProgressBar(String message, long id)
980 progressBar.setProgressBar(message, id);
984 public void registerHandler(final long id,
985 final IProgressIndicatorHandler handler)
987 progressBar.registerHandler(id, handler);
992 * @return true if any progress bars are still active
995 public boolean operationInProgress()
997 return progressBar.operationInProgress();
1001 public void setStatus(String text)
1003 statusBar.setText(text);
1007 * Added so Castor Mapping file can obtain Jalview Version
1009 public String getVersion()
1011 return jalview.bin.Cache.getProperty("VERSION");
1014 public FeatureRenderer getFeatureRenderer()
1016 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1020 public void fetchSequence_actionPerformed(ActionEvent e)
1022 new jalview.gui.SequenceFetcher(this);
1026 public void addFromFile_actionPerformed(ActionEvent e)
1028 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1032 public void hmmBuild_actionPerformed(ActionEvent e)
1033 throws IOException, InterruptedException
1035 new Thread(new HMMBuildThread(this)).start();
1036 alignPanel.repaint();
1041 public void hmmAlign_actionPerformed(ActionEvent e)
1042 throws IOException, InterruptedException
1044 new Thread(new HMMAlignThread(this, true)).start();
1045 alignPanel.repaint();
1049 public void changeHMMERLocation_actionPerformed(ActionEvent e)
1051 String location = JOptionPane.showInputDialog(
1052 MessageManager.getString("label.enter_location"));
1053 Cache.setProperty(Preferences.HMMER_PATH, location);
1057 public void autoAlignSeqs_actionPerformed(boolean autoAlignSeqs)
1059 autoAlignNewSequences = autoAlignSeqs;
1060 alignPanel.repaint();
1064 public void hmmSearch_actionPerformed(ActionEvent e)
1066 alignPanel.repaint();
1070 public void reload_actionPerformed(ActionEvent e)
1072 if (fileName != null)
1074 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1075 // originating file's format
1076 // TODO: work out how to recover feature settings for correct view(s) when
1077 // file is reloaded.
1078 if (FileFormat.Jalview.equals(currentFileFormat))
1080 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1081 for (int i = 0; i < frames.length; i++)
1083 if (frames[i] instanceof AlignFrame && frames[i] != this
1084 && ((AlignFrame) frames[i]).fileName != null
1085 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1089 frames[i].setSelected(true);
1090 Desktop.instance.closeAssociatedWindows();
1091 } catch (java.beans.PropertyVetoException ex)
1097 Desktop.instance.closeAssociatedWindows();
1099 FileLoader loader = new FileLoader();
1100 DataSourceType protocol = fileName.startsWith("http:")
1101 ? DataSourceType.URL
1102 : DataSourceType.FILE;
1103 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1107 Rectangle bounds = this.getBounds();
1109 FileLoader loader = new FileLoader();
1110 DataSourceType protocol = fileName.startsWith("http:")
1111 ? DataSourceType.URL
1112 : DataSourceType.FILE;
1113 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1114 protocol, currentFileFormat);
1116 newframe.setBounds(bounds);
1117 if (featureSettings != null && featureSettings.isShowing())
1119 final Rectangle fspos = featureSettings.frame.getBounds();
1120 // TODO: need a 'show feature settings' function that takes bounds -
1121 // need to refactor Desktop.addFrame
1122 newframe.featureSettings_actionPerformed(null);
1123 final FeatureSettings nfs = newframe.featureSettings;
1124 SwingUtilities.invokeLater(new Runnable()
1129 nfs.frame.setBounds(fspos);
1132 this.featureSettings.close();
1133 this.featureSettings = null;
1135 this.closeMenuItem_actionPerformed(true);
1141 public void addFromText_actionPerformed(ActionEvent e)
1144 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1148 public void addFromURL_actionPerformed(ActionEvent e)
1150 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1154 public void save_actionPerformed(ActionEvent e)
1156 if (fileName == null || (currentFileFormat == null)
1157 || fileName.startsWith("http"))
1159 saveAs_actionPerformed(null);
1163 saveAlignment(fileName, currentFileFormat);
1174 public void saveAs_actionPerformed(ActionEvent e)
1176 String format = currentFileFormat == null ? null
1177 : currentFileFormat.getName();
1178 JalviewFileChooser chooser = JalviewFileChooser
1179 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1181 chooser.setFileView(new JalviewFileView());
1182 chooser.setDialogTitle(
1183 MessageManager.getString("label.save_alignment_to_file"));
1184 chooser.setToolTipText(MessageManager.getString("action.save"));
1186 int value = chooser.showSaveDialog(this);
1188 if (value == JalviewFileChooser.APPROVE_OPTION)
1190 currentFileFormat = chooser.getSelectedFormat();
1191 while (currentFileFormat == null)
1193 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1194 MessageManager.getString(
1195 "label.select_file_format_before_saving"),
1196 MessageManager.getString("label.file_format_not_specified"),
1197 JvOptionPane.WARNING_MESSAGE);
1198 currentFileFormat = chooser.getSelectedFormat();
1199 value = chooser.showSaveDialog(this);
1200 if (value != JalviewFileChooser.APPROVE_OPTION)
1206 fileName = chooser.getSelectedFile().getPath();
1208 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1210 Cache.setProperty("LAST_DIRECTORY", fileName);
1211 saveAlignment(fileName, currentFileFormat);
1215 public boolean saveAlignment(String file, FileFormatI format)
1217 boolean success = true;
1219 if (FileFormat.Jalview.equals(format))
1221 String shortName = title;
1223 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1225 shortName = shortName.substring(
1226 shortName.lastIndexOf(java.io.File.separatorChar) + 1);
1229 success = new Jalview2XML().saveAlignment(this, file, shortName);
1231 statusBar.setText(MessageManager.formatMessage(
1232 "label.successfully_saved_to_file_in_format", new Object[]
1233 { fileName, format }));
1238 AlignmentExportData exportData = getAlignmentForExport(format,
1240 if (exportData.getSettings().isCancelled())
1244 FormatAdapter f = new FormatAdapter(alignPanel,
1245 exportData.getSettings());
1246 String output = f.formatSequences(format, exportData.getAlignment(), // class
1250 // occur in the distant future
1251 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1252 f.getCacheSuffixDefault(format),
1253 viewport.getAlignment().getHiddenColumns());
1263 PrintWriter out = new PrintWriter(new FileWriter(file));
1267 this.setTitle(file);
1268 statusBar.setText(MessageManager.formatMessage(
1269 "label.successfully_saved_to_file_in_format", new Object[]
1270 { fileName, format.getName() }));
1271 } catch (Exception ex)
1274 ex.printStackTrace();
1281 JvOptionPane.showInternalMessageDialog(this, MessageManager
1282 .formatMessage("label.couldnt_save_file", new Object[]
1284 MessageManager.getString("label.error_saving_file"),
1285 JvOptionPane.WARNING_MESSAGE);
1291 private void warningMessage(String warning, String title)
1293 if (new jalview.util.Platform().isHeadless())
1295 System.err.println("Warning: " + title + "\nWarning: " + warning);
1300 JvOptionPane.showInternalMessageDialog(this, warning, title,
1301 JvOptionPane.WARNING_MESSAGE);
1313 protected void outputText_actionPerformed(ActionEvent e)
1315 FileFormatI fileFormat = FileFormats.getInstance()
1316 .forName(e.getActionCommand());
1317 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1319 if (exportData.getSettings().isCancelled())
1323 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1324 cap.setForInput(null);
1327 FileFormatI format = fileFormat;
1328 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1329 .formatSequences(format, exportData.getAlignment(),
1330 exportData.getOmitHidden(),
1331 exportData.getStartEndPostions(),
1332 viewport.getAlignment().getHiddenColumns()));
1333 Desktop.addInternalFrame(cap, MessageManager
1334 .formatMessage("label.alignment_output_command", new Object[]
1335 { e.getActionCommand() }), 600, 500);
1336 } catch (OutOfMemoryError oom)
1338 new OOMWarning("Outputting alignment as " + e.getActionCommand(),
1345 public static AlignmentExportData getAlignmentForExport(
1346 FileFormatI format, AlignViewportI viewport,
1347 AlignExportSettingI exportSettings)
1349 AlignmentI alignmentToExport = null;
1350 AlignExportSettingI settings = exportSettings;
1351 String[] omitHidden = null;
1353 HiddenSequences hiddenSeqs = viewport.getAlignment()
1354 .getHiddenSequences();
1356 alignmentToExport = viewport.getAlignment();
1358 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1359 if (settings == null)
1361 settings = new AlignExportSettings(hasHiddenSeqs,
1362 viewport.hasHiddenColumns(), format);
1364 // settings.isExportAnnotations();
1366 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1368 omitHidden = viewport.getViewAsString(false,
1369 settings.isExportHiddenSequences());
1372 int[] alignmentStartEnd = new int[2];
1373 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1375 alignmentToExport = hiddenSeqs.getFullAlignment();
1379 alignmentToExport = viewport.getAlignment();
1381 alignmentStartEnd = viewport.getAlignment().getHiddenColumns()
1382 .getVisibleStartAndEndIndex(alignmentToExport.getWidth());
1383 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1384 omitHidden, alignmentStartEnd, settings);
1395 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1397 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1398 htmlSVG.exportHTML(null);
1402 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1404 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1405 bjs.exportHTML(null);
1408 public void createImageMap(File file, String image)
1410 alignPanel.makePNGImageMap(file, image);
1420 public void createPNG(File f)
1422 alignPanel.makePNG(f);
1432 public void createEPS(File f)
1434 alignPanel.makeEPS(f);
1438 public void createSVG(File f)
1440 alignPanel.makeSVG(f);
1444 public void pageSetup_actionPerformed(ActionEvent e)
1446 PrinterJob printJob = PrinterJob.getPrinterJob();
1447 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1457 public void printMenuItem_actionPerformed(ActionEvent e)
1459 // Putting in a thread avoids Swing painting problems
1460 PrintThread thread = new PrintThread(alignPanel);
1465 public void exportFeatures_actionPerformed(ActionEvent e)
1467 new AnnotationExporter().exportFeatures(alignPanel);
1471 public void exportAnnotations_actionPerformed(ActionEvent e)
1473 new AnnotationExporter().exportAnnotations(alignPanel);
1477 public void associatedData_actionPerformed(ActionEvent e)
1478 throws IOException, InterruptedException
1480 // Pick the tree file
1481 JalviewFileChooser chooser = new JalviewFileChooser(
1482 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1483 chooser.setFileView(new JalviewFileView());
1484 chooser.setDialogTitle(
1485 MessageManager.getString("label.load_jalview_annotations"));
1486 chooser.setToolTipText(
1487 MessageManager.getString("label.load_jalview_annotations"));
1489 int value = chooser.showOpenDialog(null);
1491 if (value == JalviewFileChooser.APPROVE_OPTION)
1493 String choice = chooser.getSelectedFile().getPath();
1494 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1495 loadJalviewDataFile(choice, null, null, null);
1501 * Close the current view or all views in the alignment frame. If the frame
1502 * only contains one view then the alignment will be removed from memory.
1504 * @param closeAllTabs
1507 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1509 if (alignPanels != null && alignPanels.size() < 2)
1511 closeAllTabs = true;
1516 if (alignPanels != null)
1520 if (this.isClosed())
1522 // really close all the windows - otherwise wait till
1523 // setClosed(true) is called
1524 for (int i = 0; i < alignPanels.size(); i++)
1526 AlignmentPanel ap = alignPanels.get(i);
1533 closeView(alignPanel);
1540 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1541 * be called recursively, with the frame now in 'closed' state
1543 this.setClosed(true);
1545 } catch (Exception ex)
1547 ex.printStackTrace();
1552 * Close the specified panel and close up tabs appropriately.
1554 * @param panelToClose
1556 public void closeView(AlignmentPanel panelToClose)
1558 int index = tabbedPane.getSelectedIndex();
1559 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1560 alignPanels.remove(panelToClose);
1561 panelToClose.closePanel();
1562 panelToClose = null;
1564 tabbedPane.removeTabAt(closedindex);
1565 tabbedPane.validate();
1567 if (index > closedindex || index == tabbedPane.getTabCount())
1569 // modify currently selected tab index if necessary.
1573 this.tabSelectionChanged(index);
1579 void updateEditMenuBar()
1582 if (viewport.getHistoryList().size() > 0)
1584 undoMenuItem.setEnabled(true);
1585 CommandI command = viewport.getHistoryList().peek();
1586 undoMenuItem.setText(MessageManager
1587 .formatMessage("label.undo_command", new Object[]
1588 { command.getDescription() }));
1592 undoMenuItem.setEnabled(false);
1593 undoMenuItem.setText(MessageManager.getString("action.undo"));
1596 if (viewport.getRedoList().size() > 0)
1598 redoMenuItem.setEnabled(true);
1600 CommandI command = viewport.getRedoList().peek();
1601 redoMenuItem.setText(MessageManager
1602 .formatMessage("label.redo_command", new Object[]
1603 { command.getDescription() }));
1607 redoMenuItem.setEnabled(false);
1608 redoMenuItem.setText(MessageManager.getString("action.redo"));
1613 public void addHistoryItem(CommandI command)
1615 if (command.getSize() > 0)
1617 viewport.addToHistoryList(command);
1618 viewport.clearRedoList();
1619 updateEditMenuBar();
1620 viewport.updateHiddenColumns();
1621 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1622 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1623 // viewport.getColumnSelection()
1624 // .getHiddenColumns().size() > 0);
1630 * @return alignment objects for all views
1632 AlignmentI[] getViewAlignments()
1634 if (alignPanels != null)
1636 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1638 for (AlignmentPanel ap : alignPanels)
1640 als[i++] = ap.av.getAlignment();
1644 if (viewport != null)
1646 return new AlignmentI[] { viewport.getAlignment() };
1658 protected void undoMenuItem_actionPerformed(ActionEvent e)
1660 if (viewport.getHistoryList().isEmpty())
1664 CommandI command = viewport.getHistoryList().pop();
1665 viewport.addToRedoList(command);
1666 command.undoCommand(getViewAlignments());
1668 AlignmentViewport originalSource = getOriginatingSource(command);
1669 updateEditMenuBar();
1671 if (originalSource != null)
1673 if (originalSource != viewport)
1676 "Implementation worry: mismatch of viewport origin for undo");
1678 originalSource.updateHiddenColumns();
1679 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1681 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1682 // viewport.getColumnSelection()
1683 // .getHiddenColumns().size() > 0);
1684 originalSource.firePropertyChange("alignment", null,
1685 originalSource.getAlignment().getSequences());
1696 protected void redoMenuItem_actionPerformed(ActionEvent e)
1698 if (viewport.getRedoList().size() < 1)
1703 CommandI command = viewport.getRedoList().pop();
1704 viewport.addToHistoryList(command);
1705 command.doCommand(getViewAlignments());
1707 AlignmentViewport originalSource = getOriginatingSource(command);
1708 updateEditMenuBar();
1710 if (originalSource != null)
1713 if (originalSource != viewport)
1716 "Implementation worry: mismatch of viewport origin for redo");
1718 originalSource.updateHiddenColumns();
1719 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1721 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1722 // viewport.getColumnSelection()
1723 // .getHiddenColumns().size() > 0);
1724 originalSource.firePropertyChange("alignment", null,
1725 originalSource.getAlignment().getSequences());
1729 AlignmentViewport getOriginatingSource(CommandI command)
1731 AlignmentViewport originalSource = null;
1732 // For sequence removal and addition, we need to fire
1733 // the property change event FROM the viewport where the
1734 // original alignment was altered
1735 AlignmentI al = null;
1736 if (command instanceof EditCommand)
1738 EditCommand editCommand = (EditCommand) command;
1739 al = editCommand.getAlignment();
1740 List<Component> comps = PaintRefresher.components
1741 .get(viewport.getSequenceSetId());
1743 for (Component comp : comps)
1745 if (comp instanceof AlignmentPanel)
1747 if (al == ((AlignmentPanel) comp).av.getAlignment())
1749 originalSource = ((AlignmentPanel) comp).av;
1756 if (originalSource == null)
1758 // The original view is closed, we must validate
1759 // the current view against the closed view first
1762 PaintRefresher.validateSequences(al, viewport.getAlignment());
1765 originalSource = viewport;
1768 return originalSource;
1777 public void moveSelectedSequences(boolean up)
1779 SequenceGroup sg = viewport.getSelectionGroup();
1785 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1786 viewport.getHiddenRepSequences(), up);
1787 alignPanel.paintAlignment(true);
1790 synchronized void slideSequences(boolean right, int size)
1792 List<SequenceI> sg = new ArrayList<>();
1793 if (viewport.cursorMode)
1795 sg.add(viewport.getAlignment()
1796 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1798 else if (viewport.getSelectionGroup() != null
1799 && viewport.getSelectionGroup().getSize() != viewport
1800 .getAlignment().getHeight())
1802 sg = viewport.getSelectionGroup()
1803 .getSequences(viewport.getHiddenRepSequences());
1811 List<SequenceI> invertGroup = new ArrayList<>();
1813 for (SequenceI seq : viewport.getAlignment().getSequences())
1815 if (!sg.contains(seq))
1817 invertGroup.add(seq);
1821 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1823 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1824 for (int i = 0; i < invertGroup.size(); i++)
1826 seqs2[i] = invertGroup.get(i);
1829 SlideSequencesCommand ssc;
1832 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1833 viewport.getGapCharacter());
1837 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1838 viewport.getGapCharacter());
1841 int groupAdjustment = 0;
1842 if (ssc.getGapsInsertedBegin() && right)
1844 if (viewport.cursorMode)
1846 alignPanel.getSeqPanel().moveCursor(size, 0);
1850 groupAdjustment = size;
1853 else if (!ssc.getGapsInsertedBegin() && !right)
1855 if (viewport.cursorMode)
1857 alignPanel.getSeqPanel().moveCursor(-size, 0);
1861 groupAdjustment = -size;
1865 if (groupAdjustment != 0)
1867 viewport.getSelectionGroup().setStartRes(
1868 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1869 viewport.getSelectionGroup().setEndRes(
1870 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1874 * just extend the last slide command if compatible; but not if in
1875 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1877 boolean appendHistoryItem = false;
1878 Deque<CommandI> historyList = viewport.getHistoryList();
1879 boolean inSplitFrame = getSplitViewContainer() != null;
1880 if (!inSplitFrame && historyList != null && historyList.size() > 0
1881 && historyList.peek() instanceof SlideSequencesCommand)
1883 appendHistoryItem = ssc.appendSlideCommand(
1884 (SlideSequencesCommand) historyList.peek());
1887 if (!appendHistoryItem)
1889 addHistoryItem(ssc);
1902 protected void copy_actionPerformed(ActionEvent e)
1905 if (viewport.getSelectionGroup() == null)
1909 // TODO: preserve the ordering of displayed alignment annotation in any
1910 // internal paste (particularly sequence associated annotation)
1911 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1912 String[] omitHidden = null;
1914 if (viewport.hasHiddenColumns())
1916 omitHidden = viewport.getViewAsString(true);
1919 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1920 seqs, omitHidden, null);
1922 StringSelection ss = new StringSelection(output);
1926 jalview.gui.Desktop.internalCopy = true;
1927 // Its really worth setting the clipboard contents
1928 // to empty before setting the large StringSelection!!
1929 Toolkit.getDefaultToolkit().getSystemClipboard()
1930 .setContents(new StringSelection(""), null);
1932 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1934 } catch (OutOfMemoryError er)
1936 new OOMWarning("copying region", er);
1940 ArrayList<int[]> hiddenColumns = null;
1941 if (viewport.hasHiddenColumns())
1943 hiddenColumns = new ArrayList<>();
1945 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1946 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1947 ArrayList<int[]> hiddenRegions = viewport.getAlignment()
1948 .getHiddenColumns().getHiddenColumnsCopy();
1949 for (int[] region : hiddenRegions)
1952 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1956 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1961 Desktop.jalviewClipboard = new Object[] { seqs,
1962 viewport.getAlignment().getDataset(), hiddenColumns };
1963 statusBar.setText(MessageManager.formatMessage(
1964 "label.copied_sequences_to_clipboard", new Object[]
1965 { Integer.valueOf(seqs.length).toString() }));
1973 * @throws InterruptedException
1974 * @throws IOException
1977 protected void pasteNew_actionPerformed(ActionEvent e)
1978 throws IOException, InterruptedException
1988 * @throws InterruptedException
1989 * @throws IOException
1992 protected void pasteThis_actionPerformed(ActionEvent e)
1993 throws IOException, InterruptedException
1999 * Paste contents of Jalview clipboard
2001 * @param newAlignment
2002 * true to paste to a new alignment, otherwise add to this.
2003 * @throws InterruptedException
2004 * @throws IOException
2006 void paste(boolean newAlignment) throws IOException, InterruptedException
2008 boolean externalPaste = true;
2011 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2012 Transferable contents = c.getContents(this);
2014 if (contents == null)
2023 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2024 if (str.length() < 1)
2029 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2031 } catch (OutOfMemoryError er)
2033 new OOMWarning("Out of memory pasting sequences!!", er);
2037 SequenceI[] sequences;
2038 boolean annotationAdded = false;
2039 AlignmentI alignment = null;
2041 if (Desktop.jalviewClipboard != null)
2043 // The clipboard was filled from within Jalview, we must use the
2045 // And dataset from the copied alignment
2046 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2047 // be doubly sure that we create *new* sequence objects.
2048 sequences = new SequenceI[newseq.length];
2049 for (int i = 0; i < newseq.length; i++)
2051 sequences[i] = new Sequence(newseq[i]);
2053 alignment = new Alignment(sequences);
2054 externalPaste = false;
2058 // parse the clipboard as an alignment.
2059 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2061 sequences = alignment.getSequencesArray();
2065 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2071 if (Desktop.jalviewClipboard != null)
2073 // dataset is inherited
2074 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2078 // new dataset is constructed
2079 alignment.setDataset(null);
2081 alwidth = alignment.getWidth() + 1;
2085 AlignmentI pastedal = alignment; // preserve pasted alignment object
2086 // Add pasted sequences and dataset into existing alignment.
2087 alignment = viewport.getAlignment();
2088 alwidth = alignment.getWidth() + 1;
2089 // decide if we need to import sequences from an existing dataset
2090 boolean importDs = Desktop.jalviewClipboard != null
2091 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2092 // importDs==true instructs us to copy over new dataset sequences from
2093 // an existing alignment
2094 Vector newDs = (importDs) ? new Vector() : null; // used to create
2095 // minimum dataset set
2097 for (int i = 0; i < sequences.length; i++)
2101 newDs.addElement(null);
2103 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2105 if (importDs && ds != null)
2107 if (!newDs.contains(ds))
2109 newDs.setElementAt(ds, i);
2110 ds = new Sequence(ds);
2111 // update with new dataset sequence
2112 sequences[i].setDatasetSequence(ds);
2116 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2121 // copy and derive new dataset sequence
2122 sequences[i] = sequences[i].deriveSequence();
2123 alignment.getDataset()
2124 .addSequence(sequences[i].getDatasetSequence());
2125 // TODO: avoid creation of duplicate dataset sequences with a
2126 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2128 alignment.addSequence(sequences[i]); // merges dataset
2132 newDs.clear(); // tidy up
2134 if (alignment.getAlignmentAnnotation() != null)
2136 for (AlignmentAnnotation alan : alignment
2137 .getAlignmentAnnotation())
2139 if (alan.graphGroup > fgroup)
2141 fgroup = alan.graphGroup;
2145 if (pastedal.getAlignmentAnnotation() != null)
2147 // Add any annotation attached to alignment.
2148 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2149 for (int i = 0; i < alann.length; i++)
2151 annotationAdded = true;
2152 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2154 AlignmentAnnotation newann = new AlignmentAnnotation(
2156 if (newann.graphGroup > -1)
2158 if (newGraphGroups.size() <= newann.graphGroup
2159 || newGraphGroups.get(newann.graphGroup) == null)
2161 for (int q = newGraphGroups
2162 .size(); q <= newann.graphGroup; q++)
2164 newGraphGroups.add(q, null);
2166 newGraphGroups.set(newann.graphGroup,
2167 new Integer(++fgroup));
2169 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2173 newann.padAnnotation(alwidth);
2174 alignment.addAnnotation(newann);
2184 addHistoryItem(new EditCommand(
2185 MessageManager.getString("label.add_sequences"),
2186 Action.PASTE, sequences, 0, alignment.getWidth(),
2189 // Add any annotations attached to sequences
2190 for (int i = 0; i < sequences.length; i++)
2192 if (sequences[i].getAnnotation() != null)
2194 AlignmentAnnotation newann;
2195 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2197 annotationAdded = true;
2198 newann = sequences[i].getAnnotation()[a];
2199 newann.adjustForAlignment();
2200 newann.padAnnotation(alwidth);
2201 if (newann.graphGroup > -1)
2203 if (newann.graphGroup > -1)
2205 if (newGraphGroups.size() <= newann.graphGroup
2206 || newGraphGroups.get(newann.graphGroup) == null)
2208 for (int q = newGraphGroups
2209 .size(); q <= newann.graphGroup; q++)
2211 newGraphGroups.add(q, null);
2213 newGraphGroups.set(newann.graphGroup,
2214 new Integer(++fgroup));
2216 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2220 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2224 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2232 // propagate alignment changed.
2233 vpRanges.setEndSeq(alignment.getHeight());
2234 if (annotationAdded)
2236 // Duplicate sequence annotation in all views.
2237 AlignmentI[] alview = this.getViewAlignments();
2238 for (int i = 0; i < sequences.length; i++)
2240 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2245 for (int avnum = 0; avnum < alview.length; avnum++)
2247 if (alview[avnum] != alignment)
2249 // duplicate in a view other than the one with input focus
2250 int avwidth = alview[avnum].getWidth() + 1;
2251 // this relies on sann being preserved after we
2252 // modify the sequence's annotation array for each duplication
2253 for (int a = 0; a < sann.length; a++)
2255 AlignmentAnnotation newann = new AlignmentAnnotation(
2257 sequences[i].addAlignmentAnnotation(newann);
2258 newann.padAnnotation(avwidth);
2259 alview[avnum].addAnnotation(newann); // annotation was
2260 // duplicated earlier
2261 // TODO JAL-1145 graphGroups are not updated for sequence
2262 // annotation added to several views. This may cause
2264 alview[avnum].setAnnotationIndex(newann, a);
2269 buildSortByAnnotationScoresMenu();
2271 viewport.firePropertyChange("alignment", null,
2272 alignment.getSequences());
2273 if (alignPanels != null)
2275 for (AlignmentPanel ap : alignPanels)
2277 ap.validateAnnotationDimensions(false);
2282 alignPanel.validateAnnotationDimensions(false);
2288 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2290 String newtitle = new String("Copied sequences");
2292 if (Desktop.jalviewClipboard != null
2293 && Desktop.jalviewClipboard[2] != null)
2295 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2296 for (int[] region : hc)
2298 af.viewport.hideColumns(region[0], region[1]);
2302 // >>>This is a fix for the moment, until a better solution is
2304 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2305 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2306 .getFeatureRenderer());
2308 // TODO: maintain provenance of an alignment, rather than just make the
2309 // title a concatenation of operations.
2312 if (title.startsWith("Copied sequences"))
2318 newtitle = newtitle.concat("- from " + title);
2323 newtitle = new String("Pasted sequences");
2326 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2331 } catch (Exception ex)
2333 ex.printStackTrace();
2334 System.out.println("Exception whilst pasting: " + ex);
2335 // could be anything being pasted in here
2340 protected void expand_newalign(ActionEvent e)
2344 AlignmentI alignment = AlignmentUtils
2345 .expandContext(getViewport().getAlignment(), -1);
2346 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2348 String newtitle = new String("Flanking alignment");
2350 if (Desktop.jalviewClipboard != null
2351 && Desktop.jalviewClipboard[2] != null)
2353 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2354 for (int region[] : hc)
2356 af.viewport.hideColumns(region[0], region[1]);
2360 // >>>This is a fix for the moment, until a better solution is
2362 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2363 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2364 .getFeatureRenderer());
2366 // TODO: maintain provenance of an alignment, rather than just make the
2367 // title a concatenation of operations.
2369 if (title.startsWith("Copied sequences"))
2375 newtitle = newtitle.concat("- from " + title);
2379 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2381 } catch (Exception ex)
2383 ex.printStackTrace();
2384 System.out.println("Exception whilst pasting: " + ex);
2385 // could be anything being pasted in here
2386 } catch (OutOfMemoryError oom)
2388 new OOMWarning("Viewing flanking region of alignment", oom);
2399 protected void cut_actionPerformed(ActionEvent e)
2401 copy_actionPerformed(null);
2402 delete_actionPerformed(null);
2412 protected void delete_actionPerformed(ActionEvent evt)
2415 SequenceGroup sg = viewport.getSelectionGroup();
2422 * If the cut affects all sequences, warn, remove highlighted columns
2424 if (sg.getSize() == viewport.getAlignment().getHeight())
2426 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2427 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2428 if (isEntireAlignWidth)
2430 int confirm = JvOptionPane.showConfirmDialog(this,
2431 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2432 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2433 JvOptionPane.OK_CANCEL_OPTION);
2435 if (confirm == JvOptionPane.CANCEL_OPTION
2436 || confirm == JvOptionPane.CLOSED_OPTION)
2441 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2442 sg.getEndRes() + 1);
2444 SequenceI[] cut = sg.getSequences()
2445 .toArray(new SequenceI[sg.getSize()]);
2447 addHistoryItem(new EditCommand(
2448 MessageManager.getString("label.cut_sequences"), Action.CUT,
2449 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2450 viewport.getAlignment()));
2452 viewport.setSelectionGroup(null);
2453 viewport.sendSelection();
2454 viewport.getAlignment().deleteGroup(sg);
2456 viewport.firePropertyChange("alignment", null,
2457 viewport.getAlignment().getSequences());
2458 if (viewport.getAlignment().getHeight() < 1)
2462 this.setClosed(true);
2463 } catch (Exception ex)
2476 protected void deleteGroups_actionPerformed(ActionEvent e)
2478 if (avc.deleteGroups())
2480 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2481 alignPanel.updateAnnotation();
2482 alignPanel.paintAlignment(true);
2493 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2495 SequenceGroup sg = new SequenceGroup();
2497 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2499 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2502 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2503 viewport.setSelectionGroup(sg);
2504 viewport.sendSelection();
2505 // JAL-2034 - should delegate to
2506 // alignPanel to decide if overview needs
2508 alignPanel.paintAlignment(false);
2509 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2519 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2521 if (viewport.cursorMode)
2523 alignPanel.getSeqPanel().keyboardNo1 = null;
2524 alignPanel.getSeqPanel().keyboardNo2 = null;
2526 viewport.setSelectionGroup(null);
2527 viewport.getColumnSelection().clear();
2528 viewport.setSelectionGroup(null);
2529 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2530 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2531 // JAL-2034 - should delegate to
2532 // alignPanel to decide if overview needs
2534 alignPanel.paintAlignment(false);
2535 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2536 viewport.sendSelection();
2546 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2548 SequenceGroup sg = viewport.getSelectionGroup();
2552 selectAllSequenceMenuItem_actionPerformed(null);
2557 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2559 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2561 // JAL-2034 - should delegate to
2562 // alignPanel to decide if overview needs
2565 alignPanel.paintAlignment(true);
2566 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2567 viewport.sendSelection();
2571 public void invertColSel_actionPerformed(ActionEvent e)
2573 viewport.invertColumnSelection();
2574 alignPanel.paintAlignment(true);
2575 viewport.sendSelection();
2585 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2587 trimAlignment(true);
2597 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2599 trimAlignment(false);
2602 void trimAlignment(boolean trimLeft)
2604 ColumnSelection colSel = viewport.getColumnSelection();
2607 if (!colSel.isEmpty())
2611 column = colSel.getMin();
2615 column = colSel.getMax();
2619 if (viewport.getSelectionGroup() != null)
2621 seqs = viewport.getSelectionGroup()
2622 .getSequencesAsArray(viewport.getHiddenRepSequences());
2626 seqs = viewport.getAlignment().getSequencesArray();
2629 TrimRegionCommand trimRegion;
2632 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2633 column, viewport.getAlignment());
2634 vpRanges.setStartRes(0);
2638 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2639 column, viewport.getAlignment());
2642 statusBar.setText(MessageManager
2643 .formatMessage("label.removed_columns", new String[]
2644 { Integer.valueOf(trimRegion.getSize()).toString() }));
2646 addHistoryItem(trimRegion);
2648 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2650 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2651 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2653 viewport.getAlignment().deleteGroup(sg);
2657 viewport.firePropertyChange("alignment", null,
2658 viewport.getAlignment().getSequences());
2669 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2671 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2674 if (viewport.getSelectionGroup() != null)
2676 seqs = viewport.getSelectionGroup()
2677 .getSequencesAsArray(viewport.getHiddenRepSequences());
2678 start = viewport.getSelectionGroup().getStartRes();
2679 end = viewport.getSelectionGroup().getEndRes();
2683 seqs = viewport.getAlignment().getSequencesArray();
2686 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2687 "Remove Gapped Columns", seqs, start, end,
2688 viewport.getAlignment());
2690 addHistoryItem(removeGapCols);
2692 statusBar.setText(MessageManager
2693 .formatMessage("label.removed_empty_columns", new Object[]
2694 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2696 // This is to maintain viewport position on first residue
2697 // of first sequence
2698 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2699 int startRes = seq.findPosition(vpRanges.getStartRes());
2700 // ShiftList shifts;
2701 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2702 // edit.alColumnChanges=shifts.getInverse();
2703 // if (viewport.hasHiddenColumns)
2704 // viewport.getColumnSelection().compensateForEdits(shifts);
2705 vpRanges.setStartRes(seq.findIndex(startRes) - 1);
2706 viewport.firePropertyChange("alignment", null,
2707 viewport.getAlignment().getSequences());
2718 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2720 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2723 if (viewport.getSelectionGroup() != null)
2725 seqs = viewport.getSelectionGroup()
2726 .getSequencesAsArray(viewport.getHiddenRepSequences());
2727 start = viewport.getSelectionGroup().getStartRes();
2728 end = viewport.getSelectionGroup().getEndRes();
2732 seqs = viewport.getAlignment().getSequencesArray();
2735 // This is to maintain viewport position on first residue
2736 // of first sequence
2737 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2738 int startRes = seq.findPosition(vpRanges.getStartRes());
2740 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2741 viewport.getAlignment()));
2743 vpRanges.setStartRes(seq.findIndex(startRes) - 1);
2745 viewport.firePropertyChange("alignment", null,
2746 viewport.getAlignment().getSequences());
2757 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2759 viewport.setPadGaps(padGapsMenuitem.isSelected());
2760 viewport.firePropertyChange("alignment", null,
2761 viewport.getAlignment().getSequences());
2771 public void findMenuItem_actionPerformed(ActionEvent e)
2777 * Create a new view of the current alignment.
2780 public void newView_actionPerformed(ActionEvent e)
2782 newView(null, true);
2786 * Creates and shows a new view of the current alignment.
2789 * title of newly created view; if null, one will be generated
2790 * @param copyAnnotation
2791 * if true then duplicate all annnotation, groups and settings
2792 * @return new alignment panel, already displayed.
2794 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2797 * Create a new AlignmentPanel (with its own, new Viewport)
2799 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2801 if (!copyAnnotation)
2804 * remove all groups and annotation except for the automatic stuff
2806 newap.av.getAlignment().deleteAllGroups();
2807 newap.av.getAlignment().deleteAllAnnotations(false);
2810 newap.av.setGatherViewsHere(false);
2812 if (viewport.viewName == null)
2814 viewport.viewName = MessageManager
2815 .getString("label.view_name_original");
2819 * Views share the same edits undo and redo stacks
2821 newap.av.setHistoryList(viewport.getHistoryList());
2822 newap.av.setRedoList(viewport.getRedoList());
2825 * Views share the same mappings; need to deregister any new mappings
2826 * created by copyAlignPanel, and register the new reference to the shared
2829 newap.av.replaceMappings(viewport.getAlignment());
2832 * start up cDNA consensus (if applicable) now mappings are in place
2834 if (newap.av.initComplementConsensus())
2836 newap.refresh(true); // adjust layout of annotations
2839 newap.av.viewName = getNewViewName(viewTitle);
2841 addAlignmentPanel(newap, true);
2842 newap.alignmentChanged();
2844 if (alignPanels.size() == 2)
2846 viewport.setGatherViewsHere(true);
2848 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2853 * Make a new name for the view, ensuring it is unique within the current
2854 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2855 * these now use viewId. Unique view names are still desirable for usability.)
2860 protected String getNewViewName(String viewTitle)
2862 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2863 boolean addFirstIndex = false;
2864 if (viewTitle == null || viewTitle.trim().length() == 0)
2866 viewTitle = MessageManager.getString("action.view");
2867 addFirstIndex = true;
2871 index = 1;// we count from 1 if given a specific name
2873 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2875 List<Component> comps = PaintRefresher.components
2876 .get(viewport.getSequenceSetId());
2878 List<String> existingNames = getExistingViewNames(comps);
2880 while (existingNames.contains(newViewName))
2882 newViewName = viewTitle + " " + (++index);
2888 * Returns a list of distinct view names found in the given list of
2889 * components. View names are held on the viewport of an AlignmentPanel.
2894 protected List<String> getExistingViewNames(List<Component> comps)
2896 List<String> existingNames = new ArrayList<>();
2897 for (Component comp : comps)
2899 if (comp instanceof AlignmentPanel)
2901 AlignmentPanel ap = (AlignmentPanel) comp;
2902 if (!existingNames.contains(ap.av.viewName))
2904 existingNames.add(ap.av.viewName);
2908 return existingNames;
2912 * Explode tabbed views into separate windows.
2915 public void expandViews_actionPerformed(ActionEvent e)
2917 Desktop.explodeViews(this);
2921 * Gather views in separate windows back into a tabbed presentation.
2924 public void gatherViews_actionPerformed(ActionEvent e)
2926 Desktop.instance.gatherViews(this);
2936 public void font_actionPerformed(ActionEvent e)
2938 new FontChooser(alignPanel);
2948 protected void seqLimit_actionPerformed(ActionEvent e)
2950 viewport.setShowJVSuffix(seqLimits.isSelected());
2952 alignPanel.getIdPanel().getIdCanvas()
2953 .setPreferredSize(alignPanel.calculateIdWidth());
2954 alignPanel.paintAlignment(true);
2958 public void idRightAlign_actionPerformed(ActionEvent e)
2960 viewport.setRightAlignIds(idRightAlign.isSelected());
2961 alignPanel.paintAlignment(true);
2965 public void centreColumnLabels_actionPerformed(ActionEvent e)
2967 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2968 alignPanel.paintAlignment(true);
2974 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2977 protected void followHighlight_actionPerformed()
2980 * Set the 'follow' flag on the Viewport (and scroll to position if now
2983 final boolean state = this.followHighlightMenuItem.getState();
2984 viewport.setFollowHighlight(state);
2987 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2998 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3000 viewport.setColourText(colourTextMenuItem.isSelected());
3001 alignPanel.paintAlignment(true);
3011 public void wrapMenuItem_actionPerformed(ActionEvent e)
3013 scaleAbove.setVisible(wrapMenuItem.isSelected());
3014 scaleLeft.setVisible(wrapMenuItem.isSelected());
3015 scaleRight.setVisible(wrapMenuItem.isSelected());
3016 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3017 alignPanel.updateLayout();
3021 public void showAllSeqs_actionPerformed(ActionEvent e)
3023 viewport.showAllHiddenSeqs();
3027 public void showAllColumns_actionPerformed(ActionEvent e)
3029 viewport.showAllHiddenColumns();
3030 alignPanel.paintAlignment(true);
3031 viewport.sendSelection();
3035 public void hideSelSequences_actionPerformed(ActionEvent e)
3037 viewport.hideAllSelectedSeqs();
3041 * called by key handler and the hide all/show all menu items
3046 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3049 boolean hide = false;
3050 SequenceGroup sg = viewport.getSelectionGroup();
3051 if (!toggleSeqs && !toggleCols)
3053 // Hide everything by the current selection - this is a hack - we do the
3054 // invert and then hide
3055 // first check that there will be visible columns after the invert.
3056 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3057 && sg.getStartRes() <= sg.getEndRes()))
3059 // now invert the sequence set, if required - empty selection implies
3060 // that no hiding is required.
3063 invertSequenceMenuItem_actionPerformed(null);
3064 sg = viewport.getSelectionGroup();
3068 viewport.expandColSelection(sg, true);
3069 // finally invert the column selection and get the new sequence
3071 invertColSel_actionPerformed(null);
3078 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3080 hideSelSequences_actionPerformed(null);
3083 else if (!(toggleCols && viewport.hasSelectedColumns()))
3085 showAllSeqs_actionPerformed(null);
3091 if (viewport.hasSelectedColumns())
3093 hideSelColumns_actionPerformed(null);
3096 viewport.setSelectionGroup(sg);
3101 showAllColumns_actionPerformed(null);
3110 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3111 * event.ActionEvent)
3114 public void hideAllButSelection_actionPerformed(ActionEvent e)
3116 toggleHiddenRegions(false, false);
3117 viewport.sendSelection();
3124 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3128 public void hideAllSelection_actionPerformed(ActionEvent e)
3130 SequenceGroup sg = viewport.getSelectionGroup();
3131 viewport.expandColSelection(sg, false);
3132 viewport.hideAllSelectedSeqs();
3133 viewport.hideSelectedColumns();
3134 alignPanel.paintAlignment(true);
3135 viewport.sendSelection();
3142 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3146 public void showAllhidden_actionPerformed(ActionEvent e)
3148 viewport.showAllHiddenColumns();
3149 viewport.showAllHiddenSeqs();
3150 alignPanel.paintAlignment(true);
3151 viewport.sendSelection();
3155 public void hideSelColumns_actionPerformed(ActionEvent e)
3157 viewport.hideSelectedColumns();
3158 alignPanel.paintAlignment(true);
3159 viewport.sendSelection();
3163 public void hiddenMarkers_actionPerformed(ActionEvent e)
3165 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3176 protected void scaleAbove_actionPerformed(ActionEvent e)
3178 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3179 alignPanel.paintAlignment(true);
3189 protected void scaleLeft_actionPerformed(ActionEvent e)
3191 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3192 alignPanel.paintAlignment(true);
3202 protected void scaleRight_actionPerformed(ActionEvent e)
3204 viewport.setScaleRightWrapped(scaleRight.isSelected());
3205 alignPanel.paintAlignment(true);
3215 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3217 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3218 alignPanel.paintAlignment(true);
3228 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3230 viewport.setShowText(viewTextMenuItem.isSelected());
3231 alignPanel.paintAlignment(true);
3241 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3243 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3244 alignPanel.paintAlignment(true);
3247 public FeatureSettings featureSettings;
3250 public FeatureSettingsControllerI getFeatureSettingsUI()
3252 return featureSettings;
3256 public void featureSettings_actionPerformed(ActionEvent e)
3258 if (featureSettings != null)
3260 featureSettings.close();
3261 featureSettings = null;
3263 if (!showSeqFeatures.isSelected())
3265 // make sure features are actually displayed
3266 showSeqFeatures.setSelected(true);
3267 showSeqFeatures_actionPerformed(null);
3269 featureSettings = new FeatureSettings(this);
3273 * Set or clear 'Show Sequence Features'
3279 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3281 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3282 alignPanel.paintAlignment(true);
3286 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3287 * the annotations panel as a whole.
3289 * The options to show/hide all annotations should be enabled when the panel
3290 * is shown, and disabled when the panel is hidden.
3295 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3297 final boolean setVisible = annotationPanelMenuItem.isSelected();
3298 viewport.setShowAnnotation(setVisible);
3299 this.showAllSeqAnnotations.setEnabled(setVisible);
3300 this.hideAllSeqAnnotations.setEnabled(setVisible);
3301 this.showAllAlAnnotations.setEnabled(setVisible);
3302 this.hideAllAlAnnotations.setEnabled(setVisible);
3303 alignPanel.updateLayout();
3307 public void alignmentProperties()
3309 JEditorPane editPane = new JEditorPane("text/html", "");
3310 editPane.setEditable(false);
3311 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3314 MessageManager.formatMessage("label.html_content", new Object[]
3315 { contents.toString() }));
3316 JInternalFrame frame = new JInternalFrame();
3317 frame.getContentPane().add(new JScrollPane(editPane));
3319 Desktop.addInternalFrame(frame, MessageManager
3320 .formatMessage("label.alignment_properties", new Object[]
3321 { getTitle() }), 500, 400);
3331 public void overviewMenuItem_actionPerformed(ActionEvent e)
3333 if (alignPanel.overviewPanel != null)
3338 JInternalFrame frame = new JInternalFrame();
3339 final OverviewPanel overview = new OverviewPanel(alignPanel);
3340 frame.setContentPane(overview);
3341 Desktop.addInternalFrame(frame, MessageManager
3342 .formatMessage("label.overview_params", new Object[]
3343 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3346 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3347 frame.addInternalFrameListener(
3348 new javax.swing.event.InternalFrameAdapter()
3351 public void internalFrameClosed(
3352 javax.swing.event.InternalFrameEvent evt)
3355 alignPanel.setOverviewPanel(null);
3359 alignPanel.setOverviewPanel(overview);
3363 public void textColour_actionPerformed()
3365 new TextColourChooser().chooseColour(alignPanel, null);
3369 * public void covariationColour_actionPerformed() {
3371 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3375 public void annotationColour_actionPerformed()
3377 new AnnotationColourChooser(viewport, alignPanel);
3381 public void annotationColumn_actionPerformed(ActionEvent e)
3383 new AnnotationColumnChooser(viewport, alignPanel);
3387 * Action on the user checking or unchecking the option to apply the selected
3388 * colour scheme to all groups. If unchecked, groups may have their own
3389 * independent colour schemes.
3394 public void applyToAllGroups_actionPerformed(boolean selected)
3396 viewport.setColourAppliesToAllGroups(selected);
3400 * Action on user selecting a colour from the colour menu
3403 * the name (not the menu item label!) of the colour scheme
3406 public void changeColour_actionPerformed(String name)
3409 * 'User Defined' opens a panel to configure or load a
3410 * user-defined colour scheme
3412 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3414 new UserDefinedColours(alignPanel);
3419 * otherwise set the chosen colour scheme (or null for 'None')
3421 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3422 viewport.getAlignment(), viewport.getHiddenRepSequences());
3427 * Actions on setting or changing the alignment colour scheme
3432 public void changeColour(ColourSchemeI cs)
3434 // TODO: pull up to controller method
3435 ColourMenuHelper.setColourSelected(colourMenu, cs);
3437 viewport.setGlobalColourScheme(cs);
3439 alignPanel.paintAlignment(true);
3443 * Show the PID threshold slider panel
3446 protected void modifyPID_actionPerformed()
3448 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3449 alignPanel.getViewName());
3450 SliderPanel.showPIDSlider();
3454 * Show the Conservation slider panel
3457 protected void modifyConservation_actionPerformed()
3459 SliderPanel.setConservationSlider(alignPanel,
3460 viewport.getResidueShading(), alignPanel.getViewName());
3461 SliderPanel.showConservationSlider();
3465 * Action on selecting or deselecting (Colour) By Conservation
3468 public void conservationMenuItem_actionPerformed(boolean selected)
3470 modifyConservation.setEnabled(selected);
3471 viewport.setConservationSelected(selected);
3472 viewport.getResidueShading().setConservationApplied(selected);
3474 changeColour(viewport.getGlobalColourScheme());
3477 modifyConservation_actionPerformed();
3481 SliderPanel.hideConservationSlider();
3486 * Action on selecting or deselecting (Colour) Above PID Threshold
3489 public void abovePIDThreshold_actionPerformed(boolean selected)
3491 modifyPID.setEnabled(selected);
3492 viewport.setAbovePIDThreshold(selected);
3495 viewport.getResidueShading().setThreshold(0,
3496 viewport.isIgnoreGapsConsensus());
3499 changeColour(viewport.getGlobalColourScheme());
3502 modifyPID_actionPerformed();
3506 SliderPanel.hidePIDSlider();
3517 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3519 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3520 AlignmentSorter.sortByPID(viewport.getAlignment(),
3521 viewport.getAlignment().getSequenceAt(0));
3522 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3523 viewport.getAlignment()));
3524 alignPanel.paintAlignment(true);
3534 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3536 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3537 AlignmentSorter.sortByID(viewport.getAlignment());
3539 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3540 alignPanel.paintAlignment(true);
3550 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3552 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3553 AlignmentSorter.sortByLength(viewport.getAlignment());
3554 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3555 viewport.getAlignment()));
3556 alignPanel.paintAlignment(true);
3566 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3568 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3569 AlignmentSorter.sortByGroup(viewport.getAlignment());
3570 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3571 viewport.getAlignment()));
3573 alignPanel.paintAlignment(true);
3583 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3585 new RedundancyPanel(alignPanel, this);
3595 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3597 if ((viewport.getSelectionGroup() == null)
3598 || (viewport.getSelectionGroup().getSize() < 2))
3600 JvOptionPane.showInternalMessageDialog(this,
3601 MessageManager.getString(
3602 "label.you_must_select_least_two_sequences"),
3603 MessageManager.getString("label.invalid_selection"),
3604 JvOptionPane.WARNING_MESSAGE);
3608 JInternalFrame frame = new JInternalFrame();
3609 frame.setContentPane(new PairwiseAlignPanel(viewport));
3610 Desktop.addInternalFrame(frame,
3611 MessageManager.getString("action.pairwise_alignment"), 600,
3617 public void autoCalculate_actionPerformed(ActionEvent e)
3619 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3620 if (viewport.autoCalculateConsensus)
3622 viewport.firePropertyChange("alignment", null,
3623 viewport.getAlignment().getSequences());
3628 public void sortByTreeOption_actionPerformed(ActionEvent e)
3630 viewport.sortByTree = sortByTree.isSelected();
3634 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3636 viewport.followSelection = listenToViewSelections.isSelected();
3640 * Constructs a tree panel and adds it to the desktop
3643 * tree type (NJ or AV)
3645 * name of score model used to compute the tree
3647 * parameters for the distance or similarity calculation
3649 void newTreePanel(String type, String modelName,
3650 SimilarityParamsI options)
3652 String frameTitle = "";
3655 boolean onSelection = false;
3656 if (viewport.getSelectionGroup() != null
3657 && viewport.getSelectionGroup().getSize() > 0)
3659 SequenceGroup sg = viewport.getSelectionGroup();
3661 /* Decide if the selection is a column region */
3662 for (SequenceI _s : sg.getSequences())
3664 if (_s.getLength() < sg.getEndRes())
3666 JvOptionPane.showMessageDialog(Desktop.desktop,
3667 MessageManager.getString(
3668 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3669 MessageManager.getString(
3670 "label.sequences_selection_not_aligned"),
3671 JvOptionPane.WARNING_MESSAGE);
3680 if (viewport.getAlignment().getHeight() < 2)
3686 tp = new TreePanel(alignPanel, type, modelName, options);
3687 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3689 frameTitle += " from ";
3691 if (viewport.viewName != null)
3693 frameTitle += viewport.viewName + " of ";
3696 frameTitle += this.title;
3698 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3709 public void addSortByOrderMenuItem(String title,
3710 final AlignmentOrder order)
3712 final JMenuItem item = new JMenuItem(MessageManager
3713 .formatMessage("action.by_title_param", new Object[]
3716 item.addActionListener(new java.awt.event.ActionListener()
3719 public void actionPerformed(ActionEvent e)
3721 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3723 // TODO: JBPNote - have to map order entries to curent SequenceI
3725 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3727 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3728 viewport.getAlignment()));
3730 alignPanel.paintAlignment(true);
3736 * Add a new sort by annotation score menu item
3739 * the menu to add the option to
3741 * the label used to retrieve scores for each sequence on the
3744 public void addSortByAnnotScoreMenuItem(JMenu sort,
3745 final String scoreLabel)
3747 final JMenuItem item = new JMenuItem(scoreLabel);
3749 item.addActionListener(new java.awt.event.ActionListener()
3752 public void actionPerformed(ActionEvent e)
3754 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3755 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3756 viewport.getAlignment());// ,viewport.getSelectionGroup());
3757 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3758 viewport.getAlignment()));
3759 alignPanel.paintAlignment(true);
3765 * last hash for alignment's annotation array - used to minimise cost of
3768 protected int _annotationScoreVectorHash;
3771 * search the alignment and rebuild the sort by annotation score submenu the
3772 * last alignment annotation vector hash is stored to minimize cost of
3773 * rebuilding in subsequence calls.
3777 public void buildSortByAnnotationScoresMenu()
3779 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3784 if (viewport.getAlignment().getAlignmentAnnotation()
3785 .hashCode() != _annotationScoreVectorHash)
3787 sortByAnnotScore.removeAll();
3788 // almost certainly a quicker way to do this - but we keep it simple
3789 Hashtable scoreSorts = new Hashtable();
3790 AlignmentAnnotation aann[];
3791 for (SequenceI sqa : viewport.getAlignment().getSequences())
3793 aann = sqa.getAnnotation();
3794 for (int i = 0; aann != null && i < aann.length; i++)
3796 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3798 scoreSorts.put(aann[i].label, aann[i].label);
3802 Enumeration labels = scoreSorts.keys();
3803 while (labels.hasMoreElements())
3805 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3806 (String) labels.nextElement());
3808 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3811 _annotationScoreVectorHash = viewport.getAlignment()
3812 .getAlignmentAnnotation().hashCode();
3817 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3818 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3819 * call. Listeners are added to remove the menu item when the treePanel is
3820 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3824 public void buildTreeSortMenu()
3826 sortByTreeMenu.removeAll();
3828 List<Component> comps = PaintRefresher.components
3829 .get(viewport.getSequenceSetId());
3830 List<TreePanel> treePanels = new ArrayList<>();
3831 for (Component comp : comps)
3833 if (comp instanceof TreePanel)
3835 treePanels.add((TreePanel) comp);
3839 if (treePanels.size() < 1)
3841 sortByTreeMenu.setVisible(false);
3845 sortByTreeMenu.setVisible(true);
3847 for (final TreePanel tp : treePanels)
3849 final JMenuItem item = new JMenuItem(tp.getTitle());
3850 item.addActionListener(new java.awt.event.ActionListener()
3853 public void actionPerformed(ActionEvent e)
3855 tp.sortByTree_actionPerformed();
3856 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3861 sortByTreeMenu.add(item);
3865 public boolean sortBy(AlignmentOrder alorder, String undoname)
3867 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3868 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3869 if (undoname != null)
3871 addHistoryItem(new OrderCommand(undoname, oldOrder,
3872 viewport.getAlignment()));
3874 alignPanel.paintAlignment(true);
3879 * Work out whether the whole set of sequences or just the selected set will
3880 * be submitted for multiple alignment.
3883 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3885 // Now, check we have enough sequences
3886 AlignmentView msa = null;
3888 if ((viewport.getSelectionGroup() != null)
3889 && (viewport.getSelectionGroup().getSize() > 1))
3891 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3892 // some common interface!
3894 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3895 * SequenceI[sz = seqs.getSize(false)];
3897 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3898 * seqs.getSequenceAt(i); }
3900 msa = viewport.getAlignmentView(true);
3902 else if (viewport.getSelectionGroup() != null
3903 && viewport.getSelectionGroup().getSize() == 1)
3905 int option = JvOptionPane.showConfirmDialog(this,
3906 MessageManager.getString("warn.oneseq_msainput_selection"),
3907 MessageManager.getString("label.invalid_selection"),
3908 JvOptionPane.OK_CANCEL_OPTION);
3909 if (option == JvOptionPane.OK_OPTION)
3911 msa = viewport.getAlignmentView(false);
3916 msa = viewport.getAlignmentView(false);
3922 * Decides what is submitted to a secondary structure prediction service: the
3923 * first sequence in the alignment, or in the current selection, or, if the
3924 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3925 * region or the whole alignment. (where the first sequence in the set is the
3926 * one that the prediction will be for).
3928 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3930 AlignmentView seqs = null;
3932 if ((viewport.getSelectionGroup() != null)
3933 && (viewport.getSelectionGroup().getSize() > 0))
3935 seqs = viewport.getAlignmentView(true);
3939 seqs = viewport.getAlignmentView(false);
3941 // limit sequences - JBPNote in future - could spawn multiple prediction
3943 // TODO: viewport.getAlignment().isAligned is a global state - the local
3944 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3945 if (!viewport.getAlignment().isAligned(false))
3947 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3948 // TODO: if seqs.getSequences().length>1 then should really have warned
3962 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3964 // Pick the tree file
3965 JalviewFileChooser chooser = new JalviewFileChooser(
3966 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3967 chooser.setFileView(new JalviewFileView());
3968 chooser.setDialogTitle(
3969 MessageManager.getString("label.select_newick_like_tree_file"));
3970 chooser.setToolTipText(
3971 MessageManager.getString("label.load_tree_file"));
3973 int value = chooser.showOpenDialog(null);
3975 if (value == JalviewFileChooser.APPROVE_OPTION)
3977 String filePath = chooser.getSelectedFile().getPath();
3978 Cache.setProperty("LAST_DIRECTORY", filePath);
3979 NewickFile fin = null;
3982 fin = new NewickFile(filePath, DataSourceType.FILE);
3983 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
3984 } catch (Exception ex)
3986 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
3987 MessageManager.getString("label.problem_reading_tree_file"),
3988 JvOptionPane.WARNING_MESSAGE);
3989 ex.printStackTrace();
3991 if (fin != null && fin.hasWarningMessage())
3993 JvOptionPane.showMessageDialog(Desktop.desktop,
3994 fin.getWarningMessage(),
3996 .getString("label.possible_problem_with_tree_file"),
3997 JvOptionPane.WARNING_MESSAGE);
4002 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4004 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4007 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4008 int h, int x, int y)
4010 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4014 * Add a treeviewer for the tree extracted from a Newick file object to the
4015 * current alignment view
4022 * Associated alignment input data (or null)
4031 * @return TreePanel handle
4033 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4034 AlignmentView input, int w, int h, int x, int y)
4036 TreePanel tp = null;
4042 if (nf.getTree() != null)
4044 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4050 tp.setLocation(x, y);
4053 Desktop.addInternalFrame(tp, treeTitle, w, h);
4055 } catch (Exception ex)
4057 ex.printStackTrace();
4063 private boolean buildingMenu = false;
4066 * Generates menu items and listener event actions for web service clients
4069 public void BuildWebServiceMenu()
4071 while (buildingMenu)
4075 System.err.println("Waiting for building menu to finish.");
4077 } catch (Exception e)
4081 final AlignFrame me = this;
4082 buildingMenu = true;
4083 new Thread(new Runnable()
4088 final List<JMenuItem> legacyItems = new ArrayList<>();
4091 // System.err.println("Building ws menu again "
4092 // + Thread.currentThread());
4093 // TODO: add support for context dependent disabling of services based
4095 // alignment and current selection
4096 // TODO: add additional serviceHandle parameter to specify abstract
4098 // class independently of AbstractName
4099 // TODO: add in rediscovery GUI function to restart discoverer
4100 // TODO: group services by location as well as function and/or
4102 // object broker mechanism.
4103 final Vector<JMenu> wsmenu = new Vector<>();
4104 final IProgressIndicator af = me;
4107 * do not i18n these strings - they are hard-coded in class
4108 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4109 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4111 final JMenu msawsmenu = new JMenu("Alignment");
4112 final JMenu secstrmenu = new JMenu(
4113 "Secondary Structure Prediction");
4114 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4115 final JMenu analymenu = new JMenu("Analysis");
4116 final JMenu dismenu = new JMenu("Protein Disorder");
4117 // JAL-940 - only show secondary structure prediction services from
4118 // the legacy server
4119 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4121 Discoverer.services != null && (Discoverer.services.size() > 0))
4123 // TODO: refactor to allow list of AbstractName/Handler bindings to
4125 // stored or retrieved from elsewhere
4126 // No MSAWS used any more:
4127 // Vector msaws = null; // (Vector)
4128 // Discoverer.services.get("MsaWS");
4129 Vector secstrpr = (Vector) Discoverer.services
4131 if (secstrpr != null)
4133 // Add any secondary structure prediction services
4134 for (int i = 0, j = secstrpr.size(); i < j; i++)
4136 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4138 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4139 .getServiceClient(sh);
4140 int p = secstrmenu.getItemCount();
4141 impl.attachWSMenuEntry(secstrmenu, me);
4142 int q = secstrmenu.getItemCount();
4143 for (int litm = p; litm < q; litm++)
4145 legacyItems.add(secstrmenu.getItem(litm));
4151 // Add all submenus in the order they should appear on the web
4153 wsmenu.add(msawsmenu);
4154 wsmenu.add(secstrmenu);
4155 wsmenu.add(dismenu);
4156 wsmenu.add(analymenu);
4157 // No search services yet
4158 // wsmenu.add(seqsrchmenu);
4160 javax.swing.SwingUtilities.invokeLater(new Runnable()
4167 webService.removeAll();
4168 // first, add discovered services onto the webservices menu
4169 if (wsmenu.size() > 0)
4171 for (int i = 0, j = wsmenu.size(); i < j; i++)
4173 webService.add(wsmenu.get(i));
4178 webService.add(me.webServiceNoServices);
4180 // TODO: move into separate menu builder class.
4181 boolean new_sspred = false;
4182 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4184 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4185 if (jws2servs != null)
4187 if (jws2servs.hasServices())
4189 jws2servs.attachWSMenuEntry(webService, me);
4190 for (Jws2Instance sv : jws2servs.getServices())
4192 if (sv.description.toLowerCase().contains("jpred"))
4194 for (JMenuItem jmi : legacyItems)
4196 jmi.setVisible(false);
4202 if (jws2servs.isRunning())
4204 JMenuItem tm = new JMenuItem(
4205 "Still discovering JABA Services");
4206 tm.setEnabled(false);
4211 build_urlServiceMenu(me.webService);
4212 build_fetchdbmenu(webService);
4213 for (JMenu item : wsmenu)
4215 if (item.getItemCount() == 0)
4217 item.setEnabled(false);
4221 item.setEnabled(true);
4224 } catch (Exception e)
4227 "Exception during web service menu building process.",
4232 } catch (Exception e)
4235 buildingMenu = false;
4242 * construct any groupURL type service menu entries.
4246 private void build_urlServiceMenu(JMenu webService)
4248 // TODO: remove this code when 2.7 is released
4249 // DEBUG - alignmentView
4251 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4252 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4254 * @Override public void actionPerformed(ActionEvent e) {
4255 * jalview.datamodel.AlignmentView
4256 * .testSelectionViews(af.viewport.getAlignment(),
4257 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4259 * }); webService.add(testAlView);
4261 // TODO: refactor to RestClient discoverer and merge menu entries for
4262 // rest-style services with other types of analysis/calculation service
4263 // SHmmr test client - still being implemented.
4264 // DEBUG - alignmentView
4266 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4269 client.attachWSMenuEntry(
4270 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4276 * Searches the alignment sequences for xRefs and builds the Show
4277 * Cross-References menu (formerly called Show Products), with database
4278 * sources for which cross-references are found (protein sources for a
4279 * nucleotide alignment and vice versa)
4281 * @return true if Show Cross-references menu should be enabled
4283 public boolean canShowProducts()
4285 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4286 AlignmentI dataset = viewport.getAlignment().getDataset();
4288 showProducts.removeAll();
4289 final boolean dna = viewport.getAlignment().isNucleotide();
4291 if (seqs == null || seqs.length == 0)
4293 // nothing to see here.
4297 boolean showp = false;
4300 List<String> ptypes = new CrossRef(seqs, dataset)
4301 .findXrefSourcesForSequences(dna);
4303 for (final String source : ptypes)
4306 final AlignFrame af = this;
4307 JMenuItem xtype = new JMenuItem(source);
4308 xtype.addActionListener(new ActionListener()
4311 public void actionPerformed(ActionEvent e)
4313 showProductsFor(af.viewport.getSequenceSelection(), dna,
4317 showProducts.add(xtype);
4319 showProducts.setVisible(showp);
4320 showProducts.setEnabled(showp);
4321 } catch (Exception e)
4324 "canShowProducts threw an exception - please report to help@jalview.org",
4332 * Finds and displays cross-references for the selected sequences (protein
4333 * products for nucleotide sequences, dna coding sequences for peptides).
4336 * the sequences to show cross-references for
4338 * true if from a nucleotide alignment (so showing proteins)
4340 * the database to show cross-references for
4342 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4343 final String source)
4345 new Thread(CrossRefAction.showProductsFor(sel, _odna, source, this))
4350 * Construct and display a new frame containing the translation of this
4351 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4354 public void showTranslation_actionPerformed(ActionEvent e)
4356 AlignmentI al = null;
4359 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4361 al = dna.translateCdna();
4362 } catch (Exception ex)
4364 jalview.bin.Cache.log.error(
4365 "Exception during translation. Please report this !", ex);
4366 final String msg = MessageManager.getString(
4367 "label.error_when_translating_sequences_submit_bug_report");
4368 final String errorTitle = MessageManager
4369 .getString("label.implementation_error")
4370 + MessageManager.getString("label.translation_failed");
4371 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4372 JvOptionPane.ERROR_MESSAGE);
4375 if (al == null || al.getHeight() == 0)
4377 final String msg = MessageManager.getString(
4378 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4379 final String errorTitle = MessageManager
4380 .getString("label.translation_failed");
4381 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4382 JvOptionPane.WARNING_MESSAGE);
4386 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4387 af.setFileFormat(this.currentFileFormat);
4388 final String newTitle = MessageManager
4389 .formatMessage("label.translation_of_params", new Object[]
4390 { this.getTitle() });
4391 af.setTitle(newTitle);
4392 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4394 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4395 viewport.openSplitFrame(af, new Alignment(seqs));
4399 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4406 * Set the file format
4410 public void setFileFormat(FileFormatI format)
4412 this.currentFileFormat = format;
4416 * Try to load a features file onto the alignment.
4419 * contents or path to retrieve file
4421 * access mode of file (see jalview.io.AlignFile)
4422 * @return true if features file was parsed correctly.
4424 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4426 return avc.parseFeaturesFile(file, sourceType,
4427 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4432 public void refreshFeatureUI(boolean enableIfNecessary)
4434 // note - currently this is only still here rather than in the controller
4435 // because of the featureSettings hard reference that is yet to be
4437 if (enableIfNecessary)
4439 viewport.setShowSequenceFeatures(true);
4440 showSeqFeatures.setSelected(true);
4446 public void dragEnter(DropTargetDragEvent evt)
4451 public void dragExit(DropTargetEvent evt)
4456 public void dragOver(DropTargetDragEvent evt)
4461 public void dropActionChanged(DropTargetDragEvent evt)
4466 public void drop(DropTargetDropEvent evt)
4468 // JAL-1552 - acceptDrop required before getTransferable call for
4469 // Java's Transferable for native dnd
4470 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4471 Transferable t = evt.getTransferable();
4472 List<String> files = new ArrayList<>();
4473 List<DataSourceType> protocols = new ArrayList<>();
4477 Desktop.transferFromDropTarget(files, protocols, evt, t);
4478 } catch (Exception e)
4480 e.printStackTrace();
4486 // check to see if any of these files have names matching sequences in
4488 SequenceIdMatcher idm = new SequenceIdMatcher(
4489 viewport.getAlignment().getSequencesArray());
4491 * Object[] { String,SequenceI}
4493 ArrayList<Object[]> filesmatched = new ArrayList<>();
4494 ArrayList<String> filesnotmatched = new ArrayList<>();
4495 for (int i = 0; i < files.size(); i++)
4497 String file = files.get(i).toString();
4499 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4500 if (protocol == DataSourceType.FILE)
4502 File fl = new File(file);
4503 pdbfn = fl.getName();
4505 else if (protocol == DataSourceType.URL)
4507 URL url = new URL(file);
4508 pdbfn = url.getFile();
4510 if (pdbfn.length() > 0)
4512 // attempt to find a match in the alignment
4513 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4514 int l = 0, c = pdbfn.indexOf(".");
4515 while (mtch == null && c != -1)
4520 } while ((c = pdbfn.indexOf(".", l)) > l);
4523 pdbfn = pdbfn.substring(0, l);
4525 mtch = idm.findAllIdMatches(pdbfn);
4529 FileFormatI type = null;
4532 type = new IdentifyFile().identify(file, protocol);
4533 } catch (Exception ex)
4537 if (type != null && type.isStructureFile())
4539 filesmatched.add(new Object[] { file, protocol, mtch });
4543 // File wasn't named like one of the sequences or wasn't a PDB file.
4544 filesnotmatched.add(file);
4548 if (filesmatched.size() > 0)
4550 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4551 || JvOptionPane.showConfirmDialog(this,
4552 MessageManager.formatMessage(
4553 "label.automatically_associate_structure_files_with_sequences_same_name",
4555 { Integer.valueOf(filesmatched.size())
4557 MessageManager.getString(
4558 "label.automatically_associate_structure_files_by_name"),
4559 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION)
4562 for (Object[] fm : filesmatched)
4564 // try and associate
4565 // TODO: may want to set a standard ID naming formalism for
4566 // associating PDB files which have no IDs.
4567 for (SequenceI toassoc : (SequenceI[]) fm[2])
4569 PDBEntry pe = new AssociatePdbFileWithSeq()
4570 .associatePdbWithSeq((String) fm[0],
4571 (DataSourceType) fm[1], toassoc, false,
4575 System.err.println("Associated file : " + ((String) fm[0])
4576 + " with " + toassoc.getDisplayId(true));
4580 alignPanel.paintAlignment(true);
4584 if (filesnotmatched.size() > 0)
4586 if (assocfiles > 0 && (Cache.getDefault(
4587 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4588 || JvOptionPane.showConfirmDialog(this,
4589 "<html>" + MessageManager.formatMessage(
4590 "label.ignore_unmatched_dropped_files_info",
4592 { Integer.valueOf(filesnotmatched.size())
4595 MessageManager.getString(
4596 "label.ignore_unmatched_dropped_files"),
4597 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4601 for (String fn : filesnotmatched)
4603 loadJalviewDataFile(fn, null, null, null);
4607 } catch (Exception ex)
4609 ex.printStackTrace();
4615 * Attempt to load a "dropped" file or URL string, by testing in turn for
4617 * <li>an Annotation file</li>
4618 * <li>a JNet file</li>
4619 * <li>a features file</li>
4620 * <li>else try to interpret as an alignment file</li>
4624 * either a filename or a URL string.
4625 * @throws InterruptedException
4626 * @throws IOException
4628 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4629 FileFormatI format, SequenceI assocSeq)
4633 if (sourceType == null)
4635 sourceType = FormatAdapter.checkProtocol(file);
4637 // if the file isn't identified, or not positively identified as some
4638 // other filetype (PFAM is default unidentified alignment file type) then
4639 // try to parse as annotation.
4640 boolean isAnnotation = (format == null
4641 || FileFormat.Pfam.equals(format))
4642 ? new AnnotationFile().annotateAlignmentView(viewport,
4648 // first see if its a T-COFFEE score file
4649 TCoffeeScoreFile tcf = null;
4652 tcf = new TCoffeeScoreFile(file, sourceType);
4655 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4659 new TCoffeeColourScheme(viewport.getAlignment()));
4660 isAnnotation = true;
4661 statusBar.setText(MessageManager.getString(
4662 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4666 // some problem - if no warning its probable that the ID matching
4667 // process didn't work
4668 JvOptionPane.showMessageDialog(Desktop.desktop,
4669 tcf.getWarningMessage() == null
4670 ? MessageManager.getString(
4671 "label.check_file_matches_sequence_ids_alignment")
4672 : tcf.getWarningMessage(),
4673 MessageManager.getString(
4674 "label.problem_reading_tcoffee_score_file"),
4675 JvOptionPane.WARNING_MESSAGE);
4682 } catch (Exception x)
4685 "Exception when processing data source as T-COFFEE score file",
4691 // try to see if its a JNet 'concise' style annotation file *before*
4693 // try to parse it as a features file
4696 format = new IdentifyFile().identify(file, sourceType);
4698 if (FileFormat.ScoreMatrix == format)
4700 ScoreMatrixFile sm = new ScoreMatrixFile(
4701 new FileParse(file, sourceType));
4703 // todo: i18n this message
4704 statusBar.setText(MessageManager.formatMessage(
4705 "label.successfully_loaded_matrix",
4706 sm.getMatrixName()));
4708 else if (FileFormat.Jnet.equals(format))
4710 JPredFile predictions = new JPredFile(file, sourceType);
4711 new JnetAnnotationMaker();
4712 JnetAnnotationMaker.add_annotation(predictions,
4713 viewport.getAlignment(), 0, false);
4714 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
4715 viewport.getAlignment().setSeqrep(repseq);
4716 HiddenColumns cs = new HiddenColumns();
4717 cs.hideInsertionsFor(repseq);
4718 viewport.getAlignment().setHiddenColumns(cs);
4719 isAnnotation = true;
4721 // else if (IdentifyFile.FeaturesFile.equals(format))
4722 else if (FileFormat.Features.equals(format))
4724 if (parseFeaturesFile(file, sourceType))
4726 alignPanel.paintAlignment(true);
4731 new FileLoader().LoadFile(viewport, file, sourceType, format);
4737 alignPanel.adjustAnnotationHeight();
4738 viewport.updateSequenceIdColours();
4739 buildSortByAnnotationScoresMenu();
4740 alignPanel.paintAlignment(true);
4742 } catch (Exception ex)
4744 ex.printStackTrace();
4745 } catch (OutOfMemoryError oom)
4750 } catch (Exception x)
4755 + (sourceType != null
4756 ? (sourceType == DataSourceType.PASTE
4758 : "using " + sourceType + " from "
4762 ? "(parsing as '" + format + "' file)"
4764 oom, Desktop.desktop);
4769 * Method invoked by the ChangeListener on the tabbed pane, in other words
4770 * when a different tabbed pane is selected by the user or programmatically.
4773 public void tabSelectionChanged(int index)
4777 alignPanel = alignPanels.get(index);
4778 viewport = alignPanel.av;
4779 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4780 setMenusFromViewport(viewport);
4784 * 'focus' any colour slider that is open to the selected viewport
4786 if (viewport.getConservationSelected())
4788 SliderPanel.setConservationSlider(alignPanel,
4789 viewport.getResidueShading(), alignPanel.getViewName());
4793 SliderPanel.hideConservationSlider();
4795 if (viewport.getAbovePIDThreshold())
4797 SliderPanel.setPIDSliderSource(alignPanel,
4798 viewport.getResidueShading(), alignPanel.getViewName());
4802 SliderPanel.hidePIDSlider();
4806 * If there is a frame linked to this one in a SplitPane, switch it to the
4807 * same view tab index. No infinite recursion of calls should happen, since
4808 * tabSelectionChanged() should not get invoked on setting the selected
4809 * index to an unchanged value. Guard against setting an invalid index
4810 * before the new view peer tab has been created.
4812 final AlignViewportI peer = viewport.getCodingComplement();
4815 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4816 .getAlignPanel().alignFrame;
4817 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4819 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4825 * On right mouse click on view tab, prompt for and set new view name.
4828 public void tabbedPane_mousePressed(MouseEvent e)
4830 if (e.isPopupTrigger())
4832 String msg = MessageManager.getString("label.enter_view_name");
4833 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4834 JvOptionPane.QUESTION_MESSAGE);
4838 viewport.viewName = reply;
4839 // TODO warn if reply is in getExistingViewNames()?
4840 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4845 public AlignViewport getCurrentView()
4851 * Open the dialog for regex description parsing.
4854 protected void extractScores_actionPerformed(ActionEvent e)
4856 ParseProperties pp = new jalview.analysis.ParseProperties(
4857 viewport.getAlignment());
4858 // TODO: verify regex and introduce GUI dialog for version 2.5
4859 // if (pp.getScoresFromDescription("col", "score column ",
4860 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4862 if (pp.getScoresFromDescription("description column",
4863 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4865 buildSortByAnnotationScoresMenu();
4873 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4877 protected void showDbRefs_actionPerformed(ActionEvent e)
4879 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4885 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4889 protected void showNpFeats_actionPerformed(ActionEvent e)
4891 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4895 * find the viewport amongst the tabs in this alignment frame and close that
4900 public boolean closeView(AlignViewportI av)
4904 this.closeMenuItem_actionPerformed(false);
4907 Component[] comp = tabbedPane.getComponents();
4908 for (int i = 0; comp != null && i < comp.length; i++)
4910 if (comp[i] instanceof AlignmentPanel)
4912 if (((AlignmentPanel) comp[i]).av == av)
4915 closeView((AlignmentPanel) comp[i]);
4923 protected void build_fetchdbmenu(JMenu webService)
4925 // Temporary hack - DBRef Fetcher always top level ws entry.
4926 // TODO We probably want to store a sequence database checklist in
4927 // preferences and have checkboxes.. rather than individual sources selected
4929 final JMenu rfetch = new JMenu(
4930 MessageManager.getString("action.fetch_db_references"));
4931 rfetch.setToolTipText(MessageManager.getString(
4932 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4933 webService.add(rfetch);
4935 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4936 MessageManager.getString("option.trim_retrieved_seqs"));
4937 trimrs.setToolTipText(
4938 MessageManager.getString("label.trim_retrieved_sequences"));
4939 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
4940 trimrs.addActionListener(new ActionListener()
4943 public void actionPerformed(ActionEvent e)
4945 trimrs.setSelected(trimrs.isSelected());
4946 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
4947 Boolean.valueOf(trimrs.isSelected()).toString());
4951 JMenuItem fetchr = new JMenuItem(
4952 MessageManager.getString("label.standard_databases"));
4953 fetchr.setToolTipText(
4954 MessageManager.getString("label.fetch_embl_uniprot"));
4955 fetchr.addActionListener(new ActionListener()
4959 public void actionPerformed(ActionEvent e)
4961 new Thread(new Runnable()
4966 boolean isNucleotide = alignPanel.alignFrame.getViewport()
4967 .getAlignment().isNucleotide();
4968 DBRefFetcher dbRefFetcher = new DBRefFetcher(
4969 alignPanel.av.getSequenceSelection(),
4970 alignPanel.alignFrame, null,
4971 alignPanel.alignFrame.featureSettings, isNucleotide);
4972 dbRefFetcher.addListener(new FetchFinishedListenerI()
4975 public void finished()
4977 AlignFrame.this.setMenusForViewport();
4980 dbRefFetcher.fetchDBRefs(false);
4988 final AlignFrame me = this;
4989 new Thread(new Runnable()
4994 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
4995 .getSequenceFetcherSingleton(me);
4996 javax.swing.SwingUtilities.invokeLater(new Runnable()
5001 String[] dbclasses = sf.getOrderedSupportedSources();
5002 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5003 // jalview.util.QuickSort.sort(otherdb, otherdb);
5004 List<DbSourceProxy> otherdb;
5005 JMenu dfetch = new JMenu();
5006 JMenu ifetch = new JMenu();
5007 JMenuItem fetchr = null;
5008 int comp = 0, icomp = 0, mcomp = 15;
5009 String mname = null;
5011 for (String dbclass : dbclasses)
5013 otherdb = sf.getSourceProxy(dbclass);
5014 // add a single entry for this class, or submenu allowing 'fetch
5016 if (otherdb == null || otherdb.size() < 1)
5020 // List<DbSourceProxy> dbs=otherdb;
5021 // otherdb=new ArrayList<DbSourceProxy>();
5022 // for (DbSourceProxy db:dbs)
5024 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5028 mname = "From " + dbclass;
5030 if (otherdb.size() == 1)
5032 final DbSourceProxy[] dassource = otherdb
5033 .toArray(new DbSourceProxy[0]);
5034 DbSourceProxy src = otherdb.get(0);
5035 fetchr = new JMenuItem(src.getDbSource());
5036 fetchr.addActionListener(new ActionListener()
5040 public void actionPerformed(ActionEvent e)
5042 new Thread(new Runnable()
5048 boolean isNucleotide = alignPanel.alignFrame
5049 .getViewport().getAlignment()
5051 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5052 alignPanel.av.getSequenceSelection(),
5053 alignPanel.alignFrame, dassource,
5054 alignPanel.alignFrame.featureSettings,
5057 .addListener(new FetchFinishedListenerI()
5060 public void finished()
5062 AlignFrame.this.setMenusForViewport();
5065 dbRefFetcher.fetchDBRefs(false);
5071 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5072 MessageManager.formatMessage(
5073 "label.fetch_retrieve_from", new Object[]
5074 { src.getDbName() })));
5080 final DbSourceProxy[] dassource = otherdb
5081 .toArray(new DbSourceProxy[0]);
5083 DbSourceProxy src = otherdb.get(0);
5084 fetchr = new JMenuItem(MessageManager
5085 .formatMessage("label.fetch_all_param", new Object[]
5086 { src.getDbSource() }));
5087 fetchr.addActionListener(new ActionListener()
5090 public void actionPerformed(ActionEvent e)
5092 new Thread(new Runnable()
5098 boolean isNucleotide = alignPanel.alignFrame
5099 .getViewport().getAlignment()
5101 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5102 alignPanel.av.getSequenceSelection(),
5103 alignPanel.alignFrame, dassource,
5104 alignPanel.alignFrame.featureSettings,
5107 .addListener(new FetchFinishedListenerI()
5110 public void finished()
5112 AlignFrame.this.setMenusForViewport();
5115 dbRefFetcher.fetchDBRefs(false);
5121 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5122 MessageManager.formatMessage(
5123 "label.fetch_retrieve_from_all_sources",
5125 { Integer.valueOf(otherdb.size())
5127 src.getDbSource(), src.getDbName() })));
5130 // and then build the rest of the individual menus
5131 ifetch = new JMenu(MessageManager.formatMessage(
5132 "label.source_from_db_source", new Object[]
5133 { src.getDbSource() }));
5135 String imname = null;
5137 for (DbSourceProxy sproxy : otherdb)
5139 String dbname = sproxy.getDbName();
5140 String sname = dbname.length() > 5
5141 ? dbname.substring(0, 5) + "..."
5143 String msname = dbname.length() > 10
5144 ? dbname.substring(0, 10) + "..."
5148 imname = MessageManager
5149 .formatMessage("label.from_msname", new Object[]
5152 fetchr = new JMenuItem(msname);
5153 final DbSourceProxy[] dassrc = { sproxy };
5154 fetchr.addActionListener(new ActionListener()
5158 public void actionPerformed(ActionEvent e)
5160 new Thread(new Runnable()
5166 boolean isNucleotide = alignPanel.alignFrame
5167 .getViewport().getAlignment()
5169 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5170 alignPanel.av.getSequenceSelection(),
5171 alignPanel.alignFrame, dassrc,
5172 alignPanel.alignFrame.featureSettings,
5175 .addListener(new FetchFinishedListenerI()
5178 public void finished()
5180 AlignFrame.this.setMenusForViewport();
5183 dbRefFetcher.fetchDBRefs(false);
5189 fetchr.setToolTipText(
5190 "<html>" + MessageManager.formatMessage(
5191 "label.fetch_retrieve_from", new Object[]
5195 if (++icomp >= mcomp || i == (otherdb.size()))
5197 ifetch.setText(MessageManager.formatMessage(
5198 "label.source_to_target", imname, sname));
5200 ifetch = new JMenu();
5208 if (comp >= mcomp || dbi >= (dbclasses.length))
5210 dfetch.setText(MessageManager.formatMessage(
5211 "label.source_to_target", mname, dbclass));
5213 dfetch = new JMenu();
5226 * Left justify the whole alignment.
5229 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5231 AlignmentI al = viewport.getAlignment();
5233 viewport.firePropertyChange("alignment", null, al);
5237 * Right justify the whole alignment.
5240 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5242 AlignmentI al = viewport.getAlignment();
5244 viewport.firePropertyChange("alignment", null, al);
5248 public void setShowSeqFeatures(boolean b)
5250 showSeqFeatures.setSelected(b);
5251 viewport.setShowSequenceFeatures(b);
5258 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5259 * awt.event.ActionEvent)
5262 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5264 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5265 alignPanel.paintAlignment(true);
5272 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5276 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5278 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5279 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5287 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5288 * .event.ActionEvent)
5291 protected void showGroupConservation_actionPerformed(ActionEvent e)
5293 viewport.setShowGroupConservation(showGroupConservation.getState());
5294 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5301 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5302 * .event.ActionEvent)
5305 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5307 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5308 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5315 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5316 * .event.ActionEvent)
5319 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5321 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5322 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5326 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5328 showSequenceLogo.setState(true);
5329 viewport.setShowSequenceLogo(true);
5330 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5331 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5335 protected void showInformationHistogram_actionPerformed(ActionEvent e)
5337 viewport.setShowInformationHistogram(
5338 showInformationHistogram.getState());
5339 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5343 protected void showHMMSequenceLogo_actionPerformed(ActionEvent e)
5345 viewport.setShowHMMSequenceLogo(showHMMSequenceLogo.getState());
5346 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5350 protected void normaliseHMMSequenceLogo_actionPerformed(ActionEvent e)
5352 showHMMSequenceLogo.setState(true);
5353 viewport.setShowHMMSequenceLogo(true);
5354 viewport.setNormaliseHMMSequenceLogo(normaliseSequenceLogo.getState());
5355 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5359 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5361 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5368 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5369 * .event.ActionEvent)
5372 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5374 if (avc.makeGroupsFromSelection())
5376 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5377 alignPanel.updateAnnotation();
5378 alignPanel.paintAlignment(true);
5382 public void clearAlignmentSeqRep()
5384 // TODO refactor alignmentseqrep to controller
5385 if (viewport.getAlignment().hasSeqrep())
5387 viewport.getAlignment().setSeqrep(null);
5388 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5389 alignPanel.updateAnnotation();
5390 alignPanel.paintAlignment(true);
5395 protected void createGroup_actionPerformed(ActionEvent e)
5397 if (avc.createGroup())
5399 alignPanel.alignmentChanged();
5404 protected void unGroup_actionPerformed(ActionEvent e)
5408 alignPanel.alignmentChanged();
5413 * make the given alignmentPanel the currently selected tab
5415 * @param alignmentPanel
5417 public void setDisplayedView(AlignmentPanel alignmentPanel)
5419 if (!viewport.getSequenceSetId()
5420 .equals(alignmentPanel.av.getSequenceSetId()))
5422 throw new Error(MessageManager.getString(
5423 "error.implementation_error_cannot_show_view_alignment_frame"));
5425 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5426 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5428 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5433 * Action on selection of menu options to Show or Hide annotations.
5436 * @param forSequences
5437 * update sequence-related annotations
5438 * @param forAlignment
5439 * update non-sequence-related annotations
5442 protected void setAnnotationsVisibility(boolean visible,
5443 boolean forSequences, boolean forAlignment)
5445 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5446 .getAlignmentAnnotation();
5451 for (AlignmentAnnotation aa : anns)
5454 * don't display non-positional annotations on an alignment
5456 if (aa.annotations == null)
5460 boolean apply = (aa.sequenceRef == null && forAlignment)
5461 || (aa.sequenceRef != null && forSequences);
5464 aa.visible = visible;
5467 alignPanel.validateAnnotationDimensions(true);
5468 alignPanel.alignmentChanged();
5472 * Store selected annotation sort order for the view and repaint.
5475 protected void sortAnnotations_actionPerformed()
5477 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5479 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5480 alignPanel.paintAlignment(true);
5485 * @return alignment panels in this alignment frame
5487 public List<? extends AlignmentViewPanel> getAlignPanels()
5489 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5493 * Open a new alignment window, with the cDNA associated with this (protein)
5494 * alignment, aligned as is the protein.
5496 protected void viewAsCdna_actionPerformed()
5498 // TODO no longer a menu action - refactor as required
5499 final AlignmentI alignment = getViewport().getAlignment();
5500 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5501 if (mappings == null)
5505 List<SequenceI> cdnaSeqs = new ArrayList<>();
5506 for (SequenceI aaSeq : alignment.getSequences())
5508 for (AlignedCodonFrame acf : mappings)
5510 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5514 * There is a cDNA mapping for this protein sequence - add to new
5515 * alignment. It will share the same dataset sequence as other mapped
5516 * cDNA (no new mappings need to be created).
5518 final Sequence newSeq = new Sequence(dnaSeq);
5519 newSeq.setDatasetSequence(dnaSeq);
5520 cdnaSeqs.add(newSeq);
5524 if (cdnaSeqs.size() == 0)
5526 // show a warning dialog no mapped cDNA
5529 AlignmentI cdna = new Alignment(
5530 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5531 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5532 AlignFrame.DEFAULT_HEIGHT);
5533 cdna.alignAs(alignment);
5534 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5536 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5537 AlignFrame.DEFAULT_HEIGHT);
5541 * Set visibility of dna/protein complement view (available when shown in a
5547 protected void showComplement_actionPerformed(boolean show)
5549 SplitContainerI sf = getSplitViewContainer();
5552 sf.setComplementVisible(this, show);
5557 * Generate the reverse (optionally complemented) of the selected sequences,
5558 * and add them to the alignment
5561 protected void showReverse_actionPerformed(boolean complement)
5563 AlignmentI al = null;
5566 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5567 al = dna.reverseCdna(complement);
5568 viewport.addAlignment(al, "");
5569 addHistoryItem(new EditCommand(
5570 MessageManager.getString("label.add_sequences"), Action.PASTE,
5571 al.getSequencesArray(), 0, al.getWidth(),
5572 viewport.getAlignment()));
5573 } catch (Exception ex)
5575 System.err.println(ex.getMessage());
5581 * Try to run a script in the Groovy console, having first ensured that this
5582 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5583 * be targeted at this alignment.
5586 protected void runGroovy_actionPerformed()
5588 Jalview.setCurrentAlignFrame(this);
5589 groovy.ui.Console console = Desktop.getGroovyConsole();
5590 if (console != null)
5594 console.runScript();
5595 } catch (Exception ex)
5597 System.err.println((ex.toString()));
5598 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5599 MessageManager.getString("label.couldnt_run_groovy_script"),
5600 MessageManager.getString("label.groovy_support_failed"),
5601 JvOptionPane.ERROR_MESSAGE);
5606 System.err.println("Can't run Groovy script as console not found");
5611 * Hides columns containing (or not containing) a specified feature, provided
5612 * that would not leave all columns hidden
5614 * @param featureType
5615 * @param columnsContaining
5618 public boolean hideFeatureColumns(String featureType,
5619 boolean columnsContaining)
5621 boolean notForHiding = avc.markColumnsContainingFeatures(
5622 columnsContaining, false, false, featureType);
5625 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5626 false, featureType))
5628 getViewport().hideSelectedColumns();
5636 protected void selectHighlightedColumns_actionPerformed(
5637 ActionEvent actionEvent)
5639 // include key modifier check in case user selects from menu
5640 avc.markHighlightedColumns(
5641 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5642 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5643 | ActionEvent.CTRL_MASK)) != 0);
5647 * Rebuilds the Colour menu, including any user-defined colours which have
5648 * been loaded either on startup or during the session
5650 public void buildColourMenu()
5652 colourMenu.removeAll();
5654 colourMenu.add(applyToAllGroups);
5655 colourMenu.add(textColour);
5656 colourMenu.addSeparator();
5658 ColourMenuHelper.addMenuItems(colourMenu, this, viewport.getAlignment(),
5661 colourMenu.addSeparator();
5662 colourMenu.add(conservationMenuItem);
5663 colourMenu.add(modifyConservation);
5664 colourMenu.add(abovePIDThreshold);
5665 colourMenu.add(modifyPID);
5666 colourMenu.add(annotationColour);
5668 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5669 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5673 * Open a dialog (if not already open) that allows the user to select and
5674 * calculate PCA or Tree analysis
5676 protected void openTreePcaDialog()
5678 if (alignPanel.getCalculationDialog() == null)
5680 new CalculationChooser(AlignFrame.this);
5685 * Sets the status of the HMMER menu
5689 public void updateHMMERStatus(boolean status)
5691 hmmerMenu.setEnabled(status);
5695 * Returns the selected hidden Markov model.
5699 public HiddenMarkovModel getSelectedHMM()
5705 * Sets the selected hidden Markov model
5707 * @param selectedHMM
5709 public void setSelectedHMM(HiddenMarkovModel selectedHMM)
5711 this.selectedHMM = selectedHMM;
5712 hmmAlign.setText(MessageManager.getString("label.hmmalign") + " to "
5713 + selectedHMM.getName() + "_HMM");
5714 hmmSearch.setText(MessageManager.getString("label.hmmsearch") + " with "
5715 + selectedHMM.getName() + "_HMM");
5719 public void hmmerMenu_actionPerformed(ActionEvent e)
5721 SequenceGroup grp = getViewport().getSelectionGroup();
5724 hmmBuild.setText(MessageManager.getString("label.hmmbuild") + " from "
5729 hmmBuild.setText(MessageManager.getString("label.hmmbuild")
5730 + " from Alignment");
5736 class PrintThread extends Thread
5740 public PrintThread(AlignmentPanel ap)
5745 static PageFormat pf;
5750 PrinterJob printJob = PrinterJob.getPrinterJob();
5754 printJob.setPrintable(ap, pf);
5758 printJob.setPrintable(ap);
5761 if (printJob.printDialog())
5766 } catch (Exception PrintException)
5768 PrintException.printStackTrace();