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.AlignExportSettingsI;
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.AlignExportSettingsAdapter;
49 import jalview.datamodel.AlignedCodonFrame;
50 import jalview.datamodel.Alignment;
51 import jalview.datamodel.AlignmentAnnotation;
52 import jalview.datamodel.AlignmentExportData;
53 import jalview.datamodel.AlignmentI;
54 import jalview.datamodel.AlignmentOrder;
55 import jalview.datamodel.AlignmentView;
56 import jalview.datamodel.ColumnSelection;
57 import jalview.datamodel.HiddenColumns;
58 import jalview.datamodel.PDBEntry;
59 import jalview.datamodel.SeqCigar;
60 import jalview.datamodel.Sequence;
61 import jalview.datamodel.SequenceGroup;
62 import jalview.datamodel.SequenceI;
63 import jalview.gui.ColourMenuHelper.ColourChangeListener;
64 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
65 import jalview.io.AlignmentProperties;
66 import jalview.io.AnnotationFile;
67 import jalview.io.BioJsHTMLOutput;
68 import jalview.io.DataSourceType;
69 import jalview.io.FileFormat;
70 import jalview.io.FileFormatI;
71 import jalview.io.FileFormats;
72 import jalview.io.FileLoader;
73 import jalview.io.FileParse;
74 import jalview.io.FormatAdapter;
75 import jalview.io.HtmlSvgOutput;
76 import jalview.io.IdentifyFile;
77 import jalview.io.JPredFile;
78 import jalview.io.JalviewFileChooser;
79 import jalview.io.JalviewFileView;
80 import jalview.io.JnetAnnotationMaker;
81 import jalview.io.NewickFile;
82 import jalview.io.ScoreMatrixFile;
83 import jalview.io.TCoffeeScoreFile;
84 import jalview.io.vcf.VCFLoader;
85 import jalview.jbgui.GAlignFrame;
86 import jalview.schemes.ColourSchemeI;
87 import jalview.schemes.ColourSchemes;
88 import jalview.schemes.ResidueColourScheme;
89 import jalview.schemes.TCoffeeColourScheme;
90 import jalview.util.ImageMaker.TYPE;
91 import jalview.util.MessageManager;
92 import jalview.viewmodel.AlignmentViewport;
93 import jalview.viewmodel.ViewportRanges;
94 import jalview.ws.DBRefFetcher;
95 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
96 import jalview.ws.jws1.Discoverer;
97 import jalview.ws.jws2.Jws2Discoverer;
98 import jalview.ws.jws2.jabaws2.Jws2Instance;
99 import jalview.ws.seqfetcher.DbSourceProxy;
101 import java.awt.BorderLayout;
102 import java.awt.Color;
103 import java.awt.Component;
104 import java.awt.Rectangle;
105 import java.awt.Toolkit;
106 import java.awt.datatransfer.Clipboard;
107 import java.awt.datatransfer.DataFlavor;
108 import java.awt.datatransfer.StringSelection;
109 import java.awt.datatransfer.Transferable;
110 import java.awt.dnd.DnDConstants;
111 import java.awt.dnd.DropTargetDragEvent;
112 import java.awt.dnd.DropTargetDropEvent;
113 import java.awt.dnd.DropTargetEvent;
114 import java.awt.dnd.DropTargetListener;
115 import java.awt.event.ActionEvent;
116 import java.awt.event.ActionListener;
117 import java.awt.event.FocusAdapter;
118 import java.awt.event.FocusEvent;
119 import java.awt.event.ItemEvent;
120 import java.awt.event.ItemListener;
121 import java.awt.event.KeyAdapter;
122 import java.awt.event.KeyEvent;
123 import java.awt.event.MouseEvent;
124 import java.awt.print.PageFormat;
125 import java.awt.print.PrinterJob;
126 import java.beans.PropertyChangeEvent;
128 import java.io.FileWriter;
129 import java.io.PrintWriter;
131 import java.util.ArrayList;
132 import java.util.Arrays;
133 import java.util.Deque;
134 import java.util.Enumeration;
135 import java.util.Hashtable;
136 import java.util.List;
137 import java.util.Vector;
139 import javax.swing.JCheckBoxMenuItem;
140 import javax.swing.JComponent;
141 import javax.swing.JEditorPane;
142 import javax.swing.JInternalFrame;
143 import javax.swing.JLabel;
144 import javax.swing.JLayeredPane;
145 import javax.swing.JMenu;
146 import javax.swing.JMenuItem;
147 import javax.swing.JPanel;
148 import javax.swing.JScrollPane;
149 import javax.swing.SwingUtilities;
155 * @version $Revision$
157 public class AlignFrame extends GAlignFrame implements DropTargetListener,
158 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
161 public static final int DEFAULT_WIDTH = 700;
163 public static final int DEFAULT_HEIGHT = 500;
166 * The currently displayed panel (selected tabbed view if more than one)
168 public AlignmentPanel alignPanel;
170 AlignViewport viewport;
172 public AlignViewControllerI avc;
174 List<AlignmentPanel> alignPanels = new ArrayList<>();
177 * Last format used to load or save alignments in this window
179 FileFormatI currentFileFormat = null;
182 * Current filename for this alignment
184 String fileName = null;
189 * Creates a new AlignFrame object with specific width and height.
195 public AlignFrame(AlignmentI al, int width, int height)
197 this(al, null, width, height);
201 * Creates a new AlignFrame object with specific width, height and
207 * @param sequenceSetId
209 public AlignFrame(AlignmentI al, int width, int height,
210 String sequenceSetId)
212 this(al, null, width, height, sequenceSetId);
216 * Creates a new AlignFrame object with specific width, height and
222 * @param sequenceSetId
225 public AlignFrame(AlignmentI al, int width, int height,
226 String sequenceSetId, String viewId)
228 this(al, null, width, height, sequenceSetId, viewId);
232 * new alignment window with hidden columns
236 * @param hiddenColumns
237 * ColumnSelection or null
239 * Width of alignment frame
243 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
246 this(al, hiddenColumns, width, height, null);
250 * Create alignment frame for al with hiddenColumns, a specific width and
251 * height, and specific sequenceId
254 * @param hiddenColumns
257 * @param sequenceSetId
260 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
261 int height, String sequenceSetId)
263 this(al, hiddenColumns, width, height, sequenceSetId, null);
267 * Create alignment frame for al with hiddenColumns, a specific width and
268 * height, and specific sequenceId
271 * @param hiddenColumns
274 * @param sequenceSetId
279 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
280 int height, String sequenceSetId, String viewId)
282 setSize(width, height);
284 if (al.getDataset() == null)
289 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
291 alignPanel = new AlignmentPanel(this, viewport);
293 addAlignmentPanel(alignPanel, true);
297 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
298 HiddenColumns hiddenColumns, int width, int height)
300 setSize(width, height);
302 if (al.getDataset() == null)
307 viewport = new AlignViewport(al, hiddenColumns);
309 if (hiddenSeqs != null && hiddenSeqs.length > 0)
311 viewport.hideSequence(hiddenSeqs);
313 alignPanel = new AlignmentPanel(this, viewport);
314 addAlignmentPanel(alignPanel, true);
319 * Make a new AlignFrame from existing alignmentPanels
326 public AlignFrame(AlignmentPanel ap)
330 addAlignmentPanel(ap, false);
335 * initalise the alignframe from the underlying viewport data and the
340 if (!Jalview.isHeadlessMode())
342 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
345 avc = new jalview.controller.AlignViewController(this, viewport,
347 if (viewport.getAlignmentConservationAnnotation() == null)
349 // BLOSUM62Colour.setEnabled(false);
350 conservationMenuItem.setEnabled(false);
351 modifyConservation.setEnabled(false);
352 // PIDColour.setEnabled(false);
353 // abovePIDThreshold.setEnabled(false);
354 // modifyPID.setEnabled(false);
357 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
360 if (sortby.equals("Id"))
362 sortIDMenuItem_actionPerformed(null);
364 else if (sortby.equals("Pairwise Identity"))
366 sortPairwiseMenuItem_actionPerformed(null);
370 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
372 setMenusFromViewport(viewport);
373 buildSortByAnnotationScoresMenu();
374 calculateTree.addActionListener(new ActionListener()
378 public void actionPerformed(ActionEvent e)
385 if (Desktop.desktop != null)
387 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
389 * BH 2018 ignore service listeners
395 addServiceListeners();
400 if (viewport.getWrapAlignment())
402 wrapMenuItem_actionPerformed(null);
405 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
407 this.overviewMenuItem_actionPerformed(null);
412 final List<AlignmentPanel> selviews = new ArrayList<>();
413 final List<AlignmentPanel> origview = new ArrayList<>();
414 final String menuLabel = MessageManager
415 .getString("label.copy_format_from");
416 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
417 new ViewSetProvider()
421 public AlignmentPanel[] getAllAlignmentPanels()
424 origview.add(alignPanel);
425 // make an array of all alignment panels except for this one
426 List<AlignmentPanel> aps = new ArrayList<>(
427 Arrays.asList(Desktop.getAlignmentPanels(null)));
428 aps.remove(AlignFrame.this.alignPanel);
429 return aps.toArray(new AlignmentPanel[aps.size()]);
431 }, selviews, new ItemListener()
435 public void itemStateChanged(ItemEvent e)
437 if (origview.size() > 0)
439 final AlignmentPanel ap = origview.get(0);
442 * Copy the ViewStyle of the selected panel to 'this one'.
443 * Don't change value of 'scaleProteinAsCdna' unless copying
446 ViewStyleI vs = selviews.get(0).getAlignViewport()
448 boolean fromSplitFrame = selviews.get(0)
449 .getAlignViewport().getCodingComplement() != null;
452 vs.setScaleProteinAsCdna(ap.getAlignViewport()
453 .getViewStyle().isScaleProteinAsCdna());
455 ap.getAlignViewport().setViewStyle(vs);
458 * Also rescale ViewStyle of SplitFrame complement if there is
459 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
460 * the whole ViewStyle (allow cDNA protein to have different
463 AlignViewportI complement = ap.getAlignViewport()
464 .getCodingComplement();
465 if (complement != null && vs.isScaleProteinAsCdna())
467 AlignFrame af = Desktop.getAlignFrameFor(complement);
468 ((SplitFrame) af.getSplitViewContainer())
470 af.setMenusForViewport();
474 ap.setSelected(true);
475 ap.alignFrame.setMenusForViewport();
480 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
481 .indexOf("devel") > -1
482 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
483 .indexOf("test") > -1)
485 formatMenu.add(vsel);
487 addFocusListener(new FocusAdapter()
490 public void focusGained(FocusEvent e)
492 Jalview.setCurrentAlignFrame(AlignFrame.this);
499 * Change the filename and format for the alignment, and enable the 'reload'
500 * button functionality.
507 public void setFileName(String file, FileFormatI format)
510 setFileFormat(format);
511 reload.setEnabled(true);
515 * JavaScript will have this, maybe others. More dependable than a file name
516 * and maintains a reference to the actual bytes loaded.
520 public void setFileObject(File file)
522 this.fileObject = file;
526 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
529 void addKeyListener()
531 addKeyListener(new KeyAdapter()
534 public void keyPressed(KeyEvent evt)
536 if (viewport.cursorMode
537 && ((evt.getKeyCode() >= KeyEvent.VK_0
538 && evt.getKeyCode() <= KeyEvent.VK_9)
539 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
540 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
541 && Character.isDigit(evt.getKeyChar()))
543 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
546 switch (evt.getKeyCode())
549 case 27: // escape key
550 deselectAllSequenceMenuItem_actionPerformed(null);
554 case KeyEvent.VK_DOWN:
555 if (evt.isAltDown() || !viewport.cursorMode)
557 moveSelectedSequences(false);
559 if (viewport.cursorMode)
561 alignPanel.getSeqPanel().moveCursor(0, 1);
566 if (evt.isAltDown() || !viewport.cursorMode)
568 moveSelectedSequences(true);
570 if (viewport.cursorMode)
572 alignPanel.getSeqPanel().moveCursor(0, -1);
577 case KeyEvent.VK_LEFT:
578 if (evt.isAltDown() || !viewport.cursorMode)
580 slideSequences(false,
581 alignPanel.getSeqPanel().getKeyboardNo1());
585 alignPanel.getSeqPanel().moveCursor(-1, 0);
590 case KeyEvent.VK_RIGHT:
591 if (evt.isAltDown() || !viewport.cursorMode)
593 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
597 alignPanel.getSeqPanel().moveCursor(1, 0);
601 case KeyEvent.VK_SPACE:
602 if (viewport.cursorMode)
604 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
605 || evt.isShiftDown() || evt.isAltDown());
609 // case KeyEvent.VK_A:
610 // if (viewport.cursorMode)
612 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
613 // //System.out.println("A");
617 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
618 * System.out.println("closing bracket"); } break;
620 case KeyEvent.VK_DELETE:
621 case KeyEvent.VK_BACK_SPACE:
622 if (!viewport.cursorMode)
624 cut_actionPerformed(null);
628 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
629 || evt.isShiftDown() || evt.isAltDown());
635 if (viewport.cursorMode)
637 alignPanel.getSeqPanel().setCursorRow();
641 if (viewport.cursorMode && !evt.isControlDown())
643 alignPanel.getSeqPanel().setCursorColumn();
647 if (viewport.cursorMode)
649 alignPanel.getSeqPanel().setCursorPosition();
653 case KeyEvent.VK_ENTER:
654 case KeyEvent.VK_COMMA:
655 if (viewport.cursorMode)
657 alignPanel.getSeqPanel().setCursorRowAndColumn();
662 if (viewport.cursorMode)
664 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
668 if (viewport.cursorMode)
670 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
675 viewport.cursorMode = !viewport.cursorMode;
676 setStatus(MessageManager
677 .formatMessage("label.keyboard_editing_mode", new String[]
678 { (viewport.cursorMode ? "on" : "off") }));
679 if (viewport.cursorMode)
681 ViewportRanges ranges = viewport.getRanges();
682 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
684 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
687 alignPanel.getSeqPanel().seqCanvas.repaint();
693 Help.showHelpWindow();
694 } catch (Exception ex)
696 ex.printStackTrace();
701 boolean toggleSeqs = !evt.isControlDown();
702 boolean toggleCols = !evt.isShiftDown();
703 toggleHiddenRegions(toggleSeqs, toggleCols);
708 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
709 boolean modifyExisting = true; // always modify, don't clear
710 // evt.isShiftDown();
711 boolean invertHighlighted = evt.isAltDown();
712 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
716 case KeyEvent.VK_PAGE_UP:
717 viewport.getRanges().pageUp();
719 case KeyEvent.VK_PAGE_DOWN:
720 viewport.getRanges().pageDown();
726 public void keyReleased(KeyEvent evt)
728 switch (evt.getKeyCode())
730 case KeyEvent.VK_LEFT:
731 if (evt.isAltDown() || !viewport.cursorMode)
733 viewport.firePropertyChange("alignment", null,
734 viewport.getAlignment().getSequences());
738 case KeyEvent.VK_RIGHT:
739 if (evt.isAltDown() || !viewport.cursorMode)
741 viewport.firePropertyChange("alignment", null,
742 viewport.getAlignment().getSequences());
750 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
752 ap.alignFrame = this;
753 avc = new jalview.controller.AlignViewController(this, viewport,
758 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
760 int aSize = alignPanels.size();
762 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
764 if (aSize == 1 && ap.av.getViewName() == null)
766 this.getContentPane().add(ap, BorderLayout.CENTER);
772 setInitialTabVisible();
775 expandViews.setEnabled(true);
776 gatherViews.setEnabled(true);
777 tabbedPane.addTab(ap.av.getViewName(), ap);
779 ap.setVisible(false);
784 if (ap.av.isPadGaps())
786 ap.av.getAlignment().padGaps();
788 ap.av.updateConservation(ap);
789 ap.av.updateConsensus(ap);
790 ap.av.updateStrucConsensus(ap);
794 public void setInitialTabVisible()
796 expandViews.setEnabled(true);
797 gatherViews.setEnabled(true);
798 tabbedPane.setVisible(true);
799 AlignmentPanel first = alignPanels.get(0);
800 tabbedPane.addTab(first.av.getViewName(), first);
801 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
804 public AlignViewport getViewport()
809 /* Set up intrinsic listeners for dynamically generated GUI bits. */
810 private void addServiceListeners()
812 final java.beans.PropertyChangeListener thisListener;
813 Desktop.instance.addJalviewPropertyChangeListener("services",
814 thisListener = new java.beans.PropertyChangeListener()
817 public void propertyChange(PropertyChangeEvent evt)
819 // // System.out.println("Discoverer property change.");
820 // if (evt.getPropertyName().equals("services"))
822 SwingUtilities.invokeLater(new Runnable()
829 "Rebuild WS Menu for service change");
830 BuildWebServiceMenu();
837 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
840 public void internalFrameClosed(
841 javax.swing.event.InternalFrameEvent evt)
843 // System.out.println("deregistering discoverer listener");
844 Desktop.instance.removeJalviewPropertyChangeListener("services",
846 closeMenuItem_actionPerformed(true);
849 // Finally, build the menu once to get current service state
850 new Thread(new Runnable()
855 BuildWebServiceMenu();
861 * Configure menu items that vary according to whether the alignment is
862 * nucleotide or protein
864 public void setGUINucleotide()
866 AlignmentI al = getViewport().getAlignment();
867 boolean nucleotide = al.isNucleotide();
869 loadVcf.setVisible(nucleotide);
870 showTranslation.setVisible(nucleotide);
871 showReverse.setVisible(nucleotide);
872 showReverseComplement.setVisible(nucleotide);
873 conservationMenuItem.setEnabled(!nucleotide);
875 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
876 showGroupConservation.setEnabled(!nucleotide);
878 showComplementMenuItem
879 .setText(nucleotide ? MessageManager.getString("label.protein")
880 : MessageManager.getString("label.nucleotide"));
884 * set up menus for the current viewport. This may be called after any
885 * operation that affects the data in the current view (selection changed,
886 * etc) to update the menus to reflect the new state.
889 public void setMenusForViewport()
891 setMenusFromViewport(viewport);
895 * Need to call this method when tabs are selected for multiple views, or when
896 * loading from Jalview2XML.java
901 public void setMenusFromViewport(AlignViewport av)
903 padGapsMenuitem.setSelected(av.isPadGaps());
904 colourTextMenuItem.setSelected(av.isShowColourText());
905 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
906 modifyPID.setEnabled(abovePIDThreshold.isSelected());
907 conservationMenuItem.setSelected(av.getConservationSelected());
908 modifyConservation.setEnabled(conservationMenuItem.isSelected());
909 seqLimits.setSelected(av.getShowJVSuffix());
910 idRightAlign.setSelected(av.isRightAlignIds());
911 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
912 renderGapsMenuItem.setSelected(av.isRenderGaps());
913 wrapMenuItem.setSelected(av.getWrapAlignment());
914 scaleAbove.setVisible(av.getWrapAlignment());
915 scaleLeft.setVisible(av.getWrapAlignment());
916 scaleRight.setVisible(av.getWrapAlignment());
917 annotationPanelMenuItem.setState(av.isShowAnnotation());
919 * Show/hide annotations only enabled if annotation panel is shown
921 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
922 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
923 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
924 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
925 viewBoxesMenuItem.setSelected(av.getShowBoxes());
926 viewTextMenuItem.setSelected(av.getShowText());
927 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
928 showGroupConsensus.setSelected(av.isShowGroupConsensus());
929 showGroupConservation.setSelected(av.isShowGroupConservation());
930 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
931 showSequenceLogo.setSelected(av.isShowSequenceLogo());
932 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
934 ColourMenuHelper.setColourSelected(colourMenu,
935 av.getGlobalColourScheme());
937 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
938 hiddenMarkers.setState(av.getShowHiddenMarkers());
939 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
940 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
941 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
942 autoCalculate.setSelected(av.autoCalculateConsensus);
943 sortByTree.setSelected(av.sortByTree);
944 listenToViewSelections.setSelected(av.followSelection);
946 showProducts.setEnabled(canShowProducts());
947 setGroovyEnabled(Desktop.getGroovyConsole() != null);
953 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
957 public void setGroovyEnabled(boolean b)
959 runGroovy.setEnabled(b);
962 private IProgressIndicator progressBar;
967 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
970 public void setProgressBar(String message, long id)
972 progressBar.setProgressBar(message, id);
976 public void registerHandler(final long id,
977 final IProgressIndicatorHandler handler)
979 progressBar.registerHandler(id, handler);
984 * @return true if any progress bars are still active
987 public boolean operationInProgress()
989 return progressBar.operationInProgress();
993 public void setStatus(String text)
995 statusBar.setText(text);
999 * Added so Castor Mapping file can obtain Jalview Version
1001 public String getVersion()
1003 return jalview.bin.Cache.getProperty("VERSION");
1006 public FeatureRenderer getFeatureRenderer()
1008 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1012 public void fetchSequence_actionPerformed()
1014 new SequenceFetcher(this);
1018 public void addFromFile_actionPerformed(ActionEvent e)
1020 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1024 public void reload_actionPerformed(ActionEvent e)
1026 if (fileName != null)
1028 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1029 // originating file's format
1030 // TODO: work out how to recover feature settings for correct view(s) when
1031 // file is reloaded.
1032 if (FileFormat.Jalview.equals(currentFileFormat))
1034 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1035 for (int i = 0; i < frames.length; i++)
1037 if (frames[i] instanceof AlignFrame && frames[i] != this
1038 && ((AlignFrame) frames[i]).fileName != null
1039 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1043 frames[i].setSelected(true);
1044 Desktop.instance.closeAssociatedWindows();
1045 } catch (java.beans.PropertyVetoException ex)
1051 Desktop.instance.closeAssociatedWindows();
1053 FileLoader loader = new FileLoader();
1054 DataSourceType protocol = fileName.startsWith("http:")
1055 ? DataSourceType.URL
1056 : DataSourceType.FILE;
1057 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1061 Rectangle bounds = this.getBounds();
1063 FileLoader loader = new FileLoader();
1065 AlignFrame newframe = null;
1067 if (fileObject == null)
1070 DataSourceType protocol = (fileName.startsWith("http:")
1071 ? DataSourceType.URL
1072 : DataSourceType.FILE);
1073 newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1078 newframe = loader.LoadFileWaitTillLoaded(fileObject,
1079 DataSourceType.FILE, currentFileFormat);
1082 newframe.setBounds(bounds);
1083 if (featureSettings != null && featureSettings.isShowing())
1085 final Rectangle fspos = featureSettings.frame.getBounds();
1086 // TODO: need a 'show feature settings' function that takes bounds -
1087 // need to refactor Desktop.addFrame
1088 newframe.featureSettings_actionPerformed(null);
1089 final FeatureSettings nfs = newframe.featureSettings;
1090 SwingUtilities.invokeLater(new Runnable()
1095 nfs.frame.setBounds(fspos);
1098 this.featureSettings.close();
1099 this.featureSettings = null;
1101 this.closeMenuItem_actionPerformed(true);
1107 public void addFromText_actionPerformed(ActionEvent e)
1110 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1114 public void addFromURL_actionPerformed(ActionEvent e)
1116 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1120 public void save_actionPerformed(ActionEvent e)
1122 if (fileName == null || (currentFileFormat == null)
1123 || fileName.startsWith("http"))
1125 saveAs_actionPerformed();
1129 saveAlignment(fileName, currentFileFormat);
1134 * Saves the alignment to a file with a name chosen by the user, if necessary
1135 * warning if a file would be overwritten
1138 public void saveAs_actionPerformed()
1140 String format = currentFileFormat == null ? null
1141 : currentFileFormat.getName();
1142 JalviewFileChooser chooser = JalviewFileChooser
1143 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1145 chooser.setFileView(new JalviewFileView());
1146 chooser.setDialogTitle(
1147 MessageManager.getString("label.save_alignment_to_file"));
1148 chooser.setToolTipText(MessageManager.getString("action.save"));
1150 int value = chooser.showSaveDialog(this);
1152 if (value != JalviewFileChooser.APPROVE_OPTION)
1156 currentFileFormat = chooser.getSelectedFormat();
1157 // todo is this (2005) test now obsolete - value is never null?
1158 while (currentFileFormat == null)
1160 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1162 .getString("label.select_file_format_before_saving"),
1163 MessageManager.getString("label.file_format_not_specified"),
1164 JvOptionPane.WARNING_MESSAGE);
1165 currentFileFormat = chooser.getSelectedFormat();
1166 value = chooser.showSaveDialog(this);
1167 if (value != JalviewFileChooser.APPROVE_OPTION)
1173 fileName = chooser.getSelectedFile().getPath();
1175 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1176 Cache.setProperty("LAST_DIRECTORY", fileName);
1177 saveAlignment(fileName, currentFileFormat);
1180 boolean lastSaveSuccessful = false;
1182 FileFormatI lastFormatSaved;
1184 String lastFilenameSaved;
1187 * Raise a dialog or status message for the last call to saveAlignment.
1189 * @return true if last call to saveAlignment(file, format) was successful.
1191 public boolean isSaveAlignmentSuccessful()
1194 if (!lastSaveSuccessful)
1196 JvOptionPane.showInternalMessageDialog(this, MessageManager
1197 .formatMessage("label.couldnt_save_file", new Object[]
1198 { lastFilenameSaved }),
1199 MessageManager.getString("label.error_saving_file"),
1200 JvOptionPane.WARNING_MESSAGE);
1205 setStatus(MessageManager.formatMessage(
1206 "label.successfully_saved_to_file_in_format", new Object[]
1207 { lastFilenameSaved, lastFormatSaved }));
1210 return lastSaveSuccessful;
1214 * Saves the alignment to the specified file path, in the specified format,
1215 * which may be an alignment format, or Jalview project format. If the
1216 * alignment has hidden regions, or the format is one capable of including
1217 * non-sequence data (features, annotations, groups), then the user may be
1218 * prompted to specify what to include in the output.
1223 public void saveAlignment(String file, FileFormatI format)
1225 lastSaveSuccessful = false;
1226 lastFilenameSaved = file;
1227 lastFormatSaved = format;
1229 if (FileFormat.Jalview.equals(format))
1231 String shortName = title;
1232 if (shortName.indexOf(File.separatorChar) > -1)
1234 shortName = shortName.substring(
1235 shortName.lastIndexOf(File.separatorChar) + 1);
1237 lastSaveSuccessful = new jalview.project.Jalview2XML().saveAlignment(this, file,
1240 statusBar.setText(MessageManager.formatMessage(
1241 "label.successfully_saved_to_file_in_format", new Object[]
1242 { fileName, format }));
1247 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1248 Runnable cancelAction = new Runnable()
1253 lastSaveSuccessful = false;
1256 Runnable outputAction = new Runnable()
1261 // todo defer this to inside formatSequences (or later)
1262 AlignmentExportData exportData = viewport
1263 .getAlignExportData(options);
1264 String output = new FormatAdapter(alignPanel, options)
1265 .formatSequences(format, exportData.getAlignment(),
1266 exportData.getOmitHidden(),
1267 exportData.getStartEndPostions(),
1268 viewport.getAlignment().getHiddenColumns());
1271 lastSaveSuccessful = false;
1277 PrintWriter out = new PrintWriter(new FileWriter(file));
1280 AlignFrame.this.setTitle(file);
1281 setStatus(MessageManager.formatMessage(
1282 "label.successfully_saved_to_file_in_format",
1284 { fileName, format.getName() }));
1285 } catch (Exception ex)
1287 lastSaveSuccessful = false;
1288 ex.printStackTrace();
1295 * show dialog with export options if applicable; else just do it
1297 if (AlignExportOptions.isNeeded(viewport, format))
1299 AlignExportOptions choices = new AlignExportOptions(
1300 alignPanel.getAlignViewport(), format, options);
1301 choices.setResponseAction(0, outputAction);
1302 choices.setResponseAction(1, cancelAction);
1303 choices.showDialog();
1312 * Outputs the alignment to textbox in the requested format, if necessary
1313 * first prompting the user for whether to include hidden regions or
1316 * @param fileFormatName
1319 protected void outputText_actionPerformed(String fileFormatName)
1321 FileFormatI fileFormat = FileFormats.getInstance()
1322 .forName(fileFormatName);
1323 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1324 Runnable outputAction = new Runnable()
1329 // todo defer this to inside formatSequences (or later)
1330 AlignmentExportData exportData = viewport
1331 .getAlignExportData(options);
1332 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1333 cap.setForInput(null);
1336 FileFormatI format = fileFormat;
1337 cap.setText(new FormatAdapter(alignPanel, options)
1338 .formatSequences(format, exportData.getAlignment(),
1339 exportData.getOmitHidden(),
1340 exportData.getStartEndPostions(),
1341 viewport.getAlignment().getHiddenColumns()));
1342 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1343 "label.alignment_output_command", new Object[]
1344 { fileFormat.getName() }), 600, 500);
1345 } catch (OutOfMemoryError oom)
1347 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1355 * show dialog with export options if applicable; else just do it
1357 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1359 AlignExportOptions choices = new AlignExportOptions(
1360 alignPanel.getAlignViewport(), fileFormat, options);
1361 choices.setResponseAction(0, outputAction);
1362 choices.showDialog();
1377 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1379 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1380 htmlSVG.exportHTML(null);
1384 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1386 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1387 bjs.exportHTML(null);
1390 public void createImageMap(File file, String image)
1392 alignPanel.makePNGImageMap(file, image);
1396 * Creates a PNG image of the alignment and writes it to the given file. If
1397 * the file is null, the user is prompted to choose a file.
1402 public void createPNG(File f)
1404 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1408 * Creates an EPS image of the alignment and writes it to the given file. If
1409 * the file is null, the user is prompted to choose a file.
1414 public void createEPS(File f)
1416 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1420 * Creates an SVG image of the alignment and writes it to the given file. If
1421 * the file is null, the user is prompted to choose a file.
1426 public void createSVG(File f)
1428 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1432 public void pageSetup_actionPerformed(ActionEvent e)
1434 PrinterJob printJob = PrinterJob.getPrinterJob();
1435 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1445 public void printMenuItem_actionPerformed(ActionEvent e)
1447 // Putting in a thread avoids Swing painting problems
1448 PrintThread thread = new PrintThread(alignPanel);
1453 public void exportFeatures_actionPerformed(ActionEvent e)
1455 new AnnotationExporter(alignPanel).exportFeatures();
1459 public void exportAnnotations_actionPerformed(ActionEvent e)
1461 new AnnotationExporter(alignPanel).exportAnnotations();
1465 public void associatedData_actionPerformed(ActionEvent e)
1467 final JalviewFileChooser chooser = new JalviewFileChooser(
1468 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1469 chooser.setFileView(new JalviewFileView());
1470 chooser.setDialogTitle(
1471 MessageManager.getString("label.load_jalview_annotations"));
1472 chooser.setToolTipText(
1473 MessageManager.getString("label.load_jalview_annotations"));
1474 chooser.setResponseHandler(0, new Runnable()
1479 String choice = chooser.getSelectedFile().getPath();
1480 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1481 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1485 chooser.showOpenDialog(this);
1489 * Close the current view or all views in the alignment frame. If the frame
1490 * only contains one view then the alignment will be removed from memory.
1492 * @param closeAllTabs
1495 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1497 if (alignPanels != null && alignPanels.size() < 2)
1499 closeAllTabs = true;
1504 if (alignPanels != null)
1508 if (this.isClosed())
1510 // really close all the windows - otherwise wait till
1511 // setClosed(true) is called
1512 for (int i = 0; i < alignPanels.size(); i++)
1514 AlignmentPanel ap = alignPanels.get(i);
1521 closeView(alignPanel);
1528 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1529 * be called recursively, with the frame now in 'closed' state
1531 this.setClosed(true);
1533 } catch (Exception ex)
1535 ex.printStackTrace();
1540 * Close the specified panel and close up tabs appropriately.
1542 * @param panelToClose
1544 public void closeView(AlignmentPanel panelToClose)
1546 int index = tabbedPane.getSelectedIndex();
1547 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1548 alignPanels.remove(panelToClose);
1549 panelToClose.closePanel();
1550 panelToClose = null;
1552 tabbedPane.removeTabAt(closedindex);
1553 tabbedPane.validate();
1555 if (index > closedindex || index == tabbedPane.getTabCount())
1557 // modify currently selected tab index if necessary.
1561 this.tabSelectionChanged(index);
1567 void updateEditMenuBar()
1570 if (viewport.getHistoryList().size() > 0)
1572 undoMenuItem.setEnabled(true);
1573 CommandI command = viewport.getHistoryList().peek();
1574 undoMenuItem.setText(MessageManager
1575 .formatMessage("label.undo_command", new Object[]
1576 { command.getDescription() }));
1580 undoMenuItem.setEnabled(false);
1581 undoMenuItem.setText(MessageManager.getString("action.undo"));
1584 if (viewport.getRedoList().size() > 0)
1586 redoMenuItem.setEnabled(true);
1588 CommandI command = viewport.getRedoList().peek();
1589 redoMenuItem.setText(MessageManager
1590 .formatMessage("label.redo_command", new Object[]
1591 { command.getDescription() }));
1595 redoMenuItem.setEnabled(false);
1596 redoMenuItem.setText(MessageManager.getString("action.redo"));
1601 public void addHistoryItem(CommandI command)
1603 if (command.getSize() > 0)
1605 viewport.addToHistoryList(command);
1606 viewport.clearRedoList();
1607 updateEditMenuBar();
1608 viewport.updateHiddenColumns();
1609 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1610 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1611 // viewport.getColumnSelection()
1612 // .getHiddenColumns().size() > 0);
1618 * @return alignment objects for all views
1620 AlignmentI[] getViewAlignments()
1622 if (alignPanels != null)
1624 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1626 for (AlignmentPanel ap : alignPanels)
1628 als[i++] = ap.av.getAlignment();
1632 if (viewport != null)
1634 return new AlignmentI[] { viewport.getAlignment() };
1646 protected void undoMenuItem_actionPerformed(ActionEvent e)
1648 if (viewport.getHistoryList().isEmpty())
1652 CommandI command = viewport.getHistoryList().pop();
1653 viewport.addToRedoList(command);
1654 command.undoCommand(getViewAlignments());
1656 AlignmentViewport originalSource = getOriginatingSource(command);
1657 updateEditMenuBar();
1659 if (originalSource != null)
1661 if (originalSource != viewport)
1664 "Implementation worry: mismatch of viewport origin for undo");
1666 originalSource.updateHiddenColumns();
1667 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1669 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1670 // viewport.getColumnSelection()
1671 // .getHiddenColumns().size() > 0);
1672 originalSource.firePropertyChange("alignment", null,
1673 originalSource.getAlignment().getSequences());
1684 protected void redoMenuItem_actionPerformed(ActionEvent e)
1686 if (viewport.getRedoList().size() < 1)
1691 CommandI command = viewport.getRedoList().pop();
1692 viewport.addToHistoryList(command);
1693 command.doCommand(getViewAlignments());
1695 AlignmentViewport originalSource = getOriginatingSource(command);
1696 updateEditMenuBar();
1698 if (originalSource != null)
1701 if (originalSource != viewport)
1704 "Implementation worry: mismatch of viewport origin for redo");
1706 originalSource.updateHiddenColumns();
1707 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1709 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1710 // viewport.getColumnSelection()
1711 // .getHiddenColumns().size() > 0);
1712 originalSource.firePropertyChange("alignment", null,
1713 originalSource.getAlignment().getSequences());
1717 AlignmentViewport getOriginatingSource(CommandI command)
1719 AlignmentViewport originalSource = null;
1720 // For sequence removal and addition, we need to fire
1721 // the property change event FROM the viewport where the
1722 // original alignment was altered
1723 AlignmentI al = null;
1724 if (command instanceof EditCommand)
1726 EditCommand editCommand = (EditCommand) command;
1727 al = editCommand.getAlignment();
1728 List<Component> comps = PaintRefresher.components
1729 .get(viewport.getSequenceSetId());
1731 for (Component comp : comps)
1733 if (comp instanceof AlignmentPanel)
1735 if (al == ((AlignmentPanel) comp).av.getAlignment())
1737 originalSource = ((AlignmentPanel) comp).av;
1744 if (originalSource == null)
1746 // The original view is closed, we must validate
1747 // the current view against the closed view first
1750 PaintRefresher.validateSequences(al, viewport.getAlignment());
1753 originalSource = viewport;
1756 return originalSource;
1765 public void moveSelectedSequences(boolean up)
1767 SequenceGroup sg = viewport.getSelectionGroup();
1773 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1774 viewport.getHiddenRepSequences(), up);
1775 alignPanel.paintAlignment(true, false);
1778 synchronized void slideSequences(boolean right, int size)
1780 List<SequenceI> sg = new ArrayList<>();
1781 if (viewport.cursorMode)
1783 sg.add(viewport.getAlignment()
1784 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1786 else if (viewport.getSelectionGroup() != null
1787 && viewport.getSelectionGroup().getSize() != viewport
1788 .getAlignment().getHeight())
1790 sg = viewport.getSelectionGroup()
1791 .getSequences(viewport.getHiddenRepSequences());
1799 List<SequenceI> invertGroup = new ArrayList<>();
1801 for (SequenceI seq : viewport.getAlignment().getSequences())
1803 if (!sg.contains(seq))
1805 invertGroup.add(seq);
1809 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1811 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1812 for (int i = 0; i < invertGroup.size(); i++)
1814 seqs2[i] = invertGroup.get(i);
1817 SlideSequencesCommand ssc;
1820 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1821 viewport.getGapCharacter());
1825 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1826 viewport.getGapCharacter());
1829 int groupAdjustment = 0;
1830 if (ssc.getGapsInsertedBegin() && right)
1832 if (viewport.cursorMode)
1834 alignPanel.getSeqPanel().moveCursor(size, 0);
1838 groupAdjustment = size;
1841 else if (!ssc.getGapsInsertedBegin() && !right)
1843 if (viewport.cursorMode)
1845 alignPanel.getSeqPanel().moveCursor(-size, 0);
1849 groupAdjustment = -size;
1853 if (groupAdjustment != 0)
1855 viewport.getSelectionGroup().setStartRes(
1856 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1857 viewport.getSelectionGroup().setEndRes(
1858 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1862 * just extend the last slide command if compatible; but not if in
1863 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1865 boolean appendHistoryItem = false;
1866 Deque<CommandI> historyList = viewport.getHistoryList();
1867 boolean inSplitFrame = getSplitViewContainer() != null;
1868 if (!inSplitFrame && historyList != null && historyList.size() > 0
1869 && historyList.peek() instanceof SlideSequencesCommand)
1871 appendHistoryItem = ssc.appendSlideCommand(
1872 (SlideSequencesCommand) historyList.peek());
1875 if (!appendHistoryItem)
1877 addHistoryItem(ssc);
1890 protected void copy_actionPerformed(ActionEvent e)
1892 if (viewport.getSelectionGroup() == null)
1896 // TODO: preserve the ordering of displayed alignment annotation in any
1897 // internal paste (particularly sequence associated annotation)
1898 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1899 String[] omitHidden = null;
1901 if (viewport.hasHiddenColumns())
1903 omitHidden = viewport.getViewAsString(true);
1906 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1907 seqs, omitHidden, null);
1909 StringSelection ss = new StringSelection(output);
1913 jalview.gui.Desktop.internalCopy = true;
1914 // Its really worth setting the clipboard contents
1915 // to empty before setting the large StringSelection!!
1916 Toolkit.getDefaultToolkit().getSystemClipboard()
1917 .setContents(new StringSelection(""), null);
1919 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1921 } catch (OutOfMemoryError er)
1923 new OOMWarning("copying region", er);
1927 HiddenColumns hiddenColumns = null;
1928 if (viewport.hasHiddenColumns())
1930 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1931 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1933 // create new HiddenColumns object with copy of hidden regions
1934 // between startRes and endRes, offset by startRes
1935 hiddenColumns = new HiddenColumns(
1936 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
1937 hiddenCutoff, hiddenOffset);
1940 Desktop.jalviewClipboard = new Object[] { seqs,
1941 viewport.getAlignment().getDataset(), hiddenColumns };
1942 setStatus(MessageManager.formatMessage(
1943 "label.copied_sequences_to_clipboard", new Object[]
1944 { Integer.valueOf(seqs.length).toString() }));
1954 protected void pasteNew_actionPerformed(ActionEvent e)
1966 protected void pasteThis_actionPerformed(ActionEvent e)
1972 * Paste contents of Jalview clipboard
1974 * @param newAlignment
1975 * true to paste to a new alignment, otherwise add to this.
1977 void paste(boolean newAlignment)
1979 boolean externalPaste = true;
1982 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1983 Transferable contents = c.getContents(this);
1985 if (contents == null)
1994 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1995 if (str.length() < 1)
2000 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2002 } catch (OutOfMemoryError er)
2004 new OOMWarning("Out of memory pasting sequences!!", er);
2008 SequenceI[] sequences;
2009 boolean annotationAdded = false;
2010 AlignmentI alignment = null;
2012 if (Desktop.jalviewClipboard != null)
2014 // The clipboard was filled from within Jalview, we must use the
2016 // And dataset from the copied alignment
2017 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2018 // be doubly sure that we create *new* sequence objects.
2019 sequences = new SequenceI[newseq.length];
2020 for (int i = 0; i < newseq.length; i++)
2022 sequences[i] = new Sequence(newseq[i]);
2024 alignment = new Alignment(sequences);
2025 externalPaste = false;
2029 // parse the clipboard as an alignment.
2030 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2032 sequences = alignment.getSequencesArray();
2036 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2042 if (Desktop.jalviewClipboard != null)
2044 // dataset is inherited
2045 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2049 // new dataset is constructed
2050 alignment.setDataset(null);
2052 alwidth = alignment.getWidth() + 1;
2056 AlignmentI pastedal = alignment; // preserve pasted alignment object
2057 // Add pasted sequences and dataset into existing alignment.
2058 alignment = viewport.getAlignment();
2059 alwidth = alignment.getWidth() + 1;
2060 // decide if we need to import sequences from an existing dataset
2061 boolean importDs = Desktop.jalviewClipboard != null
2062 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2063 // importDs==true instructs us to copy over new dataset sequences from
2064 // an existing alignment
2065 Vector newDs = (importDs) ? new Vector() : null; // used to create
2066 // minimum dataset set
2068 for (int i = 0; i < sequences.length; i++)
2072 newDs.addElement(null);
2074 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2076 if (importDs && ds != null)
2078 if (!newDs.contains(ds))
2080 newDs.setElementAt(ds, i);
2081 ds = new Sequence(ds);
2082 // update with new dataset sequence
2083 sequences[i].setDatasetSequence(ds);
2087 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2092 // copy and derive new dataset sequence
2093 sequences[i] = sequences[i].deriveSequence();
2094 alignment.getDataset()
2095 .addSequence(sequences[i].getDatasetSequence());
2096 // TODO: avoid creation of duplicate dataset sequences with a
2097 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2099 alignment.addSequence(sequences[i]); // merges dataset
2103 newDs.clear(); // tidy up
2105 if (alignment.getAlignmentAnnotation() != null)
2107 for (AlignmentAnnotation alan : alignment
2108 .getAlignmentAnnotation())
2110 if (alan.graphGroup > fgroup)
2112 fgroup = alan.graphGroup;
2116 if (pastedal.getAlignmentAnnotation() != null)
2118 // Add any annotation attached to alignment.
2119 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2120 for (int i = 0; i < alann.length; i++)
2122 annotationAdded = true;
2123 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2125 AlignmentAnnotation newann = new AlignmentAnnotation(
2127 if (newann.graphGroup > -1)
2129 if (newGraphGroups.size() <= newann.graphGroup
2130 || newGraphGroups.get(newann.graphGroup) == null)
2132 for (int q = newGraphGroups
2133 .size(); q <= newann.graphGroup; q++)
2135 newGraphGroups.add(q, null);
2137 newGraphGroups.set(newann.graphGroup,
2138 new Integer(++fgroup));
2140 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2144 newann.padAnnotation(alwidth);
2145 alignment.addAnnotation(newann);
2155 addHistoryItem(new EditCommand(
2156 MessageManager.getString("label.add_sequences"),
2157 Action.PASTE, sequences, 0, alignment.getWidth(),
2160 // Add any annotations attached to sequences
2161 for (int i = 0; i < sequences.length; i++)
2163 if (sequences[i].getAnnotation() != null)
2165 AlignmentAnnotation newann;
2166 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2168 annotationAdded = true;
2169 newann = sequences[i].getAnnotation()[a];
2170 newann.adjustForAlignment();
2171 newann.padAnnotation(alwidth);
2172 if (newann.graphGroup > -1)
2174 if (newann.graphGroup > -1)
2176 if (newGraphGroups.size() <= newann.graphGroup
2177 || newGraphGroups.get(newann.graphGroup) == null)
2179 for (int q = newGraphGroups
2180 .size(); q <= newann.graphGroup; q++)
2182 newGraphGroups.add(q, null);
2184 newGraphGroups.set(newann.graphGroup,
2185 new Integer(++fgroup));
2187 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2191 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2195 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2203 // propagate alignment changed.
2204 viewport.getRanges().setEndSeq(alignment.getHeight());
2205 if (annotationAdded)
2207 // Duplicate sequence annotation in all views.
2208 AlignmentI[] alview = this.getViewAlignments();
2209 for (int i = 0; i < sequences.length; i++)
2211 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2216 for (int avnum = 0; avnum < alview.length; avnum++)
2218 if (alview[avnum] != alignment)
2220 // duplicate in a view other than the one with input focus
2221 int avwidth = alview[avnum].getWidth() + 1;
2222 // this relies on sann being preserved after we
2223 // modify the sequence's annotation array for each duplication
2224 for (int a = 0; a < sann.length; a++)
2226 AlignmentAnnotation newann = new AlignmentAnnotation(
2228 sequences[i].addAlignmentAnnotation(newann);
2229 newann.padAnnotation(avwidth);
2230 alview[avnum].addAnnotation(newann); // annotation was
2231 // duplicated earlier
2232 // TODO JAL-1145 graphGroups are not updated for sequence
2233 // annotation added to several views. This may cause
2235 alview[avnum].setAnnotationIndex(newann, a);
2240 buildSortByAnnotationScoresMenu();
2242 viewport.firePropertyChange("alignment", null,
2243 alignment.getSequences());
2244 if (alignPanels != null)
2246 for (AlignmentPanel ap : alignPanels)
2248 ap.validateAnnotationDimensions(false);
2253 alignPanel.validateAnnotationDimensions(false);
2259 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2261 String newtitle = new String("Copied sequences");
2263 if (Desktop.jalviewClipboard != null
2264 && Desktop.jalviewClipboard[2] != null)
2266 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2267 af.viewport.setHiddenColumns(hc);
2270 // >>>This is a fix for the moment, until a better solution is
2272 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2273 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2274 .getFeatureRenderer());
2276 // TODO: maintain provenance of an alignment, rather than just make the
2277 // title a concatenation of operations.
2280 if (title.startsWith("Copied sequences"))
2286 newtitle = newtitle.concat("- from " + title);
2291 newtitle = new String("Pasted sequences");
2294 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2299 } catch (Exception ex)
2301 ex.printStackTrace();
2302 System.out.println("Exception whilst pasting: " + ex);
2303 // could be anything being pasted in here
2309 protected void expand_newalign(ActionEvent e)
2313 AlignmentI alignment = AlignmentUtils
2314 .expandContext(getViewport().getAlignment(), -1);
2315 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2317 String newtitle = new String("Flanking alignment");
2319 if (Desktop.jalviewClipboard != null
2320 && Desktop.jalviewClipboard[2] != null)
2322 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2323 af.viewport.setHiddenColumns(hc);
2326 // >>>This is a fix for the moment, until a better solution is
2328 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2329 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2330 .getFeatureRenderer());
2332 // TODO: maintain provenance of an alignment, rather than just make the
2333 // title a concatenation of operations.
2335 if (title.startsWith("Copied sequences"))
2341 newtitle = newtitle.concat("- from " + title);
2345 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2347 } catch (Exception ex)
2349 ex.printStackTrace();
2350 System.out.println("Exception whilst pasting: " + ex);
2351 // could be anything being pasted in here
2352 } catch (OutOfMemoryError oom)
2354 new OOMWarning("Viewing flanking region of alignment", oom);
2365 protected void cut_actionPerformed(ActionEvent e)
2367 copy_actionPerformed(null);
2368 delete_actionPerformed(null);
2378 protected void delete_actionPerformed(ActionEvent evt)
2381 SequenceGroup sg = viewport.getSelectionGroup();
2388 * If the cut affects all sequences, warn, remove highlighted columns
2390 if (sg.getSize() == viewport.getAlignment().getHeight())
2392 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2393 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2394 if (isEntireAlignWidth)
2396 int confirm = JvOptionPane.showConfirmDialog(this,
2397 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2398 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2399 JvOptionPane.OK_CANCEL_OPTION);
2401 if (confirm == JvOptionPane.CANCEL_OPTION
2402 || confirm == JvOptionPane.CLOSED_OPTION)
2407 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2408 sg.getEndRes() + 1);
2410 SequenceI[] cut = sg.getSequences()
2411 .toArray(new SequenceI[sg.getSize()]);
2413 addHistoryItem(new EditCommand(
2414 MessageManager.getString("label.cut_sequences"), Action.CUT,
2415 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2416 viewport.getAlignment()));
2418 viewport.setSelectionGroup(null);
2419 viewport.sendSelection();
2420 viewport.getAlignment().deleteGroup(sg);
2422 viewport.firePropertyChange("alignment", null,
2423 viewport.getAlignment().getSequences());
2424 if (viewport.getAlignment().getHeight() < 1)
2428 this.setClosed(true);
2429 } catch (Exception ex)
2442 protected void deleteGroups_actionPerformed(ActionEvent e)
2444 if (avc.deleteGroups())
2446 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2447 alignPanel.updateAnnotation();
2448 alignPanel.paintAlignment(true, true);
2459 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2461 SequenceGroup sg = new SequenceGroup();
2463 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2465 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2468 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2469 viewport.setSelectionGroup(sg);
2470 viewport.sendSelection();
2471 // JAL-2034 - should delegate to
2472 // alignPanel to decide if overview needs
2474 alignPanel.paintAlignment(false, false);
2475 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2485 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2487 if (viewport.cursorMode)
2489 alignPanel.getSeqPanel().keyboardNo1 = null;
2490 alignPanel.getSeqPanel().keyboardNo2 = null;
2492 viewport.setSelectionGroup(null);
2493 viewport.getColumnSelection().clear();
2494 viewport.setSelectionGroup(null);
2495 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2496 // JAL-2034 - should delegate to
2497 // alignPanel to decide if overview needs
2499 alignPanel.paintAlignment(false, false);
2500 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2501 viewport.sendSelection();
2511 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2513 SequenceGroup sg = viewport.getSelectionGroup();
2517 selectAllSequenceMenuItem_actionPerformed(null);
2522 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2524 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2526 // JAL-2034 - should delegate to
2527 // alignPanel to decide if overview needs
2530 alignPanel.paintAlignment(true, false);
2531 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2532 viewport.sendSelection();
2536 public void invertColSel_actionPerformed(ActionEvent e)
2538 viewport.invertColumnSelection();
2539 alignPanel.paintAlignment(true, false);
2540 viewport.sendSelection();
2550 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2552 trimAlignment(true);
2562 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2564 trimAlignment(false);
2567 void trimAlignment(boolean trimLeft)
2569 ColumnSelection colSel = viewport.getColumnSelection();
2572 if (!colSel.isEmpty())
2576 column = colSel.getMin();
2580 column = colSel.getMax();
2584 if (viewport.getSelectionGroup() != null)
2586 seqs = viewport.getSelectionGroup()
2587 .getSequencesAsArray(viewport.getHiddenRepSequences());
2591 seqs = viewport.getAlignment().getSequencesArray();
2594 TrimRegionCommand trimRegion;
2597 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2598 column, viewport.getAlignment());
2599 viewport.getRanges().setStartRes(0);
2603 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2604 column, viewport.getAlignment());
2607 setStatus(MessageManager
2608 .formatMessage("label.removed_columns", new String[]
2609 { Integer.valueOf(trimRegion.getSize()).toString() }));
2611 addHistoryItem(trimRegion);
2613 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2615 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2616 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2618 viewport.getAlignment().deleteGroup(sg);
2622 viewport.firePropertyChange("alignment", null,
2623 viewport.getAlignment().getSequences());
2634 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2636 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2639 if (viewport.getSelectionGroup() != null)
2641 seqs = viewport.getSelectionGroup()
2642 .getSequencesAsArray(viewport.getHiddenRepSequences());
2643 start = viewport.getSelectionGroup().getStartRes();
2644 end = viewport.getSelectionGroup().getEndRes();
2648 seqs = viewport.getAlignment().getSequencesArray();
2651 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2652 "Remove Gapped Columns", seqs, start, end,
2653 viewport.getAlignment());
2655 addHistoryItem(removeGapCols);
2657 setStatus(MessageManager
2658 .formatMessage("label.removed_empty_columns", new Object[]
2659 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2661 // This is to maintain viewport position on first residue
2662 // of first sequence
2663 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2664 ViewportRanges ranges = viewport.getRanges();
2665 int startRes = seq.findPosition(ranges.getStartRes());
2666 // ShiftList shifts;
2667 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2668 // edit.alColumnChanges=shifts.getInverse();
2669 // if (viewport.hasHiddenColumns)
2670 // viewport.getColumnSelection().compensateForEdits(shifts);
2671 ranges.setStartRes(seq.findIndex(startRes) - 1);
2672 viewport.firePropertyChange("alignment", null,
2673 viewport.getAlignment().getSequences());
2684 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2686 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2689 if (viewport.getSelectionGroup() != null)
2691 seqs = viewport.getSelectionGroup()
2692 .getSequencesAsArray(viewport.getHiddenRepSequences());
2693 start = viewport.getSelectionGroup().getStartRes();
2694 end = viewport.getSelectionGroup().getEndRes();
2698 seqs = viewport.getAlignment().getSequencesArray();
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(viewport.getRanges().getStartRes());
2706 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2707 viewport.getAlignment()));
2709 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2711 viewport.firePropertyChange("alignment", null,
2712 viewport.getAlignment().getSequences());
2723 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2725 viewport.setPadGaps(padGapsMenuitem.isSelected());
2726 viewport.firePropertyChange("alignment", null,
2727 viewport.getAlignment().getSequences());
2737 public void findMenuItem_actionPerformed(ActionEvent e)
2743 * Create a new view of the current alignment.
2746 public void newView_actionPerformed(ActionEvent e)
2748 newView(null, true);
2752 * Creates and shows a new view of the current alignment.
2755 * title of newly created view; if null, one will be generated
2756 * @param copyAnnotation
2757 * if true then duplicate all annnotation, groups and settings
2758 * @return new alignment panel, already displayed.
2760 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2763 * Create a new AlignmentPanel (with its own, new Viewport)
2765 AlignmentPanel newap = new jalview.project.Jalview2XML()
2766 .copyAlignPanel(alignPanel);
2767 if (!copyAnnotation)
2770 * remove all groups and annotation except for the automatic stuff
2772 newap.av.getAlignment().deleteAllGroups();
2773 newap.av.getAlignment().deleteAllAnnotations(false);
2776 newap.av.setGatherViewsHere(false);
2778 if (viewport.getViewName() == null)
2780 viewport.setViewName(MessageManager
2781 .getString("label.view_name_original"));
2785 * Views share the same edits undo and redo stacks
2787 newap.av.setHistoryList(viewport.getHistoryList());
2788 newap.av.setRedoList(viewport.getRedoList());
2791 * Views share the same mappings; need to deregister any new mappings
2792 * created by copyAlignPanel, and register the new reference to the shared
2795 newap.av.replaceMappings(viewport.getAlignment());
2798 * start up cDNA consensus (if applicable) now mappings are in place
2800 if (newap.av.initComplementConsensus())
2802 newap.refresh(true); // adjust layout of annotations
2805 newap.av.setViewName(getNewViewName(viewTitle));
2807 addAlignmentPanel(newap, true);
2808 newap.alignmentChanged();
2810 if (alignPanels.size() == 2)
2812 viewport.setGatherViewsHere(true);
2814 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2819 * Make a new name for the view, ensuring it is unique within the current
2820 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2821 * these now use viewId. Unique view names are still desirable for usability.)
2826 protected String getNewViewName(String viewTitle)
2828 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2829 boolean addFirstIndex = false;
2830 if (viewTitle == null || viewTitle.trim().length() == 0)
2832 viewTitle = MessageManager.getString("action.view");
2833 addFirstIndex = true;
2837 index = 1;// we count from 1 if given a specific name
2839 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2841 List<Component> comps = PaintRefresher.components
2842 .get(viewport.getSequenceSetId());
2844 List<String> existingNames = getExistingViewNames(comps);
2846 while (existingNames.contains(newViewName))
2848 newViewName = viewTitle + " " + (++index);
2854 * Returns a list of distinct view names found in the given list of
2855 * components. View names are held on the viewport of an AlignmentPanel.
2860 protected List<String> getExistingViewNames(List<Component> comps)
2862 List<String> existingNames = new ArrayList<>();
2863 for (Component comp : comps)
2865 if (comp instanceof AlignmentPanel)
2867 AlignmentPanel ap = (AlignmentPanel) comp;
2868 if (!existingNames.contains(ap.av.getViewName()))
2870 existingNames.add(ap.av.getViewName());
2874 return existingNames;
2878 * Explode tabbed views into separate windows.
2881 public void expandViews_actionPerformed(ActionEvent e)
2883 Desktop.explodeViews(this);
2887 * Gather views in separate windows back into a tabbed presentation.
2890 public void gatherViews_actionPerformed(ActionEvent e)
2892 Desktop.instance.gatherViews(this);
2902 public void font_actionPerformed(ActionEvent e)
2904 new FontChooser(alignPanel);
2914 protected void seqLimit_actionPerformed(ActionEvent e)
2916 viewport.setShowJVSuffix(seqLimits.isSelected());
2918 alignPanel.getIdPanel().getIdCanvas()
2919 .setPreferredSize(alignPanel.calculateIdWidth());
2920 alignPanel.paintAlignment(true, false);
2924 public void idRightAlign_actionPerformed(ActionEvent e)
2926 viewport.setRightAlignIds(idRightAlign.isSelected());
2927 alignPanel.paintAlignment(false, false);
2931 public void centreColumnLabels_actionPerformed(ActionEvent e)
2933 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2934 alignPanel.paintAlignment(false, false);
2940 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2943 protected void followHighlight_actionPerformed()
2946 * Set the 'follow' flag on the Viewport (and scroll to position if now
2949 final boolean state = this.followHighlightMenuItem.getState();
2950 viewport.setFollowHighlight(state);
2953 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2964 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2966 viewport.setColourText(colourTextMenuItem.isSelected());
2967 alignPanel.paintAlignment(false, false);
2977 public void wrapMenuItem_actionPerformed(ActionEvent e)
2979 scaleAbove.setVisible(wrapMenuItem.isSelected());
2980 scaleLeft.setVisible(wrapMenuItem.isSelected());
2981 scaleRight.setVisible(wrapMenuItem.isSelected());
2982 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2983 alignPanel.updateLayout();
2987 public void showAllSeqs_actionPerformed(ActionEvent e)
2989 viewport.showAllHiddenSeqs();
2993 public void showAllColumns_actionPerformed(ActionEvent e)
2995 viewport.showAllHiddenColumns();
2996 alignPanel.paintAlignment(true, true);
2997 viewport.sendSelection();
3001 public void hideSelSequences_actionPerformed(ActionEvent e)
3003 viewport.hideAllSelectedSeqs();
3007 * called by key handler and the hide all/show all menu items
3012 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3015 boolean hide = false;
3016 SequenceGroup sg = viewport.getSelectionGroup();
3017 if (!toggleSeqs && !toggleCols)
3019 // Hide everything by the current selection - this is a hack - we do the
3020 // invert and then hide
3021 // first check that there will be visible columns after the invert.
3022 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3023 && sg.getStartRes() <= sg.getEndRes()))
3025 // now invert the sequence set, if required - empty selection implies
3026 // that no hiding is required.
3029 invertSequenceMenuItem_actionPerformed(null);
3030 sg = viewport.getSelectionGroup();
3034 viewport.expandColSelection(sg, true);
3035 // finally invert the column selection and get the new sequence
3037 invertColSel_actionPerformed(null);
3044 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3046 hideSelSequences_actionPerformed(null);
3049 else if (!(toggleCols && viewport.hasSelectedColumns()))
3051 showAllSeqs_actionPerformed(null);
3057 if (viewport.hasSelectedColumns())
3059 hideSelColumns_actionPerformed(null);
3062 viewport.setSelectionGroup(sg);
3067 showAllColumns_actionPerformed(null);
3076 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3077 * event.ActionEvent)
3080 public void hideAllButSelection_actionPerformed(ActionEvent e)
3082 toggleHiddenRegions(false, false);
3083 viewport.sendSelection();
3090 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3094 public void hideAllSelection_actionPerformed(ActionEvent e)
3096 SequenceGroup sg = viewport.getSelectionGroup();
3097 viewport.expandColSelection(sg, false);
3098 viewport.hideAllSelectedSeqs();
3099 viewport.hideSelectedColumns();
3100 alignPanel.paintAlignment(true, true);
3101 viewport.sendSelection();
3108 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3112 public void showAllhidden_actionPerformed(ActionEvent e)
3114 viewport.showAllHiddenColumns();
3115 viewport.showAllHiddenSeqs();
3116 alignPanel.paintAlignment(true, true);
3117 viewport.sendSelection();
3121 public void hideSelColumns_actionPerformed(ActionEvent e)
3123 viewport.hideSelectedColumns();
3124 alignPanel.paintAlignment(true, true);
3125 viewport.sendSelection();
3129 public void hiddenMarkers_actionPerformed(ActionEvent e)
3131 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3142 protected void scaleAbove_actionPerformed(ActionEvent e)
3144 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3145 // TODO: do we actually need to update overview for scale above change ?
3146 alignPanel.paintAlignment(true, false);
3156 protected void scaleLeft_actionPerformed(ActionEvent e)
3158 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3159 alignPanel.paintAlignment(true, false);
3169 protected void scaleRight_actionPerformed(ActionEvent e)
3171 viewport.setScaleRightWrapped(scaleRight.isSelected());
3172 alignPanel.paintAlignment(true, false);
3182 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3184 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3185 alignPanel.paintAlignment(false, false);
3195 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3197 viewport.setShowText(viewTextMenuItem.isSelected());
3198 alignPanel.paintAlignment(false, false);
3208 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3210 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3211 alignPanel.paintAlignment(false, false);
3214 public FeatureSettings featureSettings;
3217 public FeatureSettingsControllerI getFeatureSettingsUI()
3219 return featureSettings;
3223 public void featureSettings_actionPerformed(ActionEvent e)
3225 if (featureSettings != null)
3227 featureSettings.close();
3228 featureSettings = null;
3230 if (!showSeqFeatures.isSelected())
3232 // make sure features are actually displayed
3233 showSeqFeatures.setSelected(true);
3234 showSeqFeatures_actionPerformed(null);
3236 featureSettings = new FeatureSettings(this);
3240 * Set or clear 'Show Sequence Features'
3246 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3248 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3249 alignPanel.paintAlignment(true, true);
3253 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3254 * the annotations panel as a whole.
3256 * The options to show/hide all annotations should be enabled when the panel
3257 * is shown, and disabled when the panel is hidden.
3262 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3264 final boolean setVisible = annotationPanelMenuItem.isSelected();
3265 viewport.setShowAnnotation(setVisible);
3266 this.showAllSeqAnnotations.setEnabled(setVisible);
3267 this.hideAllSeqAnnotations.setEnabled(setVisible);
3268 this.showAllAlAnnotations.setEnabled(setVisible);
3269 this.hideAllAlAnnotations.setEnabled(setVisible);
3270 alignPanel.updateLayout();
3274 public void alignmentProperties()
3277 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3280 String content = MessageManager.formatMessage("label.html_content",
3282 { contents.toString() });
3287 JLabel textLabel = new JLabel();
3288 textLabel.setText(content);
3289 textLabel.setBackground(Color.WHITE);
3291 pane = new JPanel(new BorderLayout());
3292 ((JPanel) pane).setOpaque(true);
3293 pane.setBackground(Color.WHITE);
3294 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3298 JEditorPane editPane = new JEditorPane("text/html", "");
3299 editPane.setEditable(false);
3300 editPane.setText(content);
3304 JInternalFrame frame = new JInternalFrame();
3306 frame.getContentPane().add(new JScrollPane(pane));
3308 Desktop.addInternalFrame(frame, MessageManager
3309 .formatMessage("label.alignment_properties", new Object[]
3310 { getTitle() }), 500, 400);
3320 public void overviewMenuItem_actionPerformed(ActionEvent e)
3322 if (alignPanel.overviewPanel != null)
3327 JInternalFrame frame = new JInternalFrame();
3328 final OverviewPanel overview = new OverviewPanel(alignPanel);
3329 frame.setContentPane(overview);
3330 Desktop.addInternalFrame(frame, MessageManager
3331 .formatMessage("label.overview_params", new Object[]
3332 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3335 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3336 frame.addInternalFrameListener(
3337 new javax.swing.event.InternalFrameAdapter()
3340 public void internalFrameClosed(
3341 javax.swing.event.InternalFrameEvent evt)
3344 alignPanel.setOverviewPanel(null);
3347 if (getKeyListeners().length > 0)
3349 frame.addKeyListener(getKeyListeners()[0]);
3352 alignPanel.setOverviewPanel(overview);
3356 public void textColour_actionPerformed()
3358 new TextColourChooser().chooseColour(alignPanel, null);
3362 * public void covariationColour_actionPerformed() {
3364 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3368 public void annotationColour_actionPerformed()
3370 new AnnotationColourChooser(viewport, alignPanel);
3374 public void annotationColumn_actionPerformed(ActionEvent e)
3376 new AnnotationColumnChooser(viewport, alignPanel);
3380 * Action on the user checking or unchecking the option to apply the selected
3381 * colour scheme to all groups. If unchecked, groups may have their own
3382 * independent colour schemes.
3387 public void applyToAllGroups_actionPerformed(boolean selected)
3389 viewport.setColourAppliesToAllGroups(selected);
3393 * Action on user selecting a colour from the colour menu
3396 * the name (not the menu item label!) of the colour scheme
3399 public void changeColour_actionPerformed(String name)
3402 * 'User Defined' opens a panel to configure or load a
3403 * user-defined colour scheme
3405 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3407 new UserDefinedColours(alignPanel);
3412 * otherwise set the chosen colour scheme (or null for 'None')
3414 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3415 viewport.getAlignment(), viewport.getHiddenRepSequences());
3420 * Actions on setting or changing the alignment colour scheme
3425 public void changeColour(ColourSchemeI cs)
3427 // TODO: pull up to controller method
3428 ColourMenuHelper.setColourSelected(colourMenu, cs);
3430 viewport.setGlobalColourScheme(cs);
3432 alignPanel.paintAlignment(true, true);
3436 * Show the PID threshold slider panel
3439 protected void modifyPID_actionPerformed()
3441 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3442 alignPanel.getViewName());
3443 SliderPanel.showPIDSlider();
3447 * Show the Conservation slider panel
3450 protected void modifyConservation_actionPerformed()
3452 SliderPanel.setConservationSlider(alignPanel,
3453 viewport.getResidueShading(), alignPanel.getViewName());
3454 SliderPanel.showConservationSlider();
3458 * Action on selecting or deselecting (Colour) By Conservation
3461 public void conservationMenuItem_actionPerformed(boolean selected)
3463 modifyConservation.setEnabled(selected);
3464 viewport.setConservationSelected(selected);
3465 viewport.getResidueShading().setConservationApplied(selected);
3467 changeColour(viewport.getGlobalColourScheme());
3470 modifyConservation_actionPerformed();
3474 SliderPanel.hideConservationSlider();
3479 * Action on selecting or deselecting (Colour) Above PID Threshold
3482 public void abovePIDThreshold_actionPerformed(boolean selected)
3484 modifyPID.setEnabled(selected);
3485 viewport.setAbovePIDThreshold(selected);
3488 viewport.getResidueShading().setThreshold(0,
3489 viewport.isIgnoreGapsConsensus());
3492 changeColour(viewport.getGlobalColourScheme());
3495 modifyPID_actionPerformed();
3499 SliderPanel.hidePIDSlider();
3510 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3512 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3513 AlignmentSorter.sortByPID(viewport.getAlignment(),
3514 viewport.getAlignment().getSequenceAt(0));
3515 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3516 viewport.getAlignment()));
3517 alignPanel.paintAlignment(true, false);
3527 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3529 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3530 AlignmentSorter.sortByID(viewport.getAlignment());
3532 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3533 alignPanel.paintAlignment(true, false);
3543 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3545 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3546 AlignmentSorter.sortByLength(viewport.getAlignment());
3547 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3548 viewport.getAlignment()));
3549 alignPanel.paintAlignment(true, false);
3559 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3561 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3562 AlignmentSorter.sortByGroup(viewport.getAlignment());
3563 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3564 viewport.getAlignment()));
3566 alignPanel.paintAlignment(true, false);
3576 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3578 new RedundancyPanel(alignPanel, this);
3588 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3590 if ((viewport.getSelectionGroup() == null)
3591 || (viewport.getSelectionGroup().getSize() < 2))
3593 JvOptionPane.showInternalMessageDialog(this,
3594 MessageManager.getString(
3595 "label.you_must_select_least_two_sequences"),
3596 MessageManager.getString("label.invalid_selection"),
3597 JvOptionPane.WARNING_MESSAGE);
3601 JInternalFrame frame = new JInternalFrame();
3602 frame.setContentPane(new PairwiseAlignPanel(viewport));
3603 Desktop.addInternalFrame(frame,
3604 MessageManager.getString("action.pairwise_alignment"), 600,
3610 public void autoCalculate_actionPerformed(ActionEvent e)
3612 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3613 if (viewport.autoCalculateConsensus)
3615 viewport.firePropertyChange("alignment", null,
3616 viewport.getAlignment().getSequences());
3621 public void sortByTreeOption_actionPerformed(ActionEvent e)
3623 viewport.sortByTree = sortByTree.isSelected();
3627 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3629 viewport.followSelection = listenToViewSelections.isSelected();
3633 * Constructs a tree panel and adds it to the desktop
3636 * tree type (NJ or AV)
3638 * name of score model used to compute the tree
3640 * parameters for the distance or similarity calculation
3642 void newTreePanel(String type, String modelName,
3643 SimilarityParamsI options)
3645 String frameTitle = "";
3648 boolean onSelection = false;
3649 if (viewport.getSelectionGroup() != null
3650 && viewport.getSelectionGroup().getSize() > 0)
3652 SequenceGroup sg = viewport.getSelectionGroup();
3654 /* Decide if the selection is a column region */
3655 for (SequenceI _s : sg.getSequences())
3657 if (_s.getLength() < sg.getEndRes())
3659 JvOptionPane.showMessageDialog(Desktop.desktop,
3660 MessageManager.getString(
3661 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3662 MessageManager.getString(
3663 "label.sequences_selection_not_aligned"),
3664 JvOptionPane.WARNING_MESSAGE);
3673 if (viewport.getAlignment().getHeight() < 2)
3679 tp = new TreePanel(alignPanel, type, modelName, options);
3680 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3682 frameTitle += " from ";
3684 if (viewport.getViewName() != null)
3686 frameTitle += viewport.getViewName() + " of ";
3689 frameTitle += this.title;
3691 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3702 public void addSortByOrderMenuItem(String title,
3703 final AlignmentOrder order)
3705 final JMenuItem item = new JMenuItem(MessageManager
3706 .formatMessage("action.by_title_param", new Object[]
3709 item.addActionListener(new java.awt.event.ActionListener()
3712 public void actionPerformed(ActionEvent e)
3714 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3716 // TODO: JBPNote - have to map order entries to curent SequenceI
3718 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3720 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3721 viewport.getAlignment()));
3723 alignPanel.paintAlignment(true, false);
3729 * Add a new sort by annotation score menu item
3732 * the menu to add the option to
3734 * the label used to retrieve scores for each sequence on the
3737 public void addSortByAnnotScoreMenuItem(JMenu sort,
3738 final String scoreLabel)
3740 final JMenuItem item = new JMenuItem(scoreLabel);
3742 item.addActionListener(new java.awt.event.ActionListener()
3745 public void actionPerformed(ActionEvent e)
3747 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3748 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3749 viewport.getAlignment());// ,viewport.getSelectionGroup());
3750 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3751 viewport.getAlignment()));
3752 alignPanel.paintAlignment(true, false);
3758 * last hash for alignment's annotation array - used to minimise cost of
3761 protected int _annotationScoreVectorHash;
3764 * search the alignment and rebuild the sort by annotation score submenu the
3765 * last alignment annotation vector hash is stored to minimize cost of
3766 * rebuilding in subsequence calls.
3770 public void buildSortByAnnotationScoresMenu()
3772 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3777 if (viewport.getAlignment().getAlignmentAnnotation()
3778 .hashCode() != _annotationScoreVectorHash)
3780 sortByAnnotScore.removeAll();
3781 // almost certainly a quicker way to do this - but we keep it simple
3782 Hashtable scoreSorts = new Hashtable();
3783 AlignmentAnnotation aann[];
3784 for (SequenceI sqa : viewport.getAlignment().getSequences())
3786 aann = sqa.getAnnotation();
3787 for (int i = 0; aann != null && i < aann.length; i++)
3789 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3791 scoreSorts.put(aann[i].label, aann[i].label);
3795 Enumeration labels = scoreSorts.keys();
3796 while (labels.hasMoreElements())
3798 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3799 (String) labels.nextElement());
3801 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3804 _annotationScoreVectorHash = viewport.getAlignment()
3805 .getAlignmentAnnotation().hashCode();
3810 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3811 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3812 * call. Listeners are added to remove the menu item when the treePanel is
3813 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3817 public void buildTreeSortMenu()
3819 sortByTreeMenu.removeAll();
3821 List<Component> comps = PaintRefresher.components
3822 .get(viewport.getSequenceSetId());
3823 List<TreePanel> treePanels = new ArrayList<>();
3824 for (Component comp : comps)
3826 if (comp instanceof TreePanel)
3828 treePanels.add((TreePanel) comp);
3832 if (treePanels.size() < 1)
3834 sortByTreeMenu.setVisible(false);
3838 sortByTreeMenu.setVisible(true);
3840 for (final TreePanel tp : treePanels)
3842 final JMenuItem item = new JMenuItem(tp.getTitle());
3843 item.addActionListener(new java.awt.event.ActionListener()
3846 public void actionPerformed(ActionEvent e)
3848 tp.sortByTree_actionPerformed();
3849 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3854 sortByTreeMenu.add(item);
3858 public boolean sortBy(AlignmentOrder alorder, String undoname)
3860 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3861 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3862 if (undoname != null)
3864 addHistoryItem(new OrderCommand(undoname, oldOrder,
3865 viewport.getAlignment()));
3867 alignPanel.paintAlignment(true, false);
3872 * Work out whether the whole set of sequences or just the selected set will
3873 * be submitted for multiple alignment.
3876 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3878 // Now, check we have enough sequences
3879 AlignmentView msa = null;
3881 if ((viewport.getSelectionGroup() != null)
3882 && (viewport.getSelectionGroup().getSize() > 1))
3884 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3885 // some common interface!
3887 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3888 * SequenceI[sz = seqs.getSize(false)];
3890 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3891 * seqs.getSequenceAt(i); }
3893 msa = viewport.getAlignmentView(true);
3895 else if (viewport.getSelectionGroup() != null
3896 && viewport.getSelectionGroup().getSize() == 1)
3898 int option = JvOptionPane.showConfirmDialog(this,
3899 MessageManager.getString("warn.oneseq_msainput_selection"),
3900 MessageManager.getString("label.invalid_selection"),
3901 JvOptionPane.OK_CANCEL_OPTION);
3902 if (option == JvOptionPane.OK_OPTION)
3904 msa = viewport.getAlignmentView(false);
3909 msa = viewport.getAlignmentView(false);
3915 * Decides what is submitted to a secondary structure prediction service: the
3916 * first sequence in the alignment, or in the current selection, or, if the
3917 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3918 * region or the whole alignment. (where the first sequence in the set is the
3919 * one that the prediction will be for).
3921 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3923 AlignmentView seqs = null;
3925 if ((viewport.getSelectionGroup() != null)
3926 && (viewport.getSelectionGroup().getSize() > 0))
3928 seqs = viewport.getAlignmentView(true);
3932 seqs = viewport.getAlignmentView(false);
3934 // limit sequences - JBPNote in future - could spawn multiple prediction
3936 // TODO: viewport.getAlignment().isAligned is a global state - the local
3937 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3938 if (!viewport.getAlignment().isAligned(false))
3940 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3941 // TODO: if seqs.getSequences().length>1 then should really have warned
3955 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3957 // Pick the tree file
3958 JalviewFileChooser chooser = new JalviewFileChooser(
3959 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3960 chooser.setFileView(new JalviewFileView());
3961 chooser.setDialogTitle(
3962 MessageManager.getString("label.select_newick_like_tree_file"));
3963 chooser.setToolTipText(
3964 MessageManager.getString("label.load_tree_file"));
3966 chooser.setResponseHandler(0,new Runnable()
3971 String filePath = chooser.getSelectedFile().getPath();
3972 Cache.setProperty("LAST_DIRECTORY", filePath);
3973 NewickFile fin = null;
3976 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
3977 DataSourceType.FILE));
3978 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
3979 } catch (Exception ex)
3981 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
3983 .getString("label.problem_reading_tree_file"),
3984 JvOptionPane.WARNING_MESSAGE);
3985 ex.printStackTrace();
3987 if (fin != null && fin.hasWarningMessage())
3989 JvOptionPane.showMessageDialog(Desktop.desktop,
3990 fin.getWarningMessage(),
3991 MessageManager.getString(
3992 "label.possible_problem_with_tree_file"),
3993 JvOptionPane.WARNING_MESSAGE);
3997 chooser.showOpenDialog(this);
4000 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4002 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4005 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4006 int h, int x, int y)
4008 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4012 * Add a treeviewer for the tree extracted from a Newick file object to the
4013 * current alignment view
4020 * Associated alignment input data (or null)
4029 * @return TreePanel handle
4031 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4032 AlignmentView input, int w, int h, int x, int y)
4034 TreePanel tp = null;
4040 if (nf.getTree() != null)
4042 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4048 tp.setLocation(x, y);
4051 Desktop.addInternalFrame(tp, treeTitle, w, h);
4053 } catch (Exception ex)
4055 ex.printStackTrace();
4061 private boolean buildingMenu = false;
4064 * Generates menu items and listener event actions for web service clients
4067 public void BuildWebServiceMenu()
4069 while (buildingMenu)
4073 System.err.println("Waiting for building menu to finish.");
4075 } catch (Exception e)
4079 final AlignFrame me = this;
4080 buildingMenu = true;
4081 new Thread(new Runnable()
4086 final List<JMenuItem> legacyItems = new ArrayList<>();
4089 // System.err.println("Building ws menu again "
4090 // + Thread.currentThread());
4091 // TODO: add support for context dependent disabling of services based
4093 // alignment and current selection
4094 // TODO: add additional serviceHandle parameter to specify abstract
4096 // class independently of AbstractName
4097 // TODO: add in rediscovery GUI function to restart discoverer
4098 // TODO: group services by location as well as function and/or
4100 // object broker mechanism.
4101 final Vector<JMenu> wsmenu = new Vector<>();
4102 final IProgressIndicator af = me;
4105 * do not i18n these strings - they are hard-coded in class
4106 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4107 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4109 final JMenu msawsmenu = new JMenu("Alignment");
4110 final JMenu secstrmenu = new JMenu(
4111 "Secondary Structure Prediction");
4112 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4113 final JMenu analymenu = new JMenu("Analysis");
4114 final JMenu dismenu = new JMenu("Protein Disorder");
4115 // JAL-940 - only show secondary structure prediction services from
4116 // the legacy server
4117 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4119 Discoverer.services != null && (Discoverer.services.size() > 0))
4121 // TODO: refactor to allow list of AbstractName/Handler bindings to
4123 // stored or retrieved from elsewhere
4124 // No MSAWS used any more:
4125 // Vector msaws = null; // (Vector)
4126 // Discoverer.services.get("MsaWS");
4127 Vector secstrpr = (Vector) Discoverer.services
4129 if (secstrpr != null)
4131 // Add any secondary structure prediction services
4132 for (int i = 0, j = secstrpr.size(); i < j; i++)
4134 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4136 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4137 .getServiceClient(sh);
4138 int p = secstrmenu.getItemCount();
4139 impl.attachWSMenuEntry(secstrmenu, me);
4140 int q = secstrmenu.getItemCount();
4141 for (int litm = p; litm < q; litm++)
4143 legacyItems.add(secstrmenu.getItem(litm));
4149 // Add all submenus in the order they should appear on the web
4151 wsmenu.add(msawsmenu);
4152 wsmenu.add(secstrmenu);
4153 wsmenu.add(dismenu);
4154 wsmenu.add(analymenu);
4155 // No search services yet
4156 // wsmenu.add(seqsrchmenu);
4158 javax.swing.SwingUtilities.invokeLater(new Runnable()
4165 webService.removeAll();
4166 // first, add discovered services onto the webservices menu
4167 if (wsmenu.size() > 0)
4169 for (int i = 0, j = wsmenu.size(); i < j; i++)
4171 webService.add(wsmenu.get(i));
4176 webService.add(me.webServiceNoServices);
4178 // TODO: move into separate menu builder class.
4179 boolean new_sspred = false;
4180 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4182 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4183 if (jws2servs != null)
4185 if (jws2servs.hasServices())
4187 jws2servs.attachWSMenuEntry(webService, me);
4188 for (Jws2Instance sv : jws2servs.getServices())
4190 if (sv.description.toLowerCase().contains("jpred"))
4192 for (JMenuItem jmi : legacyItems)
4194 jmi.setVisible(false);
4200 if (jws2servs.isRunning())
4202 JMenuItem tm = new JMenuItem(
4203 "Still discovering JABA Services");
4204 tm.setEnabled(false);
4209 build_urlServiceMenu(me.webService);
4210 build_fetchdbmenu(webService);
4211 for (JMenu item : wsmenu)
4213 if (item.getItemCount() == 0)
4215 item.setEnabled(false);
4219 item.setEnabled(true);
4222 } catch (Exception e)
4225 "Exception during web service menu building process.",
4230 } catch (Exception e)
4233 buildingMenu = false;
4240 * construct any groupURL type service menu entries.
4244 private void build_urlServiceMenu(JMenu webService)
4246 // TODO: remove this code when 2.7 is released
4247 // DEBUG - alignmentView
4249 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4250 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4252 * @Override public void actionPerformed(ActionEvent e) {
4253 * jalview.datamodel.AlignmentView
4254 * .testSelectionViews(af.viewport.getAlignment(),
4255 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4257 * }); webService.add(testAlView);
4259 // TODO: refactor to RestClient discoverer and merge menu entries for
4260 // rest-style services with other types of analysis/calculation service
4261 // SHmmr test client - still being implemented.
4262 // DEBUG - alignmentView
4264 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4267 client.attachWSMenuEntry(
4268 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4274 * Searches the alignment sequences for xRefs and builds the Show
4275 * Cross-References menu (formerly called Show Products), with database
4276 * sources for which cross-references are found (protein sources for a
4277 * nucleotide alignment and vice versa)
4279 * @return true if Show Cross-references menu should be enabled
4281 public boolean canShowProducts()
4283 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4284 AlignmentI dataset = viewport.getAlignment().getDataset();
4286 showProducts.removeAll();
4287 final boolean dna = viewport.getAlignment().isNucleotide();
4289 if (seqs == null || seqs.length == 0)
4291 // nothing to see here.
4295 boolean showp = false;
4298 List<String> ptypes = new CrossRef(seqs, dataset)
4299 .findXrefSourcesForSequences(dna);
4301 for (final String source : ptypes)
4304 final AlignFrame af = this;
4305 JMenuItem xtype = new JMenuItem(source);
4306 xtype.addActionListener(new ActionListener()
4309 public void actionPerformed(ActionEvent e)
4311 showProductsFor(af.viewport.getSequenceSelection(), dna,
4315 showProducts.add(xtype);
4317 showProducts.setVisible(showp);
4318 showProducts.setEnabled(showp);
4319 } catch (Exception e)
4322 "canShowProducts threw an exception - please report to help@jalview.org",
4330 * Finds and displays cross-references for the selected sequences (protein
4331 * products for nucleotide sequences, dna coding sequences for peptides).
4334 * the sequences to show cross-references for
4336 * true if from a nucleotide alignment (so showing proteins)
4338 * the database to show cross-references for
4340 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4341 final String source)
4343 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4348 * Construct and display a new frame containing the translation of this
4349 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4352 public void showTranslation_actionPerformed(ActionEvent e)
4354 AlignmentI al = null;
4357 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4359 al = dna.translateCdna();
4360 } catch (Exception ex)
4362 jalview.bin.Cache.log.error(
4363 "Exception during translation. Please report this !", ex);
4364 final String msg = MessageManager.getString(
4365 "label.error_when_translating_sequences_submit_bug_report");
4366 final String errorTitle = MessageManager
4367 .getString("label.implementation_error")
4368 + MessageManager.getString("label.translation_failed");
4369 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4370 JvOptionPane.ERROR_MESSAGE);
4373 if (al == null || al.getHeight() == 0)
4375 final String msg = MessageManager.getString(
4376 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4377 final String errorTitle = MessageManager
4378 .getString("label.translation_failed");
4379 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4380 JvOptionPane.WARNING_MESSAGE);
4384 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4385 af.setFileFormat(this.currentFileFormat);
4386 final String newTitle = MessageManager
4387 .formatMessage("label.translation_of_params", new Object[]
4388 { this.getTitle() });
4389 af.setTitle(newTitle);
4390 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4392 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4393 viewport.openSplitFrame(af, new Alignment(seqs));
4397 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4404 * Set the file format
4408 public void setFileFormat(FileFormatI format)
4410 this.currentFileFormat = format;
4414 * Try to load a features file onto the alignment.
4417 * contents or path to retrieve file or a File object
4419 * access mode of file (see jalview.io.AlignFile)
4420 * @return true if features file was parsed correctly.
4422 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4425 return avc.parseFeaturesFile(file, sourceType,
4426 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4431 public void refreshFeatureUI(boolean enableIfNecessary)
4433 // note - currently this is only still here rather than in the controller
4434 // because of the featureSettings hard reference that is yet to be
4436 if (enableIfNecessary)
4438 viewport.setShowSequenceFeatures(true);
4439 showSeqFeatures.setSelected(true);
4445 public void dragEnter(DropTargetDragEvent evt)
4450 public void dragExit(DropTargetEvent evt)
4455 public void dragOver(DropTargetDragEvent evt)
4460 public void dropActionChanged(DropTargetDragEvent evt)
4465 public void drop(DropTargetDropEvent evt)
4467 // JAL-1552 - acceptDrop required before getTransferable call for
4468 // Java's Transferable for native dnd
4469 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4470 Transferable t = evt.getTransferable();
4472 final AlignFrame thisaf = this;
4473 final List<Object> files = new ArrayList<>();
4474 List<DataSourceType> protocols = new ArrayList<>();
4478 Desktop.transferFromDropTarget(files, protocols, evt, t);
4479 } catch (Exception e)
4481 e.printStackTrace();
4485 new Thread(new Runnable()
4492 // check to see if any of these files have names matching sequences
4495 SequenceIdMatcher idm = new SequenceIdMatcher(
4496 viewport.getAlignment().getSequencesArray());
4498 * Object[] { String,SequenceI}
4500 ArrayList<Object[]> filesmatched = new ArrayList<>();
4501 ArrayList<Object> filesnotmatched = new ArrayList<>();
4502 for (int i = 0; i < files.size(); i++)
4505 Object file = files.get(i);
4506 String fileName = file.toString();
4508 DataSourceType protocol = (file instanceof File
4509 ? DataSourceType.FILE
4510 : FormatAdapter.checkProtocol(fileName));
4511 if (protocol == DataSourceType.FILE)
4513 File fl = (file instanceof File ? (File) file
4514 : new File(fileName));
4515 pdbfn = fl.getName();
4517 else if (protocol == DataSourceType.URL)
4519 URL url = new URL(fileName);
4520 pdbfn = url.getFile();
4522 if (pdbfn.length() > 0)
4524 // attempt to find a match in the alignment
4525 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4526 int l = 0, c = pdbfn.indexOf(".");
4527 while (mtch == null && c != -1)
4532 } while ((c = pdbfn.indexOf(".", l)) > l);
4535 pdbfn = pdbfn.substring(0, l);
4537 mtch = idm.findAllIdMatches(pdbfn);
4544 type = new IdentifyFile().identify(file, protocol);
4545 } catch (Exception ex)
4549 if (type != null && type.isStructureFile())
4551 filesmatched.add(new Object[] { file, protocol, mtch });
4555 // File wasn't named like one of the sequences or wasn't a PDB
4557 filesnotmatched.add(file);
4561 if (filesmatched.size() > 0)
4563 boolean autoAssociate = Cache
4564 .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4567 String msg = MessageManager.formatMessage(
4568 "label.automatically_associate_structure_files_with_sequences_same_name",
4570 { Integer.valueOf(filesmatched.size())
4572 String ttl = MessageManager.getString(
4573 "label.automatically_associate_structure_files_by_name");
4574 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4575 ttl, JvOptionPane.YES_NO_OPTION);
4576 autoAssociate = choice == JvOptionPane.YES_OPTION;
4580 for (Object[] fm : filesmatched)
4582 // try and associate
4583 // TODO: may want to set a standard ID naming formalism for
4584 // associating PDB files which have no IDs.
4585 for (SequenceI toassoc : (SequenceI[]) fm[2])
4587 PDBEntry pe = new AssociatePdbFileWithSeq()
4588 .associatePdbWithSeq(fm[0].toString(),
4589 (DataSourceType) fm[1], toassoc, false,
4593 System.err.println("Associated file : "
4594 + (fm[0].toString()) + " with "
4595 + toassoc.getDisplayId(true));
4599 // TODO: do we need to update overview ? only if features are
4601 alignPanel.paintAlignment(true, false);
4607 * add declined structures as sequences
4609 for (Object[] o : filesmatched)
4611 filesnotmatched.add(o[0]);
4615 if (filesnotmatched.size() > 0)
4617 if (assocfiles > 0 && (Cache.getDefault(
4618 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4619 || JvOptionPane.showConfirmDialog(thisaf,
4620 "<html>" + MessageManager.formatMessage(
4621 "label.ignore_unmatched_dropped_files_info",
4624 filesnotmatched.size())
4627 MessageManager.getString(
4628 "label.ignore_unmatched_dropped_files"),
4629 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4633 for (Object fn : filesnotmatched)
4635 loadJalviewDataFile(fn, null, null, null);
4639 } catch (Exception ex)
4641 ex.printStackTrace();
4649 * Attempt to load a "dropped" file or URL string, by testing in turn for
4651 * <li>an Annotation file</li>
4652 * <li>a JNet file</li>
4653 * <li>a features file</li>
4654 * <li>else try to interpret as an alignment file</li>
4658 * either a filename or a URL string.
4660 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4661 FileFormatI format, SequenceI assocSeq)
4663 // BH 2018 was String file
4666 if (sourceType == null)
4668 sourceType = FormatAdapter.checkProtocol(file);
4670 // if the file isn't identified, or not positively identified as some
4671 // other filetype (PFAM is default unidentified alignment file type) then
4672 // try to parse as annotation.
4673 boolean isAnnotation = (format == null
4674 || FileFormat.Pfam.equals(format))
4675 ? new AnnotationFile().annotateAlignmentView(viewport,
4681 // first see if its a T-COFFEE score file
4682 TCoffeeScoreFile tcf = null;
4685 tcf = new TCoffeeScoreFile(file, sourceType);
4688 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4692 new TCoffeeColourScheme(viewport.getAlignment()));
4693 isAnnotation = true;
4694 setStatus(MessageManager.getString(
4695 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4699 // some problem - if no warning its probable that the ID matching
4700 // process didn't work
4701 JvOptionPane.showMessageDialog(Desktop.desktop,
4702 tcf.getWarningMessage() == null
4703 ? MessageManager.getString(
4704 "label.check_file_matches_sequence_ids_alignment")
4705 : tcf.getWarningMessage(),
4706 MessageManager.getString(
4707 "label.problem_reading_tcoffee_score_file"),
4708 JvOptionPane.WARNING_MESSAGE);
4715 } catch (Exception x)
4718 "Exception when processing data source as T-COFFEE score file",
4724 // try to see if its a JNet 'concise' style annotation file *before*
4726 // try to parse it as a features file
4729 format = new IdentifyFile().identify(file, sourceType);
4731 if (FileFormat.ScoreMatrix == format)
4733 ScoreMatrixFile sm = new ScoreMatrixFile(
4734 new FileParse(file, sourceType));
4736 // todo: i18n this message
4737 setStatus(MessageManager.formatMessage(
4738 "label.successfully_loaded_matrix",
4739 sm.getMatrixName()));
4741 else if (FileFormat.Jnet.equals(format))
4743 JPredFile predictions = new JPredFile(file, sourceType);
4744 new JnetAnnotationMaker();
4745 JnetAnnotationMaker.add_annotation(predictions,
4746 viewport.getAlignment(), 0, false);
4747 viewport.getAlignment().setupJPredAlignment();
4748 isAnnotation = true;
4750 // else if (IdentifyFile.FeaturesFile.equals(format))
4751 else if (FileFormat.Features.equals(format))
4753 if (parseFeaturesFile(file, sourceType))
4755 alignPanel.paintAlignment(true, true);
4760 new FileLoader().LoadFile(viewport, file, sourceType, format);
4767 alignPanel.adjustAnnotationHeight();
4768 viewport.updateSequenceIdColours();
4769 buildSortByAnnotationScoresMenu();
4770 alignPanel.paintAlignment(true, true);
4772 } catch (Exception ex)
4774 ex.printStackTrace();
4775 } catch (OutOfMemoryError oom)
4780 } catch (Exception x)
4785 + (sourceType != null
4786 ? (sourceType == DataSourceType.PASTE
4788 : "using " + sourceType + " from "
4792 ? "(parsing as '" + format + "' file)"
4794 oom, Desktop.desktop);
4799 * Method invoked by the ChangeListener on the tabbed pane, in other words
4800 * when a different tabbed pane is selected by the user or programmatically.
4803 public void tabSelectionChanged(int index)
4807 alignPanel = alignPanels.get(index);
4808 viewport = alignPanel.av;
4809 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4810 setMenusFromViewport(viewport);
4814 * 'focus' any colour slider that is open to the selected viewport
4816 if (viewport.getConservationSelected())
4818 SliderPanel.setConservationSlider(alignPanel,
4819 viewport.getResidueShading(), alignPanel.getViewName());
4823 SliderPanel.hideConservationSlider();
4825 if (viewport.getAbovePIDThreshold())
4827 SliderPanel.setPIDSliderSource(alignPanel,
4828 viewport.getResidueShading(), alignPanel.getViewName());
4832 SliderPanel.hidePIDSlider();
4836 * If there is a frame linked to this one in a SplitPane, switch it to the
4837 * same view tab index. No infinite recursion of calls should happen, since
4838 * tabSelectionChanged() should not get invoked on setting the selected
4839 * index to an unchanged value. Guard against setting an invalid index
4840 * before the new view peer tab has been created.
4842 final AlignViewportI peer = viewport.getCodingComplement();
4845 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4846 .getAlignPanel().alignFrame;
4847 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4849 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4855 * On right mouse click on view tab, prompt for and set new view name.
4858 public void tabbedPane_mousePressed(MouseEvent e)
4860 if (e.isPopupTrigger())
4862 String msg = MessageManager.getString("label.enter_view_name");
4863 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
4864 String reply = JvOptionPane.showInputDialog(msg, ttl);
4868 viewport.setViewName(reply);
4869 // TODO warn if reply is in getExistingViewNames()?
4870 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4875 public AlignViewport getCurrentView()
4881 * Open the dialog for regex description parsing.
4884 protected void extractScores_actionPerformed(ActionEvent e)
4886 ParseProperties pp = new jalview.analysis.ParseProperties(
4887 viewport.getAlignment());
4888 // TODO: verify regex and introduce GUI dialog for version 2.5
4889 // if (pp.getScoresFromDescription("col", "score column ",
4890 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4892 if (pp.getScoresFromDescription("description column",
4893 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4895 buildSortByAnnotationScoresMenu();
4903 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4907 protected void showDbRefs_actionPerformed(ActionEvent e)
4909 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4915 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4919 protected void showNpFeats_actionPerformed(ActionEvent e)
4921 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4925 * find the viewport amongst the tabs in this alignment frame and close that
4930 public boolean closeView(AlignViewportI av)
4934 this.closeMenuItem_actionPerformed(false);
4937 Component[] comp = tabbedPane.getComponents();
4938 for (int i = 0; comp != null && i < comp.length; i++)
4940 if (comp[i] instanceof AlignmentPanel)
4942 if (((AlignmentPanel) comp[i]).av == av)
4945 closeView((AlignmentPanel) comp[i]);
4953 protected void build_fetchdbmenu(JMenu webService)
4955 // Temporary hack - DBRef Fetcher always top level ws entry.
4956 // TODO We probably want to store a sequence database checklist in
4957 // preferences and have checkboxes.. rather than individual sources selected
4959 final JMenu rfetch = new JMenu(
4960 MessageManager.getString("action.fetch_db_references"));
4961 rfetch.setToolTipText(MessageManager.getString(
4962 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4963 webService.add(rfetch);
4965 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4966 MessageManager.getString("option.trim_retrieved_seqs"));
4967 trimrs.setToolTipText(
4968 MessageManager.getString("label.trim_retrieved_sequences"));
4970 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
4971 trimrs.addActionListener(new ActionListener()
4974 public void actionPerformed(ActionEvent e)
4976 trimrs.setSelected(trimrs.isSelected());
4977 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
4978 Boolean.valueOf(trimrs.isSelected()).toString());
4982 JMenuItem fetchr = new JMenuItem(
4983 MessageManager.getString("label.standard_databases"));
4984 fetchr.setToolTipText(
4985 MessageManager.getString("label.fetch_embl_uniprot"));
4986 fetchr.addActionListener(new ActionListener()
4990 public void actionPerformed(ActionEvent e)
4992 new Thread(new Runnable()
4997 boolean isNucleotide = alignPanel.alignFrame.getViewport()
4998 .getAlignment().isNucleotide();
4999 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5000 alignPanel.av.getSequenceSelection(),
5001 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 new Thread(new Runnable()
5024 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5025 .getSequenceFetcherSingleton();
5026 javax.swing.SwingUtilities.invokeLater(new Runnable()
5031 String[] dbclasses = sf.getNonAlignmentSources();
5032 List<DbSourceProxy> otherdb;
5033 JMenu dfetch = new JMenu();
5034 JMenu ifetch = new JMenu();
5035 JMenuItem fetchr = null;
5036 int comp = 0, icomp = 0, mcomp = 15;
5037 String mname = null;
5039 for (String dbclass : dbclasses)
5041 otherdb = sf.getSourceProxy(dbclass);
5042 // add a single entry for this class, or submenu allowing 'fetch
5044 if (otherdb == null || otherdb.size() < 1)
5050 mname = "From " + dbclass;
5052 if (otherdb.size() == 1)
5054 final DbSourceProxy[] dassource = otherdb
5055 .toArray(new DbSourceProxy[0]);
5056 DbSourceProxy src = otherdb.get(0);
5057 fetchr = new JMenuItem(src.getDbSource());
5058 fetchr.addActionListener(new ActionListener()
5062 public void actionPerformed(ActionEvent e)
5064 new Thread(new Runnable()
5070 boolean isNucleotide = alignPanel.alignFrame
5071 .getViewport().getAlignment()
5073 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5074 alignPanel.av.getSequenceSelection(),
5075 alignPanel.alignFrame, dassource,
5076 alignPanel.alignFrame.featureSettings,
5079 .addListener(new FetchFinishedListenerI()
5082 public void finished()
5084 AlignFrame.this.setMenusForViewport();
5087 dbRefFetcher.fetchDBRefs(false);
5093 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5094 MessageManager.formatMessage(
5095 "label.fetch_retrieve_from", new Object[]
5096 { src.getDbName() })));
5102 final DbSourceProxy[] dassource = otherdb
5103 .toArray(new DbSourceProxy[0]);
5105 DbSourceProxy src = otherdb.get(0);
5106 fetchr = new JMenuItem(MessageManager
5107 .formatMessage("label.fetch_all_param", new Object[]
5108 { src.getDbSource() }));
5109 fetchr.addActionListener(new ActionListener()
5112 public void actionPerformed(ActionEvent e)
5114 new Thread(new Runnable()
5120 boolean isNucleotide = alignPanel.alignFrame
5121 .getViewport().getAlignment()
5123 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5124 alignPanel.av.getSequenceSelection(),
5125 alignPanel.alignFrame, dassource,
5126 alignPanel.alignFrame.featureSettings,
5129 .addListener(new FetchFinishedListenerI()
5132 public void finished()
5134 AlignFrame.this.setMenusForViewport();
5137 dbRefFetcher.fetchDBRefs(false);
5143 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5144 MessageManager.formatMessage(
5145 "label.fetch_retrieve_from_all_sources",
5147 { Integer.valueOf(otherdb.size())
5149 src.getDbSource(), src.getDbName() })));
5152 // and then build the rest of the individual menus
5153 ifetch = new JMenu(MessageManager.formatMessage(
5154 "label.source_from_db_source", new Object[]
5155 { src.getDbSource() }));
5157 String imname = null;
5159 for (DbSourceProxy sproxy : otherdb)
5161 String dbname = sproxy.getDbName();
5162 String sname = dbname.length() > 5
5163 ? dbname.substring(0, 5) + "..."
5165 String msname = dbname.length() > 10
5166 ? dbname.substring(0, 10) + "..."
5170 imname = MessageManager
5171 .formatMessage("label.from_msname", new Object[]
5174 fetchr = new JMenuItem(msname);
5175 final DbSourceProxy[] dassrc = { sproxy };
5176 fetchr.addActionListener(new ActionListener()
5180 public void actionPerformed(ActionEvent e)
5182 new Thread(new Runnable()
5188 boolean isNucleotide = alignPanel.alignFrame
5189 .getViewport().getAlignment()
5191 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5192 alignPanel.av.getSequenceSelection(),
5193 alignPanel.alignFrame, dassrc,
5194 alignPanel.alignFrame.featureSettings,
5197 .addListener(new FetchFinishedListenerI()
5200 public void finished()
5202 AlignFrame.this.setMenusForViewport();
5205 dbRefFetcher.fetchDBRefs(false);
5211 fetchr.setToolTipText(
5212 "<html>" + MessageManager.formatMessage(
5213 "label.fetch_retrieve_from", new Object[]
5217 if (++icomp >= mcomp || i == (otherdb.size()))
5219 ifetch.setText(MessageManager.formatMessage(
5220 "label.source_to_target", imname, sname));
5222 ifetch = new JMenu();
5230 if (comp >= mcomp || dbi >= (dbclasses.length))
5232 dfetch.setText(MessageManager.formatMessage(
5233 "label.source_to_target", mname, dbclass));
5235 dfetch = new JMenu();
5248 * Left justify the whole alignment.
5251 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5253 AlignmentI al = viewport.getAlignment();
5255 viewport.firePropertyChange("alignment", null, al);
5259 * Right justify the whole alignment.
5262 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5264 AlignmentI al = viewport.getAlignment();
5266 viewport.firePropertyChange("alignment", null, al);
5270 public void setShowSeqFeatures(boolean b)
5272 showSeqFeatures.setSelected(b);
5273 viewport.setShowSequenceFeatures(b);
5280 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5281 * awt.event.ActionEvent)
5284 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5286 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5287 alignPanel.paintAlignment(false, false);
5294 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5298 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5300 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5301 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5309 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5310 * .event.ActionEvent)
5313 protected void showGroupConservation_actionPerformed(ActionEvent e)
5315 viewport.setShowGroupConservation(showGroupConservation.getState());
5316 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5323 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5324 * .event.ActionEvent)
5327 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5329 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5330 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5337 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5338 * .event.ActionEvent)
5341 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5343 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5344 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5348 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5350 showSequenceLogo.setState(true);
5351 viewport.setShowSequenceLogo(true);
5352 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5353 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5357 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5359 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5366 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5367 * .event.ActionEvent)
5370 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5372 if (avc.makeGroupsFromSelection())
5374 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5375 alignPanel.updateAnnotation();
5376 alignPanel.paintAlignment(true, true);
5380 public void clearAlignmentSeqRep()
5382 // TODO refactor alignmentseqrep to controller
5383 if (viewport.getAlignment().hasSeqrep())
5385 viewport.getAlignment().setSeqrep(null);
5386 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5387 alignPanel.updateAnnotation();
5388 alignPanel.paintAlignment(true, true);
5393 protected void createGroup_actionPerformed(ActionEvent e)
5395 if (avc.createGroup())
5397 if (applyAutoAnnotationSettings.isSelected())
5399 alignPanel.updateAnnotation(true, false);
5401 alignPanel.alignmentChanged();
5406 protected void unGroup_actionPerformed(ActionEvent e)
5410 alignPanel.alignmentChanged();
5415 * make the given alignmentPanel the currently selected tab
5417 * @param alignmentPanel
5419 public void setDisplayedView(AlignmentPanel alignmentPanel)
5421 if (!viewport.getSequenceSetId()
5422 .equals(alignmentPanel.av.getSequenceSetId()))
5424 throw new Error(MessageManager.getString(
5425 "error.implementation_error_cannot_show_view_alignment_frame"));
5427 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5428 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5430 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5435 * Action on selection of menu options to Show or Hide annotations.
5438 * @param forSequences
5439 * update sequence-related annotations
5440 * @param forAlignment
5441 * update non-sequence-related annotations
5444 protected void setAnnotationsVisibility(boolean visible,
5445 boolean forSequences, boolean forAlignment)
5447 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5448 .getAlignmentAnnotation();
5453 for (AlignmentAnnotation aa : anns)
5456 * don't display non-positional annotations on an alignment
5458 if (aa.annotations == null)
5462 boolean apply = (aa.sequenceRef == null && forAlignment)
5463 || (aa.sequenceRef != null && forSequences);
5466 aa.visible = visible;
5469 alignPanel.validateAnnotationDimensions(true);
5470 alignPanel.alignmentChanged();
5474 * Store selected annotation sort order for the view and repaint.
5477 protected void sortAnnotations_actionPerformed()
5479 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5481 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5482 alignPanel.paintAlignment(false, false);
5487 * @return alignment panels in this alignment frame
5489 public List<? extends AlignmentViewPanel> getAlignPanels()
5491 // alignPanels is never null
5492 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5497 * Open a new alignment window, with the cDNA associated with this (protein)
5498 * alignment, aligned as is the protein.
5500 protected void viewAsCdna_actionPerformed()
5502 // TODO no longer a menu action - refactor as required
5503 final AlignmentI alignment = getViewport().getAlignment();
5504 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5505 if (mappings == null)
5509 List<SequenceI> cdnaSeqs = new ArrayList<>();
5510 for (SequenceI aaSeq : alignment.getSequences())
5512 for (AlignedCodonFrame acf : mappings)
5514 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5518 * There is a cDNA mapping for this protein sequence - add to new
5519 * alignment. It will share the same dataset sequence as other mapped
5520 * cDNA (no new mappings need to be created).
5522 final Sequence newSeq = new Sequence(dnaSeq);
5523 newSeq.setDatasetSequence(dnaSeq);
5524 cdnaSeqs.add(newSeq);
5528 if (cdnaSeqs.size() == 0)
5530 // show a warning dialog no mapped cDNA
5533 AlignmentI cdna = new Alignment(
5534 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5535 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5536 AlignFrame.DEFAULT_HEIGHT);
5537 cdna.alignAs(alignment);
5538 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5540 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5541 AlignFrame.DEFAULT_HEIGHT);
5545 * Set visibility of dna/protein complement view (available when shown in a
5551 protected void showComplement_actionPerformed(boolean show)
5553 SplitContainerI sf = getSplitViewContainer();
5556 sf.setComplementVisible(this, show);
5561 * Generate the reverse (optionally complemented) of the selected sequences,
5562 * and add them to the alignment
5565 protected void showReverse_actionPerformed(boolean complement)
5567 AlignmentI al = null;
5570 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5571 al = dna.reverseCdna(complement);
5572 viewport.addAlignment(al, "");
5573 addHistoryItem(new EditCommand(
5574 MessageManager.getString("label.add_sequences"), Action.PASTE,
5575 al.getSequencesArray(), 0, al.getWidth(),
5576 viewport.getAlignment()));
5577 } catch (Exception ex)
5579 System.err.println(ex.getMessage());
5585 * Try to run a script in the Groovy console, having first ensured that this
5586 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5587 * be targeted at this alignment.
5590 protected void runGroovy_actionPerformed()
5592 Jalview.setCurrentAlignFrame(this);
5593 groovy.ui.Console console = Desktop.getGroovyConsole();
5594 if (console != null)
5598 console.runScript();
5599 } catch (Exception ex)
5601 System.err.println((ex.toString()));
5602 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5603 MessageManager.getString("label.couldnt_run_groovy_script"),
5604 MessageManager.getString("label.groovy_support_failed"),
5605 JvOptionPane.ERROR_MESSAGE);
5610 System.err.println("Can't run Groovy script as console not found");
5615 * Hides columns containing (or not containing) a specified feature, provided
5616 * that would not leave all columns hidden
5618 * @param featureType
5619 * @param columnsContaining
5622 public boolean hideFeatureColumns(String featureType,
5623 boolean columnsContaining)
5625 boolean notForHiding = avc.markColumnsContainingFeatures(
5626 columnsContaining, false, false, featureType);
5629 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5630 false, featureType))
5632 getViewport().hideSelectedColumns();
5640 protected void selectHighlightedColumns_actionPerformed(
5641 ActionEvent actionEvent)
5643 // include key modifier check in case user selects from menu
5644 avc.markHighlightedColumns(
5645 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5646 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5647 | ActionEvent.CTRL_MASK)) != 0);
5651 * Rebuilds the Colour menu, including any user-defined colours which have
5652 * been loaded either on startup or during the session
5654 public void buildColourMenu()
5656 colourMenu.removeAll();
5658 colourMenu.add(applyToAllGroups);
5659 colourMenu.add(textColour);
5660 colourMenu.addSeparator();
5662 ColourMenuHelper.addMenuItems(colourMenu, this, viewport.getAlignment(),
5665 colourMenu.addSeparator();
5666 colourMenu.add(conservationMenuItem);
5667 colourMenu.add(modifyConservation);
5668 colourMenu.add(abovePIDThreshold);
5669 colourMenu.add(modifyPID);
5670 colourMenu.add(annotationColour);
5672 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5673 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5677 * Open a dialog (if not already open) that allows the user to select and
5678 * calculate PCA or Tree analysis
5680 protected void openTreePcaDialog()
5682 if (alignPanel.getCalculationDialog() == null)
5684 new CalculationChooser(AlignFrame.this);
5689 protected void loadVcf_actionPerformed()
5691 JalviewFileChooser chooser = new JalviewFileChooser(
5692 Cache.getProperty("LAST_DIRECTORY"));
5693 chooser.setFileView(new JalviewFileView());
5694 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5695 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5696 final AlignFrame us = this;
5697 chooser.setResponseHandler(0, new Runnable()
5702 String choice = chooser.getSelectedFile().getPath();
5703 Cache.setProperty("LAST_DIRECTORY", choice);
5704 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5705 new VCFLoader(choice).loadVCF(seqs, us);
5708 chooser.showOpenDialog(null);
5714 class PrintThread extends Thread
5718 public PrintThread(AlignmentPanel ap)
5723 static PageFormat pf;
5728 PrinterJob printJob = PrinterJob.getPrinterJob();
5732 printJob.setPrintable(ap, pf);
5736 printJob.setPrintable(ap);
5739 if (printJob.printDialog())
5744 } catch (Exception PrintException)
5746 PrintException.printStackTrace();