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 java.awt.BorderLayout;
24 import java.awt.Color;
25 import java.awt.Component;
26 import java.awt.Dimension;
27 import java.awt.Rectangle;
28 import java.awt.Toolkit;
29 import java.awt.datatransfer.Clipboard;
30 import java.awt.datatransfer.DataFlavor;
31 import java.awt.datatransfer.StringSelection;
32 import java.awt.datatransfer.Transferable;
33 import java.awt.dnd.DnDConstants;
34 import java.awt.dnd.DropTargetDragEvent;
35 import java.awt.dnd.DropTargetDropEvent;
36 import java.awt.dnd.DropTargetEvent;
37 import java.awt.dnd.DropTargetListener;
38 import java.awt.event.ActionEvent;
39 import java.awt.event.ActionListener;
40 import java.awt.event.FocusAdapter;
41 import java.awt.event.FocusEvent;
42 import java.awt.event.ItemEvent;
43 import java.awt.event.ItemListener;
44 import java.awt.event.KeyAdapter;
45 import java.awt.event.KeyEvent;
46 import java.awt.event.MouseEvent;
47 import java.awt.print.PageFormat;
48 import java.awt.print.PrinterJob;
49 import java.beans.PropertyChangeEvent;
51 import java.io.FileWriter;
52 import java.io.PrintWriter;
54 import java.util.ArrayList;
55 import java.util.Arrays;
56 import java.util.Deque;
57 import java.util.Enumeration;
58 import java.util.Hashtable;
59 import java.util.List;
60 import java.util.Vector;
62 import javax.swing.ButtonGroup;
63 import javax.swing.JCheckBoxMenuItem;
64 import javax.swing.JComponent;
65 import javax.swing.JEditorPane;
66 import javax.swing.JInternalFrame;
67 import javax.swing.JLabel;
68 import javax.swing.JLayeredPane;
69 import javax.swing.JMenu;
70 import javax.swing.JMenuItem;
71 import javax.swing.JPanel;
72 import javax.swing.JScrollPane;
73 import javax.swing.SwingUtilities;
75 import ext.vamsas.ServiceHandle;
76 import jalview.analysis.AlignmentSorter;
77 import jalview.analysis.AlignmentUtils;
78 import jalview.analysis.CrossRef;
79 import jalview.analysis.Dna;
80 import jalview.analysis.GeneticCodeI;
81 import jalview.analysis.ParseProperties;
82 import jalview.analysis.SequenceIdMatcher;
83 import jalview.api.AlignExportSettingsI;
84 import jalview.api.AlignViewControllerGuiI;
85 import jalview.api.AlignViewControllerI;
86 import jalview.api.AlignViewportI;
87 import jalview.api.AlignmentViewPanel;
88 import jalview.api.FeatureSettingsControllerI;
89 import jalview.api.FeatureSettingsModelI;
90 import jalview.api.SplitContainerI;
91 import jalview.api.ViewStyleI;
92 import jalview.api.analysis.SimilarityParamsI;
93 import jalview.bin.Cache;
94 import jalview.bin.Jalview;
95 import jalview.commands.CommandI;
96 import jalview.commands.EditCommand;
97 import jalview.commands.EditCommand.Action;
98 import jalview.commands.OrderCommand;
99 import jalview.commands.RemoveGapColCommand;
100 import jalview.commands.RemoveGapsCommand;
101 import jalview.commands.SlideSequencesCommand;
102 import jalview.commands.TrimRegionCommand;
103 import jalview.datamodel.AlignExportSettingsAdapter;
104 import jalview.datamodel.AlignedCodonFrame;
105 import jalview.datamodel.Alignment;
106 import jalview.datamodel.AlignmentAnnotation;
107 import jalview.datamodel.AlignmentExportData;
108 import jalview.datamodel.AlignmentI;
109 import jalview.datamodel.AlignmentOrder;
110 import jalview.datamodel.AlignmentView;
111 import jalview.datamodel.ColumnSelection;
112 import jalview.datamodel.HiddenColumns;
113 import jalview.datamodel.PDBEntry;
114 import jalview.datamodel.SeqCigar;
115 import jalview.datamodel.Sequence;
116 import jalview.datamodel.SequenceGroup;
117 import jalview.datamodel.SequenceI;
118 import jalview.gui.ColourMenuHelper.ColourChangeListener;
119 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
120 import jalview.io.AlignmentProperties;
121 import jalview.io.AnnotationFile;
122 import jalview.io.BackupFiles;
123 import jalview.io.BioJsHTMLOutput;
124 import jalview.io.DataSourceType;
125 import jalview.io.FileFormat;
126 import jalview.io.FileFormatI;
127 import jalview.io.FileFormats;
128 import jalview.io.FileLoader;
129 import jalview.io.FileParse;
130 import jalview.io.FormatAdapter;
131 import jalview.io.HtmlSvgOutput;
132 import jalview.io.IdentifyFile;
133 import jalview.io.JPredFile;
134 import jalview.io.JalviewFileChooser;
135 import jalview.io.JalviewFileView;
136 import jalview.io.JnetAnnotationMaker;
137 import jalview.io.NewickFile;
138 import jalview.io.ScoreMatrixFile;
139 import jalview.io.TCoffeeScoreFile;
140 import jalview.io.vcf.VCFLoader;
141 import jalview.jbgui.GAlignFrame;
142 import jalview.project.Jalview2XML;
143 import jalview.schemes.ColourSchemeI;
144 import jalview.schemes.ColourSchemes;
145 import jalview.schemes.ResidueColourScheme;
146 import jalview.schemes.TCoffeeColourScheme;
147 import jalview.util.ImageMaker.TYPE;
148 import jalview.util.MessageManager;
149 import jalview.util.Platform;
150 import jalview.viewmodel.AlignmentViewport;
151 import jalview.viewmodel.ViewportRanges;
152 import jalview.ws.DBRefFetcher;
153 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
154 import jalview.ws.jws1.Discoverer;
155 import jalview.ws.jws2.Jws2Discoverer;
156 import jalview.ws.jws2.jabaws2.Jws2Instance;
157 import jalview.ws.seqfetcher.DbSourceProxy;
163 * @version $Revision$
165 @SuppressWarnings("serial")
166 public class AlignFrame extends GAlignFrame implements DropTargetListener,
167 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
170 public static final int DEFAULT_WIDTH = 700;
172 public static final int DEFAULT_HEIGHT = 500;
175 * The currently displayed panel (selected tabbed view if more than one)
177 public AlignmentPanel alignPanel;
179 AlignViewport viewport;
181 public AlignViewControllerI avc;
183 List<AlignmentPanel> alignPanels = new ArrayList<>();
186 * Last format used to load or save alignments in this window
188 FileFormatI currentFileFormat = null;
191 * Current filename for this alignment
193 String fileName = null;
198 * Creates a new AlignFrame object with specific width and height.
204 public AlignFrame(AlignmentI al, int width, int height)
206 this(al, null, width, height);
210 * Creates a new AlignFrame object with specific width, height and
216 * @param sequenceSetId
218 public AlignFrame(AlignmentI al, int width, int height,
219 String sequenceSetId)
221 this(al, null, width, height, sequenceSetId);
225 * Creates a new AlignFrame object with specific width, height and
231 * @param sequenceSetId
234 public AlignFrame(AlignmentI al, int width, int height,
235 String sequenceSetId, String viewId)
237 this(al, null, width, height, sequenceSetId, viewId);
241 * new alignment window with hidden columns
245 * @param hiddenColumns
246 * ColumnSelection or null
248 * Width of alignment frame
252 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
255 this(al, hiddenColumns, width, height, null);
259 * Create alignment frame for al with hiddenColumns, a specific width and
260 * height, and specific sequenceId
263 * @param hiddenColumns
266 * @param sequenceSetId
269 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
270 int height, String sequenceSetId)
272 this(al, hiddenColumns, width, height, sequenceSetId, null);
276 * Create alignment frame for al with hiddenColumns, a specific width and
277 * height, and specific sequenceId
280 * @param hiddenColumns
283 * @param sequenceSetId
288 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
289 int height, String sequenceSetId, String viewId)
291 setSize(width, height);
293 if (al.getDataset() == null)
298 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
300 alignPanel = new AlignmentPanel(this, viewport);
302 addAlignmentPanel(alignPanel, true);
306 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
307 HiddenColumns hiddenColumns, int width, int height)
309 setSize(width, height);
311 if (al.getDataset() == null)
316 viewport = new AlignViewport(al, hiddenColumns);
318 if (hiddenSeqs != null && hiddenSeqs.length > 0)
320 viewport.hideSequence(hiddenSeqs);
322 alignPanel = new AlignmentPanel(this, viewport);
323 addAlignmentPanel(alignPanel, true);
328 * Make a new AlignFrame from existing alignmentPanels
335 public AlignFrame(AlignmentPanel ap)
339 addAlignmentPanel(ap, false);
344 * initalise the alignframe from the underlying viewport data and the
349 // setBackground(Color.white); // BH 2019
351 if (!Jalview.isHeadlessMode())
353 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
356 avc = new jalview.controller.AlignViewController(this, viewport,
358 if (viewport.getAlignmentConservationAnnotation() == null)
360 // BLOSUM62Colour.setEnabled(false);
361 conservationMenuItem.setEnabled(false);
362 modifyConservation.setEnabled(false);
363 // PIDColour.setEnabled(false);
364 // abovePIDThreshold.setEnabled(false);
365 // modifyPID.setEnabled(false);
368 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
371 if (sortby.equals("Id"))
373 sortIDMenuItem_actionPerformed(null);
375 else if (sortby.equals("Pairwise Identity"))
377 sortPairwiseMenuItem_actionPerformed(null);
381 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
383 setMenusFromViewport(viewport);
384 buildSortByAnnotationScoresMenu();
385 calculateTree.addActionListener(new ActionListener()
389 public void actionPerformed(ActionEvent e)
396 if (Desktop.getDesktopPane() != null)
398 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
399 if (!Platform.isJS())
401 addServiceListeners();
406 if (viewport.getWrapAlignment())
408 wrapMenuItem_actionPerformed(null);
411 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
413 this.overviewMenuItem_actionPerformed(null);
418 final List<AlignmentPanel> selviews = new ArrayList<>();
419 final List<AlignmentPanel> origview = new ArrayList<>();
420 final String menuLabel = MessageManager
421 .getString("label.copy_format_from");
422 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
423 new ViewSetProvider()
427 public AlignmentPanel[] getAllAlignmentPanels()
430 origview.add(alignPanel);
431 // make an array of all alignment panels except for this one
432 List<AlignmentPanel> aps = new ArrayList<>(
433 Arrays.asList(Desktop.getAlignmentPanels(null)));
434 aps.remove(AlignFrame.this.alignPanel);
435 return aps.toArray(new AlignmentPanel[aps.size()]);
437 }, selviews, new ItemListener()
441 public void itemStateChanged(ItemEvent e)
443 if (origview.size() > 0)
445 final AlignmentPanel ap = origview.get(0);
448 * Copy the ViewStyle of the selected panel to 'this one'.
449 * Don't change value of 'scaleProteinAsCdna' unless copying
452 ViewStyleI vs = selviews.get(0).getAlignViewport()
454 boolean fromSplitFrame = selviews.get(0)
455 .getAlignViewport().getCodingComplement() != null;
458 vs.setScaleProteinAsCdna(ap.getAlignViewport()
459 .getViewStyle().isScaleProteinAsCdna());
461 ap.getAlignViewport().setViewStyle(vs);
464 * Also rescale ViewStyle of SplitFrame complement if there is
465 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
466 * the whole ViewStyle (allow cDNA protein to have different
469 AlignViewportI complement = ap.getAlignViewport()
470 .getCodingComplement();
471 if (complement != null && vs.isScaleProteinAsCdna())
473 AlignFrame af = Desktop.getAlignFrameFor(complement);
474 ((SplitFrame) af.getSplitViewContainer())
476 af.setMenusForViewport();
480 ap.setSelected(true);
481 ap.alignFrame.setMenusForViewport();
486 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
487 .indexOf("devel") > -1
488 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
489 .indexOf("test") > -1)
491 formatMenu.add(vsel);
493 addFocusListener(new FocusAdapter()
496 public void focusGained(FocusEvent e)
498 Jalview.setCurrentAlignFrame(AlignFrame.this);
505 * Change the filename and format for the alignment, and enable the 'reload'
506 * button functionality.
513 public void setFileName(String file, FileFormatI format)
516 setFileFormat(format);
517 reload.setEnabled(true);
521 * JavaScript will have this, maybe others. More dependable than a file name
522 * and maintains a reference to the actual bytes loaded.
526 public void setFileObject(File file)
528 this.fileObject = file;
532 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
535 void addKeyListener()
537 addKeyListener(new KeyAdapter()
540 public void keyPressed(KeyEvent evt)
542 if (viewport.cursorMode
543 && ((evt.getKeyCode() >= KeyEvent.VK_0
544 && evt.getKeyCode() <= KeyEvent.VK_9)
545 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
546 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
547 && Character.isDigit(evt.getKeyChar()))
549 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
552 switch (evt.getKeyCode())
555 case 27: // escape key
556 alignPanel.deselectAllSequences();
560 case KeyEvent.VK_DOWN:
561 if (evt.isAltDown() || !viewport.cursorMode)
563 moveSelectedSequences(false);
565 if (viewport.cursorMode)
567 alignPanel.getSeqPanel().moveCursor(0, 1);
572 if (evt.isAltDown() || !viewport.cursorMode)
574 moveSelectedSequences(true);
576 if (viewport.cursorMode)
578 alignPanel.getSeqPanel().moveCursor(0, -1);
583 case KeyEvent.VK_LEFT:
584 if (evt.isAltDown() || !viewport.cursorMode)
586 slideSequences(false,
587 alignPanel.getSeqPanel().getKeyboardNo1());
591 alignPanel.getSeqPanel().moveCursor(-1, 0);
596 case KeyEvent.VK_RIGHT:
597 if (evt.isAltDown() || !viewport.cursorMode)
599 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
603 alignPanel.getSeqPanel().moveCursor(1, 0);
607 case KeyEvent.VK_SPACE:
608 if (viewport.cursorMode)
610 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
611 || evt.isShiftDown() || evt.isAltDown());
615 // case KeyEvent.VK_A:
616 // if (viewport.cursorMode)
618 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
619 // //System.out.println("A");
623 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
624 * System.out.println("closing bracket"); } break;
626 case KeyEvent.VK_DELETE:
627 case KeyEvent.VK_BACK_SPACE:
628 if (!viewport.cursorMode)
630 cut_actionPerformed();
634 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
635 || evt.isShiftDown() || evt.isAltDown());
641 if (viewport.cursorMode)
643 alignPanel.getSeqPanel().setCursorRow();
647 if (viewport.cursorMode && !evt.isControlDown())
649 alignPanel.getSeqPanel().setCursorColumn();
653 if (viewport.cursorMode)
655 alignPanel.getSeqPanel().setCursorPosition();
659 case KeyEvent.VK_ENTER:
660 case KeyEvent.VK_COMMA:
661 if (viewport.cursorMode)
663 alignPanel.getSeqPanel().setCursorRowAndColumn();
668 if (viewport.cursorMode)
670 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
674 if (viewport.cursorMode)
676 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
681 viewport.cursorMode = !viewport.cursorMode;
682 setStatus(MessageManager
683 .formatMessage("label.keyboard_editing_mode", new String[]
684 { (viewport.cursorMode ? "on" : "off") }));
685 if (viewport.cursorMode)
687 ViewportRanges ranges = viewport.getRanges();
688 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
690 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
693 alignPanel.getSeqPanel().seqCanvas.repaint();
699 Help.showHelpWindow();
700 } catch (Exception ex)
702 ex.printStackTrace();
707 boolean toggleSeqs = !evt.isControlDown();
708 boolean toggleCols = !evt.isShiftDown();
709 toggleHiddenRegions(toggleSeqs, toggleCols);
714 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
715 boolean modifyExisting = true; // always modify, don't clear
716 // evt.isShiftDown();
717 boolean invertHighlighted = evt.isAltDown();
718 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
722 case KeyEvent.VK_PAGE_UP:
723 viewport.getRanges().pageUp();
725 case KeyEvent.VK_PAGE_DOWN:
726 viewport.getRanges().pageDown();
732 public void keyReleased(KeyEvent evt)
734 switch (evt.getKeyCode())
736 case KeyEvent.VK_LEFT:
737 if (evt.isAltDown() || !viewport.cursorMode)
739 viewport.firePropertyChange("alignment", null,
740 viewport.getAlignment().getSequences());
744 case KeyEvent.VK_RIGHT:
745 if (evt.isAltDown() || !viewport.cursorMode)
747 viewport.firePropertyChange("alignment", null,
748 viewport.getAlignment().getSequences());
756 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
758 ap.alignFrame = this;
759 avc = new jalview.controller.AlignViewController(this, viewport,
764 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
766 int aSize = alignPanels.size();
768 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
770 if (aSize == 1 && ap.av.getViewName() == null)
772 this.getContentPane().add(ap, BorderLayout.CENTER);
778 setInitialTabVisible();
781 expandViews.setEnabled(true);
782 gatherViews.setEnabled(true);
783 tabbedPane.addTab(ap.av.getViewName(), ap);
785 ap.setVisible(false);
790 if (ap.av.isPadGaps())
792 ap.av.getAlignment().padGaps();
794 ap.av.updateConservation(ap);
795 ap.av.updateConsensus(ap);
796 ap.av.updateStrucConsensus(ap);
800 public void setInitialTabVisible()
802 expandViews.setEnabled(true);
803 gatherViews.setEnabled(true);
804 tabbedPane.setVisible(true);
805 AlignmentPanel first = alignPanels.get(0);
806 tabbedPane.addTab(first.av.getViewName(), first);
807 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
810 public AlignViewport getViewport()
815 /* Set up intrinsic listeners for dynamically generated GUI bits. */
816 private void addServiceListeners()
818 final java.beans.PropertyChangeListener thisListener;
819 Desktop.getInstance().addJalviewPropertyChangeListener("services",
820 thisListener = new java.beans.PropertyChangeListener()
823 public void propertyChange(PropertyChangeEvent evt)
825 // // System.out.println("Discoverer property change.");
826 // if (evt.getPropertyName().equals("services"))
828 SwingUtilities.invokeLater(new Runnable()
835 "Rebuild WS Menu for service change");
836 BuildWebServiceMenu();
843 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
846 public void internalFrameClosed(
847 javax.swing.event.InternalFrameEvent evt)
849 // System.out.println("deregistering discoverer listener");
850 Desktop.getInstance().removeJalviewPropertyChangeListener(
851 "services", thisListener);
852 closeMenuItem_actionPerformed(true);
855 // Finally, build the menu once to get current service state
856 new Thread(new Runnable()
861 BuildWebServiceMenu();
867 * Configure menu items that vary according to whether the alignment is
868 * nucleotide or protein
870 public void setGUINucleotide()
872 AlignmentI al = getViewport().getAlignment();
873 boolean nucleotide = al.isNucleotide();
875 loadVcf.setVisible(nucleotide);
876 showTranslation.setVisible(nucleotide);
877 showReverse.setVisible(nucleotide);
878 showReverseComplement.setVisible(nucleotide);
879 conservationMenuItem.setEnabled(!nucleotide);
881 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
882 showGroupConservation.setEnabled(!nucleotide);
884 showComplementMenuItem
885 .setText(nucleotide ? MessageManager.getString("label.protein")
886 : MessageManager.getString("label.nucleotide"));
890 * set up menus for the current viewport. This may be called after any
891 * operation that affects the data in the current view (selection changed,
892 * etc) to update the menus to reflect the new state.
895 public void setMenusForViewport()
897 setMenusFromViewport(viewport);
901 * Need to call this method when tabs are selected for multiple views, or when
902 * loading from Jalview2XML.java
907 public void setMenusFromViewport(AlignViewport av)
909 padGapsMenuitem.setSelected(av.isPadGaps());
910 colourTextMenuItem.setSelected(av.isShowColourText());
911 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
912 modifyPID.setEnabled(abovePIDThreshold.isSelected());
913 conservationMenuItem.setSelected(av.getConservationSelected());
914 modifyConservation.setEnabled(conservationMenuItem.isSelected());
915 seqLimits.setSelected(av.getShowJVSuffix());
916 idRightAlign.setSelected(av.isRightAlignIds());
917 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
918 renderGapsMenuItem.setSelected(av.isRenderGaps());
919 wrapMenuItem.setSelected(av.getWrapAlignment());
920 scaleAbove.setVisible(av.getWrapAlignment());
921 scaleLeft.setVisible(av.getWrapAlignment());
922 scaleRight.setVisible(av.getWrapAlignment());
923 annotationPanelMenuItem.setState(av.isShowAnnotation());
925 * Show/hide annotations only enabled if annotation panel is shown
927 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
928 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
929 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
930 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
931 viewBoxesMenuItem.setSelected(av.getShowBoxes());
932 viewTextMenuItem.setSelected(av.getShowText());
933 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
934 showGroupConsensus.setSelected(av.isShowGroupConsensus());
935 showGroupConservation.setSelected(av.isShowGroupConservation());
936 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
937 showSequenceLogo.setSelected(av.isShowSequenceLogo());
938 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
940 ColourMenuHelper.setColourSelected(colourMenu,
941 av.getGlobalColourScheme());
943 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
944 hiddenMarkers.setState(av.getShowHiddenMarkers());
945 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
946 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
947 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
948 autoCalculate.setSelected(av.autoCalculateConsensus);
949 sortByTree.setSelected(av.sortByTree);
950 listenToViewSelections.setSelected(av.followSelection);
952 showProducts.setEnabled(canShowProducts());
953 setGroovyEnabled(Desktop.getGroovyConsole() != null);
959 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
963 public void setGroovyEnabled(boolean b)
965 runGroovy.setEnabled(b);
968 private IProgressIndicator progressBar;
973 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
976 public void setProgressBar(String message, long id)
978 progressBar.setProgressBar(message, id);
982 public void registerHandler(final long id,
983 final IProgressIndicatorHandler handler)
985 progressBar.registerHandler(id, handler);
990 * @return true if any progress bars are still active
993 public boolean operationInProgress()
995 return progressBar.operationInProgress();
999 * Sets the text of the status bar. Note that setting a null or empty value
1000 * will cause the status bar to be hidden, with possibly undesirable flicker
1001 * of the screen layout.
1004 public void setStatus(String text)
1006 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1010 * Added so Castor Mapping file can obtain Jalview Version
1012 public String getVersion()
1014 return jalview.bin.Cache.getProperty("VERSION");
1017 public FeatureRenderer getFeatureRenderer()
1019 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1023 public void fetchSequence_actionPerformed()
1025 new SequenceFetcher(this);
1029 public void addFromFile_actionPerformed(ActionEvent e)
1031 Desktop.getInstance().inputLocalFileMenuItem_actionPerformed(viewport);
1035 public void reload_actionPerformed(ActionEvent e)
1037 if (fileName != null)
1039 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1040 // originating file's format
1041 // TODO: work out how to recover feature settings for correct view(s) when
1042 // file is reloaded.
1043 if (FileFormat.Jalview.equals(currentFileFormat))
1045 JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
1046 for (int i = 0; i < frames.length; i++)
1048 if (frames[i] instanceof AlignFrame && frames[i] != this
1049 && ((AlignFrame) frames[i]).fileName != null
1050 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1054 frames[i].setSelected(true);
1055 Desktop.getInstance().closeAssociatedWindows();
1056 } catch (java.beans.PropertyVetoException ex)
1062 Desktop.getInstance().closeAssociatedWindows();
1064 FileLoader loader = new FileLoader();
1065 DataSourceType protocol = fileName.startsWith("http:")
1066 ? DataSourceType.URL
1067 : DataSourceType.FILE;
1068 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1072 Rectangle bounds = this.getBounds();
1074 FileLoader loader = new FileLoader();
1076 AlignFrame newframe = null;
1078 if (fileObject == null)
1081 DataSourceType protocol = (fileName.startsWith("http:")
1082 ? DataSourceType.URL
1083 : DataSourceType.FILE);
1084 newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1089 newframe = loader.LoadFileWaitTillLoaded(fileObject,
1090 DataSourceType.FILE, currentFileFormat);
1093 newframe.setBounds(bounds);
1094 if (featureSettings != null && featureSettings.isShowing())
1096 final Rectangle fspos = featureSettings.frame.getBounds();
1097 // TODO: need a 'show feature settings' function that takes bounds -
1098 // need to refactor Desktop.addFrame
1099 newframe.featureSettings_actionPerformed(null);
1100 final FeatureSettings nfs = newframe.featureSettings;
1101 SwingUtilities.invokeLater(new Runnable()
1106 nfs.frame.setBounds(fspos);
1109 this.featureSettings.close();
1110 this.featureSettings = null;
1112 this.closeMenuItem_actionPerformed(true);
1118 public void addFromText_actionPerformed(ActionEvent e)
1120 Desktop.getInstance()
1121 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1125 public void addFromURL_actionPerformed(ActionEvent e)
1127 Desktop.getInstance().inputURLMenuItem_actionPerformed(viewport);
1131 public void save_actionPerformed(ActionEvent e)
1133 if (fileName == null || (currentFileFormat == null)
1134 || fileName.startsWith("http"))
1136 saveAs_actionPerformed();
1140 saveAlignment(fileName, currentFileFormat);
1145 * Saves the alignment to a file with a name chosen by the user, if necessary
1146 * warning if a file would be overwritten
1149 public void saveAs_actionPerformed()
1151 String format = currentFileFormat == null ? null
1152 : currentFileFormat.getName();
1153 JalviewFileChooser chooser = JalviewFileChooser
1154 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1156 chooser.setFileView(new JalviewFileView());
1157 chooser.setDialogTitle(
1158 MessageManager.getString("label.save_alignment_to_file"));
1159 chooser.setToolTipText(MessageManager.getString("action.save"));
1161 int value = chooser.showSaveDialog(this);
1163 if (value != JalviewFileChooser.APPROVE_OPTION)
1167 currentFileFormat = chooser.getSelectedFormat();
1168 // todo is this (2005) test now obsolete - value is never null?
1169 while (currentFileFormat == null)
1171 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
1173 .getString("label.select_file_format_before_saving"),
1174 MessageManager.getString("label.file_format_not_specified"),
1175 JvOptionPane.WARNING_MESSAGE);
1176 currentFileFormat = chooser.getSelectedFormat();
1177 value = chooser.showSaveDialog(this);
1178 if (value != JalviewFileChooser.APPROVE_OPTION)
1184 fileName = chooser.getSelectedFile().getPath();
1186 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1187 Cache.setProperty("LAST_DIRECTORY", fileName);
1188 saveAlignment(fileName, currentFileFormat);
1191 boolean lastSaveSuccessful = false;
1193 FileFormatI lastFormatSaved;
1195 String lastFilenameSaved;
1198 * Raise a dialog or status message for the last call to saveAlignment.
1200 * @return true if last call to saveAlignment(file, format) was successful.
1202 public boolean isSaveAlignmentSuccessful()
1205 if (!lastSaveSuccessful)
1207 JvOptionPane.showInternalMessageDialog(this, MessageManager
1208 .formatMessage("label.couldnt_save_file", new Object[]
1209 { lastFilenameSaved }),
1210 MessageManager.getString("label.error_saving_file"),
1211 JvOptionPane.WARNING_MESSAGE);
1216 setStatus(MessageManager.formatMessage(
1217 "label.successfully_saved_to_file_in_format", new Object[]
1218 { lastFilenameSaved, lastFormatSaved }));
1221 return lastSaveSuccessful;
1225 * Saves the alignment to the specified file path, in the specified format,
1226 * which may be an alignment format, or Jalview project format. If the
1227 * alignment has hidden regions, or the format is one capable of including
1228 * non-sequence data (features, annotations, groups), then the user may be
1229 * prompted to specify what to include in the output.
1234 public void saveAlignment(String file, FileFormatI format)
1236 lastSaveSuccessful = true;
1237 lastFilenameSaved = file;
1238 lastFormatSaved = format;
1240 if (FileFormat.Jalview.equals(format))
1242 String shortName = title;
1243 if (shortName.indexOf(File.separatorChar) > -1)
1245 shortName = shortName
1246 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
1248 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file,
1251 statusBar.setText(MessageManager.formatMessage(
1252 "label.successfully_saved_to_file_in_format", new Object[]
1253 { fileName, format }));
1258 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1259 Runnable cancelAction = new Runnable()
1264 lastSaveSuccessful = false;
1267 Runnable outputAction = new Runnable()
1272 // todo defer this to inside formatSequences (or later)
1273 AlignmentExportData exportData = viewport
1274 .getAlignExportData(options);
1275 String output = new FormatAdapter(alignPanel, options)
1276 .formatSequences(format, exportData.getAlignment(),
1277 exportData.getOmitHidden(),
1278 exportData.getStartEndPostions(),
1279 viewport.getAlignment().getHiddenColumns());
1282 lastSaveSuccessful = false;
1286 // create backupfiles object and get new temp filename destination
1287 boolean doBackup = BackupFiles.getEnabled();
1288 BackupFiles backupfiles = doBackup ? new BackupFiles(file) : null;
1291 String tempFilePath = doBackup ? backupfiles.getTempFilePath()
1293 PrintWriter out = new PrintWriter(new FileWriter(tempFilePath));
1297 AlignFrame.this.setTitle(file);
1298 statusBar.setText(MessageManager.formatMessage(
1299 "label.successfully_saved_to_file_in_format",
1301 { fileName, format.getName() }));
1302 lastSaveSuccessful = true;
1303 } catch (Exception ex)
1305 lastSaveSuccessful = false;
1306 ex.printStackTrace();
1311 backupfiles.setWriteSuccess(lastSaveSuccessful);
1312 // do the backup file roll and rename the temp file to actual file
1313 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1320 * show dialog with export options if applicable; else just do it
1322 if (AlignExportOptions.isNeeded(viewport, format))
1324 AlignExportOptions choices = new AlignExportOptions(
1325 alignPanel.getAlignViewport(), format, options);
1326 choices.setResponseAction(0, outputAction);
1327 choices.setResponseAction(1, cancelAction);
1328 choices.showDialog();
1337 * Outputs the alignment to textbox in the requested format, if necessary
1338 * first prompting the user for whether to include hidden regions or
1341 * @param fileFormatName
1344 protected void outputText_actionPerformed(String fileFormatName)
1346 FileFormatI fileFormat = FileFormats.getInstance()
1347 .forName(fileFormatName);
1348 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1349 Runnable outputAction = new Runnable()
1354 // todo defer this to inside formatSequences (or later)
1355 AlignmentExportData exportData = viewport
1356 .getAlignExportData(options);
1357 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1358 cap.setForInput(null);
1361 FileFormatI format = fileFormat;
1362 cap.setText(new FormatAdapter(alignPanel, options)
1363 .formatSequences(format, exportData.getAlignment(),
1364 exportData.getOmitHidden(),
1365 exportData.getStartEndPostions(),
1366 viewport.getAlignment().getHiddenColumns()));
1367 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1368 "label.alignment_output_command", new Object[]
1369 { fileFormat.getName() }), 600, 500);
1370 } catch (OutOfMemoryError oom)
1372 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1380 * show dialog with export options if applicable; else just do it
1382 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1384 AlignExportOptions choices = new AlignExportOptions(
1385 alignPanel.getAlignViewport(), fileFormat, options);
1386 choices.setResponseAction(0, outputAction);
1387 choices.showDialog();
1402 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1404 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1405 htmlSVG.exportHTML(null);
1409 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1411 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1412 bjs.exportHTML(null);
1416 * Creates a PNG image of the alignment and writes it to the given file. If
1417 * the file is null, the user is prompted to choose a file.
1422 public void createPNG(File f)
1424 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1428 * Creates an EPS image of the alignment and writes it to the given file. If
1429 * the file is null, the user is prompted to choose a file.
1434 public void createEPS(File f)
1436 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1440 * Creates an SVG image of the alignment and writes it to the given file. If
1441 * the file is null, the user is prompted to choose a file.
1446 public void createSVG(File f)
1448 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1452 public void pageSetup_actionPerformed(ActionEvent e)
1454 PrinterJob printJob = PrinterJob.getPrinterJob();
1455 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1465 public void printMenuItem_actionPerformed(ActionEvent e)
1467 // Putting in a thread avoids Swing painting problems
1468 PrintThread thread = new PrintThread(alignPanel);
1473 public void exportFeatures_actionPerformed(ActionEvent e)
1475 new AnnotationExporter(alignPanel).exportFeatures();
1479 public void exportAnnotations_actionPerformed(ActionEvent e)
1481 new AnnotationExporter(alignPanel).exportAnnotations();
1485 public void associatedData_actionPerformed(ActionEvent e)
1487 final JalviewFileChooser chooser = new JalviewFileChooser(
1488 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1489 chooser.setFileView(new JalviewFileView());
1490 String tooltip = MessageManager
1491 .getString("label.load_jalview_annotations");
1492 chooser.setDialogTitle(tooltip);
1493 chooser.setToolTipText(tooltip);
1494 chooser.setResponseHandler(0, new Runnable()
1499 String choice = chooser.getSelectedFile().getPath();
1500 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1501 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1505 chooser.showOpenDialog(this);
1509 * Close the current view or all views in the alignment frame. If the frame
1510 * only contains one view then the alignment will be removed from memory.
1512 * @param closeAllTabs
1515 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1517 if (alignPanels != null && alignPanels.size() < 2)
1519 closeAllTabs = true;
1524 if (alignPanels != null)
1528 if (this.isClosed())
1530 // really close all the windows - otherwise wait till
1531 // setClosed(true) is called
1532 for (int i = 0; i < alignPanels.size(); i++)
1534 AlignmentPanel ap = alignPanels.get(i);
1541 closeView(alignPanel);
1546 if (featureSettings != null && featureSettings.isOpen())
1548 featureSettings.close();
1549 featureSettings = null;
1552 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1553 * be called recursively, with the frame now in 'closed' state
1555 this.setClosed(true);
1557 } catch (Exception ex)
1559 ex.printStackTrace();
1564 * Close the specified panel and close up tabs appropriately.
1566 * @param panelToClose
1568 public void closeView(AlignmentPanel panelToClose)
1570 int index = tabbedPane.getSelectedIndex();
1571 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1572 alignPanels.remove(panelToClose);
1573 panelToClose.closePanel();
1574 panelToClose = null;
1576 tabbedPane.removeTabAt(closedindex);
1577 tabbedPane.validate();
1579 if (index > closedindex || index == tabbedPane.getTabCount())
1581 // modify currently selected tab index if necessary.
1585 this.tabSelectionChanged(index);
1591 void updateEditMenuBar()
1594 if (viewport.getHistoryList().size() > 0)
1596 undoMenuItem.setEnabled(true);
1597 CommandI command = viewport.getHistoryList().peek();
1598 undoMenuItem.setText(MessageManager
1599 .formatMessage("label.undo_command", new Object[]
1600 { command.getDescription() }));
1604 undoMenuItem.setEnabled(false);
1605 undoMenuItem.setText(MessageManager.getString("action.undo"));
1608 if (viewport.getRedoList().size() > 0)
1610 redoMenuItem.setEnabled(true);
1612 CommandI command = viewport.getRedoList().peek();
1613 redoMenuItem.setText(MessageManager
1614 .formatMessage("label.redo_command", new Object[]
1615 { command.getDescription() }));
1619 redoMenuItem.setEnabled(false);
1620 redoMenuItem.setText(MessageManager.getString("action.redo"));
1625 public void addHistoryItem(CommandI command)
1627 if (command.getSize() > 0)
1629 viewport.addToHistoryList(command);
1630 viewport.clearRedoList();
1631 updateEditMenuBar();
1632 viewport.updateHiddenColumns();
1633 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1634 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1635 // viewport.getColumnSelection()
1636 // .getHiddenColumns().size() > 0);
1642 * @return alignment objects for all views
1644 AlignmentI[] getViewAlignments()
1646 if (alignPanels != null)
1648 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1650 for (AlignmentPanel ap : alignPanels)
1652 als[i++] = ap.av.getAlignment();
1656 if (viewport != null)
1658 return new AlignmentI[] { viewport.getAlignment() };
1670 protected void undoMenuItem_actionPerformed(ActionEvent e)
1672 if (viewport.getHistoryList().isEmpty())
1676 CommandI command = viewport.getHistoryList().pop();
1677 viewport.addToRedoList(command);
1678 command.undoCommand(getViewAlignments());
1680 AlignmentViewport originalSource = getOriginatingSource(command);
1681 updateEditMenuBar();
1683 if (originalSource != null)
1685 if (originalSource != viewport)
1688 "Implementation worry: mismatch of viewport origin for undo");
1690 originalSource.updateHiddenColumns();
1691 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1693 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1694 // viewport.getColumnSelection()
1695 // .getHiddenColumns().size() > 0);
1696 originalSource.firePropertyChange("alignment", null,
1697 originalSource.getAlignment().getSequences());
1708 protected void redoMenuItem_actionPerformed(ActionEvent e)
1710 if (viewport.getRedoList().size() < 1)
1715 CommandI command = viewport.getRedoList().pop();
1716 viewport.addToHistoryList(command);
1717 command.doCommand(getViewAlignments());
1719 AlignmentViewport originalSource = getOriginatingSource(command);
1720 updateEditMenuBar();
1722 if (originalSource != null)
1725 if (originalSource != viewport)
1728 "Implementation worry: mismatch of viewport origin for redo");
1730 originalSource.updateHiddenColumns();
1731 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1733 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1734 // viewport.getColumnSelection()
1735 // .getHiddenColumns().size() > 0);
1736 originalSource.firePropertyChange("alignment", null,
1737 originalSource.getAlignment().getSequences());
1741 AlignmentViewport getOriginatingSource(CommandI command)
1743 AlignmentViewport originalSource = null;
1744 // For sequence removal and addition, we need to fire
1745 // the property change event FROM the viewport where the
1746 // original alignment was altered
1747 AlignmentI al = null;
1748 if (command instanceof EditCommand)
1750 EditCommand editCommand = (EditCommand) command;
1751 al = editCommand.getAlignment();
1752 List<Component> comps = PaintRefresher.components
1753 .get(viewport.getSequenceSetId());
1755 for (Component comp : comps)
1757 if (comp instanceof AlignmentPanel)
1759 if (al == ((AlignmentPanel) comp).av.getAlignment())
1761 originalSource = ((AlignmentPanel) comp).av;
1768 if (originalSource == null)
1770 // The original view is closed, we must validate
1771 // the current view against the closed view first
1774 PaintRefresher.validateSequences(al, viewport.getAlignment());
1777 originalSource = viewport;
1780 return originalSource;
1789 public void moveSelectedSequences(boolean up)
1791 SequenceGroup sg = viewport.getSelectionGroup();
1797 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1798 viewport.getHiddenRepSequences(), up);
1799 alignPanel.paintAlignment(true, false);
1802 synchronized void slideSequences(boolean right, int size)
1804 List<SequenceI> sg = new ArrayList<>();
1805 if (viewport.cursorMode)
1807 sg.add(viewport.getAlignment()
1808 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1810 else if (viewport.getSelectionGroup() != null
1811 && viewport.getSelectionGroup().getSize() != viewport
1812 .getAlignment().getHeight())
1814 sg = viewport.getSelectionGroup()
1815 .getSequences(viewport.getHiddenRepSequences());
1823 List<SequenceI> invertGroup = new ArrayList<>();
1825 for (SequenceI seq : viewport.getAlignment().getSequences())
1827 if (!sg.contains(seq))
1829 invertGroup.add(seq);
1833 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1835 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1836 for (int i = 0; i < invertGroup.size(); i++)
1838 seqs2[i] = invertGroup.get(i);
1841 SlideSequencesCommand ssc;
1844 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1845 viewport.getGapCharacter());
1849 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1850 viewport.getGapCharacter());
1853 int groupAdjustment = 0;
1854 if (ssc.getGapsInsertedBegin() && right)
1856 if (viewport.cursorMode)
1858 alignPanel.getSeqPanel().moveCursor(size, 0);
1862 groupAdjustment = size;
1865 else if (!ssc.getGapsInsertedBegin() && !right)
1867 if (viewport.cursorMode)
1869 alignPanel.getSeqPanel().moveCursor(-size, 0);
1873 groupAdjustment = -size;
1877 if (groupAdjustment != 0)
1879 viewport.getSelectionGroup().setStartRes(
1880 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1881 viewport.getSelectionGroup().setEndRes(
1882 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1886 * just extend the last slide command if compatible; but not if in
1887 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1889 boolean appendHistoryItem = false;
1890 Deque<CommandI> historyList = viewport.getHistoryList();
1891 boolean inSplitFrame = getSplitViewContainer() != null;
1892 if (!inSplitFrame && historyList != null && historyList.size() > 0
1893 && historyList.peek() instanceof SlideSequencesCommand)
1895 appendHistoryItem = ssc.appendSlideCommand(
1896 (SlideSequencesCommand) historyList.peek());
1899 if (!appendHistoryItem)
1901 addHistoryItem(ssc);
1914 protected void copy_actionPerformed()
1916 if (viewport.getSelectionGroup() == null)
1920 // TODO: preserve the ordering of displayed alignment annotation in any
1921 // internal paste (particularly sequence associated annotation)
1922 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1923 String[] omitHidden = null;
1925 if (viewport.hasHiddenColumns())
1927 omitHidden = viewport.getViewAsString(true);
1930 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1931 seqs, omitHidden, null);
1933 StringSelection ss = new StringSelection(output);
1937 Desktop.getInstance().internalCopy = true;
1938 // Its really worth setting the clipboard contents
1939 // to empty before setting the large StringSelection!!
1940 Toolkit.getDefaultToolkit().getSystemClipboard()
1941 .setContents(new StringSelection(""), null);
1943 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1944 Desktop.getInstance());
1945 } catch (OutOfMemoryError er)
1947 new OOMWarning("copying region", er);
1951 HiddenColumns hiddenColumns = null;
1952 if (viewport.hasHiddenColumns())
1954 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1955 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1957 // create new HiddenColumns object with copy of hidden regions
1958 // between startRes and endRes, offset by startRes
1959 hiddenColumns = new HiddenColumns(
1960 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
1961 hiddenCutoff, hiddenOffset);
1964 Desktop.getInstance().jalviewClipboard = new Object[] { seqs,
1965 viewport.getAlignment().getDataset(), hiddenColumns };
1966 setStatus(MessageManager.formatMessage(
1967 "label.copied_sequences_to_clipboard", new Object[]
1968 { Integer.valueOf(seqs.length).toString() }));
1978 protected void pasteNew_actionPerformed(ActionEvent e)
1990 protected void pasteThis_actionPerformed(ActionEvent e)
1996 * Paste contents of Jalview clipboard
1998 * @param newAlignment
1999 * true to paste to a new alignment, otherwise add to this.
2001 void paste(boolean newAlignment)
2003 boolean externalPaste = true;
2004 Desktop d = Desktop.getInstance();
2007 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2008 Transferable contents = c.getContents(this);
2010 if (contents == null)
2019 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2020 if (str.length() < 1)
2025 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2027 } catch (OutOfMemoryError er)
2029 new OOMWarning("Out of memory pasting sequences!!", er);
2033 SequenceI[] sequences;
2034 boolean annotationAdded = false;
2035 AlignmentI alignment = null;
2037 if (d.jalviewClipboard != null)
2039 // The clipboard was filled from within Jalview, we must use the
2041 // And dataset from the copied alignment
2042 SequenceI[] newseq = (SequenceI[]) d.jalviewClipboard[0];
2043 // be doubly sure that we create *new* sequence objects.
2044 sequences = new SequenceI[newseq.length];
2045 for (int i = 0; i < newseq.length; i++)
2047 sequences[i] = new Sequence(newseq[i]);
2049 alignment = new Alignment(sequences);
2050 externalPaste = false;
2054 // parse the clipboard as an alignment.
2055 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2057 sequences = alignment.getSequencesArray();
2061 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2067 if (d.jalviewClipboard != null)
2069 // dataset is inherited
2070 alignment.setDataset((Alignment) d.jalviewClipboard[1]);
2074 // new dataset is constructed
2075 alignment.setDataset(null);
2077 alwidth = alignment.getWidth() + 1;
2081 AlignmentI pastedal = alignment; // preserve pasted alignment object
2082 // Add pasted sequences and dataset into existing alignment.
2083 alignment = viewport.getAlignment();
2084 alwidth = alignment.getWidth() + 1;
2085 // decide if we need to import sequences from an existing dataset
2086 boolean importDs = d.jalviewClipboard != null
2087 && d.jalviewClipboard[1] != alignment.getDataset();
2088 // importDs==true instructs us to copy over new dataset sequences from
2089 // an existing alignment
2090 Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2092 // minimum dataset set
2094 for (int i = 0; i < sequences.length; i++)
2098 newDs.addElement(null);
2100 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2102 if (importDs && ds != null)
2104 if (!newDs.contains(ds))
2106 newDs.setElementAt(ds, i);
2107 ds = new Sequence(ds);
2108 // update with new dataset sequence
2109 sequences[i].setDatasetSequence(ds);
2113 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2118 // copy and derive new dataset sequence
2119 sequences[i] = sequences[i].deriveSequence();
2120 alignment.getDataset()
2121 .addSequence(sequences[i].getDatasetSequence());
2122 // TODO: avoid creation of duplicate dataset sequences with a
2123 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2125 alignment.addSequence(sequences[i]); // merges dataset
2129 newDs.clear(); // tidy up
2131 if (alignment.getAlignmentAnnotation() != null)
2133 for (AlignmentAnnotation alan : alignment
2134 .getAlignmentAnnotation())
2136 if (alan.graphGroup > fgroup)
2138 fgroup = alan.graphGroup;
2142 if (pastedal.getAlignmentAnnotation() != null)
2144 // Add any annotation attached to alignment.
2145 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2146 for (int i = 0; i < alann.length; i++)
2148 annotationAdded = true;
2149 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2151 AlignmentAnnotation newann = new AlignmentAnnotation(
2153 if (newann.graphGroup > -1)
2155 if (newGraphGroups.size() <= newann.graphGroup
2156 || newGraphGroups.get(newann.graphGroup) == null)
2158 for (int q = newGraphGroups
2159 .size(); q <= newann.graphGroup; q++)
2161 newGraphGroups.add(q, null);
2163 newGraphGroups.set(newann.graphGroup,
2164 Integer.valueOf(++fgroup));
2166 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2170 newann.padAnnotation(alwidth);
2171 alignment.addAnnotation(newann);
2181 addHistoryItem(new EditCommand(
2182 MessageManager.getString("label.add_sequences"),
2183 Action.PASTE, sequences, 0, alignment.getWidth(),
2186 // Add any annotations attached to sequences
2187 for (int i = 0; i < sequences.length; i++)
2189 if (sequences[i].getAnnotation() != null)
2191 AlignmentAnnotation newann;
2192 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2194 annotationAdded = true;
2195 newann = sequences[i].getAnnotation()[a];
2196 newann.adjustForAlignment();
2197 newann.padAnnotation(alwidth);
2198 if (newann.graphGroup > -1)
2200 if (newann.graphGroup > -1)
2202 if (newGraphGroups.size() <= newann.graphGroup
2203 || newGraphGroups.get(newann.graphGroup) == null)
2205 for (int q = newGraphGroups
2206 .size(); q <= newann.graphGroup; q++)
2208 newGraphGroups.add(q, null);
2210 newGraphGroups.set(newann.graphGroup,
2211 Integer.valueOf(++fgroup));
2213 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2217 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2221 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2229 // propagate alignment changed.
2230 viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2231 if (annotationAdded)
2233 // Duplicate sequence annotation in all views.
2234 AlignmentI[] alview = this.getViewAlignments();
2235 for (int i = 0; i < sequences.length; i++)
2237 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2242 for (int avnum = 0; avnum < alview.length; avnum++)
2244 if (alview[avnum] != alignment)
2246 // duplicate in a view other than the one with input focus
2247 int avwidth = alview[avnum].getWidth() + 1;
2248 // this relies on sann being preserved after we
2249 // modify the sequence's annotation array for each duplication
2250 for (int a = 0; a < sann.length; a++)
2252 AlignmentAnnotation newann = new AlignmentAnnotation(
2254 sequences[i].addAlignmentAnnotation(newann);
2255 newann.padAnnotation(avwidth);
2256 alview[avnum].addAnnotation(newann); // annotation was
2257 // duplicated earlier
2258 // TODO JAL-1145 graphGroups are not updated for sequence
2259 // annotation added to several views. This may cause
2261 alview[avnum].setAnnotationIndex(newann, a);
2266 buildSortByAnnotationScoresMenu();
2268 viewport.firePropertyChange("alignment", null,
2269 alignment.getSequences());
2270 if (alignPanels != null)
2272 for (AlignmentPanel ap : alignPanels)
2274 ap.validateAnnotationDimensions(false);
2279 alignPanel.validateAnnotationDimensions(false);
2285 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2287 String newtitle = new String("Copied sequences");
2289 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2291 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2292 af.viewport.setHiddenColumns(hc);
2295 // >>>This is a fix for the moment, until a better solution is
2297 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2298 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2299 .getFeatureRenderer());
2301 // TODO: maintain provenance of an alignment, rather than just make the
2302 // title a concatenation of operations.
2305 if (title.startsWith("Copied sequences"))
2311 newtitle = newtitle.concat("- from " + title);
2316 newtitle = new String("Pasted sequences");
2319 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2324 } catch (Exception ex)
2326 ex.printStackTrace();
2327 System.out.println("Exception whilst pasting: " + ex);
2328 // could be anything being pasted in here
2334 protected void expand_newalign(ActionEvent e)
2338 AlignmentI alignment = AlignmentUtils
2339 .expandContext(getViewport().getAlignment(), -1);
2340 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2342 String newtitle = new String("Flanking alignment");
2343 Desktop d = Desktop.getInstance();
2344 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2346 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2347 af.viewport.setHiddenColumns(hc);
2350 // >>>This is a fix for the moment, until a better solution is
2352 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2353 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2354 .getFeatureRenderer());
2356 // TODO: maintain provenance of an alignment, rather than just make the
2357 // title a concatenation of operations.
2359 if (title.startsWith("Copied sequences"))
2365 newtitle = newtitle.concat("- from " + title);
2369 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2371 } catch (Exception ex)
2373 ex.printStackTrace();
2374 System.out.println("Exception whilst pasting: " + ex);
2375 // could be anything being pasted in here
2376 } catch (OutOfMemoryError oom)
2378 new OOMWarning("Viewing flanking region of alignment", oom);
2383 * Action Cut (delete and copy) the selected region
2386 protected void cut_actionPerformed()
2388 copy_actionPerformed();
2389 delete_actionPerformed();
2393 * Performs menu option to Delete the currently selected region
2396 protected void delete_actionPerformed()
2399 SequenceGroup sg = viewport.getSelectionGroup();
2405 Runnable okAction = new Runnable()
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(),
2416 sg.getEndRes() - sg.getStartRes() + 1,
2417 viewport.getAlignment()));
2419 viewport.setSelectionGroup(null);
2420 viewport.sendSelection();
2421 viewport.getAlignment().deleteGroup(sg);
2423 viewport.firePropertyChange("alignment", null,
2424 viewport.getAlignment().getSequences());
2425 if (viewport.getAlignment().getHeight() < 1)
2429 AlignFrame.this.setClosed(true);
2430 } catch (Exception ex)
2438 * If the cut affects all sequences, prompt for confirmation
2440 boolean wholeHeight = sg.getSize() == viewport.getAlignment()
2442 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2443 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2444 if (wholeHeight && wholeWidth)
2446 JvOptionPane dialog = JvOptionPane
2447 .newOptionDialog(Desktop.getDesktopPane());
2448 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2449 Object[] options = new Object[] {
2450 MessageManager.getString("action.ok"),
2451 MessageManager.getString("action.cancel") };
2452 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2453 MessageManager.getString("label.delete_all"),
2454 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2455 options, options[0]);
2470 protected void deleteGroups_actionPerformed(ActionEvent e)
2472 if (avc.deleteGroups())
2474 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2475 alignPanel.updateAnnotation();
2476 alignPanel.paintAlignment(true, true);
2487 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2489 alignPanel.selectAllSequences();
2499 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2501 alignPanel.deselectAllSequences();
2511 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2513 SequenceGroup sg = viewport.getSelectionGroup();
2517 alignPanel.selectAllSequences();
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.formatMessage("label.removed_columns",
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.formatMessage("label.removed_empty_columns",
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(
2781 MessageManager.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 * copy any visualisation settings that are not saved in the project
2793 newap.av.setColourAppliesToAllGroups(
2794 viewport.getColourAppliesToAllGroups());
2797 * Views share the same mappings; need to deregister any new mappings
2798 * created by copyAlignPanel, and register the new reference to the shared
2801 newap.av.replaceMappings(viewport.getAlignment());
2804 * start up cDNA consensus (if applicable) now mappings are in place
2806 if (newap.av.initComplementConsensus())
2808 newap.refresh(true); // adjust layout of annotations
2811 newap.av.setViewName(getNewViewName(viewTitle));
2813 addAlignmentPanel(newap, true);
2814 newap.alignmentChanged();
2816 if (alignPanels.size() == 2)
2818 viewport.setGatherViewsHere(true);
2820 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2825 * Make a new name for the view, ensuring it is unique within the current
2826 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2827 * these now use viewId. Unique view names are still desirable for usability.)
2832 protected String getNewViewName(String viewTitle)
2834 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2835 boolean addFirstIndex = false;
2836 if (viewTitle == null || viewTitle.trim().length() == 0)
2838 viewTitle = MessageManager.getString("action.view");
2839 addFirstIndex = true;
2843 index = 1;// we count from 1 if given a specific name
2845 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2847 List<Component> comps = PaintRefresher.components
2848 .get(viewport.getSequenceSetId());
2850 List<String> existingNames = getExistingViewNames(comps);
2852 while (existingNames.contains(newViewName))
2854 newViewName = viewTitle + " " + (++index);
2860 * Returns a list of distinct view names found in the given list of
2861 * components. View names are held on the viewport of an AlignmentPanel.
2866 protected List<String> getExistingViewNames(List<Component> comps)
2868 List<String> existingNames = new ArrayList<>();
2869 for (Component comp : comps)
2871 if (comp instanceof AlignmentPanel)
2873 AlignmentPanel ap = (AlignmentPanel) comp;
2874 if (!existingNames.contains(ap.av.getViewName()))
2876 existingNames.add(ap.av.getViewName());
2880 return existingNames;
2884 * Explode tabbed views into separate windows.
2887 public void expandViews_actionPerformed(ActionEvent e)
2889 Desktop.explodeViews(this);
2893 * Gather views in separate windows back into a tabbed presentation.
2896 public void gatherViews_actionPerformed(ActionEvent e)
2898 Desktop.getInstance().gatherViews(this);
2908 public void font_actionPerformed(ActionEvent e)
2910 new FontChooser(alignPanel);
2920 protected void seqLimit_actionPerformed(ActionEvent e)
2922 viewport.setShowJVSuffix(seqLimits.isSelected());
2924 alignPanel.getIdPanel().getIdCanvas()
2925 .setPreferredSize(alignPanel.calculateIdWidth());
2926 alignPanel.paintAlignment(true, false);
2930 public void idRightAlign_actionPerformed(ActionEvent e)
2932 viewport.setRightAlignIds(idRightAlign.isSelected());
2933 alignPanel.paintAlignment(false, false);
2937 public void centreColumnLabels_actionPerformed(ActionEvent e)
2939 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2940 alignPanel.paintAlignment(false, false);
2946 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2949 protected void followHighlight_actionPerformed()
2952 * Set the 'follow' flag on the Viewport (and scroll to position if now
2955 final boolean state = this.followHighlightMenuItem.getState();
2956 viewport.setFollowHighlight(state);
2959 alignPanel.scrollToPosition(viewport.getSearchResults());
2970 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2972 viewport.setColourText(colourTextMenuItem.isSelected());
2973 alignPanel.paintAlignment(false, false);
2983 public void wrapMenuItem_actionPerformed(ActionEvent e)
2985 scaleAbove.setVisible(wrapMenuItem.isSelected());
2986 scaleLeft.setVisible(wrapMenuItem.isSelected());
2987 scaleRight.setVisible(wrapMenuItem.isSelected());
2988 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2989 alignPanel.updateLayout();
2993 public void showAllSeqs_actionPerformed(ActionEvent e)
2995 viewport.showAllHiddenSeqs();
2999 public void showAllColumns_actionPerformed(ActionEvent e)
3001 viewport.showAllHiddenColumns();
3002 alignPanel.paintAlignment(true, true);
3003 viewport.sendSelection();
3007 public void hideSelSequences_actionPerformed(ActionEvent e)
3009 viewport.hideAllSelectedSeqs();
3013 * called by key handler and the hide all/show all menu items
3018 protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3021 boolean hide = false;
3022 SequenceGroup sg = viewport.getSelectionGroup();
3023 if (!toggleSeqs && !toggleCols)
3025 // Hide everything by the current selection - this is a hack - we do the
3026 // invert and then hide
3027 // first check that there will be visible columns after the invert.
3028 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3029 && sg.getStartRes() <= sg.getEndRes()))
3031 // now invert the sequence set, if required - empty selection implies
3032 // that no hiding is required.
3035 invertSequenceMenuItem_actionPerformed(null);
3036 sg = viewport.getSelectionGroup();
3040 viewport.expandColSelection(sg, true);
3041 // finally invert the column selection and get the new sequence
3043 invertColSel_actionPerformed(null);
3050 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3052 hideSelSequences_actionPerformed(null);
3055 else if (!(toggleCols && viewport.hasSelectedColumns()))
3057 showAllSeqs_actionPerformed(null);
3063 if (viewport.hasSelectedColumns())
3065 hideSelColumns_actionPerformed(null);
3068 viewport.setSelectionGroup(sg);
3073 showAllColumns_actionPerformed(null);
3082 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3083 * event.ActionEvent)
3086 public void hideAllButSelection_actionPerformed(ActionEvent e)
3088 toggleHiddenRegions(false, false);
3089 viewport.sendSelection();
3096 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3100 public void hideAllSelection_actionPerformed(ActionEvent e)
3102 SequenceGroup sg = viewport.getSelectionGroup();
3103 viewport.expandColSelection(sg, false);
3104 viewport.hideAllSelectedSeqs();
3105 viewport.hideSelectedColumns();
3106 alignPanel.updateLayout();
3107 alignPanel.paintAlignment(true, true);
3108 viewport.sendSelection();
3115 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3119 public void showAllhidden_actionPerformed(ActionEvent e)
3121 viewport.showAllHiddenColumns();
3122 viewport.showAllHiddenSeqs();
3123 alignPanel.paintAlignment(true, true);
3124 viewport.sendSelection();
3128 public void hideSelColumns_actionPerformed(ActionEvent e)
3130 viewport.hideSelectedColumns();
3131 alignPanel.updateLayout();
3132 alignPanel.paintAlignment(true, true);
3133 viewport.sendSelection();
3137 public void hiddenMarkers_actionPerformed(ActionEvent e)
3139 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3150 protected void scaleAbove_actionPerformed(ActionEvent e)
3152 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3153 alignPanel.updateLayout();
3154 alignPanel.paintAlignment(true, false);
3164 protected void scaleLeft_actionPerformed(ActionEvent e)
3166 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3167 alignPanel.updateLayout();
3168 alignPanel.paintAlignment(true, false);
3178 protected void scaleRight_actionPerformed(ActionEvent e)
3180 viewport.setScaleRightWrapped(scaleRight.isSelected());
3181 alignPanel.updateLayout();
3182 alignPanel.paintAlignment(true, false);
3192 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3194 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3195 alignPanel.paintAlignment(false, false);
3205 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3207 viewport.setShowText(viewTextMenuItem.isSelected());
3208 alignPanel.paintAlignment(false, false);
3218 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3220 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3221 alignPanel.paintAlignment(false, false);
3224 public FeatureSettings featureSettings;
3227 public FeatureSettingsControllerI getFeatureSettingsUI()
3229 return featureSettings;
3233 public void featureSettings_actionPerformed(ActionEvent e)
3235 showFeatureSettingsUI();
3239 public FeatureSettingsControllerI showFeatureSettingsUI()
3241 if (featureSettings != null)
3243 featureSettings.closeOldSettings();
3244 featureSettings = null;
3246 if (!showSeqFeatures.isSelected())
3248 // make sure features are actually displayed
3249 showSeqFeatures.setSelected(true);
3250 showSeqFeatures_actionPerformed(null);
3252 featureSettings = new FeatureSettings(this);
3253 return featureSettings;
3257 * Set or clear 'Show Sequence Features'
3263 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3265 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3266 alignPanel.paintAlignment(true, true);
3270 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3271 * the annotations panel as a whole.
3273 * The options to show/hide all annotations should be enabled when the panel
3274 * is shown, and disabled when the panel is hidden.
3279 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3281 final boolean setVisible = annotationPanelMenuItem.isSelected();
3282 viewport.setShowAnnotation(setVisible);
3283 this.showAllSeqAnnotations.setEnabled(setVisible);
3284 this.hideAllSeqAnnotations.setEnabled(setVisible);
3285 this.showAllAlAnnotations.setEnabled(setVisible);
3286 this.hideAllAlAnnotations.setEnabled(setVisible);
3287 alignPanel.updateLayout();
3291 public void alignmentProperties()
3294 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3297 String content = MessageManager.formatMessage("label.html_content",
3299 { contents.toString() });
3302 if (Platform.isJS())
3304 JLabel textLabel = new JLabel();
3305 textLabel.setText(content);
3306 textLabel.setBackground(Color.WHITE);
3308 pane = new JPanel(new BorderLayout());
3309 ((JPanel) pane).setOpaque(true);
3310 pane.setBackground(Color.WHITE);
3311 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3320 JEditorPane editPane = new JEditorPane("text/html", "");
3321 editPane.setEditable(false);
3322 editPane.setText(content);
3326 JInternalFrame frame = new JInternalFrame();
3328 frame.getContentPane().add(new JScrollPane(pane));
3330 Desktop.addInternalFrame(frame, MessageManager
3331 .formatMessage("label.alignment_properties", new Object[]
3332 { getTitle() }), 500, 400);
3342 public void overviewMenuItem_actionPerformed(ActionEvent e)
3344 if (alignPanel.overviewPanel != null)
3349 JInternalFrame frame = new JInternalFrame();
3351 // BH 2019.07.26 we allow for an embedded
3352 // undecorated overview with defined size
3353 frame.setName(Platform.getAppID("overview"));
3355 Dimension dim = Platform.getDimIfEmbedded(frame, -1, -1);
3356 if (dim != null && dim.width == 0)
3358 dim = null; // hidden, not embedded
3360 OverviewPanel overview = new OverviewPanel(alignPanel, dim);
3362 frame.setContentPane(overview);
3365 dim = new Dimension();
3366 // was frame.getSize(), but that is 0,0 at this point;
3370 // we are imbedding, and so we have an undecorated frame
3371 // and we can set the the frame dimensions accordingly.
3373 // allowing for unresizable option using, style="resize:none"
3374 boolean resizable = (Platform.getEmbeddedAttribute(frame,
3375 "resize") != "none");
3376 Desktop.addInternalFrame(frame, MessageManager
3377 .formatMessage("label.overview_params", new Object[]
3378 { this.getTitle() }), true, dim.width, dim.height, resizable,
3381 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3382 frame.addInternalFrameListener(
3383 new javax.swing.event.InternalFrameAdapter()
3386 public void internalFrameClosed(
3387 javax.swing.event.InternalFrameEvent evt)
3390 alignPanel.setOverviewPanel(null);
3393 if (getKeyListeners().length > 0)
3395 frame.addKeyListener(getKeyListeners()[0]);
3398 alignPanel.setOverviewPanel(overview);
3402 public void textColour_actionPerformed()
3404 new TextColourChooser().chooseColour(alignPanel, null);
3408 * public void covariationColour_actionPerformed() {
3410 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3414 public void annotationColour_actionPerformed()
3416 new AnnotationColourChooser(viewport, alignPanel);
3420 public void annotationColumn_actionPerformed(ActionEvent e)
3422 new AnnotationColumnChooser(viewport, alignPanel);
3426 * Action on the user checking or unchecking the option to apply the selected
3427 * colour scheme to all groups. If unchecked, groups may have their own
3428 * independent colour schemes.
3433 public void applyToAllGroups_actionPerformed(boolean selected)
3435 viewport.setColourAppliesToAllGroups(selected);
3439 * Action on user selecting a colour from the colour menu
3442 * the name (not the menu item label!) of the colour scheme
3445 public void changeColour_actionPerformed(String name)
3448 * 'User Defined' opens a panel to configure or load a
3449 * user-defined colour scheme
3451 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3453 new UserDefinedColours(alignPanel);
3458 * otherwise set the chosen colour scheme (or null for 'None')
3460 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3461 viewport, viewport.getAlignment(),
3462 viewport.getHiddenRepSequences());
3467 * Actions on setting or changing the alignment colour scheme
3472 public void changeColour(ColourSchemeI cs)
3474 // TODO: pull up to controller method
3475 ColourMenuHelper.setColourSelected(colourMenu, cs);
3477 viewport.setGlobalColourScheme(cs);
3479 alignPanel.paintAlignment(true, true);
3483 * Show the PID threshold slider panel
3486 protected void modifyPID_actionPerformed()
3488 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3489 alignPanel.getViewName());
3490 SliderPanel.showPIDSlider();
3494 * Show the Conservation slider panel
3497 protected void modifyConservation_actionPerformed()
3499 SliderPanel.setConservationSlider(alignPanel,
3500 viewport.getResidueShading(), alignPanel.getViewName());
3501 SliderPanel.showConservationSlider();
3505 * Action on selecting or deselecting (Colour) By Conservation
3508 public void conservationMenuItem_actionPerformed(boolean selected)
3510 modifyConservation.setEnabled(selected);
3511 viewport.setConservationSelected(selected);
3512 viewport.getResidueShading().setConservationApplied(selected);
3514 changeColour(viewport.getGlobalColourScheme());
3517 modifyConservation_actionPerformed();
3521 SliderPanel.hideConservationSlider();
3526 * Action on selecting or deselecting (Colour) Above PID Threshold
3529 public void abovePIDThreshold_actionPerformed(boolean selected)
3531 modifyPID.setEnabled(selected);
3532 viewport.setAbovePIDThreshold(selected);
3535 viewport.getResidueShading().setThreshold(0,
3536 viewport.isIgnoreGapsConsensus());
3539 changeColour(viewport.getGlobalColourScheme());
3542 modifyPID_actionPerformed();
3546 SliderPanel.hidePIDSlider();
3557 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3559 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3560 AlignmentSorter.sortByPID(viewport.getAlignment(),
3561 viewport.getAlignment().getSequenceAt(0));
3562 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3563 viewport.getAlignment()));
3564 alignPanel.paintAlignment(true, false);
3574 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3576 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3577 AlignmentSorter.sortByID(viewport.getAlignment());
3579 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3580 alignPanel.paintAlignment(true, false);
3590 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3592 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3593 AlignmentSorter.sortByLength(viewport.getAlignment());
3594 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3595 viewport.getAlignment()));
3596 alignPanel.paintAlignment(true, false);
3606 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3608 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3609 AlignmentSorter.sortByGroup(viewport.getAlignment());
3610 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3611 viewport.getAlignment()));
3613 alignPanel.paintAlignment(true, false);
3623 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3625 new RedundancyPanel(alignPanel, this);
3635 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3637 if ((viewport.getSelectionGroup() == null)
3638 || (viewport.getSelectionGroup().getSize() < 2))
3640 JvOptionPane.showInternalMessageDialog(this,
3641 MessageManager.getString(
3642 "label.you_must_select_least_two_sequences"),
3643 MessageManager.getString("label.invalid_selection"),
3644 JvOptionPane.WARNING_MESSAGE);
3648 JInternalFrame frame = new JInternalFrame();
3649 frame.setContentPane(new PairwiseAlignPanel(viewport));
3650 Desktop.addInternalFrame(frame,
3651 MessageManager.getString("action.pairwise_alignment"), 600,
3657 public void autoCalculate_actionPerformed(ActionEvent e)
3659 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3660 if (viewport.autoCalculateConsensus)
3662 viewport.firePropertyChange("alignment", null,
3663 viewport.getAlignment().getSequences());
3668 public void sortByTreeOption_actionPerformed(ActionEvent e)
3670 viewport.sortByTree = sortByTree.isSelected();
3674 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3676 viewport.followSelection = listenToViewSelections.isSelected();
3680 * Constructs a tree panel and adds it to the desktop
3683 * tree type (NJ or AV)
3685 * name of score model used to compute the tree
3687 * parameters for the distance or similarity calculation
3689 void newTreePanel(String type, String modelName,
3690 SimilarityParamsI options)
3692 String frameTitle = "";
3695 boolean onSelection = false;
3696 if (viewport.getSelectionGroup() != null
3697 && viewport.getSelectionGroup().getSize() > 0)
3699 SequenceGroup sg = viewport.getSelectionGroup();
3701 /* Decide if the selection is a column region */
3702 for (SequenceI _s : sg.getSequences())
3704 if (_s.getLength() < sg.getEndRes())
3706 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
3707 MessageManager.getString(
3708 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3709 MessageManager.getString(
3710 "label.sequences_selection_not_aligned"),
3711 JvOptionPane.WARNING_MESSAGE);
3720 if (viewport.getAlignment().getHeight() < 2)
3726 tp = new TreePanel(alignPanel, type, modelName, options);
3727 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3729 frameTitle += " from ";
3731 if (viewport.getViewName() != null)
3733 frameTitle += viewport.getViewName() + " of ";
3736 frameTitle += this.title;
3738 Dimension dim = Platform.getDimIfEmbedded(tp, 600, 500);
3739 Desktop.addInternalFrame(tp, frameTitle, dim.width, dim.height);
3750 public void addSortByOrderMenuItem(String title,
3751 final AlignmentOrder order)
3753 final JMenuItem item = new JMenuItem(MessageManager
3754 .formatMessage("action.by_title_param", new Object[]
3757 item.addActionListener(new java.awt.event.ActionListener()
3760 public void actionPerformed(ActionEvent e)
3762 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3764 // TODO: JBPNote - have to map order entries to curent SequenceI
3766 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3768 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3769 viewport.getAlignment()));
3771 alignPanel.paintAlignment(true, false);
3777 * Add a new sort by annotation score menu item
3780 * the menu to add the option to
3782 * the label used to retrieve scores for each sequence on the
3785 public void addSortByAnnotScoreMenuItem(JMenu sort,
3786 final String scoreLabel)
3788 final JMenuItem item = new JMenuItem(scoreLabel);
3790 item.addActionListener(new java.awt.event.ActionListener()
3793 public void actionPerformed(ActionEvent e)
3795 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3796 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3797 viewport.getAlignment());// ,viewport.getSelectionGroup());
3798 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3799 viewport.getAlignment()));
3800 alignPanel.paintAlignment(true, false);
3806 * last hash for alignment's annotation array - used to minimise cost of
3809 protected int _annotationScoreVectorHash;
3812 * search the alignment and rebuild the sort by annotation score submenu the
3813 * last alignment annotation vector hash is stored to minimize cost of
3814 * rebuilding in subsequence calls.
3818 public void buildSortByAnnotationScoresMenu()
3820 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3825 if (viewport.getAlignment().getAlignmentAnnotation()
3826 .hashCode() != _annotationScoreVectorHash)
3828 sortByAnnotScore.removeAll();
3829 // almost certainly a quicker way to do this - but we keep it simple
3830 Hashtable<String, String> scoreSorts = new Hashtable<>();
3831 AlignmentAnnotation aann[];
3832 for (SequenceI sqa : viewport.getAlignment().getSequences())
3834 aann = sqa.getAnnotation();
3835 for (int i = 0; aann != null && i < aann.length; i++)
3837 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3839 scoreSorts.put(aann[i].label, aann[i].label);
3843 Enumeration<String> labels = scoreSorts.keys();
3844 while (labels.hasMoreElements())
3846 addSortByAnnotScoreMenuItem(sortByAnnotScore, labels.nextElement());
3848 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3851 _annotationScoreVectorHash = viewport.getAlignment()
3852 .getAlignmentAnnotation().hashCode();
3857 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3858 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3859 * call. Listeners are added to remove the menu item when the treePanel is
3860 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3864 public void buildTreeSortMenu()
3866 sortByTreeMenu.removeAll();
3868 List<Component> comps = PaintRefresher.components
3869 .get(viewport.getSequenceSetId());
3870 List<TreePanel> treePanels = new ArrayList<>();
3871 for (Component comp : comps)
3873 if (comp instanceof TreePanel)
3875 treePanels.add((TreePanel) comp);
3879 if (treePanels.size() < 1)
3881 sortByTreeMenu.setVisible(false);
3885 sortByTreeMenu.setVisible(true);
3887 for (final TreePanel tp : treePanels)
3889 final JMenuItem item = new JMenuItem(tp.getTitle());
3890 item.addActionListener(new java.awt.event.ActionListener()
3893 public void actionPerformed(ActionEvent e)
3895 tp.sortByTree_actionPerformed();
3896 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3901 sortByTreeMenu.add(item);
3905 public boolean sortBy(AlignmentOrder alorder, String undoname)
3907 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3908 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3909 if (undoname != null)
3911 addHistoryItem(new OrderCommand(undoname, oldOrder,
3912 viewport.getAlignment()));
3914 alignPanel.paintAlignment(true, false);
3919 * Work out whether the whole set of sequences or just the selected set will
3920 * be submitted for multiple alignment.
3923 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3925 // Now, check we have enough sequences
3926 AlignmentView msa = null;
3928 if ((viewport.getSelectionGroup() != null)
3929 && (viewport.getSelectionGroup().getSize() > 1))
3931 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3932 // some common interface!
3934 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3935 * SequenceI[sz = seqs.getSize(false)];
3937 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3938 * seqs.getSequenceAt(i); }
3940 msa = viewport.getAlignmentView(true);
3942 else if (viewport.getSelectionGroup() != null
3943 && viewport.getSelectionGroup().getSize() == 1)
3945 int option = JvOptionPane.showConfirmDialog(this,
3946 MessageManager.getString("warn.oneseq_msainput_selection"),
3947 MessageManager.getString("label.invalid_selection"),
3948 JvOptionPane.OK_CANCEL_OPTION);
3949 if (option == JvOptionPane.OK_OPTION)
3951 msa = viewport.getAlignmentView(false);
3956 msa = viewport.getAlignmentView(false);
3962 * Decides what is submitted to a secondary structure prediction service: the
3963 * first sequence in the alignment, or in the current selection, or, if the
3964 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3965 * region or the whole alignment. (where the first sequence in the set is the
3966 * one that the prediction will be for).
3968 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3970 AlignmentView seqs = null;
3972 if ((viewport.getSelectionGroup() != null)
3973 && (viewport.getSelectionGroup().getSize() > 0))
3975 seqs = viewport.getAlignmentView(true);
3979 seqs = viewport.getAlignmentView(false);
3981 // limit sequences - JBPNote in future - could spawn multiple prediction
3983 // TODO: viewport.getAlignment().isAligned is a global state - the local
3984 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3985 if (!viewport.getAlignment().isAligned(false))
3987 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3988 // TODO: if seqs.getSequences().length>1 then should really have warned
4002 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4004 // Pick the tree file
4005 JalviewFileChooser chooser = new JalviewFileChooser(
4006 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4007 chooser.setFileView(new JalviewFileView());
4008 chooser.setDialogTitle(
4009 MessageManager.getString("label.select_newick_like_tree_file"));
4010 chooser.setToolTipText(
4011 MessageManager.getString("label.load_tree_file"));
4013 chooser.setResponseHandler(0, new Runnable()
4018 String filePath = chooser.getSelectedFile().getPath();
4019 Cache.setProperty("LAST_DIRECTORY", filePath);
4020 NewickFile fin = null;
4023 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4024 DataSourceType.FILE));
4025 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4026 } catch (Exception ex)
4028 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4031 .getString("label.problem_reading_tree_file"),
4032 JvOptionPane.WARNING_MESSAGE);
4033 ex.printStackTrace();
4035 if (fin != null && fin.hasWarningMessage())
4037 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4038 fin.getWarningMessage(),
4039 MessageManager.getString(
4040 "label.possible_problem_with_tree_file"),
4041 JvOptionPane.WARNING_MESSAGE);
4045 chooser.showOpenDialog(this);
4048 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4050 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4053 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4054 int h, int x, int y)
4056 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4060 * Add a treeviewer for the tree extracted from a Newick file object to the
4061 * current alignment view
4068 * Associated alignment input data (or null)
4077 * @return TreePanel handle
4079 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4080 AlignmentView input, int w, int h, int x, int y)
4082 TreePanel tp = null;
4088 if (nf.getTree() != null)
4090 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4091 Dimension dim = Platform.getDimIfEmbedded(tp, -1, -1);
4094 dim = new Dimension(w, h);
4098 // no offset, either
4101 tp.setSize(dim.width, dim.height);
4105 tp.setLocation(x, y);
4108 Desktop.addInternalFrame(tp, treeTitle, dim.width, dim.height);
4110 } catch (Exception ex)
4112 ex.printStackTrace();
4118 private boolean buildingMenu = false;
4121 * Generates menu items and listener event actions for web service clients
4124 public void BuildWebServiceMenu()
4126 while (buildingMenu)
4130 System.err.println("Waiting for building menu to finish.");
4132 } catch (Exception e)
4136 final AlignFrame me = this;
4137 buildingMenu = true;
4138 new Thread(new Runnable()
4143 final List<JMenuItem> legacyItems = new ArrayList<>();
4146 // System.err.println("Building ws menu again "
4147 // + Thread.currentThread());
4148 // TODO: add support for context dependent disabling of services based
4150 // alignment and current selection
4151 // TODO: add additional serviceHandle parameter to specify abstract
4153 // class independently of AbstractName
4154 // TODO: add in rediscovery GUI function to restart discoverer
4155 // TODO: group services by location as well as function and/or
4157 // object broker mechanism.
4158 final Vector<JMenu> wsmenu = new Vector<>();
4159 final IProgressIndicator af = me;
4162 * do not i18n these strings - they are hard-coded in class
4163 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4164 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4166 final JMenu msawsmenu = new JMenu("Alignment");
4167 final JMenu secstrmenu = new JMenu(
4168 "Secondary Structure Prediction");
4169 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4170 final JMenu analymenu = new JMenu("Analysis");
4171 final JMenu dismenu = new JMenu("Protein Disorder");
4172 // JAL-940 - only show secondary structure prediction services from
4173 // the legacy server
4174 Hashtable<String, Vector<ServiceHandle>> ds = Discoverer
4177 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4179 ds != null && (ds.size() > 0))
4181 // TODO: refactor to allow list of AbstractName/Handler bindings to
4183 // stored or retrieved from elsewhere
4184 // No MSAWS used any more:
4185 // Vector msaws = null; // (Vector)
4186 // Discoverer.services.get("MsaWS");
4187 Vector<ServiceHandle> secstrpr = ds.get("SecStrPred");
4188 if (secstrpr != null)
4190 // Add any secondary structure prediction services
4191 for (int i = 0, j = secstrpr.size(); i < j; i++)
4193 final ext.vamsas.ServiceHandle sh = secstrpr.get(i);
4194 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4195 .getServiceClient(sh);
4196 int p = secstrmenu.getItemCount();
4197 impl.attachWSMenuEntry(secstrmenu, me);
4198 int q = secstrmenu.getItemCount();
4199 for (int litm = p; litm < q; litm++)
4201 legacyItems.add(secstrmenu.getItem(litm));
4207 // Add all submenus in the order they should appear on the web
4209 wsmenu.add(msawsmenu);
4210 wsmenu.add(secstrmenu);
4211 wsmenu.add(dismenu);
4212 wsmenu.add(analymenu);
4213 // No search services yet
4214 // wsmenu.add(seqsrchmenu);
4216 javax.swing.SwingUtilities.invokeLater(new Runnable()
4223 webService.removeAll();
4224 // first, add discovered services onto the webservices menu
4225 if (wsmenu.size() > 0)
4227 for (int i = 0, j = wsmenu.size(); i < j; i++)
4229 webService.add(wsmenu.get(i));
4234 webService.add(me.webServiceNoServices);
4236 // TODO: move into separate menu builder class.
4237 boolean new_sspred = false;
4238 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4240 Jws2Discoverer jws2servs = Jws2Discoverer.getInstance();
4241 if (jws2servs != null)
4243 if (jws2servs.hasServices())
4245 jws2servs.attachWSMenuEntry(webService, me);
4246 for (Jws2Instance sv : jws2servs.getServices())
4248 if (sv.description.toLowerCase().contains("jpred"))
4250 for (JMenuItem jmi : legacyItems)
4252 jmi.setVisible(false);
4258 if (jws2servs.isRunning())
4260 JMenuItem tm = new JMenuItem(
4261 "Still discovering JABA Services");
4262 tm.setEnabled(false);
4267 build_urlServiceMenu(me.webService);
4268 build_fetchdbmenu(webService);
4269 for (JMenu item : wsmenu)
4271 if (item.getItemCount() == 0)
4273 item.setEnabled(false);
4277 item.setEnabled(true);
4280 } catch (Exception e)
4283 "Exception during web service menu building process.",
4288 } catch (Exception e)
4291 buildingMenu = false;
4298 * construct any groupURL type service menu entries.
4302 protected void build_urlServiceMenu(JMenu webService)
4304 // TODO: remove this code when 2.7 is released
4305 // DEBUG - alignmentView
4307 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4308 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4310 * @Override public void actionPerformed(ActionEvent e) {
4311 * jalview.datamodel.AlignmentView
4312 * .testSelectionViews(af.viewport.getAlignment(),
4313 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4315 * }); webService.add(testAlView);
4317 // TODO: refactor to RestClient discoverer and merge menu entries for
4318 // rest-style services with other types of analysis/calculation service
4319 // SHmmr test client - still being implemented.
4320 // DEBUG - alignmentView
4322 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4325 client.attachWSMenuEntry(
4326 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4332 * Searches the alignment sequences for xRefs and builds the Show
4333 * Cross-References menu (formerly called Show Products), with database
4334 * sources for which cross-references are found (protein sources for a
4335 * nucleotide alignment and vice versa)
4337 * @return true if Show Cross-references menu should be enabled
4339 public boolean canShowProducts()
4341 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4342 AlignmentI dataset = viewport.getAlignment().getDataset();
4344 showProducts.removeAll();
4345 final boolean dna = viewport.getAlignment().isNucleotide();
4347 if (seqs == null || seqs.length == 0)
4349 // nothing to see here.
4353 boolean showp = false;
4356 List<String> ptypes = new CrossRef(seqs, dataset)
4357 .findXrefSourcesForSequences(dna);
4359 for (final String source : ptypes)
4362 final AlignFrame af = this;
4363 JMenuItem xtype = new JMenuItem(source);
4364 xtype.addActionListener(new ActionListener()
4367 public void actionPerformed(ActionEvent e)
4369 showProductsFor(af.viewport.getSequenceSelection(), dna,
4373 showProducts.add(xtype);
4375 showProducts.setVisible(showp);
4376 showProducts.setEnabled(showp);
4377 } catch (Exception e)
4380 "canShowProducts threw an exception - please report to help@jalview.org",
4388 * Finds and displays cross-references for the selected sequences (protein
4389 * products for nucleotide sequences, dna coding sequences for peptides).
4392 * the sequences to show cross-references for
4394 * true if from a nucleotide alignment (so showing proteins)
4396 * the database to show cross-references for
4398 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4399 final String source)
4401 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4406 * Construct and display a new frame containing the translation of this
4407 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4410 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4412 AlignmentI al = null;
4415 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4417 al = dna.translateCdna(codeTable);
4418 } catch (Exception ex)
4420 jalview.bin.Cache.log.error(
4421 "Exception during translation. Please report this !", ex);
4422 final String msg = MessageManager.getString(
4423 "label.error_when_translating_sequences_submit_bug_report");
4424 final String errorTitle = MessageManager
4425 .getString("label.implementation_error")
4426 + MessageManager.getString("label.translation_failed");
4427 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4428 errorTitle, JvOptionPane.ERROR_MESSAGE);
4431 if (al == null || al.getHeight() == 0)
4433 final String msg = MessageManager.getString(
4434 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4435 final String errorTitle = MessageManager
4436 .getString("label.translation_failed");
4437 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4438 errorTitle, JvOptionPane.WARNING_MESSAGE);
4442 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4443 af.setFileFormat(this.currentFileFormat);
4444 final String newTitle = MessageManager
4445 .formatMessage("label.translation_of_params", new Object[]
4446 { this.getTitle(), codeTable.getId() });
4447 af.setTitle(newTitle);
4448 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4450 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4451 AlignViewport.openSplitFrame(this, af, new Alignment(seqs));
4455 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4462 * Set the file format
4466 public void setFileFormat(FileFormatI format)
4468 this.currentFileFormat = format;
4472 * Try to load a features file onto the alignment.
4475 * contents or path to retrieve file or a File object
4477 * access mode of file (see jalview.io.AlignFile)
4478 * @return true if features file was parsed correctly.
4480 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4483 return avc.parseFeaturesFile(file, sourceType,
4484 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4489 public void refreshFeatureUI(boolean enableIfNecessary)
4491 // note - currently this is only still here rather than in the controller
4492 // because of the featureSettings hard reference that is yet to be
4494 if (enableIfNecessary)
4496 viewport.setShowSequenceFeatures(true);
4497 showSeqFeatures.setSelected(true);
4503 public void dragEnter(DropTargetDragEvent evt)
4508 public void dragExit(DropTargetEvent evt)
4513 public void dragOver(DropTargetDragEvent evt)
4518 public void dropActionChanged(DropTargetDragEvent evt)
4523 public void drop(DropTargetDropEvent evt)
4525 // JAL-1552 - acceptDrop required before getTransferable call for
4526 // Java's Transferable for native dnd
4527 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4528 Transferable t = evt.getTransferable();
4530 final List<Object> files = new ArrayList<>();
4531 List<DataSourceType> protocols = new ArrayList<>();
4535 Desktop.transferFromDropTarget(files, protocols, evt, t);
4536 if (files.size() > 0)
4538 new Thread(new Runnable()
4543 loadDroppedFiles(files, protocols, evt, t);
4547 } catch (Exception e)
4549 e.printStackTrace();
4553 protected void loadDroppedFiles(List<Object> files,
4554 List<DataSourceType> protocols, DropTargetDropEvent evt,
4559 // check to see if any of these files have names matching sequences
4562 SequenceIdMatcher idm = new SequenceIdMatcher(
4563 viewport.getAlignment().getSequencesArray());
4565 * Object[] { String,SequenceI}
4567 ArrayList<Object[]> filesmatched = new ArrayList<>();
4568 ArrayList<Object> filesnotmatched = new ArrayList<>();
4569 for (int i = 0; i < files.size(); i++)
4572 Object file = files.get(i);
4573 String fileName = file.toString();
4575 DataSourceType protocol = (file instanceof File
4576 ? DataSourceType.FILE
4577 : FormatAdapter.checkProtocol(fileName));
4578 if (protocol == DataSourceType.FILE)
4581 if (file instanceof File)
4584 Platform.cacheFileData(fl);
4588 fl = new File(fileName);
4590 pdbfn = fl.getName();
4592 else if (protocol == DataSourceType.URL)
4594 URL url = new URL(fileName);
4595 pdbfn = url.getFile();
4597 if (pdbfn.length() > 0)
4599 // attempt to find a match in the alignment
4600 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4601 int l = 0, c = pdbfn.indexOf(".");
4602 while (mtch == null && c != -1)
4607 } while ((c = pdbfn.indexOf(".", l)) > l);
4610 pdbfn = pdbfn.substring(0, l);
4612 mtch = idm.findAllIdMatches(pdbfn);
4619 type = new IdentifyFile().identify(file, protocol);
4620 } catch (Exception ex)
4624 if (type != null && type.isStructureFile())
4626 filesmatched.add(new Object[] { file, protocol, mtch });
4630 // File wasn't named like one of the sequences or wasn't a PDB
4632 filesnotmatched.add(file);
4636 if (filesmatched.size() > 0)
4638 boolean autoAssociate = Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS",
4642 String msg = MessageManager.formatMessage(
4643 "label.automatically_associate_structure_files_with_sequences_same_name",
4645 { Integer.valueOf(filesmatched.size()).toString() });
4646 String ttl = MessageManager.getString(
4647 "label.automatically_associate_structure_files_by_name");
4648 int choice = JvOptionPane.showConfirmDialog(this, msg, ttl,
4649 JvOptionPane.YES_NO_OPTION);
4650 autoAssociate = choice == JvOptionPane.YES_OPTION;
4654 for (Object[] fm : filesmatched)
4656 // try and associate
4657 // TODO: may want to set a standard ID naming formalism for
4658 // associating PDB files which have no IDs.
4659 for (SequenceI toassoc : (SequenceI[]) fm[2])
4661 PDBEntry pe = new AssociatePdbFileWithSeq()
4662 .associatePdbWithSeq(fm[0].toString(),
4663 (DataSourceType) fm[1], toassoc, false,
4664 Desktop.getInstance());
4667 System.err.println("Associated file : " + (fm[0].toString())
4668 + " with " + toassoc.getDisplayId(true));
4672 // TODO: do we need to update overview ? only if features are
4674 alignPanel.paintAlignment(true, false);
4680 * add declined structures as sequences
4682 for (Object[] o : filesmatched)
4684 filesnotmatched.add(o[0]);
4688 if (filesnotmatched.size() > 0)
4690 if (assocfiles > 0 && (Cache
4691 .getDefault("AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4692 || JvOptionPane.showConfirmDialog(this,
4693 "<html>" + MessageManager.formatMessage(
4694 "label.ignore_unmatched_dropped_files_info",
4696 { Integer.valueOf(filesnotmatched.size())
4699 MessageManager.getString(
4700 "label.ignore_unmatched_dropped_files"),
4701 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4705 for (Object fn : filesnotmatched)
4707 loadJalviewDataFile(fn, null, null, null);
4711 } catch (Exception ex)
4713 ex.printStackTrace();
4718 * Attempt to load a "dropped" file or URL string, by testing in turn for
4720 * <li>an Annotation file</li>
4721 * <li>a JNet file</li>
4722 * <li>a features file</li>
4723 * <li>else try to interpret as an alignment file</li>
4727 * either a filename or a URL string.
4729 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4730 FileFormatI format, SequenceI assocSeq)
4732 // BH 2018 was String file
4735 if (sourceType == null)
4737 sourceType = FormatAdapter.checkProtocol(file);
4739 // if the file isn't identified, or not positively identified as some
4740 // other filetype (PFAM is default unidentified alignment file type) then
4741 // try to parse as annotation.
4742 boolean isAnnotation = (format == null
4743 || FileFormat.Pfam.equals(format))
4744 ? new AnnotationFile().annotateAlignmentView(viewport,
4750 // first see if its a T-COFFEE score file
4751 TCoffeeScoreFile tcf = null;
4754 tcf = new TCoffeeScoreFile(file, sourceType);
4757 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4761 new TCoffeeColourScheme(viewport.getAlignment()));
4762 isAnnotation = true;
4763 setStatus(MessageManager.getString(
4764 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4768 // some problem - if no warning its probable that the ID matching
4769 // process didn't work
4770 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4771 tcf.getWarningMessage() == null
4772 ? MessageManager.getString(
4773 "label.check_file_matches_sequence_ids_alignment")
4774 : tcf.getWarningMessage(),
4775 MessageManager.getString(
4776 "label.problem_reading_tcoffee_score_file"),
4777 JvOptionPane.WARNING_MESSAGE);
4784 } catch (Exception x)
4787 "Exception when processing data source as T-COFFEE score file",
4793 // try to see if its a JNet 'concise' style annotation file *before*
4795 // try to parse it as a features file
4798 format = new IdentifyFile().identify(file, sourceType);
4800 if (FileFormat.ScoreMatrix == format)
4802 ScoreMatrixFile sm = new ScoreMatrixFile(
4803 new FileParse(file, sourceType));
4805 // todo: i18n this message
4806 setStatus(MessageManager.formatMessage(
4807 "label.successfully_loaded_matrix",
4808 sm.getMatrixName()));
4810 else if (FileFormat.Jnet.equals(format))
4812 JPredFile predictions = new JPredFile(file, sourceType);
4813 new JnetAnnotationMaker();
4814 JnetAnnotationMaker.add_annotation(predictions,
4815 viewport.getAlignment(), 0, false);
4816 viewport.getAlignment().setupJPredAlignment();
4817 isAnnotation = true;
4819 // else if (IdentifyFile.FeaturesFile.equals(format))
4820 else if (FileFormat.Features.equals(format))
4822 if (parseFeaturesFile(file, sourceType))
4824 SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
4825 if (splitFrame != null)
4827 splitFrame.repaint();
4831 alignPanel.paintAlignment(true, true);
4837 new FileLoader().LoadFile(viewport, file, sourceType, format);
4843 updateForAnnotations();
4845 } catch (Exception ex)
4847 ex.printStackTrace();
4848 } catch (OutOfMemoryError oom)
4853 } catch (Exception x)
4858 + (sourceType != null
4859 ? (sourceType == DataSourceType.PASTE
4861 : "using " + sourceType + " from "
4865 ? "(parsing as '" + format + "' file)"
4867 oom, Desktop.getDesktopPane());
4872 * Do all updates necessary after an annotation file such as jnet. Also called
4873 * from Jalview.loadAppletParams for "annotations", "jnetFile"
4876 public void updateForAnnotations()
4878 alignPanel.adjustAnnotationHeight();
4879 viewport.updateSequenceIdColours();
4880 buildSortByAnnotationScoresMenu();
4881 alignPanel.paintAlignment(true, true);
4885 * Change the display state for the given feature groups -- Added by BH from
4889 * list of group strings
4891 * visible or invisible
4893 public void setFeatureGroupState(String[] groups, boolean state)
4895 jalview.api.FeatureRenderer fr = null;
4896 viewport.setShowSequenceFeatures(true);
4897 if (alignPanel != null
4898 && (fr = alignPanel.getFeatureRenderer()) != null)
4901 fr.setGroupVisibility(Arrays.asList(groups), state);
4902 alignPanel.getSeqPanel().seqCanvas.repaint();
4903 if (alignPanel.overviewPanel != null)
4905 alignPanel.overviewPanel.updateOverviewImage();
4911 * Method invoked by the ChangeListener on the tabbed pane, in other words
4912 * when a different tabbed pane is selected by the user or programmatically.
4915 public void tabSelectionChanged(int index)
4919 alignPanel = alignPanels.get(index);
4920 viewport = alignPanel.av;
4921 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4922 setMenusFromViewport(viewport);
4923 if (featureSettings != null && featureSettings.isOpen()
4924 && featureSettings.fr.getViewport() != viewport)
4926 if (viewport.isShowSequenceFeatures())
4928 // refresh the featureSettings to reflect UI change
4929 showFeatureSettingsUI();
4933 // close feature settings for this view.
4934 featureSettings.close();
4941 * 'focus' any colour slider that is open to the selected viewport
4943 if (viewport.getConservationSelected())
4945 SliderPanel.setConservationSlider(alignPanel,
4946 viewport.getResidueShading(), alignPanel.getViewName());
4950 SliderPanel.hideConservationSlider();
4952 if (viewport.getAbovePIDThreshold())
4954 SliderPanel.setPIDSliderSource(alignPanel,
4955 viewport.getResidueShading(), alignPanel.getViewName());
4959 SliderPanel.hidePIDSlider();
4963 * If there is a frame linked to this one in a SplitPane, switch it to the
4964 * same view tab index. No infinite recursion of calls should happen, since
4965 * tabSelectionChanged() should not get invoked on setting the selected
4966 * index to an unchanged value. Guard against setting an invalid index
4967 * before the new view peer tab has been created.
4969 final AlignViewportI peer = viewport.getCodingComplement();
4972 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4973 .getAlignPanel().alignFrame;
4974 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4976 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4982 * On right mouse click on view tab, prompt for and set new view name.
4985 public void tabbedPane_mousePressed(MouseEvent e)
4987 if (e.isPopupTrigger())
4989 String msg = MessageManager.getString("label.enter_view_name");
4990 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
4991 String reply = JvOptionPane.showInputDialog(msg, ttl);
4995 viewport.setViewName(reply);
4996 // TODO warn if reply is in getExistingViewNames()?
4997 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5002 public AlignViewport getCurrentView()
5008 * Open the dialog for regex description parsing.
5011 protected void extractScores_actionPerformed(ActionEvent e)
5013 ParseProperties pp = new jalview.analysis.ParseProperties(
5014 viewport.getAlignment());
5015 // TODO: verify regex and introduce GUI dialog for version 2.5
5016 // if (pp.getScoresFromDescription("col", "score column ",
5017 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5019 if (pp.getScoresFromDescription("description column",
5020 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5022 buildSortByAnnotationScoresMenu();
5030 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5034 protected void showDbRefs_actionPerformed(ActionEvent e)
5036 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5042 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5046 protected void showNpFeats_actionPerformed(ActionEvent e)
5048 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5052 * find the viewport amongst the tabs in this alignment frame and close that
5057 public boolean closeView(AlignViewportI av)
5061 this.closeMenuItem_actionPerformed(false);
5064 Component[] comp = tabbedPane.getComponents();
5065 for (int i = 0; comp != null && i < comp.length; i++)
5067 if (comp[i] instanceof AlignmentPanel)
5069 if (((AlignmentPanel) comp[i]).av == av)
5072 closeView((AlignmentPanel) comp[i]);
5080 protected void build_fetchdbmenu(JMenu webService)
5082 // Temporary hack - DBRef Fetcher always top level ws entry.
5083 // TODO We probably want to store a sequence database checklist in
5084 // preferences and have checkboxes.. rather than individual sources selected
5086 final JMenu rfetch = new JMenu(
5087 MessageManager.getString("action.fetch_db_references"));
5088 rfetch.setToolTipText(MessageManager.getString(
5089 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5090 webService.add(rfetch);
5092 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5093 MessageManager.getString("option.trim_retrieved_seqs"));
5094 trimrs.setToolTipText(
5095 MessageManager.getString("label.trim_retrieved_sequences"));
5097 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5098 trimrs.addActionListener(new ActionListener()
5101 public void actionPerformed(ActionEvent e)
5103 trimrs.setSelected(trimrs.isSelected());
5104 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5105 Boolean.valueOf(trimrs.isSelected()).toString());
5109 JMenuItem fetchr = new JMenuItem(
5110 MessageManager.getString("label.standard_databases"));
5111 fetchr.setToolTipText(
5112 MessageManager.getString("label.fetch_embl_uniprot"));
5113 fetchr.addActionListener(new ActionListener()
5117 public void actionPerformed(ActionEvent e)
5119 new Thread(new Runnable()
5124 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5125 .getAlignment().isNucleotide();
5126 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5127 alignPanel.av.getSequenceSelection(),
5128 alignPanel.alignFrame, null,
5129 alignPanel.alignFrame.featureSettings, isNucleotide);
5130 dbRefFetcher.addListener(new FetchFinishedListenerI()
5133 public void finished()
5136 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5137 .getFeatureSettingsModels())
5140 alignPanel.av.mergeFeaturesStyle(srcSettings);
5142 AlignFrame.this.setMenusForViewport();
5145 dbRefFetcher.fetchDBRefs(false);
5153 new Thread(new Runnable()
5158 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5159 .getSequenceFetcherSingleton();
5160 javax.swing.SwingUtilities.invokeLater(new Runnable()
5165 String[] dbclasses = sf.getNonAlignmentSources();
5166 List<DbSourceProxy> otherdb;
5167 JMenu dfetch = new JMenu();
5168 JMenu ifetch = new JMenu();
5169 JMenuItem fetchr = null;
5170 int comp = 0, icomp = 0, mcomp = 15;
5171 String mname = null;
5173 for (String dbclass : dbclasses)
5175 otherdb = sf.getSourceProxy(dbclass);
5176 // add a single entry for this class, or submenu allowing 'fetch
5178 if (otherdb == null || otherdb.size() < 1)
5184 mname = "From " + dbclass;
5186 if (otherdb.size() == 1)
5188 final DbSourceProxy[] dassource = otherdb
5189 .toArray(new DbSourceProxy[0]);
5190 DbSourceProxy src = otherdb.get(0);
5191 fetchr = new JMenuItem(src.getDbSource());
5192 fetchr.addActionListener(new ActionListener()
5196 public void actionPerformed(ActionEvent e)
5198 new Thread(new Runnable()
5204 boolean isNucleotide = alignPanel.alignFrame
5205 .getViewport().getAlignment()
5207 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5208 alignPanel.av.getSequenceSelection(),
5209 alignPanel.alignFrame, dassource,
5210 alignPanel.alignFrame.featureSettings,
5213 .addListener(new FetchFinishedListenerI()
5216 public void finished()
5218 FeatureSettingsModelI srcSettings = dassource[0]
5219 .getFeatureColourScheme();
5220 alignPanel.av.mergeFeaturesStyle(
5222 AlignFrame.this.setMenusForViewport();
5225 dbRefFetcher.fetchDBRefs(false);
5231 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5232 MessageManager.formatMessage(
5233 "label.fetch_retrieve_from", new Object[]
5234 { src.getDbName() })));
5240 final DbSourceProxy[] dassource = otherdb
5241 .toArray(new DbSourceProxy[0]);
5243 DbSourceProxy src = otherdb.get(0);
5244 fetchr = new JMenuItem(MessageManager
5245 .formatMessage("label.fetch_all_param", new Object[]
5246 { src.getDbSource() }));
5247 fetchr.addActionListener(new ActionListener()
5250 public void actionPerformed(ActionEvent e)
5252 new Thread(new Runnable()
5258 boolean isNucleotide = alignPanel.alignFrame
5259 .getViewport().getAlignment()
5261 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5262 alignPanel.av.getSequenceSelection(),
5263 alignPanel.alignFrame, dassource,
5264 alignPanel.alignFrame.featureSettings,
5267 .addListener(new FetchFinishedListenerI()
5270 public void finished()
5272 AlignFrame.this.setMenusForViewport();
5275 dbRefFetcher.fetchDBRefs(false);
5281 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5282 MessageManager.formatMessage(
5283 "label.fetch_retrieve_from_all_sources",
5285 { Integer.valueOf(otherdb.size())
5287 src.getDbSource(), src.getDbName() })));
5290 // and then build the rest of the individual menus
5291 ifetch = new JMenu(MessageManager.formatMessage(
5292 "label.source_from_db_source", new Object[]
5293 { src.getDbSource() }));
5295 String imname = null;
5297 for (DbSourceProxy sproxy : otherdb)
5299 String dbname = sproxy.getDbName();
5300 String sname = dbname.length() > 5
5301 ? dbname.substring(0, 5) + "..."
5303 String msname = dbname.length() > 10
5304 ? dbname.substring(0, 10) + "..."
5308 imname = MessageManager
5309 .formatMessage("label.from_msname", new Object[]
5312 fetchr = new JMenuItem(msname);
5313 final DbSourceProxy[] dassrc = { sproxy };
5314 fetchr.addActionListener(new ActionListener()
5318 public void actionPerformed(ActionEvent e)
5320 new Thread(new Runnable()
5326 boolean isNucleotide = alignPanel.alignFrame
5327 .getViewport().getAlignment()
5329 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5330 alignPanel.av.getSequenceSelection(),
5331 alignPanel.alignFrame, dassrc,
5332 alignPanel.alignFrame.featureSettings,
5335 .addListener(new FetchFinishedListenerI()
5338 public void finished()
5340 AlignFrame.this.setMenusForViewport();
5343 dbRefFetcher.fetchDBRefs(false);
5349 fetchr.setToolTipText(
5350 "<html>" + MessageManager.formatMessage(
5351 "label.fetch_retrieve_from", new Object[]
5355 if (++icomp >= mcomp || i == (otherdb.size()))
5357 ifetch.setText(MessageManager.formatMessage(
5358 "label.source_to_target", imname, sname));
5360 ifetch = new JMenu();
5368 if (comp >= mcomp || dbi >= (dbclasses.length))
5370 dfetch.setText(MessageManager.formatMessage(
5371 "label.source_to_target", mname, dbclass));
5373 dfetch = new JMenu();
5386 * Left justify the whole alignment.
5389 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5391 AlignmentI al = viewport.getAlignment();
5393 viewport.firePropertyChange("alignment", null, al);
5397 * Right justify the whole alignment.
5400 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5402 AlignmentI al = viewport.getAlignment();
5404 viewport.firePropertyChange("alignment", null, al);
5408 public void setShowSeqFeatures(boolean b)
5410 showSeqFeatures.setSelected(b);
5411 viewport.setShowSequenceFeatures(b);
5418 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5419 * awt.event.ActionEvent)
5422 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5424 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5425 alignPanel.paintAlignment(false, false);
5432 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5436 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5438 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5439 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5447 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5448 * .event.ActionEvent)
5451 protected void showGroupConservation_actionPerformed(ActionEvent e)
5453 viewport.setShowGroupConservation(showGroupConservation.getState());
5454 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5461 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5462 * .event.ActionEvent)
5465 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5467 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5468 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5475 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5476 * .event.ActionEvent)
5479 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5481 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5482 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5486 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5488 showSequenceLogo.setState(true);
5489 viewport.setShowSequenceLogo(true);
5490 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5491 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5495 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5497 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5504 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5505 * .event.ActionEvent)
5508 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5510 if (avc.makeGroupsFromSelection())
5512 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5513 alignPanel.updateAnnotation();
5514 alignPanel.paintAlignment(true,
5515 viewport.needToUpdateStructureViews());
5519 public void clearAlignmentSeqRep()
5521 // TODO refactor alignmentseqrep to controller
5522 if (viewport.getAlignment().hasSeqrep())
5524 viewport.getAlignment().setSeqrep(null);
5525 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5526 alignPanel.updateAnnotation();
5527 alignPanel.paintAlignment(true, true);
5532 protected void createGroup_actionPerformed(ActionEvent e)
5534 if (avc.createGroup())
5536 if (applyAutoAnnotationSettings.isSelected())
5538 alignPanel.updateAnnotation(true, false);
5540 alignPanel.alignmentChanged();
5545 protected void unGroup_actionPerformed(ActionEvent e)
5549 alignPanel.alignmentChanged();
5554 * make the given alignmentPanel the currently selected tab
5556 * @param alignmentPanel
5558 public void setDisplayedView(AlignmentPanel alignmentPanel)
5560 if (!viewport.getSequenceSetId()
5561 .equals(alignmentPanel.av.getSequenceSetId()))
5563 throw new Error(MessageManager.getString(
5564 "error.implementation_error_cannot_show_view_alignment_frame"));
5566 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5567 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5569 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5574 * Action on selection of menu options to Show or Hide annotations.
5577 * @param forSequences
5578 * update sequence-related annotations
5579 * @param forAlignment
5580 * update non-sequence-related annotations
5583 protected void setAnnotationsVisibility(boolean visible,
5584 boolean forSequences, boolean forAlignment)
5586 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5587 .getAlignmentAnnotation();
5592 for (AlignmentAnnotation aa : anns)
5595 * don't display non-positional annotations on an alignment
5597 if (aa.annotations == null)
5601 boolean apply = (aa.sequenceRef == null && forAlignment)
5602 || (aa.sequenceRef != null && forSequences);
5605 aa.visible = visible;
5608 alignPanel.validateAnnotationDimensions(true);
5609 alignPanel.alignmentChanged();
5613 * Store selected annotation sort order for the view and repaint.
5616 protected void sortAnnotations_actionPerformed()
5618 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5620 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5621 alignPanel.paintAlignment(false, false);
5626 * @return alignment panels in this alignment frame
5628 public List<? extends AlignmentViewPanel> getAlignPanels()
5630 // alignPanels is never null
5631 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5636 * Open a new alignment window, with the cDNA associated with this (protein)
5637 * alignment, aligned as is the protein.
5639 protected void viewAsCdna_actionPerformed()
5641 // TODO no longer a menu action - refactor as required
5642 final AlignmentI alignment = getViewport().getAlignment();
5643 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5644 if (mappings == null)
5648 List<SequenceI> cdnaSeqs = new ArrayList<>();
5649 for (SequenceI aaSeq : alignment.getSequences())
5651 for (AlignedCodonFrame acf : mappings)
5653 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5657 * There is a cDNA mapping for this protein sequence - add to new
5658 * alignment. It will share the same dataset sequence as other mapped
5659 * cDNA (no new mappings need to be created).
5661 final Sequence newSeq = new Sequence(dnaSeq);
5662 newSeq.setDatasetSequence(dnaSeq);
5663 cdnaSeqs.add(newSeq);
5667 if (cdnaSeqs.size() == 0)
5669 // show a warning dialog no mapped cDNA
5672 AlignmentI cdna = new Alignment(
5673 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5674 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5675 AlignFrame.DEFAULT_HEIGHT);
5676 cdna.alignAs(alignment);
5677 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5679 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5680 AlignFrame.DEFAULT_HEIGHT);
5684 * Set visibility of dna/protein complement view (available when shown in a
5690 protected void showComplement_actionPerformed(boolean show)
5692 SplitContainerI sf = getSplitViewContainer();
5695 sf.setComplementVisible(this, show);
5700 * Generate the reverse (optionally complemented) of the selected sequences,
5701 * and add them to the alignment
5704 protected void showReverse_actionPerformed(boolean complement)
5706 AlignmentI al = null;
5709 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5710 al = dna.reverseCdna(complement);
5711 viewport.addAlignment(al, "");
5712 addHistoryItem(new EditCommand(
5713 MessageManager.getString("label.add_sequences"), Action.PASTE,
5714 al.getSequencesArray(), 0, al.getWidth(),
5715 viewport.getAlignment()));
5716 } catch (Exception ex)
5718 System.err.println(ex.getMessage());
5724 * Try to run a script in the Groovy console, having first ensured that this
5725 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5726 * be targeted at this alignment.
5729 protected void runGroovy_actionPerformed()
5731 Jalview.setCurrentAlignFrame(this);
5732 groovy.ui.Console console = Desktop.getGroovyConsole();
5733 if (console != null)
5737 console.runScript();
5738 } catch (Exception ex)
5740 System.err.println((ex.toString()));
5741 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
5742 MessageManager.getString("label.couldnt_run_groovy_script"),
5743 MessageManager.getString("label.groovy_support_failed"),
5744 JvOptionPane.ERROR_MESSAGE);
5749 System.err.println("Can't run Groovy script as console not found");
5754 * Hides columns containing (or not containing) a specified feature, provided
5755 * that would not leave all columns hidden
5757 * @param featureType
5758 * @param columnsContaining
5761 public boolean hideFeatureColumns(String featureType,
5762 boolean columnsContaining)
5764 boolean notForHiding = avc.markColumnsContainingFeatures(
5765 columnsContaining, false, false, featureType);
5768 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5769 false, featureType))
5771 getViewport().hideSelectedColumns();
5779 protected void selectHighlightedColumns_actionPerformed(
5780 ActionEvent actionEvent)
5782 // include key modifier check in case user selects from menu
5783 avc.markHighlightedColumns(
5784 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5785 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5786 | ActionEvent.CTRL_MASK)) != 0);
5790 * Rebuilds the Colour menu, including any user-defined colours which have
5791 * been loaded either on startup or during the session
5793 public void buildColourMenu()
5795 colourMenu.removeAll();
5797 colourMenu.add(applyToAllGroups);
5798 colourMenu.add(textColour);
5799 colourMenu.addSeparator();
5801 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5802 viewport.getAlignment(), false);
5804 colourMenu.add(annotationColour);
5805 bg.add(annotationColour);
5806 colourMenu.addSeparator();
5807 colourMenu.add(conservationMenuItem);
5808 colourMenu.add(modifyConservation);
5809 colourMenu.add(abovePIDThreshold);
5810 colourMenu.add(modifyPID);
5812 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5813 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5817 * Open a dialog (if not already open) that allows the user to select and
5818 * calculate PCA or Tree analysis
5820 protected void openTreePcaDialog()
5822 if (alignPanel.getCalculationDialog() == null)
5824 new CalculationChooser(AlignFrame.this);
5829 protected void loadVcf_actionPerformed()
5831 JalviewFileChooser chooser = new JalviewFileChooser(
5832 Cache.getProperty("LAST_DIRECTORY"));
5833 chooser.setFileView(new JalviewFileView());
5834 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5835 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5836 final AlignFrame us = this;
5837 chooser.setResponseHandler(0, new Runnable()
5842 String choice = chooser.getSelectedFile().getPath();
5843 Cache.setProperty("LAST_DIRECTORY", choice);
5844 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5845 new VCFLoader(choice).loadVCF(seqs, us);
5848 chooser.showOpenDialog(null);
5852 private Rectangle lastFeatureSettingsBounds = null;
5855 public void setFeatureSettingsGeometry(Rectangle bounds)
5857 lastFeatureSettingsBounds = bounds;
5861 public Rectangle getFeatureSettingsGeometry()
5863 return lastFeatureSettingsBounds;
5866 public void scrollTo(int row, int column)
5868 alignPanel.getSeqPanel().scrollTo(row, column);
5871 public void scrollToRow(int row)
5873 alignPanel.getSeqPanel().scrollToRow(row);
5876 public void scrollToColumn(int column)
5878 alignPanel.getSeqPanel().scrollToColumn(column);
5882 * BH 2019 from JalviewLite
5884 * get sequence feature groups that are hidden or shown
5890 public String[] getFeatureGroupsOfState(boolean visible)
5892 jalview.api.FeatureRenderer fr = null;
5893 if (alignPanel != null
5894 && (fr = alignPanel.getFeatureRenderer()) != null)
5896 List<String> gps = fr.getGroups(visible);
5897 String[] _gps = gps.toArray(new String[gps.size()]);
5905 * @return list of feature groups on the view
5907 public String[] getFeatureGroups()
5909 jalview.api.FeatureRenderer fr = null;
5910 if (alignPanel != null
5911 && (fr = alignPanel.getFeatureRenderer()) != null)
5913 List<String> gps = fr.getFeatureGroups();
5914 String[] _gps = gps.toArray(new String[gps.size()]);
5920 public void select(SequenceGroup sel, ColumnSelection csel,
5921 HiddenColumns hidden)
5923 alignPanel.getSeqPanel().selection(sel, csel, hidden, null);
5928 class PrintThread extends Thread
5932 public PrintThread(AlignmentPanel ap)
5937 static PageFormat pf;
5942 PrinterJob printJob = PrinterJob.getPrinterJob();
5946 printJob.setPrintable(ap, pf);
5950 printJob.setPrintable(ap);
5953 if (printJob.printDialog())
5958 } catch (Exception PrintException)
5960 PrintException.printStackTrace();