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.HMMFile;
79 import jalview.io.HtmlSvgOutput;
80 import jalview.io.IdentifyFile;
81 import jalview.io.JPredFile;
82 import jalview.io.JalviewFileChooser;
83 import jalview.io.JalviewFileView;
84 import jalview.io.JnetAnnotationMaker;
85 import jalview.io.NewickFile;
86 import jalview.io.ScoreMatrixFile;
87 import jalview.io.TCoffeeScoreFile;
88 import jalview.jbgui.GAlignFrame;
89 import jalview.schemes.ColourSchemeI;
90 import jalview.schemes.ColourSchemes;
91 import jalview.schemes.ResidueColourScheme;
92 import jalview.schemes.TCoffeeColourScheme;
93 import jalview.util.MessageManager;
94 import jalview.viewmodel.AlignmentViewport;
95 import jalview.viewmodel.ViewportRanges;
96 import jalview.ws.DBRefFetcher;
97 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
98 import jalview.ws.jws1.Discoverer;
99 import jalview.ws.jws2.Jws2Discoverer;
100 import jalview.ws.jws2.jabaws2.Jws2Instance;
101 import jalview.ws.seqfetcher.DbSourceProxy;
103 import java.awt.BorderLayout;
104 import java.awt.Component;
105 import java.awt.Rectangle;
106 import java.awt.Toolkit;
107 import java.awt.datatransfer.Clipboard;
108 import java.awt.datatransfer.DataFlavor;
109 import java.awt.datatransfer.StringSelection;
110 import java.awt.datatransfer.Transferable;
111 import java.awt.dnd.DnDConstants;
112 import java.awt.dnd.DropTargetDragEvent;
113 import java.awt.dnd.DropTargetDropEvent;
114 import java.awt.dnd.DropTargetEvent;
115 import java.awt.dnd.DropTargetListener;
116 import java.awt.event.ActionEvent;
117 import java.awt.event.ActionListener;
118 import java.awt.event.FocusAdapter;
119 import java.awt.event.FocusEvent;
120 import java.awt.event.ItemEvent;
121 import java.awt.event.ItemListener;
122 import java.awt.event.KeyAdapter;
123 import java.awt.event.KeyEvent;
124 import java.awt.event.MouseEvent;
125 import java.awt.print.PageFormat;
126 import java.awt.print.PrinterJob;
127 import java.beans.PropertyChangeEvent;
129 import java.io.FileWriter;
130 import java.io.IOException;
131 import java.io.PrintWriter;
133 import java.util.ArrayList;
134 import java.util.Arrays;
135 import java.util.Deque;
136 import java.util.Enumeration;
137 import java.util.HashMap;
138 import java.util.Hashtable;
139 import java.util.List;
140 import java.util.Map;
141 import java.util.Vector;
143 import javax.swing.JCheckBoxMenuItem;
144 import javax.swing.JEditorPane;
145 import javax.swing.JInternalFrame;
146 import javax.swing.JLayeredPane;
147 import javax.swing.JMenu;
148 import javax.swing.JMenuItem;
149 import javax.swing.JScrollPane;
150 import javax.swing.SwingUtilities;
156 * @version $Revision$
158 public class AlignFrame extends GAlignFrame implements DropTargetListener,
159 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
162 Map<String, Float> distribution = new HashMap<>(); // temporary
164 public static final int DEFAULT_WIDTH = 700;
166 public static final int DEFAULT_HEIGHT = 500;
168 boolean autoAlignNewSequences;
173 * The currently displayed panel (selected tabbed view if more than one)
175 public AlignmentPanel alignPanel;
177 AlignViewport viewport;
179 ViewportRanges vpRanges;
181 public AlignViewControllerI avc;
183 List<AlignmentPanel> alignPanels = new ArrayList<>();
186 * Last format used to load or save alignments in this window
188 FileFormatI currentFileFormat = null;
191 * Current filename for this alignment
193 String fileName = null;
197 * Creates a new AlignFrame object with specific width and height.
203 public AlignFrame(AlignmentI al, int width, int height)
205 this(al, null, width, height);
209 * Creates a new AlignFrame object with specific width, height and
215 * @param sequenceSetId
217 public AlignFrame(AlignmentI al, int width, int height,
218 String sequenceSetId)
220 this(al, null, width, height, sequenceSetId);
224 * Creates a new AlignFrame object with specific width, height and
230 * @param sequenceSetId
233 public AlignFrame(AlignmentI al, int width, int height,
234 String sequenceSetId, String viewId)
236 this(al, null, width, height, sequenceSetId, viewId);
240 * new alignment window with hidden columns
244 * @param hiddenColumns
245 * ColumnSelection or null
247 * Width of alignment frame
251 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns,
252 int width, int height)
254 this(al, hiddenColumns, width, height, null);
258 * Create alignment frame for al with hiddenColumns, a specific width and
259 * height, and specific sequenceId
262 * @param hiddenColumns
265 * @param sequenceSetId
268 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns,
269 int width, int height, String sequenceSetId)
271 this(al, hiddenColumns, width, height, sequenceSetId, null);
275 * Create alignment frame for al with hiddenColumns, a specific width and
276 * height, and specific sequenceId
279 * @param hiddenColumns
282 * @param sequenceSetId
287 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns,
288 int width, int height, String sequenceSetId, String viewId)
290 setSize(width, height);
292 if (al.getDataset() == null)
297 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
299 alignPanel = new AlignmentPanel(this, viewport);
301 addAlignmentPanel(alignPanel, true);
305 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
306 HiddenColumns hiddenColumns, int width, int height)
308 setSize(width, height);
310 if (al.getDataset() == null)
315 viewport = new AlignViewport(al, hiddenColumns);
317 if (hiddenSeqs != null && hiddenSeqs.length > 0)
319 viewport.hideSequence(hiddenSeqs);
321 alignPanel = new AlignmentPanel(this, viewport);
322 addAlignmentPanel(alignPanel, true);
327 * Make a new AlignFrame from existing alignmentPanels
334 public AlignFrame(AlignmentPanel ap)
338 addAlignmentPanel(ap, false);
343 * initalise the alignframe from the underlying viewport data and the
348 if (!Jalview.isHeadlessMode())
350 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
353 vpRanges = viewport.getRanges();
354 avc = new jalview.controller.AlignViewController(this, viewport,
356 if (viewport.getAlignmentConservationAnnotation() == null)
358 // BLOSUM62Colour.setEnabled(false);
359 conservationMenuItem.setEnabled(false);
360 modifyConservation.setEnabled(false);
361 // PIDColour.setEnabled(false);
362 // abovePIDThreshold.setEnabled(false);
363 // modifyPID.setEnabled(false);
366 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
369 if (sortby.equals("Id"))
371 sortIDMenuItem_actionPerformed(null);
373 else if (sortby.equals("Pairwise Identity"))
375 sortPairwiseMenuItem_actionPerformed(null);
379 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
381 setMenusFromViewport(viewport);
382 buildSortByAnnotationScoresMenu();
383 calculateTree.addActionListener(new ActionListener()
387 public void actionPerformed(ActionEvent e)
395 if (Desktop.desktop != null)
397 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
398 addServiceListeners();
402 if (viewport.getWrapAlignment())
404 wrapMenuItem_actionPerformed(null);
407 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
409 this.overviewMenuItem_actionPerformed(null);
414 final List<AlignmentPanel> selviews = new ArrayList<>();
415 final List<AlignmentPanel> origview = new ArrayList<>();
416 final String menuLabel = MessageManager
417 .getString("label.copy_format_from");
418 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
419 new ViewSetProvider()
423 public AlignmentPanel[] getAllAlignmentPanels()
426 origview.add(alignPanel);
427 // make an array of all alignment panels except for this one
428 List<AlignmentPanel> aps = new ArrayList<>(
429 Arrays.asList(Desktop.getAlignmentPanels(null)));
430 aps.remove(AlignFrame.this.alignPanel);
431 return aps.toArray(new AlignmentPanel[aps.size()]);
433 }, selviews, new ItemListener()
437 public void itemStateChanged(ItemEvent e)
439 if (origview.size() > 0)
441 final AlignmentPanel ap = origview.get(0);
444 * Copy the ViewStyle of the selected panel to 'this one'.
445 * Don't change value of 'scaleProteinAsCdna' unless copying
448 ViewStyleI vs = selviews.get(0).getAlignViewport()
450 boolean fromSplitFrame = selviews.get(0)
451 .getAlignViewport().getCodingComplement() != null;
454 vs.setScaleProteinAsCdna(ap.getAlignViewport()
455 .getViewStyle().isScaleProteinAsCdna());
457 ap.getAlignViewport().setViewStyle(vs);
460 * Also rescale ViewStyle of SplitFrame complement if there is
461 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
462 * the whole ViewStyle (allow cDNA protein to have different
465 AlignViewportI complement = ap.getAlignViewport()
466 .getCodingComplement();
467 if (complement != null && vs.isScaleProteinAsCdna())
469 AlignFrame af = Desktop.getAlignFrameFor(complement);
470 ((SplitFrame) af.getSplitViewContainer())
472 af.setMenusForViewport();
476 ap.setSelected(true);
477 ap.alignFrame.setMenusForViewport();
482 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
483 .indexOf("devel") > -1
484 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
485 .indexOf("test") > -1)
487 formatMenu.add(vsel);
489 addFocusListener(new FocusAdapter()
492 public void focusGained(FocusEvent e)
494 Jalview.setCurrentAlignFrame(AlignFrame.this);
500 private void buildHMMERMenu()
502 hmmerMenu.removeAll();
504 hmmerMenu.add(autoAlignSeqs);
505 hmmerMenu.addSeparator();
507 hmmerMenu.add(hmmAlign);
508 hmmerMenu.add(hmmBuild);
509 hmmerMenu.add(hmmSearch);
514 * Change the filename and format for the alignment, and enable the 'reload'
515 * button functionality.
522 public void setFileName(String file, FileFormatI format)
525 setFileFormat(format);
526 reload.setEnabled(true);
530 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
533 void addKeyListener()
535 addKeyListener(new KeyAdapter()
538 public void keyPressed(KeyEvent evt)
540 if (viewport.cursorMode
541 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
542 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
543 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
544 && Character.isDigit(evt.getKeyChar()))
546 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
549 switch (evt.getKeyCode())
552 case 27: // escape key
553 deselectAllSequenceMenuItem_actionPerformed(null);
557 case KeyEvent.VK_DOWN:
558 if (evt.isAltDown() || !viewport.cursorMode)
560 moveSelectedSequences(false);
562 if (viewport.cursorMode)
564 alignPanel.getSeqPanel().moveCursor(0, 1);
569 if (evt.isAltDown() || !viewport.cursorMode)
571 moveSelectedSequences(true);
573 if (viewport.cursorMode)
575 alignPanel.getSeqPanel().moveCursor(0, -1);
580 case KeyEvent.VK_LEFT:
581 if (evt.isAltDown() || !viewport.cursorMode)
583 slideSequences(false, alignPanel.getSeqPanel().getKeyboardNo1());
587 alignPanel.getSeqPanel().moveCursor(-1, 0);
592 case KeyEvent.VK_RIGHT:
593 if (evt.isAltDown() || !viewport.cursorMode)
595 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
599 alignPanel.getSeqPanel().moveCursor(1, 0);
603 case KeyEvent.VK_SPACE:
604 if (viewport.cursorMode)
606 alignPanel.getSeqPanel().insertGapAtCursor(
607 evt.isControlDown() || evt.isShiftDown()
612 // case KeyEvent.VK_A:
613 // if (viewport.cursorMode)
615 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
616 // //System.out.println("A");
620 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
621 * System.out.println("closing bracket"); } break;
623 case KeyEvent.VK_DELETE:
624 case KeyEvent.VK_BACK_SPACE:
625 if (!viewport.cursorMode)
627 cut_actionPerformed(null);
631 alignPanel.getSeqPanel().deleteGapAtCursor(
632 evt.isControlDown() || evt.isShiftDown()
639 if (viewport.cursorMode)
641 alignPanel.getSeqPanel().setCursorRow();
645 if (viewport.cursorMode && !evt.isControlDown())
647 alignPanel.getSeqPanel().setCursorColumn();
651 if (viewport.cursorMode)
653 alignPanel.getSeqPanel().setCursorPosition();
657 case KeyEvent.VK_ENTER:
658 case KeyEvent.VK_COMMA:
659 if (viewport.cursorMode)
661 alignPanel.getSeqPanel().setCursorRowAndColumn();
666 if (viewport.cursorMode)
668 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
672 if (viewport.cursorMode)
674 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
679 viewport.cursorMode = !viewport.cursorMode;
680 statusBar.setText(MessageManager.formatMessage(
681 "label.keyboard_editing_mode",
682 new String[] { (viewport.cursorMode ? "on" : "off") }));
683 if (viewport.cursorMode)
685 alignPanel.getSeqPanel().seqCanvas.cursorX = vpRanges
687 alignPanel.getSeqPanel().seqCanvas.cursorY = vpRanges
690 alignPanel.getSeqPanel().seqCanvas.repaint();
696 Help.showHelpWindow();
697 } catch (Exception ex)
699 ex.printStackTrace();
704 boolean toggleSeqs = !evt.isControlDown();
705 boolean toggleCols = !evt.isShiftDown();
706 toggleHiddenRegions(toggleSeqs, toggleCols);
711 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
712 boolean modifyExisting = true; // always modify, don't clear
713 // evt.isShiftDown();
714 boolean invertHighlighted = evt.isAltDown();
715 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
719 case KeyEvent.VK_PAGE_UP:
720 if (viewport.getWrapAlignment())
722 vpRanges.scrollUp(true);
729 case KeyEvent.VK_PAGE_DOWN:
730 if (viewport.getWrapAlignment())
732 vpRanges.scrollUp(false);
743 public void keyReleased(KeyEvent evt)
745 switch (evt.getKeyCode())
747 case KeyEvent.VK_LEFT:
748 if (evt.isAltDown() || !viewport.cursorMode)
750 viewport.firePropertyChange("alignment", null, viewport
751 .getAlignment().getSequences());
755 case KeyEvent.VK_RIGHT:
756 if (evt.isAltDown() || !viewport.cursorMode)
758 viewport.firePropertyChange("alignment", null, viewport
759 .getAlignment().getSequences());
767 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
769 ap.alignFrame = this;
770 avc = new jalview.controller.AlignViewController(this, viewport,
775 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
777 int aSize = alignPanels.size();
779 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
781 if (aSize == 1 && ap.av.viewName == null)
783 this.getContentPane().add(ap, BorderLayout.CENTER);
789 setInitialTabVisible();
792 expandViews.setEnabled(true);
793 gatherViews.setEnabled(true);
794 tabbedPane.addTab(ap.av.viewName, ap);
796 ap.setVisible(false);
801 if (ap.av.isPadGaps())
803 ap.av.getAlignment().padGaps();
805 ap.av.updateConservation(ap);
806 ap.av.updateConsensus(ap);
807 ap.av.updateStrucConsensus(ap);
808 ap.av.updateInformation(ap);
812 public void setInitialTabVisible()
814 expandViews.setEnabled(true);
815 gatherViews.setEnabled(true);
816 tabbedPane.setVisible(true);
817 AlignmentPanel first = alignPanels.get(0);
818 tabbedPane.addTab(first.av.viewName, first);
819 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
822 public AlignViewport getViewport()
827 /* Set up intrinsic listeners for dynamically generated GUI bits. */
828 private void addServiceListeners()
830 final java.beans.PropertyChangeListener thisListener;
831 Desktop.instance.addJalviewPropertyChangeListener("services",
832 thisListener = new java.beans.PropertyChangeListener()
835 public void propertyChange(PropertyChangeEvent evt)
837 // // System.out.println("Discoverer property change.");
838 // if (evt.getPropertyName().equals("services"))
840 SwingUtilities.invokeLater(new Runnable()
847 .println("Rebuild WS Menu for service change");
848 BuildWebServiceMenu();
855 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
858 public void internalFrameClosed(
859 javax.swing.event.InternalFrameEvent evt)
861 // System.out.println("deregistering discoverer listener");
862 Desktop.instance.removeJalviewPropertyChangeListener("services",
864 closeMenuItem_actionPerformed(true);
867 // Finally, build the menu once to get current service state
868 new Thread(new Runnable()
873 BuildWebServiceMenu();
879 * Configure menu items that vary according to whether the alignment is
880 * nucleotide or protein
882 public void setGUINucleotide()
884 AlignmentI al = getViewport().getAlignment();
885 boolean nucleotide = al.isNucleotide();
887 showTranslation.setVisible(nucleotide);
888 showReverse.setVisible(nucleotide);
889 showReverseComplement.setVisible(nucleotide);
890 conservationMenuItem.setEnabled(!nucleotide);
891 modifyConservation.setEnabled(!nucleotide
892 && conservationMenuItem.isSelected());
893 showGroupConservation.setEnabled(!nucleotide);
895 showComplementMenuItem.setText(nucleotide ? MessageManager
896 .getString("label.protein") : MessageManager
897 .getString("label.nucleotide"));
901 * set up menus for the current viewport. This may be called after any
902 * operation that affects the data in the current view (selection changed,
903 * etc) to update the menus to reflect the new state.
906 public void setMenusForViewport()
908 setMenusFromViewport(viewport);
912 * Need to call this method when tabs are selected for multiple views, or when
913 * loading from Jalview2XML.java
918 void setMenusFromViewport(AlignViewport av)
920 padGapsMenuitem.setSelected(av.isPadGaps());
921 colourTextMenuItem.setSelected(av.isShowColourText());
922 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
923 modifyPID.setEnabled(abovePIDThreshold.isSelected());
924 conservationMenuItem.setSelected(av.getConservationSelected());
925 modifyConservation.setEnabled(conservationMenuItem.isSelected());
926 seqLimits.setSelected(av.getShowJVSuffix());
927 idRightAlign.setSelected(av.isRightAlignIds());
928 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
929 renderGapsMenuItem.setSelected(av.isRenderGaps());
930 wrapMenuItem.setSelected(av.getWrapAlignment());
931 scaleAbove.setVisible(av.getWrapAlignment());
932 scaleLeft.setVisible(av.getWrapAlignment());
933 scaleRight.setVisible(av.getWrapAlignment());
934 annotationPanelMenuItem.setState(av.isShowAnnotation());
936 * Show/hide annotations only enabled if annotation panel is shown
938 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
939 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
940 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
941 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
942 viewBoxesMenuItem.setSelected(av.getShowBoxes());
943 viewTextMenuItem.setSelected(av.getShowText());
944 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
945 showGroupConsensus.setSelected(av.isShowGroupConsensus());
946 showGroupConservation.setSelected(av.isShowGroupConservation());
947 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
948 showSequenceLogo.setSelected(av.isShowSequenceLogo());
949 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
950 showInformationHistogram.setSelected(av.isShowInformationHistogram());
951 showHMMSequenceLogo.setSelected(av.isShowHMMSequenceLogo());
952 normaliseHMMSequenceLogo.setSelected(av.isNormaliseHMMSequenceLogo());
954 ColourMenuHelper.setColourSelected(colourMenu,
955 av.getGlobalColourScheme());
957 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
958 hiddenMarkers.setState(av.getShowHiddenMarkers());
959 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
960 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
961 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
962 autoCalculate.setSelected(av.autoCalculateConsensus);
963 sortByTree.setSelected(av.sortByTree);
964 listenToViewSelections.setSelected(av.followSelection);
966 showProducts.setEnabled(canShowProducts());
967 setGroovyEnabled(Desktop.getGroovyConsole() != null);
973 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
977 public void setGroovyEnabled(boolean b)
979 runGroovy.setEnabled(b);
982 private IProgressIndicator progressBar;
987 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
990 public void setProgressBar(String message, long id)
992 progressBar.setProgressBar(message, id);
996 public void registerHandler(final long id,
997 final IProgressIndicatorHandler handler)
999 progressBar.registerHandler(id, handler);
1004 * @return true if any progress bars are still active
1007 public boolean operationInProgress()
1009 return progressBar.operationInProgress();
1013 public void setStatus(String text)
1015 statusBar.setText(text);
1019 * Added so Castor Mapping file can obtain Jalview Version
1021 public String getVersion()
1023 return jalview.bin.Cache.getProperty("VERSION");
1026 public FeatureRenderer getFeatureRenderer()
1028 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1032 public void fetchSequence_actionPerformed(ActionEvent e)
1034 new jalview.gui.SequenceFetcher(this);
1038 public void addFromFile_actionPerformed(ActionEvent e)
1040 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1044 public void hmmBuild_actionPerformed(ActionEvent e)
1045 throws IOException, InterruptedException
1047 new Thread(new HMMBuildThread(this)).start();
1048 alignPanel.repaint();
1053 public void hmmAlign_actionPerformed(ActionEvent e)
1054 throws IOException, InterruptedException
1056 SequenceI seq = getViewport().getAlignment()
1057 .getHMMConsensusSequences(false).get(0);
1058 new Thread(new HMMAlignThread(this, true)).start();
1059 alignPanel.repaint();
1063 public void autoAlignSeqs_actionPerformed(boolean autoAlignSeqs)
1065 autoAlignNewSequences = autoAlignSeqs;
1066 alignPanel.repaint();
1070 public void hmmSearch_actionPerformed(ActionEvent e)
1072 alignPanel.repaint();
1076 public void reload_actionPerformed(ActionEvent e)
1078 if (fileName != null)
1080 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1081 // originating file's format
1082 // TODO: work out how to recover feature settings for correct view(s) when
1083 // file is reloaded.
1084 if (FileFormat.Jalview.equals(currentFileFormat))
1086 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1087 for (int i = 0; i < frames.length; i++)
1089 if (frames[i] instanceof AlignFrame && frames[i] != this
1090 && ((AlignFrame) frames[i]).fileName != null
1091 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1095 frames[i].setSelected(true);
1096 Desktop.instance.closeAssociatedWindows();
1097 } catch (java.beans.PropertyVetoException ex)
1103 Desktop.instance.closeAssociatedWindows();
1105 FileLoader loader = new FileLoader();
1106 DataSourceType protocol = fileName.startsWith("http:") ? DataSourceType.URL
1107 : DataSourceType.FILE;
1108 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1112 Rectangle bounds = this.getBounds();
1114 FileLoader loader = new FileLoader();
1115 DataSourceType protocol = fileName.startsWith("http:") ? DataSourceType.URL
1116 : DataSourceType.FILE;
1117 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1118 protocol, currentFileFormat);
1120 newframe.setBounds(bounds);
1121 if (featureSettings != null && featureSettings.isShowing())
1123 final Rectangle fspos = featureSettings.frame.getBounds();
1124 // TODO: need a 'show feature settings' function that takes bounds -
1125 // need to refactor Desktop.addFrame
1126 newframe.featureSettings_actionPerformed(null);
1127 final FeatureSettings nfs = newframe.featureSettings;
1128 SwingUtilities.invokeLater(new Runnable()
1133 nfs.frame.setBounds(fspos);
1136 this.featureSettings.close();
1137 this.featureSettings = null;
1139 this.closeMenuItem_actionPerformed(true);
1145 public void addFromText_actionPerformed(ActionEvent e)
1147 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport
1152 public void addFromURL_actionPerformed(ActionEvent e)
1154 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1158 public void save_actionPerformed(ActionEvent e)
1160 if (fileName == null || (currentFileFormat == null)
1161 || fileName.startsWith("http"))
1163 saveAs_actionPerformed(null);
1167 saveAlignment(fileName, currentFileFormat);
1178 public void saveAs_actionPerformed(ActionEvent e)
1180 String format = currentFileFormat == null ? null : currentFileFormat
1182 JalviewFileChooser chooser = JalviewFileChooser.forWrite(
1183 Cache.getProperty("LAST_DIRECTORY"), format);
1185 chooser.setFileView(new JalviewFileView());
1186 chooser.setDialogTitle(MessageManager
1187 .getString("label.save_alignment_to_file"));
1188 chooser.setToolTipText(MessageManager.getString("action.save"));
1190 int value = chooser.showSaveDialog(this);
1192 if (value == JalviewFileChooser.APPROVE_OPTION)
1194 currentFileFormat = chooser.getSelectedFormat();
1195 while (currentFileFormat == null)
1198 .showInternalMessageDialog(
1201 .getString("label.select_file_format_before_saving"),
1203 .getString("label.file_format_not_specified"),
1204 JvOptionPane.WARNING_MESSAGE);
1205 currentFileFormat = chooser.getSelectedFormat();
1206 value = chooser.showSaveDialog(this);
1207 if (value != JalviewFileChooser.APPROVE_OPTION)
1213 fileName = chooser.getSelectedFile().getPath();
1215 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1217 Cache.setProperty("LAST_DIRECTORY", fileName);
1218 saveAlignment(fileName, currentFileFormat);
1222 public boolean saveAlignment(String file, FileFormatI format)
1224 boolean success = true;
1226 if (FileFormat.Jalview.equals(format))
1228 String shortName = title;
1230 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1232 shortName = shortName.substring(shortName
1233 .lastIndexOf(java.io.File.separatorChar) + 1);
1236 success = new Jalview2XML().saveAlignment(this, file, shortName);
1238 statusBar.setText(MessageManager.formatMessage(
1239 "label.successfully_saved_to_file_in_format", new Object[] {
1240 fileName, format }));
1245 AlignmentExportData exportData = getAlignmentForExport(format,
1247 if (exportData.getSettings().isCancelled())
1251 FormatAdapter f = new FormatAdapter(alignPanel,
1252 exportData.getSettings());
1253 String output = f.formatSequences(
1255 exportData.getAlignment(), // class cast exceptions will
1256 // occur in the distant future
1257 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1258 f.getCacheSuffixDefault(format), viewport.getAlignment()
1259 .getHiddenColumns());
1269 PrintWriter out = new PrintWriter(new FileWriter(file));
1273 this.setTitle(file);
1274 statusBar.setText(MessageManager.formatMessage(
1275 "label.successfully_saved_to_file_in_format",
1276 new Object[] { fileName, format.getName() }));
1277 } catch (Exception ex)
1280 ex.printStackTrace();
1287 JvOptionPane.showInternalMessageDialog(this, MessageManager
1288 .formatMessage("label.couldnt_save_file",
1289 new Object[] { fileName }), MessageManager
1290 .getString("label.error_saving_file"),
1291 JvOptionPane.WARNING_MESSAGE);
1297 private void warningMessage(String warning, String title)
1299 if (new jalview.util.Platform().isHeadless())
1301 System.err.println("Warning: " + title + "\nWarning: " + warning);
1306 JvOptionPane.showInternalMessageDialog(this, warning, title,
1307 JvOptionPane.WARNING_MESSAGE);
1319 protected void outputText_actionPerformed(ActionEvent e)
1321 FileFormatI fileFormat = FileFormats.getInstance().forName(
1322 e.getActionCommand());
1323 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1325 if (exportData.getSettings().isCancelled())
1329 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1330 cap.setForInput(null);
1333 FileFormatI format = fileFormat;
1334 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1335 .formatSequences(format, exportData.getAlignment(),
1336 exportData.getOmitHidden(),
1338 .getStartEndPostions(), viewport
1339 .getAlignment().getHiddenColumns()));
1340 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1341 "label.alignment_output_command",
1342 new Object[] { e.getActionCommand() }), 600, 500);
1343 } catch (OutOfMemoryError oom)
1345 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1351 public static AlignmentExportData getAlignmentForExport(
1352 FileFormatI format, AlignViewportI viewport,
1353 AlignExportSettingI exportSettings)
1355 AlignmentI alignmentToExport = null;
1356 AlignExportSettingI settings = exportSettings;
1357 String[] omitHidden = null;
1359 HiddenSequences hiddenSeqs = viewport.getAlignment()
1360 .getHiddenSequences();
1362 alignmentToExport = viewport.getAlignment();
1364 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1365 if (settings == null)
1367 settings = new AlignExportSettings(hasHiddenSeqs,
1368 viewport.hasHiddenColumns(), format);
1370 // settings.isExportAnnotations();
1372 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1374 omitHidden = viewport.getViewAsString(false,
1375 settings.isExportHiddenSequences());
1378 int[] alignmentStartEnd = new int[2];
1379 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1381 alignmentToExport = hiddenSeqs.getFullAlignment();
1385 alignmentToExport = viewport.getAlignment();
1387 alignmentStartEnd = alignmentToExport
1388 .getVisibleStartAndEndIndex(viewport.getAlignment()
1390 .getHiddenRegions());
1391 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1392 omitHidden, alignmentStartEnd, settings);
1403 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1405 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1406 htmlSVG.exportHTML(null);
1410 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1412 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1413 bjs.exportHTML(null);
1416 public void createImageMap(File file, String image)
1418 alignPanel.makePNGImageMap(file, image);
1428 public void createPNG(File f)
1430 alignPanel.makePNG(f);
1440 public void createEPS(File f)
1442 alignPanel.makeEPS(f);
1446 public void createSVG(File f)
1448 alignPanel.makeSVG(f);
1452 public void pageSetup_actionPerformed(ActionEvent e)
1454 PrinterJob printJob = PrinterJob.getPrinterJob();
1455 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1465 public void printMenuItem_actionPerformed(ActionEvent e)
1467 // Putting in a thread avoids Swing painting problems
1468 PrintThread thread = new PrintThread(alignPanel);
1473 public void exportFeatures_actionPerformed(ActionEvent e)
1475 new AnnotationExporter().exportFeatures(alignPanel);
1479 public void exportAnnotations_actionPerformed(ActionEvent e)
1481 new AnnotationExporter().exportAnnotations(alignPanel);
1485 public void associatedData_actionPerformed(ActionEvent e)
1486 throws IOException, InterruptedException
1488 // Pick the tree file
1489 JalviewFileChooser chooser = new JalviewFileChooser(
1490 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1491 chooser.setFileView(new JalviewFileView());
1492 chooser.setDialogTitle(MessageManager
1493 .getString("label.load_jalview_annotations"));
1494 chooser.setToolTipText(MessageManager
1495 .getString("label.load_jalview_annotations"));
1497 int value = chooser.showOpenDialog(null);
1499 if (value == JalviewFileChooser.APPROVE_OPTION)
1501 String choice = chooser.getSelectedFile().getPath();
1502 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1503 loadJalviewDataFile(choice, null, null, null);
1509 * Close the current view or all views in the alignment frame. If the frame
1510 * only contains one view then the alignment will be removed from memory.
1512 * @param closeAllTabs
1515 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1517 if (alignPanels != null && alignPanels.size() < 2)
1519 closeAllTabs = true;
1524 if (alignPanels != null)
1528 if (this.isClosed())
1530 // really close all the windows - otherwise wait till
1531 // setClosed(true) is called
1532 for (int i = 0; i < alignPanels.size(); i++)
1534 AlignmentPanel ap = alignPanels.get(i);
1541 closeView(alignPanel);
1548 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1549 * be called recursively, with the frame now in 'closed' state
1551 this.setClosed(true);
1553 } catch (Exception ex)
1555 ex.printStackTrace();
1560 * Close the specified panel and close up tabs appropriately.
1562 * @param panelToClose
1564 public void closeView(AlignmentPanel panelToClose)
1566 int index = tabbedPane.getSelectedIndex();
1567 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1568 alignPanels.remove(panelToClose);
1569 panelToClose.closePanel();
1570 panelToClose = null;
1572 tabbedPane.removeTabAt(closedindex);
1573 tabbedPane.validate();
1575 if (index > closedindex || index == tabbedPane.getTabCount())
1577 // modify currently selected tab index if necessary.
1581 this.tabSelectionChanged(index);
1587 void updateEditMenuBar()
1590 if (viewport.getHistoryList().size() > 0)
1592 undoMenuItem.setEnabled(true);
1593 CommandI command = viewport.getHistoryList().peek();
1594 undoMenuItem.setText(MessageManager.formatMessage(
1595 "label.undo_command",
1596 new Object[] { command.getDescription() }));
1600 undoMenuItem.setEnabled(false);
1601 undoMenuItem.setText(MessageManager.getString("action.undo"));
1604 if (viewport.getRedoList().size() > 0)
1606 redoMenuItem.setEnabled(true);
1608 CommandI command = viewport.getRedoList().peek();
1609 redoMenuItem.setText(MessageManager.formatMessage(
1610 "label.redo_command",
1611 new Object[] { command.getDescription() }));
1615 redoMenuItem.setEnabled(false);
1616 redoMenuItem.setText(MessageManager.getString("action.redo"));
1621 public void addHistoryItem(CommandI command)
1623 if (command.getSize() > 0)
1625 viewport.addToHistoryList(command);
1626 viewport.clearRedoList();
1627 updateEditMenuBar();
1628 viewport.updateHiddenColumns();
1629 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1630 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1631 // viewport.getColumnSelection()
1632 // .getHiddenColumns().size() > 0);
1638 * @return alignment objects for all views
1640 AlignmentI[] getViewAlignments()
1642 if (alignPanels != null)
1644 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1646 for (AlignmentPanel ap : alignPanels)
1648 als[i++] = ap.av.getAlignment();
1652 if (viewport != null)
1654 return new AlignmentI[] { viewport.getAlignment() };
1666 protected void undoMenuItem_actionPerformed(ActionEvent e)
1668 if (viewport.getHistoryList().isEmpty())
1672 CommandI command = viewport.getHistoryList().pop();
1673 viewport.addToRedoList(command);
1674 command.undoCommand(getViewAlignments());
1676 AlignmentViewport originalSource = getOriginatingSource(command);
1677 updateEditMenuBar();
1679 if (originalSource != null)
1681 if (originalSource != viewport)
1684 .warn("Implementation worry: mismatch of viewport origin for undo");
1686 originalSource.updateHiddenColumns();
1687 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1689 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1690 // viewport.getColumnSelection()
1691 // .getHiddenColumns().size() > 0);
1692 originalSource.firePropertyChange("alignment", null, originalSource
1693 .getAlignment().getSequences());
1704 protected void redoMenuItem_actionPerformed(ActionEvent e)
1706 if (viewport.getRedoList().size() < 1)
1711 CommandI command = viewport.getRedoList().pop();
1712 viewport.addToHistoryList(command);
1713 command.doCommand(getViewAlignments());
1715 AlignmentViewport originalSource = getOriginatingSource(command);
1716 updateEditMenuBar();
1718 if (originalSource != null)
1721 if (originalSource != viewport)
1724 .warn("Implementation worry: mismatch of viewport origin for redo");
1726 originalSource.updateHiddenColumns();
1727 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1729 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1730 // viewport.getColumnSelection()
1731 // .getHiddenColumns().size() > 0);
1732 originalSource.firePropertyChange("alignment", null, originalSource
1733 .getAlignment().getSequences());
1737 AlignmentViewport getOriginatingSource(CommandI command)
1739 AlignmentViewport originalSource = null;
1740 // For sequence removal and addition, we need to fire
1741 // the property change event FROM the viewport where the
1742 // original alignment was altered
1743 AlignmentI al = null;
1744 if (command instanceof EditCommand)
1746 EditCommand editCommand = (EditCommand) command;
1747 al = editCommand.getAlignment();
1748 List<Component> comps = PaintRefresher.components.get(viewport
1749 .getSequenceSetId());
1751 for (Component comp : comps)
1753 if (comp instanceof AlignmentPanel)
1755 if (al == ((AlignmentPanel) comp).av.getAlignment())
1757 originalSource = ((AlignmentPanel) comp).av;
1764 if (originalSource == null)
1766 // The original view is closed, we must validate
1767 // the current view against the closed view first
1770 PaintRefresher.validateSequences(al, viewport.getAlignment());
1773 originalSource = viewport;
1776 return originalSource;
1785 public void moveSelectedSequences(boolean up)
1787 SequenceGroup sg = viewport.getSelectionGroup();
1793 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1794 viewport.getHiddenRepSequences(), up);
1795 alignPanel.paintAlignment(true);
1798 synchronized void slideSequences(boolean right, int size)
1800 List<SequenceI> sg = new ArrayList<>();
1801 if (viewport.cursorMode)
1803 sg.add(viewport.getAlignment().getSequenceAt(
1804 alignPanel.getSeqPanel().seqCanvas.cursorY));
1806 else if (viewport.getSelectionGroup() != null
1807 && viewport.getSelectionGroup().getSize() != viewport
1808 .getAlignment().getHeight())
1810 sg = viewport.getSelectionGroup().getSequences(
1811 viewport.getHiddenRepSequences());
1819 List<SequenceI> invertGroup = new ArrayList<>();
1821 for (SequenceI seq : viewport.getAlignment().getSequences())
1823 if (!sg.contains(seq))
1825 invertGroup.add(seq);
1829 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1831 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1832 for (int i = 0; i < invertGroup.size(); i++)
1834 seqs2[i] = invertGroup.get(i);
1837 SlideSequencesCommand ssc;
1840 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1841 size, viewport.getGapCharacter());
1845 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1846 size, viewport.getGapCharacter());
1849 int groupAdjustment = 0;
1850 if (ssc.getGapsInsertedBegin() && right)
1852 if (viewport.cursorMode)
1854 alignPanel.getSeqPanel().moveCursor(size, 0);
1858 groupAdjustment = size;
1861 else if (!ssc.getGapsInsertedBegin() && !right)
1863 if (viewport.cursorMode)
1865 alignPanel.getSeqPanel().moveCursor(-size, 0);
1869 groupAdjustment = -size;
1873 if (groupAdjustment != 0)
1875 viewport.getSelectionGroup().setStartRes(
1876 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1877 viewport.getSelectionGroup().setEndRes(
1878 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1882 * just extend the last slide command if compatible; but not if in
1883 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1885 boolean appendHistoryItem = false;
1886 Deque<CommandI> historyList = viewport.getHistoryList();
1887 boolean inSplitFrame = getSplitViewContainer() != null;
1888 if (!inSplitFrame && historyList != null && historyList.size() > 0
1889 && historyList.peek() instanceof SlideSequencesCommand)
1891 appendHistoryItem = ssc
1892 .appendSlideCommand((SlideSequencesCommand) historyList
1896 if (!appendHistoryItem)
1898 addHistoryItem(ssc);
1911 protected void copy_actionPerformed(ActionEvent e)
1914 if (viewport.getSelectionGroup() == null)
1918 // TODO: preserve the ordering of displayed alignment annotation in any
1919 // internal paste (particularly sequence associated annotation)
1920 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1921 String[] omitHidden = null;
1923 if (viewport.hasHiddenColumns())
1925 omitHidden = viewport.getViewAsString(true);
1928 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1929 seqs, omitHidden, null);
1931 StringSelection ss = new StringSelection(output);
1935 jalview.gui.Desktop.internalCopy = true;
1936 // Its really worth setting the clipboard contents
1937 // to empty before setting the large StringSelection!!
1938 Toolkit.getDefaultToolkit().getSystemClipboard()
1939 .setContents(new StringSelection(""), null);
1941 Toolkit.getDefaultToolkit().getSystemClipboard()
1942 .setContents(ss, Desktop.instance);
1943 } catch (OutOfMemoryError er)
1945 new OOMWarning("copying region", er);
1949 ArrayList<int[]> hiddenColumns = null;
1950 if (viewport.hasHiddenColumns())
1952 hiddenColumns = new ArrayList<>();
1953 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1954 .getSelectionGroup().getEndRes();
1955 for (int[] region : viewport.getAlignment().getHiddenColumns()
1956 .getHiddenRegions())
1958 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1960 hiddenColumns.add(new int[] { region[0] - hiddenOffset,
1961 region[1] - hiddenOffset });
1966 Desktop.jalviewClipboard = new Object[] { seqs,
1967 viewport.getAlignment().getDataset(), hiddenColumns };
1968 statusBar.setText(MessageManager.formatMessage(
1969 "label.copied_sequences_to_clipboard", new Object[] { Integer
1970 .valueOf(seqs.length).toString() }));
1978 * @throws InterruptedException
1979 * @throws IOException
1982 protected void pasteNew_actionPerformed(ActionEvent e)
1983 throws IOException, InterruptedException
1993 * @throws InterruptedException
1994 * @throws IOException
1997 protected void pasteThis_actionPerformed(ActionEvent e)
1998 throws IOException, InterruptedException
2004 * Paste contents of Jalview clipboard
2006 * @param newAlignment
2007 * true to paste to a new alignment, otherwise add to this.
2008 * @throws InterruptedException
2009 * @throws IOException
2011 void paste(boolean newAlignment) throws IOException, InterruptedException
2013 boolean externalPaste = true;
2016 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2017 Transferable contents = c.getContents(this);
2019 if (contents == null)
2028 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2029 if (str.length() < 1)
2034 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2036 } catch (OutOfMemoryError er)
2038 new OOMWarning("Out of memory pasting sequences!!", er);
2042 SequenceI[] sequences;
2043 boolean annotationAdded = false;
2044 AlignmentI alignment = null;
2046 if (Desktop.jalviewClipboard != null)
2048 // The clipboard was filled from within Jalview, we must use the
2050 // And dataset from the copied alignment
2051 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2052 // be doubly sure that we create *new* sequence objects.
2053 sequences = new SequenceI[newseq.length];
2054 for (int i = 0; i < newseq.length; i++)
2056 sequences[i] = new Sequence(newseq[i]);
2058 alignment = new Alignment(sequences);
2059 externalPaste = false;
2063 // parse the clipboard as an alignment.
2064 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2066 sequences = alignment.getSequencesArray();
2070 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2076 if (Desktop.jalviewClipboard != null)
2078 // dataset is inherited
2079 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2083 // new dataset is constructed
2084 alignment.setDataset(null);
2086 alwidth = alignment.getWidth() + 1;
2090 AlignmentI pastedal = alignment; // preserve pasted alignment object
2091 // Add pasted sequences and dataset into existing alignment.
2092 alignment = viewport.getAlignment();
2093 alwidth = alignment.getWidth() + 1;
2094 // decide if we need to import sequences from an existing dataset
2095 boolean importDs = Desktop.jalviewClipboard != null
2096 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2097 // importDs==true instructs us to copy over new dataset sequences from
2098 // an existing alignment
2099 Vector newDs = (importDs) ? new Vector() : null; // used to create
2100 // minimum dataset set
2102 for (int i = 0; i < sequences.length; i++)
2106 newDs.addElement(null);
2108 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2110 if (importDs && ds != null)
2112 if (!newDs.contains(ds))
2114 newDs.setElementAt(ds, i);
2115 ds = new Sequence(ds);
2116 // update with new dataset sequence
2117 sequences[i].setDatasetSequence(ds);
2121 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2126 // copy and derive new dataset sequence
2127 sequences[i] = sequences[i].deriveSequence();
2128 alignment.getDataset().addSequence(
2129 sequences[i].getDatasetSequence());
2130 // TODO: avoid creation of duplicate dataset sequences with a
2131 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2133 alignment.addSequence(sequences[i]); // merges dataset
2137 newDs.clear(); // tidy up
2139 if (alignment.getAlignmentAnnotation() != null)
2141 for (AlignmentAnnotation alan : alignment
2142 .getAlignmentAnnotation())
2144 if (alan.graphGroup > fgroup)
2146 fgroup = alan.graphGroup;
2150 if (pastedal.getAlignmentAnnotation() != null)
2152 // Add any annotation attached to alignment.
2153 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2154 for (int i = 0; i < alann.length; i++)
2156 annotationAdded = true;
2157 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2159 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2160 if (newann.graphGroup > -1)
2162 if (newGraphGroups.size() <= newann.graphGroup
2163 || newGraphGroups.get(newann.graphGroup) == null)
2165 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2167 newGraphGroups.add(q, null);
2169 newGraphGroups.set(newann.graphGroup, new Integer(
2172 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2176 newann.padAnnotation(alwidth);
2177 alignment.addAnnotation(newann);
2187 addHistoryItem(new EditCommand(
2188 MessageManager.getString("label.add_sequences"),
2189 Action.PASTE, sequences, 0, alignment.getWidth(), alignment));
2191 // Add any annotations attached to sequences
2192 for (int i = 0; i < sequences.length; i++)
2194 if (sequences[i].getAnnotation() != null)
2196 AlignmentAnnotation newann;
2197 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2199 annotationAdded = true;
2200 newann = sequences[i].getAnnotation()[a];
2201 newann.adjustForAlignment();
2202 newann.padAnnotation(alwidth);
2203 if (newann.graphGroup > -1)
2205 if (newann.graphGroup > -1)
2207 if (newGraphGroups.size() <= newann.graphGroup
2208 || newGraphGroups.get(newann.graphGroup) == null)
2210 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2212 newGraphGroups.add(q, null);
2214 newGraphGroups.set(newann.graphGroup, new Integer(
2217 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2221 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2226 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2233 // propagate alignment changed.
2234 vpRanges.setEndSeq(alignment.getHeight());
2235 if (annotationAdded)
2237 // Duplicate sequence annotation in all views.
2238 AlignmentI[] alview = this.getViewAlignments();
2239 for (int i = 0; i < sequences.length; i++)
2241 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2246 for (int avnum = 0; avnum < alview.length; avnum++)
2248 if (alview[avnum] != alignment)
2250 // duplicate in a view other than the one with input focus
2251 int avwidth = alview[avnum].getWidth() + 1;
2252 // this relies on sann being preserved after we
2253 // modify the sequence's annotation array for each duplication
2254 for (int a = 0; a < sann.length; a++)
2256 AlignmentAnnotation newann = new AlignmentAnnotation(
2258 sequences[i].addAlignmentAnnotation(newann);
2259 newann.padAnnotation(avwidth);
2260 alview[avnum].addAnnotation(newann); // annotation was
2261 // duplicated earlier
2262 // TODO JAL-1145 graphGroups are not updated for sequence
2263 // annotation added to several views. This may cause
2265 alview[avnum].setAnnotationIndex(newann, a);
2270 buildSortByAnnotationScoresMenu();
2272 viewport.firePropertyChange("alignment", null,
2273 alignment.getSequences());
2274 if (alignPanels != null)
2276 for (AlignmentPanel ap : alignPanels)
2278 ap.validateAnnotationDimensions(false);
2283 alignPanel.validateAnnotationDimensions(false);
2289 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2291 String newtitle = new String("Copied sequences");
2293 if (Desktop.jalviewClipboard != null
2294 && Desktop.jalviewClipboard[2] != null)
2296 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2297 for (int[] region : hc)
2299 af.viewport.hideColumns(region[0], region[1]);
2303 // >>>This is a fix for the moment, until a better solution is
2305 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2307 alignPanel.getSeqPanel().seqCanvas
2308 .getFeatureRenderer());
2310 // TODO: maintain provenance of an alignment, rather than just make the
2311 // title a concatenation of operations.
2314 if (title.startsWith("Copied sequences"))
2320 newtitle = newtitle.concat("- from " + title);
2325 newtitle = new String("Pasted sequences");
2328 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2333 } catch (Exception ex)
2335 ex.printStackTrace();
2336 System.out.println("Exception whilst pasting: " + ex);
2337 // could be anything being pasted in here
2342 protected void expand_newalign(ActionEvent e)
2346 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2347 .getAlignment(), -1);
2348 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2350 String newtitle = new String("Flanking alignment");
2352 if (Desktop.jalviewClipboard != null
2353 && Desktop.jalviewClipboard[2] != null)
2355 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2356 for (int region[] : hc)
2358 af.viewport.hideColumns(region[0], region[1]);
2362 // >>>This is a fix for the moment, until a better solution is
2364 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2366 alignPanel.getSeqPanel().seqCanvas
2367 .getFeatureRenderer());
2369 // TODO: maintain provenance of an alignment, rather than just make the
2370 // title a concatenation of operations.
2372 if (title.startsWith("Copied sequences"))
2378 newtitle = newtitle.concat("- from " + title);
2382 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2384 } catch (Exception ex)
2386 ex.printStackTrace();
2387 System.out.println("Exception whilst pasting: " + ex);
2388 // could be anything being pasted in here
2389 } catch (OutOfMemoryError oom)
2391 new OOMWarning("Viewing flanking region of alignment", oom);
2402 protected void cut_actionPerformed(ActionEvent e)
2404 copy_actionPerformed(null);
2405 delete_actionPerformed(null);
2415 protected void delete_actionPerformed(ActionEvent evt)
2418 SequenceGroup sg = viewport.getSelectionGroup();
2425 * If the cut affects all sequences, warn, remove highlighted columns
2427 if (sg.getSize() == viewport.getAlignment().getHeight())
2429 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes()) + 1) == viewport
2430 .getAlignment().getWidth()) ? true : false;
2431 if (isEntireAlignWidth)
2433 int confirm = JvOptionPane.showConfirmDialog(this,
2434 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2435 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2436 JvOptionPane.OK_CANCEL_OPTION);
2438 if (confirm == JvOptionPane.CANCEL_OPTION
2439 || confirm == JvOptionPane.CLOSED_OPTION)
2444 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2445 sg.getEndRes() + 1);
2447 SequenceI[] cut = sg.getSequences()
2448 .toArray(new SequenceI[sg.getSize()]);
2450 addHistoryItem(new EditCommand(
2451 MessageManager.getString("label.cut_sequences"), Action.CUT,
2452 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2453 viewport.getAlignment()));
2455 viewport.setSelectionGroup(null);
2456 viewport.sendSelection();
2457 viewport.getAlignment().deleteGroup(sg);
2459 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2461 if (viewport.getAlignment().getHeight() < 1)
2465 this.setClosed(true);
2466 } catch (Exception ex)
2479 protected void deleteGroups_actionPerformed(ActionEvent e)
2481 if (avc.deleteGroups())
2483 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2484 alignPanel.updateAnnotation();
2485 alignPanel.paintAlignment(true);
2496 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2498 SequenceGroup sg = new SequenceGroup();
2500 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2502 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2505 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2506 viewport.setSelectionGroup(sg);
2507 viewport.sendSelection();
2508 // JAL-2034 - should delegate to
2509 // alignPanel to decide if overview needs
2511 alignPanel.paintAlignment(false);
2512 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2522 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2524 if (viewport.cursorMode)
2526 alignPanel.getSeqPanel().keyboardNo1 = null;
2527 alignPanel.getSeqPanel().keyboardNo2 = null;
2529 viewport.setSelectionGroup(null);
2530 viewport.getColumnSelection().clear();
2531 viewport.setSelectionGroup(null);
2532 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2533 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2534 // JAL-2034 - should delegate to
2535 // alignPanel to decide if overview needs
2537 alignPanel.paintAlignment(false);
2538 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2539 viewport.sendSelection();
2549 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2551 SequenceGroup sg = viewport.getSelectionGroup();
2555 selectAllSequenceMenuItem_actionPerformed(null);
2560 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2562 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2564 // JAL-2034 - should delegate to
2565 // alignPanel to decide if overview needs
2568 alignPanel.paintAlignment(true);
2569 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2570 viewport.sendSelection();
2574 public void invertColSel_actionPerformed(ActionEvent e)
2576 viewport.invertColumnSelection();
2577 alignPanel.paintAlignment(true);
2578 viewport.sendSelection();
2588 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2590 trimAlignment(true);
2600 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2602 trimAlignment(false);
2605 void trimAlignment(boolean trimLeft)
2607 ColumnSelection colSel = viewport.getColumnSelection();
2610 if (!colSel.isEmpty())
2614 column = colSel.getMin();
2618 column = colSel.getMax();
2622 if (viewport.getSelectionGroup() != null)
2624 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2625 viewport.getHiddenRepSequences());
2629 seqs = viewport.getAlignment().getSequencesArray();
2632 TrimRegionCommand trimRegion;
2635 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2636 column, viewport.getAlignment());
2637 vpRanges.setStartRes(0);
2641 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2642 column, viewport.getAlignment());
2645 statusBar.setText(MessageManager.formatMessage(
2646 "label.removed_columns",
2647 new String[] { Integer.valueOf(trimRegion.getSize())
2650 addHistoryItem(trimRegion);
2652 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2654 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2655 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2657 viewport.getAlignment().deleteGroup(sg);
2661 viewport.firePropertyChange("alignment", null, viewport
2662 .getAlignment().getSequences());
2673 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2675 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2678 if (viewport.getSelectionGroup() != null)
2680 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2681 viewport.getHiddenRepSequences());
2682 start = viewport.getSelectionGroup().getStartRes();
2683 end = viewport.getSelectionGroup().getEndRes();
2687 seqs = viewport.getAlignment().getSequencesArray();
2690 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2691 "Remove Gapped Columns", seqs, start, end,
2692 viewport.getAlignment());
2694 addHistoryItem(removeGapCols);
2696 statusBar.setText(MessageManager.formatMessage(
2697 "label.removed_empty_columns",
2698 new Object[] { Integer.valueOf(removeGapCols.getSize())
2701 // This is to maintain viewport position on first residue
2702 // of first sequence
2703 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2704 int startRes = seq.findPosition(vpRanges.getStartRes());
2705 // ShiftList shifts;
2706 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2707 // edit.alColumnChanges=shifts.getInverse();
2708 // if (viewport.hasHiddenColumns)
2709 // viewport.getColumnSelection().compensateForEdits(shifts);
2710 vpRanges.setStartRes(seq.findIndex(startRes) - 1);
2711 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2723 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2725 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2728 if (viewport.getSelectionGroup() != null)
2730 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2731 viewport.getHiddenRepSequences());
2732 start = viewport.getSelectionGroup().getStartRes();
2733 end = viewport.getSelectionGroup().getEndRes();
2737 seqs = viewport.getAlignment().getSequencesArray();
2740 // This is to maintain viewport position on first residue
2741 // of first sequence
2742 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2743 int startRes = seq.findPosition(vpRanges.getStartRes());
2745 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2746 viewport.getAlignment()));
2748 vpRanges.setStartRes(seq.findIndex(startRes) - 1);
2750 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2762 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2764 viewport.setPadGaps(padGapsMenuitem.isSelected());
2765 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2776 public void findMenuItem_actionPerformed(ActionEvent e)
2782 * Create a new view of the current alignment.
2785 public void newView_actionPerformed(ActionEvent e)
2787 newView(null, true);
2791 * Creates and shows a new view of the current alignment.
2794 * title of newly created view; if null, one will be generated
2795 * @param copyAnnotation
2796 * if true then duplicate all annnotation, groups and settings
2797 * @return new alignment panel, already displayed.
2799 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2802 * Create a new AlignmentPanel (with its own, new Viewport)
2804 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2806 if (!copyAnnotation)
2809 * remove all groups and annotation except for the automatic stuff
2811 newap.av.getAlignment().deleteAllGroups();
2812 newap.av.getAlignment().deleteAllAnnotations(false);
2815 newap.av.setGatherViewsHere(false);
2817 if (viewport.viewName == null)
2819 viewport.viewName = MessageManager
2820 .getString("label.view_name_original");
2824 * Views share the same edits undo and redo stacks
2826 newap.av.setHistoryList(viewport.getHistoryList());
2827 newap.av.setRedoList(viewport.getRedoList());
2830 * Views share the same mappings; need to deregister any new mappings
2831 * created by copyAlignPanel, and register the new reference to the shared
2834 newap.av.replaceMappings(viewport.getAlignment());
2837 * start up cDNA consensus (if applicable) now mappings are in place
2839 if (newap.av.initComplementConsensus())
2841 newap.refresh(true); // adjust layout of annotations
2844 newap.av.viewName = getNewViewName(viewTitle);
2846 addAlignmentPanel(newap, true);
2847 newap.alignmentChanged();
2849 if (alignPanels.size() == 2)
2851 viewport.setGatherViewsHere(true);
2853 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2858 * Make a new name for the view, ensuring it is unique within the current
2859 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2860 * these now use viewId. Unique view names are still desirable for usability.)
2865 protected String getNewViewName(String viewTitle)
2867 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2868 boolean addFirstIndex = false;
2869 if (viewTitle == null || viewTitle.trim().length() == 0)
2871 viewTitle = MessageManager.getString("action.view");
2872 addFirstIndex = true;
2876 index = 1;// we count from 1 if given a specific name
2878 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2880 List<Component> comps = PaintRefresher.components.get(viewport
2881 .getSequenceSetId());
2883 List<String> existingNames = getExistingViewNames(comps);
2885 while (existingNames.contains(newViewName))
2887 newViewName = viewTitle + " " + (++index);
2893 * Returns a list of distinct view names found in the given list of
2894 * components. View names are held on the viewport of an AlignmentPanel.
2899 protected List<String> getExistingViewNames(List<Component> comps)
2901 List<String> existingNames = new ArrayList<>();
2902 for (Component comp : comps)
2904 if (comp instanceof AlignmentPanel)
2906 AlignmentPanel ap = (AlignmentPanel) comp;
2907 if (!existingNames.contains(ap.av.viewName))
2909 existingNames.add(ap.av.viewName);
2913 return existingNames;
2917 * Explode tabbed views into separate windows.
2920 public void expandViews_actionPerformed(ActionEvent e)
2922 Desktop.explodeViews(this);
2926 * Gather views in separate windows back into a tabbed presentation.
2929 public void gatherViews_actionPerformed(ActionEvent e)
2931 Desktop.instance.gatherViews(this);
2941 public void font_actionPerformed(ActionEvent e)
2943 new FontChooser(alignPanel);
2953 protected void seqLimit_actionPerformed(ActionEvent e)
2955 viewport.setShowJVSuffix(seqLimits.isSelected());
2957 alignPanel.getIdPanel().getIdCanvas()
2958 .setPreferredSize(alignPanel.calculateIdWidth());
2959 alignPanel.paintAlignment(true);
2963 public void idRightAlign_actionPerformed(ActionEvent e)
2965 viewport.setRightAlignIds(idRightAlign.isSelected());
2966 alignPanel.paintAlignment(true);
2970 public void centreColumnLabels_actionPerformed(ActionEvent e)
2972 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2973 alignPanel.paintAlignment(true);
2979 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2982 protected void followHighlight_actionPerformed()
2985 * Set the 'follow' flag on the Viewport (and scroll to position if now
2988 final boolean state = this.followHighlightMenuItem.getState();
2989 viewport.setFollowHighlight(state);
2992 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
3003 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3005 viewport.setColourText(colourTextMenuItem.isSelected());
3006 alignPanel.paintAlignment(true);
3016 public void wrapMenuItem_actionPerformed(ActionEvent e)
3018 scaleAbove.setVisible(wrapMenuItem.isSelected());
3019 scaleLeft.setVisible(wrapMenuItem.isSelected());
3020 scaleRight.setVisible(wrapMenuItem.isSelected());
3021 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3022 alignPanel.updateLayout();
3026 public void showAllSeqs_actionPerformed(ActionEvent e)
3028 viewport.showAllHiddenSeqs();
3032 public void showAllColumns_actionPerformed(ActionEvent e)
3034 viewport.showAllHiddenColumns();
3036 viewport.sendSelection();
3040 public void hideSelSequences_actionPerformed(ActionEvent e)
3042 viewport.hideAllSelectedSeqs();
3043 // alignPanel.paintAlignment(true);
3047 * called by key handler and the hide all/show all menu items
3052 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3055 boolean hide = false;
3056 SequenceGroup sg = viewport.getSelectionGroup();
3057 if (!toggleSeqs && !toggleCols)
3059 // Hide everything by the current selection - this is a hack - we do the
3060 // invert and then hide
3061 // first check that there will be visible columns after the invert.
3062 if (viewport.hasSelectedColumns()
3063 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
3066 // now invert the sequence set, if required - empty selection implies
3067 // that no hiding is required.
3070 invertSequenceMenuItem_actionPerformed(null);
3071 sg = viewport.getSelectionGroup();
3075 viewport.expandColSelection(sg, true);
3076 // finally invert the column selection and get the new sequence
3078 invertColSel_actionPerformed(null);
3085 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3087 hideSelSequences_actionPerformed(null);
3090 else if (!(toggleCols && viewport.hasSelectedColumns()))
3092 showAllSeqs_actionPerformed(null);
3098 if (viewport.hasSelectedColumns())
3100 hideSelColumns_actionPerformed(null);
3103 viewport.setSelectionGroup(sg);
3108 showAllColumns_actionPerformed(null);
3117 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3118 * event.ActionEvent)
3121 public void hideAllButSelection_actionPerformed(ActionEvent e)
3123 toggleHiddenRegions(false, false);
3124 viewport.sendSelection();
3131 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3135 public void hideAllSelection_actionPerformed(ActionEvent e)
3137 SequenceGroup sg = viewport.getSelectionGroup();
3138 viewport.expandColSelection(sg, false);
3139 viewport.hideAllSelectedSeqs();
3140 viewport.hideSelectedColumns();
3141 alignPanel.paintAlignment(true);
3142 viewport.sendSelection();
3149 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3153 public void showAllhidden_actionPerformed(ActionEvent e)
3155 viewport.showAllHiddenColumns();
3156 viewport.showAllHiddenSeqs();
3157 alignPanel.paintAlignment(true);
3158 viewport.sendSelection();
3162 public void hideSelColumns_actionPerformed(ActionEvent e)
3164 viewport.hideSelectedColumns();
3165 alignPanel.paintAlignment(true);
3166 viewport.sendSelection();
3170 public void hiddenMarkers_actionPerformed(ActionEvent e)
3172 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3183 protected void scaleAbove_actionPerformed(ActionEvent e)
3185 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3186 alignPanel.paintAlignment(true);
3196 protected void scaleLeft_actionPerformed(ActionEvent e)
3198 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3199 alignPanel.paintAlignment(true);
3209 protected void scaleRight_actionPerformed(ActionEvent e)
3211 viewport.setScaleRightWrapped(scaleRight.isSelected());
3212 alignPanel.paintAlignment(true);
3222 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3224 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3225 alignPanel.paintAlignment(true);
3235 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3237 viewport.setShowText(viewTextMenuItem.isSelected());
3238 alignPanel.paintAlignment(true);
3248 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3250 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3251 alignPanel.paintAlignment(true);
3254 public FeatureSettings featureSettings;
3257 public FeatureSettingsControllerI getFeatureSettingsUI()
3259 return featureSettings;
3263 public void featureSettings_actionPerformed(ActionEvent e)
3265 if (featureSettings != null)
3267 featureSettings.close();
3268 featureSettings = null;
3270 if (!showSeqFeatures.isSelected())
3272 // make sure features are actually displayed
3273 showSeqFeatures.setSelected(true);
3274 showSeqFeatures_actionPerformed(null);
3276 featureSettings = new FeatureSettings(this);
3280 * Set or clear 'Show Sequence Features'
3286 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3288 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3289 alignPanel.paintAlignment(true);
3290 if (alignPanel.getOverviewPanel() != null)
3292 alignPanel.getOverviewPanel().updateOverviewImage();
3297 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3298 * the annotations panel as a whole.
3300 * The options to show/hide all annotations should be enabled when the panel
3301 * is shown, and disabled when the panel is hidden.
3306 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3308 final boolean setVisible = annotationPanelMenuItem.isSelected();
3309 viewport.setShowAnnotation(setVisible);
3310 this.showAllSeqAnnotations.setEnabled(setVisible);
3311 this.hideAllSeqAnnotations.setEnabled(setVisible);
3312 this.showAllAlAnnotations.setEnabled(setVisible);
3313 this.hideAllAlAnnotations.setEnabled(setVisible);
3314 alignPanel.updateLayout();
3318 public void alignmentProperties()
3320 JEditorPane editPane = new JEditorPane("text/html", "");
3321 editPane.setEditable(false);
3322 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3324 editPane.setText(MessageManager.formatMessage("label.html_content",
3325 new Object[] { contents.toString() }));
3326 JInternalFrame frame = new JInternalFrame();
3327 frame.getContentPane().add(new JScrollPane(editPane));
3329 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3330 "label.alignment_properties", new Object[] { getTitle() }),
3341 public void overviewMenuItem_actionPerformed(ActionEvent e)
3343 if (alignPanel.overviewPanel != null)
3348 JInternalFrame frame = new JInternalFrame();
3349 OverviewPanel overview = new OverviewPanel(alignPanel);
3350 frame.setContentPane(overview);
3351 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3352 "label.overview_params", new Object[] { this.getTitle() }),
3353 true, frame.getWidth(), frame.getHeight(), true, true);
3355 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3356 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3359 public void internalFrameClosed(
3360 javax.swing.event.InternalFrameEvent evt)
3362 alignPanel.setOverviewPanel(null);
3366 alignPanel.setOverviewPanel(overview);
3370 public void textColour_actionPerformed()
3372 new TextColourChooser().chooseColour(alignPanel, null);
3376 * public void covariationColour_actionPerformed() {
3378 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3382 public void annotationColour_actionPerformed()
3384 new AnnotationColourChooser(viewport, alignPanel);
3388 public void annotationColumn_actionPerformed(ActionEvent e)
3390 new AnnotationColumnChooser(viewport, alignPanel);
3394 * Action on the user checking or unchecking the option to apply the selected
3395 * colour scheme to all groups. If unchecked, groups may have their own
3396 * independent colour schemes.
3401 public void applyToAllGroups_actionPerformed(boolean selected)
3403 viewport.setColourAppliesToAllGroups(selected);
3407 * Action on user selecting a colour from the colour menu
3410 * the name (not the menu item label!) of the colour scheme
3413 public void changeColour_actionPerformed(String name)
3416 * 'User Defined' opens a panel to configure or load a
3417 * user-defined colour scheme
3419 if (ResidueColourScheme.USER_DEFINED.equals(name))
3421 new UserDefinedColours(alignPanel);
3426 * otherwise set the chosen colour scheme (or null for 'None')
3428 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3429 viewport.getAlignment(), viewport.getHiddenRepSequences());
3434 * Actions on setting or changing the alignment colour scheme
3439 public void changeColour(ColourSchemeI cs)
3441 // TODO: pull up to controller method
3442 ColourMenuHelper.setColourSelected(colourMenu, cs);
3444 viewport.setGlobalColourScheme(cs);
3446 alignPanel.paintAlignment(true);
3450 * Show the PID threshold slider panel
3453 protected void modifyPID_actionPerformed()
3455 SliderPanel.setPIDSliderSource(alignPanel,
3456 viewport.getResidueShading(), alignPanel.getViewName());
3457 SliderPanel.showPIDSlider();
3461 * Show the Conservation slider panel
3464 protected void modifyConservation_actionPerformed()
3466 SliderPanel.setConservationSlider(alignPanel,
3467 viewport.getResidueShading(), alignPanel.getViewName());
3468 SliderPanel.showConservationSlider();
3472 * Action on selecting or deselecting (Colour) By Conservation
3475 public void conservationMenuItem_actionPerformed(boolean selected)
3477 modifyConservation.setEnabled(selected);
3478 viewport.setConservationSelected(selected);
3479 viewport.getResidueShading().setConservationApplied(selected);
3481 changeColour(viewport.getGlobalColourScheme());
3484 modifyConservation_actionPerformed();
3488 SliderPanel.hideConservationSlider();
3493 * Action on selecting or deselecting (Colour) Above PID Threshold
3496 public void abovePIDThreshold_actionPerformed(boolean selected)
3498 modifyPID.setEnabled(selected);
3499 viewport.setAbovePIDThreshold(selected);
3502 viewport.getResidueShading().setThreshold(0,
3503 viewport.isIgnoreGapsConsensus());
3506 changeColour(viewport.getGlobalColourScheme());
3509 modifyPID_actionPerformed();
3513 SliderPanel.hidePIDSlider();
3524 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3526 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3527 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3528 .getAlignment().getSequenceAt(0));
3529 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3530 viewport.getAlignment()));
3531 alignPanel.paintAlignment(true);
3541 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3543 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3544 AlignmentSorter.sortByID(viewport.getAlignment());
3545 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3546 viewport.getAlignment()));
3547 alignPanel.paintAlignment(true);
3557 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3559 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3560 AlignmentSorter.sortByLength(viewport.getAlignment());
3561 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3562 viewport.getAlignment()));
3563 alignPanel.paintAlignment(true);
3573 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3575 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3576 AlignmentSorter.sortByGroup(viewport.getAlignment());
3577 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3578 viewport.getAlignment()));
3580 alignPanel.paintAlignment(true);
3590 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3592 new RedundancyPanel(alignPanel, this);
3602 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3604 if ((viewport.getSelectionGroup() == null)
3605 || (viewport.getSelectionGroup().getSize() < 2))
3607 JvOptionPane.showInternalMessageDialog(this, MessageManager
3608 .getString("label.you_must_select_least_two_sequences"),
3609 MessageManager.getString("label.invalid_selection"),
3610 JvOptionPane.WARNING_MESSAGE);
3614 JInternalFrame frame = new JInternalFrame();
3615 frame.setContentPane(new PairwiseAlignPanel(viewport));
3616 Desktop.addInternalFrame(frame,
3617 MessageManager.getString("action.pairwise_alignment"), 600,
3623 public void autoCalculate_actionPerformed(ActionEvent e)
3625 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3626 if (viewport.autoCalculateConsensus)
3628 viewport.firePropertyChange("alignment", null, viewport
3629 .getAlignment().getSequences());
3634 public void sortByTreeOption_actionPerformed(ActionEvent e)
3636 viewport.sortByTree = sortByTree.isSelected();
3640 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3642 viewport.followSelection = listenToViewSelections.isSelected();
3646 * Constructs a tree panel and adds it to the desktop
3649 * tree type (NJ or AV)
3651 * name of score model used to compute the tree
3653 * parameters for the distance or similarity calculation
3655 void newTreePanel(String type, String modelName, SimilarityParamsI options)
3657 String frameTitle = "";
3660 boolean onSelection = false;
3661 if (viewport.getSelectionGroup() != null
3662 && viewport.getSelectionGroup().getSize() > 0)
3664 SequenceGroup sg = viewport.getSelectionGroup();
3666 /* Decide if the selection is a column region */
3667 for (SequenceI _s : sg.getSequences())
3669 if (_s.getLength() < sg.getEndRes())
3675 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3677 .getString("label.sequences_selection_not_aligned"),
3678 JvOptionPane.WARNING_MESSAGE);
3687 if (viewport.getAlignment().getHeight() < 2)
3693 tp = new TreePanel(alignPanel, type, modelName, options);
3694 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3696 frameTitle += " from ";
3698 if (viewport.viewName != null)
3700 frameTitle += viewport.viewName + " of ";
3703 frameTitle += this.title;
3705 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3716 public void addSortByOrderMenuItem(String title,
3717 final AlignmentOrder order)
3719 final JMenuItem item = new JMenuItem(MessageManager.formatMessage(
3720 "action.by_title_param", new Object[] { title }));
3722 item.addActionListener(new java.awt.event.ActionListener()
3725 public void actionPerformed(ActionEvent e)
3727 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3729 // TODO: JBPNote - have to map order entries to curent SequenceI
3731 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3733 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
3736 alignPanel.paintAlignment(true);
3742 * Add a new sort by annotation score menu item
3745 * the menu to add the option to
3747 * the label used to retrieve scores for each sequence on the
3750 public void addSortByAnnotScoreMenuItem(JMenu sort,
3751 final String scoreLabel)
3753 final JMenuItem item = new JMenuItem(scoreLabel);
3755 item.addActionListener(new java.awt.event.ActionListener()
3758 public void actionPerformed(ActionEvent e)
3760 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3761 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3762 viewport.getAlignment());// ,viewport.getSelectionGroup());
3763 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3764 viewport.getAlignment()));
3765 alignPanel.paintAlignment(true);
3771 * last hash for alignment's annotation array - used to minimise cost of
3774 protected int _annotationScoreVectorHash;
3777 * search the alignment and rebuild the sort by annotation score submenu the
3778 * last alignment annotation vector hash is stored to minimize cost of
3779 * rebuilding in subsequence calls.
3783 public void buildSortByAnnotationScoresMenu()
3785 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3790 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
3792 sortByAnnotScore.removeAll();
3793 // almost certainly a quicker way to do this - but we keep it simple
3794 Hashtable scoreSorts = new Hashtable();
3795 AlignmentAnnotation aann[];
3796 for (SequenceI sqa : viewport.getAlignment().getSequences())
3798 aann = sqa.getAnnotation();
3799 for (int i = 0; aann != null && i < aann.length; i++)
3801 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3803 scoreSorts.put(aann[i].label, aann[i].label);
3807 Enumeration labels = scoreSorts.keys();
3808 while (labels.hasMoreElements())
3810 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3811 (String) labels.nextElement());
3813 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3816 _annotationScoreVectorHash = viewport.getAlignment()
3817 .getAlignmentAnnotation().hashCode();
3822 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3823 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3824 * call. Listeners are added to remove the menu item when the treePanel is
3825 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3829 public void buildTreeSortMenu()
3831 sortByTreeMenu.removeAll();
3833 List<Component> comps = PaintRefresher.components.get(viewport
3834 .getSequenceSetId());
3835 List<TreePanel> treePanels = new ArrayList<>();
3836 for (Component comp : comps)
3838 if (comp instanceof TreePanel)
3840 treePanels.add((TreePanel) comp);
3844 if (treePanels.size() < 1)
3846 sortByTreeMenu.setVisible(false);
3850 sortByTreeMenu.setVisible(true);
3852 for (final TreePanel tp : treePanels)
3854 final JMenuItem item = new JMenuItem(tp.getTitle());
3855 item.addActionListener(new java.awt.event.ActionListener()
3858 public void actionPerformed(ActionEvent e)
3860 tp.sortByTree_actionPerformed();
3861 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3866 sortByTreeMenu.add(item);
3870 public boolean sortBy(AlignmentOrder alorder, String undoname)
3872 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3873 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3874 if (undoname != null)
3876 addHistoryItem(new OrderCommand(undoname, oldOrder,
3877 viewport.getAlignment()));
3879 alignPanel.paintAlignment(true);
3884 * Work out whether the whole set of sequences or just the selected set will
3885 * be submitted for multiple alignment.
3888 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3890 // Now, check we have enough sequences
3891 AlignmentView msa = null;
3893 if ((viewport.getSelectionGroup() != null)
3894 && (viewport.getSelectionGroup().getSize() > 1))
3896 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3897 // some common interface!
3899 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3900 * SequenceI[sz = seqs.getSize(false)];
3902 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3903 * seqs.getSequenceAt(i); }
3905 msa = viewport.getAlignmentView(true);
3907 else if (viewport.getSelectionGroup() != null
3908 && viewport.getSelectionGroup().getSize() == 1)
3910 int option = JvOptionPane.showConfirmDialog(this,
3911 MessageManager.getString("warn.oneseq_msainput_selection"),
3912 MessageManager.getString("label.invalid_selection"),
3913 JvOptionPane.OK_CANCEL_OPTION);
3914 if (option == JvOptionPane.OK_OPTION)
3916 msa = viewport.getAlignmentView(false);
3921 msa = viewport.getAlignmentView(false);
3927 * Decides what is submitted to a secondary structure prediction service: the
3928 * first sequence in the alignment, or in the current selection, or, if the
3929 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3930 * region or the whole alignment. (where the first sequence in the set is the
3931 * one that the prediction will be for).
3933 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3935 AlignmentView seqs = null;
3937 if ((viewport.getSelectionGroup() != null)
3938 && (viewport.getSelectionGroup().getSize() > 0))
3940 seqs = viewport.getAlignmentView(true);
3944 seqs = viewport.getAlignmentView(false);
3946 // limit sequences - JBPNote in future - could spawn multiple prediction
3948 // TODO: viewport.getAlignment().isAligned is a global state - the local
3949 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3950 if (!viewport.getAlignment().isAligned(false))
3952 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3953 // TODO: if seqs.getSequences().length>1 then should really have warned
3967 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3969 // Pick the tree file
3970 JalviewFileChooser chooser = new JalviewFileChooser(
3971 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3972 chooser.setFileView(new JalviewFileView());
3973 chooser.setDialogTitle(MessageManager
3974 .getString("label.select_newick_like_tree_file"));
3975 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
3977 int value = chooser.showOpenDialog(null);
3979 if (value == JalviewFileChooser.APPROVE_OPTION)
3981 String filePath = chooser.getSelectedFile().getPath();
3982 Cache.setProperty("LAST_DIRECTORY", filePath);
3983 NewickFile fin = null;
3986 fin = new NewickFile(filePath, DataSourceType.FILE);
3987 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
3988 } catch (Exception ex)
3995 .getString("label.problem_reading_tree_file"),
3996 JvOptionPane.WARNING_MESSAGE);
3997 ex.printStackTrace();
3999 if (fin != null && fin.hasWarningMessage())
4001 JvOptionPane.showMessageDialog(Desktop.desktop, fin
4002 .getWarningMessage(), MessageManager
4003 .getString("label.possible_problem_with_tree_file"),
4004 JvOptionPane.WARNING_MESSAGE);
4009 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4011 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4014 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4015 int h, int x, int y)
4017 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4021 * Add a treeviewer for the tree extracted from a Newick file object to the
4022 * current alignment view
4029 * Associated alignment input data (or null)
4038 * @return TreePanel handle
4040 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4041 AlignmentView input, int w, int h, int x, int y)
4043 TreePanel tp = null;
4049 if (nf.getTree() != null)
4051 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4057 tp.setLocation(x, y);
4060 Desktop.addInternalFrame(tp, treeTitle, w, h);
4062 } catch (Exception ex)
4064 ex.printStackTrace();
4070 private boolean buildingMenu = false;
4073 * Generates menu items and listener event actions for web service clients
4076 public void BuildWebServiceMenu()
4078 while (buildingMenu)
4082 System.err.println("Waiting for building menu to finish.");
4084 } catch (Exception e)
4088 final AlignFrame me = this;
4089 buildingMenu = true;
4090 new Thread(new Runnable()
4095 final List<JMenuItem> legacyItems = new ArrayList<>();
4098 // System.err.println("Building ws menu again "
4099 // + Thread.currentThread());
4100 // TODO: add support for context dependent disabling of services based
4102 // alignment and current selection
4103 // TODO: add additional serviceHandle parameter to specify abstract
4105 // class independently of AbstractName
4106 // TODO: add in rediscovery GUI function to restart discoverer
4107 // TODO: group services by location as well as function and/or
4109 // object broker mechanism.
4110 final Vector<JMenu> wsmenu = new Vector<>();
4111 final IProgressIndicator af = me;
4114 * do not i18n these strings - they are hard-coded in class
4115 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4116 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4118 final JMenu msawsmenu = new JMenu("Alignment");
4119 final JMenu secstrmenu = new JMenu(
4120 "Secondary Structure Prediction");
4121 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4122 final JMenu analymenu = new JMenu("Analysis");
4123 final JMenu dismenu = new JMenu("Protein Disorder");
4124 // JAL-940 - only show secondary structure prediction services from
4125 // the legacy server
4126 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4128 Discoverer.services != null && (Discoverer.services.size() > 0))
4130 // TODO: refactor to allow list of AbstractName/Handler bindings to
4132 // stored or retrieved from elsewhere
4133 // No MSAWS used any more:
4134 // Vector msaws = null; // (Vector)
4135 // Discoverer.services.get("MsaWS");
4136 Vector secstrpr = (Vector) Discoverer.services
4138 if (secstrpr != null)
4140 // Add any secondary structure prediction services
4141 for (int i = 0, j = secstrpr.size(); i < j; i++)
4143 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4145 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4146 .getServiceClient(sh);
4147 int p = secstrmenu.getItemCount();
4148 impl.attachWSMenuEntry(secstrmenu, me);
4149 int q = secstrmenu.getItemCount();
4150 for (int litm = p; litm < q; litm++)
4152 legacyItems.add(secstrmenu.getItem(litm));
4158 // Add all submenus in the order they should appear on the web
4160 wsmenu.add(msawsmenu);
4161 wsmenu.add(secstrmenu);
4162 wsmenu.add(dismenu);
4163 wsmenu.add(analymenu);
4164 // No search services yet
4165 // wsmenu.add(seqsrchmenu);
4167 javax.swing.SwingUtilities.invokeLater(new Runnable()
4174 webService.removeAll();
4175 // first, add discovered services onto the webservices menu
4176 if (wsmenu.size() > 0)
4178 for (int i = 0, j = wsmenu.size(); i < j; i++)
4180 webService.add(wsmenu.get(i));
4185 webService.add(me.webServiceNoServices);
4187 // TODO: move into separate menu builder class.
4188 boolean new_sspred = false;
4189 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4191 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4192 if (jws2servs != null)
4194 if (jws2servs.hasServices())
4196 jws2servs.attachWSMenuEntry(webService, me);
4197 for (Jws2Instance sv : jws2servs.getServices())
4199 if (sv.description.toLowerCase().contains("jpred"))
4201 for (JMenuItem jmi : legacyItems)
4203 jmi.setVisible(false);
4209 if (jws2servs.isRunning())
4211 JMenuItem tm = new JMenuItem(
4212 "Still discovering JABA Services");
4213 tm.setEnabled(false);
4218 build_urlServiceMenu(me.webService);
4219 build_fetchdbmenu(webService);
4220 for (JMenu item : wsmenu)
4222 if (item.getItemCount() == 0)
4224 item.setEnabled(false);
4228 item.setEnabled(true);
4231 } catch (Exception e)
4234 .debug("Exception during web service menu building process.",
4239 } catch (Exception e)
4242 buildingMenu = false;
4249 * construct any groupURL type service menu entries.
4253 private void build_urlServiceMenu(JMenu webService)
4255 // TODO: remove this code when 2.7 is released
4256 // DEBUG - alignmentView
4258 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4259 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4261 * @Override public void actionPerformed(ActionEvent e) {
4262 * jalview.datamodel.AlignmentView
4263 * .testSelectionViews(af.viewport.getAlignment(),
4264 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4266 * }); webService.add(testAlView);
4268 // TODO: refactor to RestClient discoverer and merge menu entries for
4269 // rest-style services with other types of analysis/calculation service
4270 // SHmmr test client - still being implemented.
4271 // DEBUG - alignmentView
4273 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4276 client.attachWSMenuEntry(
4277 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4283 * Searches the alignment sequences for xRefs and builds the Show
4284 * Cross-References menu (formerly called Show Products), with database
4285 * sources for which cross-references are found (protein sources for a
4286 * nucleotide alignment and vice versa)
4288 * @return true if Show Cross-references menu should be enabled
4290 public boolean canShowProducts()
4292 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4293 AlignmentI dataset = viewport.getAlignment().getDataset();
4295 showProducts.removeAll();
4296 final boolean dna = viewport.getAlignment().isNucleotide();
4298 if (seqs == null || seqs.length == 0)
4300 // nothing to see here.
4304 boolean showp = false;
4307 List<String> ptypes = new CrossRef(seqs, dataset)
4308 .findXrefSourcesForSequences(dna);
4310 for (final String source : ptypes)
4313 final AlignFrame af = this;
4314 JMenuItem xtype = new JMenuItem(source);
4315 xtype.addActionListener(new ActionListener()
4318 public void actionPerformed(ActionEvent e)
4320 showProductsFor(af.viewport.getSequenceSelection(), dna, source);
4323 showProducts.add(xtype);
4325 showProducts.setVisible(showp);
4326 showProducts.setEnabled(showp);
4327 } catch (Exception e)
4330 .warn("canShowProducts threw an exception - please report to help@jalview.org",
4338 * Finds and displays cross-references for the selected sequences (protein
4339 * products for nucleotide sequences, dna coding sequences for peptides).
4342 * the sequences to show cross-references for
4344 * true if from a nucleotide alignment (so showing proteins)
4346 * the database to show cross-references for
4348 protected void showProductsFor(final SequenceI[] sel,
4349 final boolean _odna, final String source)
4351 new Thread(CrossRefAction.showProductsFor(sel, _odna, source, this))
4356 * Construct and display a new frame containing the translation of this
4357 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4360 public void showTranslation_actionPerformed(ActionEvent e)
4362 AlignmentI al = null;
4365 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4367 al = dna.translateCdna();
4368 } catch (Exception ex)
4370 jalview.bin.Cache.log.error(
4371 "Exception during translation. Please report this !", ex);
4372 final String msg = MessageManager
4373 .getString("label.error_when_translating_sequences_submit_bug_report");
4374 final String errorTitle = MessageManager
4375 .getString("label.implementation_error")
4376 + MessageManager.getString("label.translation_failed");
4377 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4378 JvOptionPane.ERROR_MESSAGE);
4381 if (al == null || al.getHeight() == 0)
4383 final String msg = MessageManager
4384 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4385 final String errorTitle = MessageManager
4386 .getString("label.translation_failed");
4387 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4388 JvOptionPane.WARNING_MESSAGE);
4392 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4393 af.setFileFormat(this.currentFileFormat);
4394 final String newTitle = MessageManager.formatMessage(
4395 "label.translation_of_params",
4396 new Object[] { this.getTitle() });
4397 af.setTitle(newTitle);
4398 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4400 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4401 viewport.openSplitFrame(af, new Alignment(seqs));
4405 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4412 * Set the file format
4416 public void setFileFormat(FileFormatI format)
4418 this.currentFileFormat = format;
4422 * Try to load a features file onto the alignment.
4425 * contents or path to retrieve file
4427 * access mode of file (see jalview.io.AlignFile)
4428 * @return true if features file was parsed correctly.
4430 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4432 return avc.parseFeaturesFile(file, sourceType,
4433 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4438 public void refreshFeatureUI(boolean enableIfNecessary)
4440 // note - currently this is only still here rather than in the controller
4441 // because of the featureSettings hard reference that is yet to be
4443 if (enableIfNecessary)
4445 viewport.setShowSequenceFeatures(true);
4446 showSeqFeatures.setSelected(true);
4452 public void dragEnter(DropTargetDragEvent evt)
4457 public void dragExit(DropTargetEvent evt)
4462 public void dragOver(DropTargetDragEvent evt)
4467 public void dropActionChanged(DropTargetDragEvent evt)
4472 public void drop(DropTargetDropEvent evt)
4474 // JAL-1552 - acceptDrop required before getTransferable call for
4475 // Java's Transferable for native dnd
4476 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4477 Transferable t = evt.getTransferable();
4478 List<String> files = new ArrayList<>();
4479 List<DataSourceType> protocols = new ArrayList<>();
4483 Desktop.transferFromDropTarget(files, protocols, evt, t);
4484 } catch (Exception e)
4486 e.printStackTrace();
4492 // check to see if any of these files have names matching sequences in
4494 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4495 .getAlignment().getSequencesArray());
4497 * Object[] { String,SequenceI}
4499 ArrayList<Object[]> filesmatched = new ArrayList<>();
4500 ArrayList<String> filesnotmatched = new ArrayList<>();
4501 for (int i = 0; i < files.size(); i++)
4503 String file = files.get(i).toString();
4505 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4506 if (protocol == DataSourceType.FILE)
4508 File fl = new File(file);
4509 pdbfn = fl.getName();
4511 else if (protocol == DataSourceType.URL)
4513 URL url = new URL(file);
4514 pdbfn = url.getFile();
4516 if (pdbfn.length() > 0)
4518 // attempt to find a match in the alignment
4519 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4520 int l = 0, c = pdbfn.indexOf(".");
4521 while (mtch == null && c != -1)
4526 } while ((c = pdbfn.indexOf(".", l)) > l);
4529 pdbfn = pdbfn.substring(0, l);
4531 mtch = idm.findAllIdMatches(pdbfn);
4535 FileFormatI type = null;
4538 type = new IdentifyFile().identify(file, protocol);
4539 } catch (Exception ex)
4543 if (type != null && type.isStructureFile())
4545 filesmatched.add(new Object[] { file, protocol, mtch });
4549 // File wasn't named like one of the sequences or wasn't a PDB file.
4550 filesnotmatched.add(file);
4554 if (filesmatched.size() > 0)
4556 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4562 "label.automatically_associate_structure_files_with_sequences_same_name",
4563 new Object[] { Integer
4569 .getString("label.automatically_associate_structure_files_by_name"),
4570 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION)
4573 for (Object[] fm : filesmatched)
4575 // try and associate
4576 // TODO: may want to set a standard ID naming formalism for
4577 // associating PDB files which have no IDs.
4578 for (SequenceI toassoc : (SequenceI[]) fm[2])
4580 PDBEntry pe = new AssociatePdbFileWithSeq()
4581 .associatePdbWithSeq((String) fm[0],
4582 (DataSourceType) fm[1], toassoc, false,
4586 System.err.println("Associated file : "
4587 + ((String) fm[0]) + " with "
4588 + toassoc.getDisplayId(true));
4592 alignPanel.paintAlignment(true);
4596 if (filesnotmatched.size() > 0)
4599 && (Cache.getDefault(
4600 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JvOptionPane
4606 "label.ignore_unmatched_dropped_files_info",
4607 new Object[] { Integer
4614 .getString("label.ignore_unmatched_dropped_files"),
4615 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4619 for (String fn : filesnotmatched)
4621 loadJalviewDataFile(fn, null, null, null);
4625 } catch (Exception ex)
4627 ex.printStackTrace();
4633 * Attempt to load a "dropped" file or URL string, by testing in turn for
4635 * <li>an Annotation file</li>
4636 * <li>a JNet file</li>
4637 * <li>a features file</li>
4638 * <li>else try to interpret as an alignment file</li>
4642 * either a filename or a URL string.
4643 * @throws InterruptedException
4644 * @throws IOException
4646 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4647 FileFormatI format, SequenceI assocSeq)
4648 throws IOException, InterruptedException
4652 if (sourceType == null)
4654 sourceType = FormatAdapter.checkProtocol(file);
4656 // if the file isn't identified, or not positively identified as some
4657 // other filetype (PFAM is default unidentified alignment file type) then
4658 // try to parse as annotation.
4659 boolean isAnnotation = (format == null || FileFormat.Pfam
4660 .equals(format)) ? new AnnotationFile()
4661 .annotateAlignmentView(viewport, file, sourceType) : false;
4665 // first see if its a T-COFFEE score file
4666 TCoffeeScoreFile tcf = null;
4669 tcf = new TCoffeeScoreFile(file, sourceType);
4672 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4675 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
4676 isAnnotation = true;
4678 .setText(MessageManager
4679 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
4683 // some problem - if no warning its probable that the ID matching
4684 // process didn't work
4688 tcf.getWarningMessage() == null ? MessageManager
4689 .getString("label.check_file_matches_sequence_ids_alignment")
4690 : tcf.getWarningMessage(),
4692 .getString("label.problem_reading_tcoffee_score_file"),
4693 JvOptionPane.WARNING_MESSAGE);
4700 } catch (Exception x)
4703 .debug("Exception when processing data source as T-COFFEE score file",
4709 // try to see if its a JNet 'concise' style annotation file *before*
4711 // try to parse it as a features file
4714 format = new IdentifyFile().identify(file, sourceType);
4716 if (FileFormat.ScoreMatrix == format)
4718 ScoreMatrixFile sm = new ScoreMatrixFile(new FileParse(file,
4721 // todo: i18n this message
4723 .setText(MessageManager.formatMessage(
4724 "label.successfully_loaded_matrix",
4725 sm.getMatrixName()));
4727 else if (FileFormat.HMMER3.equals(format))
4729 HMMFile hmmFile = new HMMFile(new FileParse(file, sourceType));
4730 HiddenMarkovModel hmm = hmmFile.getHMM();
4731 SequenceI hmmSeq = hmm.initHMMSequence(this, 0);
4732 getViewport().initInformation(hmmSeq);
4733 getViewport().updateInformation(alignPanel);
4735 isAnnotation = true;
4738 else if (FileFormat.Jnet.equals(format))
4740 JPredFile predictions = new JPredFile(file, sourceType);
4741 new JnetAnnotationMaker();
4742 JnetAnnotationMaker.add_annotation(predictions,
4743 viewport.getAlignment(), 0, false);
4744 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
4745 viewport.getAlignment().setSeqrep(repseq);
4746 HiddenColumns cs = new HiddenColumns();
4747 cs.hideInsertionsFor(repseq);
4748 viewport.getAlignment().setHiddenColumns(cs);
4749 isAnnotation = true;
4751 // else if (IdentifyFile.FeaturesFile.equals(format))
4752 else if (FileFormat.Features.equals(format))
4754 if (parseFeaturesFile(file, sourceType))
4756 alignPanel.paintAlignment(true);
4761 new FileLoader().LoadFile(viewport, file, sourceType, format);
4767 alignPanel.adjustAnnotationHeight();
4768 viewport.updateSequenceIdColours();
4769 buildSortByAnnotationScoresMenu();
4770 alignPanel.paintAlignment(true);
4772 } catch (Exception ex)
4774 ex.printStackTrace();
4775 } catch (OutOfMemoryError oom)
4780 } catch (Exception x)
4785 + (sourceType != null ? (sourceType == DataSourceType.PASTE ? "from clipboard."
4786 : "using " + sourceType + " from " + file)
4788 + (format != null ? "(parsing as '" + format
4789 + "' file)" : ""), oom, Desktop.desktop);
4791 if (autoAlignNewSequences && !recurring)
4794 HiddenMarkovModel hmm = getViewport().getAlignment()
4795 .getHMMConsensusSequences(false).get(0).getHMM();
4796 new Thread(new HMMAlignThread(this, false)).start();
4802 * Method invoked by the ChangeListener on the tabbed pane, in other words
4803 * when a different tabbed pane is selected by the user or programmatically.
4806 public void tabSelectionChanged(int index)
4810 alignPanel = alignPanels.get(index);
4811 viewport = alignPanel.av;
4812 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4813 setMenusFromViewport(viewport);
4817 * 'focus' any colour slider that is open to the selected viewport
4819 if (viewport.getConservationSelected())
4821 SliderPanel.setConservationSlider(alignPanel,
4822 viewport.getResidueShading(), alignPanel.getViewName());
4826 SliderPanel.hideConservationSlider();
4828 if (viewport.getAbovePIDThreshold())
4830 SliderPanel.setPIDSliderSource(alignPanel,
4831 viewport.getResidueShading(), alignPanel.getViewName());
4835 SliderPanel.hidePIDSlider();
4839 * If there is a frame linked to this one in a SplitPane, switch it to the
4840 * same view tab index. No infinite recursion of calls should happen, since
4841 * tabSelectionChanged() should not get invoked on setting the selected
4842 * index to an unchanged value. Guard against setting an invalid index
4843 * before the new view peer tab has been created.
4845 final AlignViewportI peer = viewport.getCodingComplement();
4848 AlignFrame linkedAlignFrame = ((AlignViewport) peer).getAlignPanel().alignFrame;
4849 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4851 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4857 * On right mouse click on view tab, prompt for and set new view name.
4860 public void tabbedPane_mousePressed(MouseEvent e)
4862 if (e.isPopupTrigger())
4864 String msg = MessageManager.getString("label.enter_view_name");
4865 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4866 JvOptionPane.QUESTION_MESSAGE);
4870 viewport.viewName = reply;
4871 // TODO warn if reply is in getExistingViewNames()?
4872 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4877 public AlignViewport getCurrentView()
4883 * Open the dialog for regex description parsing.
4886 protected void extractScores_actionPerformed(ActionEvent e)
4888 ParseProperties pp = new jalview.analysis.ParseProperties(
4889 viewport.getAlignment());
4890 // TODO: verify regex and introduce GUI dialog for version 2.5
4891 // if (pp.getScoresFromDescription("col", "score column ",
4892 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4894 if (pp.getScoresFromDescription("description column",
4895 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4897 buildSortByAnnotationScoresMenu();
4905 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4909 protected void showDbRefs_actionPerformed(ActionEvent e)
4911 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4917 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4921 protected void showNpFeats_actionPerformed(ActionEvent e)
4923 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4927 * find the viewport amongst the tabs in this alignment frame and close that
4932 public boolean closeView(AlignViewportI av)
4936 this.closeMenuItem_actionPerformed(false);
4939 Component[] comp = tabbedPane.getComponents();
4940 for (int i = 0; comp != null && i < comp.length; i++)
4942 if (comp[i] instanceof AlignmentPanel)
4944 if (((AlignmentPanel) comp[i]).av == av)
4947 closeView((AlignmentPanel) comp[i]);
4955 protected void build_fetchdbmenu(JMenu webService)
4957 // Temporary hack - DBRef Fetcher always top level ws entry.
4958 // TODO We probably want to store a sequence database checklist in
4959 // preferences and have checkboxes.. rather than individual sources selected
4961 final JMenu rfetch = new JMenu(
4962 MessageManager.getString("action.fetch_db_references"));
4963 rfetch.setToolTipText(MessageManager
4964 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4965 webService.add(rfetch);
4967 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4968 MessageManager.getString("option.trim_retrieved_seqs"));
4969 trimrs.setToolTipText(MessageManager
4970 .getString("label.trim_retrieved_sequences"));
4971 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
4972 trimrs.addActionListener(new ActionListener()
4975 public void actionPerformed(ActionEvent e)
4977 trimrs.setSelected(trimrs.isSelected());
4978 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
4979 Boolean.valueOf(trimrs.isSelected()).toString());
4983 JMenuItem fetchr = new JMenuItem(
4984 MessageManager.getString("label.standard_databases"));
4985 fetchr.setToolTipText(MessageManager
4986 .getString("label.fetch_embl_uniprot"));
4987 fetchr.addActionListener(new ActionListener()
4991 public void actionPerformed(ActionEvent e)
4993 new Thread(new Runnable()
4998 boolean isNucleotide = alignPanel.alignFrame.getViewport()
4999 .getAlignment().isNucleotide();
5000 DBRefFetcher dbRefFetcher = new DBRefFetcher(alignPanel.av
5001 .getSequenceSelection(), alignPanel.alignFrame, null,
5002 alignPanel.alignFrame.featureSettings, isNucleotide);
5003 dbRefFetcher.addListener(new FetchFinishedListenerI()
5006 public void finished()
5008 AlignFrame.this.setMenusForViewport();
5011 dbRefFetcher.fetchDBRefs(false);
5019 final AlignFrame me = this;
5020 new Thread(new Runnable()
5025 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5026 .getSequenceFetcherSingleton(me);
5027 javax.swing.SwingUtilities.invokeLater(new Runnable()
5032 String[] dbclasses = sf.getOrderedSupportedSources();
5033 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5034 // jalview.util.QuickSort.sort(otherdb, otherdb);
5035 List<DbSourceProxy> otherdb;
5036 JMenu dfetch = new JMenu();
5037 JMenu ifetch = new JMenu();
5038 JMenuItem fetchr = null;
5039 int comp = 0, icomp = 0, mcomp = 15;
5040 String mname = null;
5042 for (String dbclass : dbclasses)
5044 otherdb = sf.getSourceProxy(dbclass);
5045 // add a single entry for this class, or submenu allowing 'fetch
5047 if (otherdb == null || otherdb.size() < 1)
5051 // List<DbSourceProxy> dbs=otherdb;
5052 // otherdb=new ArrayList<DbSourceProxy>();
5053 // for (DbSourceProxy db:dbs)
5055 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5059 mname = "From " + dbclass;
5061 if (otherdb.size() == 1)
5063 final DbSourceProxy[] dassource = otherdb
5064 .toArray(new DbSourceProxy[0]);
5065 DbSourceProxy src = otherdb.get(0);
5066 fetchr = new JMenuItem(src.getDbSource());
5067 fetchr.addActionListener(new ActionListener()
5071 public void actionPerformed(ActionEvent e)
5073 new Thread(new Runnable()
5079 boolean isNucleotide = alignPanel.alignFrame
5080 .getViewport().getAlignment()
5082 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5083 alignPanel.av.getSequenceSelection(),
5084 alignPanel.alignFrame, dassource,
5085 alignPanel.alignFrame.featureSettings,
5088 .addListener(new FetchFinishedListenerI()
5091 public void finished()
5093 AlignFrame.this.setMenusForViewport();
5096 dbRefFetcher.fetchDBRefs(false);
5102 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5103 MessageManager.formatMessage(
5104 "label.fetch_retrieve_from",
5105 new Object[] { src.getDbName() })));
5111 final DbSourceProxy[] dassource = otherdb
5112 .toArray(new DbSourceProxy[0]);
5114 DbSourceProxy src = otherdb.get(0);
5115 fetchr = new JMenuItem(MessageManager.formatMessage(
5116 "label.fetch_all_param",
5117 new Object[] { src.getDbSource() }));
5118 fetchr.addActionListener(new ActionListener()
5121 public void actionPerformed(ActionEvent e)
5123 new Thread(new Runnable()
5129 boolean isNucleotide = alignPanel.alignFrame
5130 .getViewport().getAlignment()
5132 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5133 alignPanel.av.getSequenceSelection(),
5134 alignPanel.alignFrame, dassource,
5135 alignPanel.alignFrame.featureSettings,
5138 .addListener(new FetchFinishedListenerI()
5141 public void finished()
5143 AlignFrame.this.setMenusForViewport();
5146 dbRefFetcher.fetchDBRefs(false);
5152 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5153 MessageManager.formatMessage(
5154 "label.fetch_retrieve_from_all_sources",
5156 Integer.valueOf(otherdb.size())
5157 .toString(), src.getDbSource(),
5158 src.getDbName() })));
5161 // and then build the rest of the individual menus
5162 ifetch = new JMenu(MessageManager.formatMessage(
5163 "label.source_from_db_source",
5164 new Object[] { src.getDbSource() }));
5166 String imname = null;
5168 for (DbSourceProxy sproxy : otherdb)
5170 String dbname = sproxy.getDbName();
5171 String sname = dbname.length() > 5 ? dbname.substring(0,
5172 5) + "..." : dbname;
5173 String msname = dbname.length() > 10 ? dbname.substring(
5174 0, 10) + "..." : dbname;
5177 imname = MessageManager.formatMessage(
5178 "label.from_msname", new Object[] { sname });
5180 fetchr = new JMenuItem(msname);
5181 final DbSourceProxy[] dassrc = { sproxy };
5182 fetchr.addActionListener(new ActionListener()
5186 public void actionPerformed(ActionEvent e)
5188 new Thread(new Runnable()
5194 boolean isNucleotide = alignPanel.alignFrame
5195 .getViewport().getAlignment()
5197 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5198 alignPanel.av.getSequenceSelection(),
5199 alignPanel.alignFrame, dassrc,
5200 alignPanel.alignFrame.featureSettings,
5203 .addListener(new FetchFinishedListenerI()
5206 public void finished()
5208 AlignFrame.this.setMenusForViewport();
5211 dbRefFetcher.fetchDBRefs(false);
5217 fetchr.setToolTipText("<html>"
5218 + MessageManager.formatMessage(
5219 "label.fetch_retrieve_from", new Object[]
5223 if (++icomp >= mcomp || i == (otherdb.size()))
5225 ifetch.setText(MessageManager.formatMessage(
5226 "label.source_to_target", imname, sname));
5228 ifetch = new JMenu();
5236 if (comp >= mcomp || dbi >= (dbclasses.length))
5238 dfetch.setText(MessageManager.formatMessage(
5239 "label.source_to_target", mname, dbclass));
5241 dfetch = new JMenu();
5254 * Left justify the whole alignment.
5257 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5259 AlignmentI al = viewport.getAlignment();
5261 viewport.firePropertyChange("alignment", null, al);
5265 * Right justify the whole alignment.
5268 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5270 AlignmentI al = viewport.getAlignment();
5272 viewport.firePropertyChange("alignment", null, al);
5276 public void setShowSeqFeatures(boolean b)
5278 showSeqFeatures.setSelected(b);
5279 viewport.setShowSequenceFeatures(b);
5286 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5287 * awt.event.ActionEvent)
5290 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5292 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5293 alignPanel.paintAlignment(true);
5300 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5304 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5306 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5307 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5315 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5316 * .event.ActionEvent)
5319 protected void showGroupConservation_actionPerformed(ActionEvent e)
5321 viewport.setShowGroupConservation(showGroupConservation.getState());
5322 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5329 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5330 * .event.ActionEvent)
5333 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5335 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5336 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5343 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5344 * .event.ActionEvent)
5347 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5349 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5350 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5354 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5356 showSequenceLogo.setState(true);
5357 viewport.setShowSequenceLogo(true);
5358 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5359 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5363 protected void showInformationHistogram_actionPerformed(ActionEvent e)
5365 viewport.setShowInformationHistogram(
5366 showInformationHistogram.getState());
5367 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5371 protected void showHMMSequenceLogo_actionPerformed(ActionEvent e)
5373 viewport.setShowHMMSequenceLogo(showHMMSequenceLogo.getState());
5374 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5378 protected void normaliseHMMSequenceLogo_actionPerformed(ActionEvent e)
5380 showHMMSequenceLogo.setState(true);
5381 viewport.setShowHMMSequenceLogo(true);
5382 viewport.setNormaliseHMMSequenceLogo(normaliseSequenceLogo.getState());
5383 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5387 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5389 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5396 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5397 * .event.ActionEvent)
5400 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5402 if (avc.makeGroupsFromSelection())
5404 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5405 alignPanel.updateAnnotation();
5406 alignPanel.paintAlignment(true);
5410 public void clearAlignmentSeqRep()
5412 // TODO refactor alignmentseqrep to controller
5413 if (viewport.getAlignment().hasSeqrep())
5415 viewport.getAlignment().setSeqrep(null);
5416 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5417 alignPanel.updateAnnotation();
5418 alignPanel.paintAlignment(true);
5423 protected void createGroup_actionPerformed(ActionEvent e)
5425 if (avc.createGroup())
5427 alignPanel.alignmentChanged();
5432 protected void unGroup_actionPerformed(ActionEvent e)
5436 alignPanel.alignmentChanged();
5441 * make the given alignmentPanel the currently selected tab
5443 * @param alignmentPanel
5445 public void setDisplayedView(AlignmentPanel alignmentPanel)
5447 if (!viewport.getSequenceSetId().equals(
5448 alignmentPanel.av.getSequenceSetId()))
5452 .getString("error.implementation_error_cannot_show_view_alignment_frame"));
5454 if (tabbedPane != null
5455 && tabbedPane.getTabCount() > 0
5456 && alignPanels.indexOf(alignmentPanel) != tabbedPane
5457 .getSelectedIndex())
5459 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5464 * Action on selection of menu options to Show or Hide annotations.
5467 * @param forSequences
5468 * update sequence-related annotations
5469 * @param forAlignment
5470 * update non-sequence-related annotations
5473 protected void setAnnotationsVisibility(boolean visible,
5474 boolean forSequences, boolean forAlignment)
5476 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5477 .getAlignmentAnnotation();
5482 for (AlignmentAnnotation aa : anns)
5485 * don't display non-positional annotations on an alignment
5487 if (aa.annotations == null)
5491 boolean apply = (aa.sequenceRef == null && forAlignment)
5492 || (aa.sequenceRef != null && forSequences);
5495 aa.visible = visible;
5498 alignPanel.validateAnnotationDimensions(true);
5499 alignPanel.alignmentChanged();
5503 * Store selected annotation sort order for the view and repaint.
5506 protected void sortAnnotations_actionPerformed()
5508 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5510 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5511 alignPanel.paintAlignment(true);
5516 * @return alignment panels in this alignment frame
5518 public List<? extends AlignmentViewPanel> getAlignPanels()
5520 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5524 * Open a new alignment window, with the cDNA associated with this (protein)
5525 * alignment, aligned as is the protein.
5527 protected void viewAsCdna_actionPerformed()
5529 // TODO no longer a menu action - refactor as required
5530 final AlignmentI alignment = getViewport().getAlignment();
5531 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5532 if (mappings == null)
5536 List<SequenceI> cdnaSeqs = new ArrayList<>();
5537 for (SequenceI aaSeq : alignment.getSequences())
5539 for (AlignedCodonFrame acf : mappings)
5541 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5545 * There is a cDNA mapping for this protein sequence - add to new
5546 * alignment. It will share the same dataset sequence as other mapped
5547 * cDNA (no new mappings need to be created).
5549 final Sequence newSeq = new Sequence(dnaSeq);
5550 newSeq.setDatasetSequence(dnaSeq);
5551 cdnaSeqs.add(newSeq);
5555 if (cdnaSeqs.size() == 0)
5557 // show a warning dialog no mapped cDNA
5560 AlignmentI cdna = new Alignment(cdnaSeqs.toArray(new SequenceI[cdnaSeqs
5562 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5563 AlignFrame.DEFAULT_HEIGHT);
5564 cdna.alignAs(alignment);
5565 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5567 Desktop.addInternalFrame(alignFrame, newtitle,
5568 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
5572 * Set visibility of dna/protein complement view (available when shown in a
5578 protected void showComplement_actionPerformed(boolean show)
5580 SplitContainerI sf = getSplitViewContainer();
5583 sf.setComplementVisible(this, show);
5588 * Generate the reverse (optionally complemented) of the selected sequences,
5589 * and add them to the alignment
5592 protected void showReverse_actionPerformed(boolean complement)
5594 AlignmentI al = null;
5597 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5598 al = dna.reverseCdna(complement);
5599 viewport.addAlignment(al, "");
5600 addHistoryItem(new EditCommand(
5601 MessageManager.getString("label.add_sequences"),
5602 Action.PASTE, al.getSequencesArray(), 0, al.getWidth(),
5603 viewport.getAlignment()));
5604 } catch (Exception ex)
5606 System.err.println(ex.getMessage());
5612 * Try to run a script in the Groovy console, having first ensured that this
5613 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5614 * be targeted at this alignment.
5617 protected void runGroovy_actionPerformed()
5619 Jalview.setCurrentAlignFrame(this);
5620 groovy.ui.Console console = Desktop.getGroovyConsole();
5621 if (console != null)
5625 console.runScript();
5626 } catch (Exception ex)
5628 System.err.println((ex.toString()));
5630 .showInternalMessageDialog(Desktop.desktop, MessageManager
5631 .getString("label.couldnt_run_groovy_script"),
5633 .getString("label.groovy_support_failed"),
5634 JvOptionPane.ERROR_MESSAGE);
5639 System.err.println("Can't run Groovy script as console not found");
5644 * Hides columns containing (or not containing) a specified feature, provided
5645 * that would not leave all columns hidden
5647 * @param featureType
5648 * @param columnsContaining
5651 public boolean hideFeatureColumns(String featureType,
5652 boolean columnsContaining)
5654 boolean notForHiding = avc.markColumnsContainingFeatures(
5655 columnsContaining, false, false, featureType);
5658 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5659 false, featureType))
5661 getViewport().hideSelectedColumns();
5669 protected void selectHighlightedColumns_actionPerformed(
5670 ActionEvent actionEvent)
5672 // include key modifier check in case user selects from menu
5673 avc.markHighlightedColumns(
5674 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0,
5676 (actionEvent.getModifiers() & (ActionEvent.META_MASK | ActionEvent.CTRL_MASK)) != 0);
5680 * Rebuilds the Colour menu, including any user-defined colours which have
5681 * been loaded either on startup or during the session
5683 public void buildColourMenu()
5685 colourMenu.removeAll();
5687 colourMenu.add(applyToAllGroups);
5688 colourMenu.add(textColour);
5689 colourMenu.addSeparator();
5691 ColourMenuHelper.addMenuItems(colourMenu, this,
5692 viewport.getAlignment(), false);
5694 colourMenu.addSeparator();
5695 colourMenu.add(conservationMenuItem);
5696 colourMenu.add(modifyConservation);
5697 colourMenu.add(abovePIDThreshold);
5698 colourMenu.add(modifyPID);
5699 colourMenu.add(annotationColour);
5701 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5702 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5706 * Open a dialog (if not already open) that allows the user to select and
5707 * calculate PCA or Tree analysis
5709 protected void openTreePcaDialog()
5711 if (alignPanel.getCalculationDialog() == null)
5713 new CalculationChooser(AlignFrame.this);
5718 class PrintThread extends Thread
5722 public PrintThread(AlignmentPanel ap)
5727 static PageFormat pf;
5732 PrinterJob printJob = PrinterJob.getPrinterJob();
5736 printJob.setPrintable(ap, pf);
5740 printJob.setPrintable(ap);
5743 if (printJob.printDialog())
5748 } catch (Exception PrintException)
5750 PrintException.printStackTrace();