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.GridLayout;
28 import java.awt.Rectangle;
29 import java.awt.Toolkit;
30 import java.awt.datatransfer.Clipboard;
31 import java.awt.datatransfer.DataFlavor;
32 import java.awt.datatransfer.StringSelection;
33 import java.awt.datatransfer.Transferable;
34 import java.awt.dnd.DnDConstants;
35 import java.awt.dnd.DropTargetDragEvent;
36 import java.awt.dnd.DropTargetDropEvent;
37 import java.awt.dnd.DropTargetEvent;
38 import java.awt.dnd.DropTargetListener;
39 import java.awt.event.ActionEvent;
40 import java.awt.event.ActionListener;
41 import java.awt.event.FocusAdapter;
42 import java.awt.event.FocusEvent;
43 import java.awt.event.ItemEvent;
44 import java.awt.event.ItemListener;
45 import java.awt.event.KeyAdapter;
46 import java.awt.event.KeyEvent;
47 import java.awt.event.MouseEvent;
48 import java.awt.print.PageFormat;
49 import java.awt.print.PrinterJob;
50 import java.beans.PropertyChangeEvent;
52 import java.io.FileWriter;
53 import java.io.IOException;
54 import java.io.PrintWriter;
56 import java.util.ArrayList;
57 import java.util.Arrays;
58 import java.util.Deque;
59 import java.util.Enumeration;
60 import java.util.Hashtable;
61 import java.util.List;
62 import java.util.Locale;
63 import java.util.StringTokenizer;
64 import java.util.Vector;
66 import javax.swing.ButtonGroup;
67 import javax.swing.JCheckBoxMenuItem;
68 import javax.swing.JComboBox;
69 import javax.swing.JComponent;
70 import javax.swing.JEditorPane;
71 import javax.swing.JInternalFrame;
72 import javax.swing.JLabel;
73 import javax.swing.JLayeredPane;
74 import javax.swing.JMenu;
75 import javax.swing.JMenuItem;
76 import javax.swing.JPanel;
77 import javax.swing.JScrollPane;
78 import javax.swing.SwingUtilities;
80 import ext.vamsas.ServiceHandle;
81 import jalview.analysis.AlignmentSorter;
82 import jalview.analysis.AlignmentUtils;
83 import jalview.analysis.CrossRef;
84 import jalview.analysis.Dna;
85 import jalview.analysis.GeneticCodeI;
86 import jalview.analysis.ParseProperties;
87 import jalview.analysis.SequenceIdMatcher;
88 import jalview.analysis.TreeModel;
89 import jalview.api.AlignExportSettingsI;
90 import jalview.api.AlignViewControllerGuiI;
91 import jalview.api.AlignViewControllerI;
92 import jalview.api.AlignViewportI;
93 import jalview.api.AlignmentViewPanel;
94 import jalview.api.FeatureSettingsControllerI;
95 import jalview.api.FeatureSettingsModelI;
96 import jalview.api.SplitContainerI;
97 import jalview.api.ViewStyleI;
98 import jalview.bin.Cache;
99 import jalview.bin.Console;
100 import jalview.bin.Jalview;
101 import jalview.commands.CommandI;
102 import jalview.commands.EditCommand;
103 import jalview.commands.EditCommand.Action;
104 import jalview.commands.OrderCommand;
105 import jalview.commands.RemoveGapColCommand;
106 import jalview.commands.RemoveGapsCommand;
107 import jalview.commands.SlideSequencesCommand;
108 import jalview.commands.TrimRegionCommand;
109 import jalview.datamodel.AlignExportSettingsAdapter;
110 import jalview.datamodel.AlignedCodonFrame;
111 import jalview.datamodel.Alignment;
112 import jalview.datamodel.AlignmentAnnotation;
113 import jalview.datamodel.AlignmentExportData;
114 import jalview.datamodel.AlignmentI;
115 import jalview.datamodel.AlignmentOrder;
116 import jalview.datamodel.AlignmentView;
117 import jalview.datamodel.ColumnSelection;
118 import jalview.datamodel.HiddenColumns;
119 import jalview.datamodel.PDBEntry;
120 import jalview.datamodel.SeqCigar;
121 import jalview.datamodel.Sequence;
122 import jalview.datamodel.SequenceGroup;
123 import jalview.datamodel.SequenceI;
124 import jalview.ext.archaeopteryx.AptxInit;
125 import jalview.ext.forester.io.SupportedTreeFileFilter;
126 import jalview.ext.forester.io.TreeParser;
127 import jalview.gui.ColourMenuHelper.ColourChangeListener;
128 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
129 import jalview.io.AlignmentProperties;
130 import jalview.io.AnnotationFile;
131 import jalview.io.BackupFiles;
132 import jalview.io.BioJsHTMLOutput;
133 import jalview.io.DataSourceType;
134 import jalview.io.FileFormat;
135 import jalview.io.FileFormatI;
136 import jalview.io.FileFormats;
137 import jalview.io.FileLoader;
138 import jalview.io.FileParse;
139 import jalview.io.FormatAdapter;
140 import jalview.io.HtmlSvgOutput;
141 import jalview.io.IdentifyFile;
142 import jalview.io.JPredFile;
143 import jalview.io.JalviewFileChooser;
144 import jalview.io.JalviewFileView;
145 import jalview.io.JnetAnnotationMaker;
146 import jalview.io.NewickFile;
147 import jalview.io.ScoreMatrixFile;
148 import jalview.io.TCoffeeScoreFile;
149 import jalview.io.vcf.VCFLoader;
150 import jalview.jbgui.GAlignFrame;
151 import jalview.project.Jalview2XML;
152 import jalview.schemes.ColourSchemeI;
153 import jalview.schemes.ColourSchemes;
154 import jalview.schemes.ResidueColourScheme;
155 import jalview.schemes.TCoffeeColourScheme;
156 import jalview.util.HttpUtils;
157 import jalview.util.ImageMaker.TYPE;
158 import jalview.util.MessageManager;
159 import jalview.util.Platform;
160 import jalview.viewmodel.AlignmentViewport;
161 import jalview.viewmodel.ViewportRanges;
162 import jalview.ws.DBRefFetcher;
163 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
164 import jalview.ws.jws1.Discoverer;
165 import jalview.ws.jws2.Jws2Discoverer;
166 import jalview.ws.jws2.jabaws2.Jws2Instance;
167 import jalview.ws.seqfetcher.DbSourceProxy;
173 * @version $Revision$
175 @SuppressWarnings("serial")
176 public class AlignFrame extends GAlignFrame implements DropTargetListener,
177 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
180 public static final int DEFAULT_WIDTH = 700;
182 public static final int DEFAULT_HEIGHT = 500;
185 * The currently displayed panel (selected tabbed view if more than one)
187 public AlignmentPanel alignPanel;
189 AlignViewport viewport;
191 public AlignViewControllerI avc;
193 List<AlignmentPanel> alignPanels = new ArrayList<>();
196 * Last format used to load or save alignments in this window
198 FileFormatI currentFileFormat = null;
201 * Current filename for this alignment
203 String fileName = null;
208 * Creates a new AlignFrame object with specific width and height.
214 public AlignFrame(AlignmentI al, int width, int height)
216 this(al, null, width, height);
220 * Creates a new AlignFrame object with specific width, height and
226 * @param sequenceSetId
228 public AlignFrame(AlignmentI al, int width, int height,
229 String sequenceSetId)
231 this(al, null, width, height, sequenceSetId);
235 * Creates a new AlignFrame object with specific width, height and
241 * @param sequenceSetId
244 public AlignFrame(AlignmentI al, int width, int height,
245 String sequenceSetId, String viewId)
247 this(al, null, width, height, sequenceSetId, viewId);
251 * new alignment window with hidden columns
255 * @param hiddenColumns
256 * ColumnSelection or null
258 * Width of alignment frame
262 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
265 this(al, hiddenColumns, width, height, null);
269 * Create alignment frame for al with hiddenColumns, a specific width and
270 * height, and specific sequenceId
273 * @param hiddenColumns
276 * @param sequenceSetId
279 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
280 int height, String sequenceSetId)
282 this(al, hiddenColumns, width, height, sequenceSetId, null);
286 * Create alignment frame for al with hiddenColumns, a specific width and
287 * height, and specific sequenceId
290 * @param hiddenColumns
293 * @param sequenceSetId
298 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
299 int height, String sequenceSetId, String viewId)
301 setSize(width, height);
303 if (al.getDataset() == null)
308 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
310 alignPanel = new AlignmentPanel(this, viewport);
312 addAlignmentPanel(alignPanel, true);
316 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
317 HiddenColumns hiddenColumns, int width, int height)
319 setSize(width, height);
321 if (al.getDataset() == null)
326 viewport = new AlignViewport(al, hiddenColumns);
328 if (hiddenSeqs != null && hiddenSeqs.length > 0)
330 viewport.hideSequence(hiddenSeqs);
332 alignPanel = new AlignmentPanel(this, viewport);
333 addAlignmentPanel(alignPanel, true);
338 * Make a new AlignFrame from existing alignmentPanels
345 public AlignFrame(AlignmentPanel ap)
349 addAlignmentPanel(ap, false);
354 * initalise the alignframe from the underlying viewport data and the
359 // setBackground(Color.white); // BH 2019
361 if (!Jalview.isHeadlessMode())
363 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
366 avc = new jalview.controller.AlignViewController(this, viewport,
368 if (viewport.getAlignmentConservationAnnotation() == null)
370 // BLOSUM62Colour.setEnabled(false);
371 conservationMenuItem.setEnabled(false);
372 modifyConservation.setEnabled(false);
373 // PIDColour.setEnabled(false);
374 // abovePIDThreshold.setEnabled(false);
375 // modifyPID.setEnabled(false);
378 String sortby = Cache.getDefault("SORT_ALIGNMENT", "No sort");
380 if (sortby.equals("Id"))
382 sortIDMenuItem_actionPerformed(null);
384 else if (sortby.equals("Pairwise Identity"))
386 sortPairwiseMenuItem_actionPerformed(null);
390 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
392 setMenusFromViewport(viewport);
393 buildSortByAnnotationScoresMenu();
394 calculateTree.addActionListener(new ActionListener()
398 public void actionPerformed(ActionEvent e)
405 if (Desktop.desktop != null)
407 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
408 if (!Platform.isJS())
410 addServiceListeners();
415 if (viewport.getWrapAlignment())
417 wrapMenuItem_actionPerformed(null);
420 if (Cache.getDefault("SHOW_OVERVIEW", false))
422 this.overviewMenuItem_actionPerformed(null);
427 final List<AlignmentViewPanel> selviews = new ArrayList<>();
428 final List<AlignmentPanel> origview = new ArrayList<>();
429 final String menuLabel = MessageManager
430 .getString("label.copy_format_from");
431 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
432 new ViewSetProvider()
436 public AlignmentPanel[] getAllAlignmentPanels()
439 origview.add(alignPanel);
440 // make an array of all alignment panels except for this one
441 List<AlignmentPanel> aps = new ArrayList<>(
442 Arrays.asList(Desktop.getAlignmentPanels(null)));
443 aps.remove(AlignFrame.this.alignPanel);
444 return aps.toArray(new AlignmentPanel[aps.size()]);
446 }, selviews, new ItemListener()
450 public void itemStateChanged(ItemEvent e)
452 if (origview.size() > 0)
454 final AlignmentPanel ap = origview.get(0);
457 * Copy the ViewStyle of the selected panel to 'this one'.
458 * Don't change value of 'scaleProteinAsCdna' unless copying
461 ViewStyleI vs = selviews.get(0).getAlignViewport()
463 boolean fromSplitFrame = selviews.get(0)
464 .getAlignViewport().getCodingComplement() != null;
467 vs.setScaleProteinAsCdna(ap.getAlignViewport()
468 .getViewStyle().isScaleProteinAsCdna());
470 ap.getAlignViewport().setViewStyle(vs);
473 * Also rescale ViewStyle of SplitFrame complement if there is
474 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
475 * the whole ViewStyle (allow cDNA protein to have different
478 AlignViewportI complement = ap.getAlignViewport()
479 .getCodingComplement();
480 if (complement != null && vs.isScaleProteinAsCdna())
482 AlignFrame af = Desktop.getAlignFrameFor(complement);
483 ((SplitFrame) af.getSplitViewContainer())
485 af.setMenusForViewport();
489 ap.setSelected(true);
490 ap.alignFrame.setMenusForViewport();
495 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase(Locale.ROOT)
496 .indexOf("devel") > -1
497 || Cache.getDefault("VERSION", "DEVELOPMENT")
498 .toLowerCase(Locale.ROOT).indexOf("test") > -1)
500 formatMenu.add(vsel);
502 addFocusListener(new FocusAdapter()
505 public void focusGained(FocusEvent e)
507 Jalview.setCurrentAlignFrame(AlignFrame.this);
514 * Change the filename and format for the alignment, and enable the 'reload'
515 * button functionality.
522 public void setFileName(String file, FileFormatI format)
525 setFileFormat(format);
526 reload.setEnabled(true);
530 * JavaScript will have this, maybe others. More dependable than a file name
531 * and maintains a reference to the actual bytes loaded.
535 public void setFileObject(File file)
537 this.fileObject = file;
541 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
544 void addKeyListener()
546 addKeyListener(new KeyAdapter()
549 public void keyPressed(KeyEvent evt)
551 if (viewport.cursorMode
552 && ((evt.getKeyCode() >= KeyEvent.VK_0
553 && evt.getKeyCode() <= KeyEvent.VK_9)
554 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
555 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
556 && Character.isDigit(evt.getKeyChar()))
558 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
561 switch (evt.getKeyCode())
564 case 27: // escape key
565 deselectAllSequenceMenuItem_actionPerformed(null);
569 case KeyEvent.VK_DOWN:
570 if (evt.isAltDown() || !viewport.cursorMode)
572 moveSelectedSequences(false);
574 if (viewport.cursorMode)
576 alignPanel.getSeqPanel().moveCursor(0, 1, evt.isShiftDown());
581 if (evt.isAltDown() || !viewport.cursorMode)
583 moveSelectedSequences(true);
585 if (viewport.cursorMode)
587 alignPanel.getSeqPanel().moveCursor(0, -1, evt.isShiftDown());
592 case KeyEvent.VK_LEFT:
593 if (evt.isAltDown() || !viewport.cursorMode)
595 slideSequences(false,
596 alignPanel.getSeqPanel().getKeyboardNo1());
600 alignPanel.getSeqPanel().moveCursor(-1, 0, evt.isShiftDown());
605 case KeyEvent.VK_RIGHT:
606 if (evt.isAltDown() || !viewport.cursorMode)
608 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
612 alignPanel.getSeqPanel().moveCursor(1, 0, evt.isShiftDown());
616 case KeyEvent.VK_SPACE:
617 if (viewport.cursorMode)
619 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
620 || evt.isShiftDown() || evt.isAltDown());
624 // case KeyEvent.VK_A:
625 // if (viewport.cursorMode)
627 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
628 // //System.out.println("A");
632 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
633 * System.out.println("closing bracket"); } break;
635 case KeyEvent.VK_DELETE:
636 case KeyEvent.VK_BACK_SPACE:
637 if (!viewport.cursorMode)
639 cut_actionPerformed();
643 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
644 || evt.isShiftDown() || evt.isAltDown());
650 if (viewport.cursorMode)
652 alignPanel.getSeqPanel().setCursorRow();
656 if (viewport.cursorMode && !evt.isControlDown())
658 alignPanel.getSeqPanel().setCursorColumn();
662 if (viewport.cursorMode)
664 alignPanel.getSeqPanel().setCursorPosition();
668 case KeyEvent.VK_ENTER:
669 case KeyEvent.VK_COMMA:
670 if (viewport.cursorMode)
672 alignPanel.getSeqPanel().setCursorRowAndColumn();
677 if (viewport.cursorMode)
679 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
683 if (viewport.cursorMode)
685 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
690 viewport.cursorMode = !viewport.cursorMode;
691 setStatus(MessageManager
692 .formatMessage("label.keyboard_editing_mode", new String[]
693 { (viewport.cursorMode ? "on" : "off") }));
694 if (viewport.cursorMode)
696 ViewportRanges ranges = viewport.getRanges();
697 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
699 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
702 alignPanel.getSeqPanel().seqCanvas.repaint();
708 Help.showHelpWindow();
709 } catch (Exception ex)
711 ex.printStackTrace();
716 boolean toggleSeqs = !evt.isControlDown();
717 boolean toggleCols = !evt.isShiftDown();
718 toggleHiddenRegions(toggleSeqs, toggleCols);
723 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
724 boolean modifyExisting = true; // always modify, don't clear
725 // evt.isShiftDown();
726 boolean invertHighlighted = evt.isAltDown();
727 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
731 case KeyEvent.VK_PAGE_UP:
732 viewport.getRanges().pageUp();
734 case KeyEvent.VK_PAGE_DOWN:
735 viewport.getRanges().pageDown();
741 public void keyReleased(KeyEvent evt)
743 switch (evt.getKeyCode())
745 case KeyEvent.VK_LEFT:
746 if (evt.isAltDown() || !viewport.cursorMode)
748 viewport.firePropertyChange("alignment", null,
749 viewport.getAlignment().getSequences());
753 case KeyEvent.VK_RIGHT:
754 if (evt.isAltDown() || !viewport.cursorMode)
756 viewport.firePropertyChange("alignment", null,
757 viewport.getAlignment().getSequences());
765 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
767 ap.alignFrame = this;
768 avc = new jalview.controller.AlignViewController(this, viewport,
773 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
775 int aSize = alignPanels.size();
777 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
779 if (aSize == 1 && ap.av.getViewName() == null)
781 this.getContentPane().add(ap, BorderLayout.CENTER);
787 setInitialTabVisible();
790 expandViews.setEnabled(true);
791 gatherViews.setEnabled(true);
792 tabbedPane.addTab(ap.av.getViewName(), ap);
794 ap.setVisible(false);
799 if (ap.av.isPadGaps())
801 ap.av.getAlignment().padGaps();
803 ap.av.updateConservation(ap);
804 ap.av.updateConsensus(ap);
805 ap.av.updateStrucConsensus(ap);
809 public void setInitialTabVisible()
811 expandViews.setEnabled(true);
812 gatherViews.setEnabled(true);
813 tabbedPane.setVisible(true);
814 AlignmentPanel first = alignPanels.get(0);
815 tabbedPane.addTab(first.av.getViewName(), first);
816 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
819 public AlignViewport getViewport()
824 /* Set up intrinsic listeners for dynamically generated GUI bits. */
825 private void addServiceListeners()
827 final java.beans.PropertyChangeListener thisListener;
828 Desktop.instance.addJalviewPropertyChangeListener("services",
829 thisListener = new java.beans.PropertyChangeListener()
832 public void propertyChange(PropertyChangeEvent evt)
834 // // System.out.println("Discoverer property change.");
835 // if (evt.getPropertyName().equals("services"))
837 SwingUtilities.invokeLater(new Runnable()
844 "Rebuild WS Menu for service change");
845 BuildWebServiceMenu();
852 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
855 public void internalFrameClosed(
856 javax.swing.event.InternalFrameEvent evt)
858 // System.out.println("deregistering discoverer listener");
859 Desktop.instance.removeJalviewPropertyChangeListener("services",
861 closeMenuItem_actionPerformed(true);
864 // Finally, build the menu once to get current service state
865 new Thread(new Runnable()
870 BuildWebServiceMenu();
876 * Configure menu items that vary according to whether the alignment is
877 * nucleotide or protein
879 public void setGUINucleotide()
881 AlignmentI al = getViewport().getAlignment();
882 boolean nucleotide = al.isNucleotide();
884 loadVcf.setVisible(nucleotide);
885 showTranslation.setVisible(nucleotide);
886 showReverse.setVisible(nucleotide);
887 showReverseComplement.setVisible(nucleotide);
888 conservationMenuItem.setEnabled(!nucleotide);
890 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
891 showGroupConservation.setEnabled(!nucleotide);
893 showComplementMenuItem
894 .setText(nucleotide ? MessageManager.getString("label.protein")
895 : MessageManager.getString("label.nucleotide"));
899 * set up menus for the current viewport. This may be called after any
900 * operation that affects the data in the current view (selection changed,
901 * etc) to update the menus to reflect the new state.
904 public void setMenusForViewport()
906 setMenusFromViewport(viewport);
910 * Need to call this method when tabs are selected for multiple views, or when
911 * loading from Jalview2XML.java
916 public void setMenusFromViewport(AlignViewport av)
918 padGapsMenuitem.setSelected(av.isPadGaps());
919 colourTextMenuItem.setSelected(av.isShowColourText());
920 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
921 modifyPID.setEnabled(abovePIDThreshold.isSelected());
922 conservationMenuItem.setSelected(av.getConservationSelected());
923 modifyConservation.setEnabled(conservationMenuItem.isSelected());
924 seqLimits.setSelected(av.getShowJVSuffix());
925 idRightAlign.setSelected(av.isRightAlignIds());
926 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
927 renderGapsMenuItem.setSelected(av.isRenderGaps());
928 wrapMenuItem.setSelected(av.getWrapAlignment());
929 scaleAbove.setVisible(av.getWrapAlignment());
930 scaleLeft.setVisible(av.getWrapAlignment());
931 scaleRight.setVisible(av.getWrapAlignment());
932 annotationPanelMenuItem.setState(av.isShowAnnotation());
934 * Show/hide annotations only enabled if annotation panel is shown
936 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
937 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
938 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
939 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
940 viewBoxesMenuItem.setSelected(av.getShowBoxes());
941 viewTextMenuItem.setSelected(av.getShowText());
942 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
943 showGroupConsensus.setSelected(av.isShowGroupConsensus());
944 showGroupConservation.setSelected(av.isShowGroupConservation());
945 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
946 showSequenceLogo.setSelected(av.isShowSequenceLogo());
947 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
949 ColourMenuHelper.setColourSelected(colourMenu,
950 av.getGlobalColourScheme());
952 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
953 hiddenMarkers.setState(av.getShowHiddenMarkers());
954 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
955 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
956 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
957 autoCalculate.setSelected(av.autoCalculateConsensus);
958 sortByTree.setSelected(av.sortByTree);
959 listenToViewSelections.setSelected(av.followSelection);
961 showProducts.setEnabled(canShowProducts());
962 setGroovyEnabled(Desktop.getGroovyConsole() != null);
968 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
972 public void setGroovyEnabled(boolean b)
974 runGroovy.setEnabled(b);
977 private IProgressIndicator progressBar;
982 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
985 public void setProgressBar(String message, long id)
987 progressBar.setProgressBar(message, id);
991 public void registerHandler(final long id,
992 final IProgressIndicatorHandler handler)
994 progressBar.registerHandler(id, handler);
999 * @return true if any progress bars are still active
1002 public boolean operationInProgress()
1004 return progressBar.operationInProgress();
1008 * Sets the text of the status bar. Note that setting a null or empty value
1009 * will cause the status bar to be hidden, with possibly undesirable flicker
1010 * of the screen layout.
1013 public void setStatus(String text)
1015 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1019 * Added so Castor Mapping file can obtain Jalview Version
1021 public String getVersion()
1023 return Cache.getProperty("VERSION");
1026 public FeatureRenderer getFeatureRenderer()
1028 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1032 public void fetchSequence_actionPerformed()
1034 new SequenceFetcher(this);
1038 public void addFromFile_actionPerformed(ActionEvent e)
1040 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1044 public void reload_actionPerformed(ActionEvent e)
1046 if (fileName != null)
1048 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1049 // originating file's format
1050 // TODO: work out how to recover feature settings for correct view(s) when
1051 // file is reloaded.
1052 if (FileFormat.Jalview.equals(currentFileFormat))
1054 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1055 for (int i = 0; i < frames.length; i++)
1057 if (frames[i] instanceof AlignFrame && frames[i] != this
1058 && ((AlignFrame) frames[i]).fileName != null
1059 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1063 frames[i].setSelected(true);
1064 Desktop.instance.closeAssociatedWindows();
1065 } catch (java.beans.PropertyVetoException ex)
1071 Desktop.instance.closeAssociatedWindows();
1073 FileLoader loader = new FileLoader();
1074 DataSourceType protocol = HttpUtils.startsWithHttpOrHttps(fileName)
1075 ? DataSourceType.URL
1076 : DataSourceType.FILE;
1077 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1081 Rectangle bounds = this.getBounds();
1083 FileLoader loader = new FileLoader();
1085 AlignFrame newframe = null;
1087 if (fileObject == null)
1090 DataSourceType protocol = HttpUtils.startsWithHttpOrHttps(
1091 fileName) ? DataSourceType.URL : DataSourceType.FILE;
1092 newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1097 newframe = loader.LoadFileWaitTillLoaded(fileObject,
1098 DataSourceType.FILE, currentFileFormat);
1101 newframe.setBounds(bounds);
1102 if (featureSettings != null && featureSettings.isShowing())
1104 final Rectangle fspos = featureSettings.frame.getBounds();
1105 // TODO: need a 'show feature settings' function that takes bounds -
1106 // need to refactor Desktop.addFrame
1107 newframe.featureSettings_actionPerformed(null);
1108 final FeatureSettings nfs = newframe.featureSettings;
1109 SwingUtilities.invokeLater(new Runnable()
1114 nfs.frame.setBounds(fspos);
1117 this.featureSettings.close();
1118 this.featureSettings = null;
1120 this.closeMenuItem_actionPerformed(true);
1126 public void addFromText_actionPerformed(ActionEvent e)
1129 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1133 public void addFromURL_actionPerformed(ActionEvent e)
1135 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1139 public void save_actionPerformed(ActionEvent e)
1141 if (fileName == null || (currentFileFormat == null)
1142 || HttpUtils.startsWithHttpOrHttps(fileName))
1144 saveAs_actionPerformed();
1148 saveAlignment(fileName, currentFileFormat);
1153 * Saves the alignment to a file with a name chosen by the user, if necessary
1154 * warning if a file would be overwritten
1157 public void saveAs_actionPerformed()
1159 String format = currentFileFormat == null ? null
1160 : currentFileFormat.getName();
1161 JalviewFileChooser chooser = JalviewFileChooser
1162 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1164 chooser.setFileView(new JalviewFileView());
1165 chooser.setDialogTitle(
1166 MessageManager.getString("label.save_alignment_to_file"));
1167 chooser.setToolTipText(MessageManager.getString("action.save"));
1169 int value = chooser.showSaveDialog(this);
1171 if (value != JalviewFileChooser.APPROVE_OPTION)
1175 currentFileFormat = chooser.getSelectedFormat();
1176 // todo is this (2005) test now obsolete - value is never null?
1177 while (currentFileFormat == null)
1179 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1181 .getString("label.select_file_format_before_saving"),
1182 MessageManager.getString("label.file_format_not_specified"),
1183 JvOptionPane.WARNING_MESSAGE);
1184 currentFileFormat = chooser.getSelectedFormat();
1185 value = chooser.showSaveDialog(this);
1186 if (value != JalviewFileChooser.APPROVE_OPTION)
1192 fileName = chooser.getSelectedFile().getPath();
1194 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1195 Cache.setProperty("LAST_DIRECTORY", fileName);
1196 saveAlignment(fileName, currentFileFormat);
1199 boolean lastSaveSuccessful = false;
1201 FileFormatI lastFormatSaved;
1203 String lastFilenameSaved;
1206 * Raise a dialog or status message for the last call to saveAlignment.
1208 * @return true if last call to saveAlignment(file, format) was successful.
1210 public boolean isSaveAlignmentSuccessful()
1213 if (!lastSaveSuccessful)
1215 if (!Platform.isHeadless())
1217 JvOptionPane.showInternalMessageDialog(this, MessageManager
1218 .formatMessage("label.couldnt_save_file", new Object[]
1219 { lastFilenameSaved }),
1220 MessageManager.getString("label.error_saving_file"),
1221 JvOptionPane.WARNING_MESSAGE);
1225 Console.error(MessageManager
1226 .formatMessage("label.couldnt_save_file", new Object[]
1227 { lastFilenameSaved }));
1233 setStatus(MessageManager.formatMessage(
1234 "label.successfully_saved_to_file_in_format", new Object[]
1235 { lastFilenameSaved, lastFormatSaved }));
1238 return lastSaveSuccessful;
1242 * Saves the alignment to the specified file path, in the specified format,
1243 * which may be an alignment format, or Jalview project format. If the
1244 * alignment has hidden regions, or the format is one capable of including
1245 * non-sequence data (features, annotations, groups), then the user may be
1246 * prompted to specify what to include in the output.
1251 public void saveAlignment(String file, FileFormatI format)
1253 lastSaveSuccessful = true;
1254 lastFilenameSaved = file;
1255 lastFormatSaved = format;
1257 if (FileFormat.Jalview.equals(format))
1259 String shortName = title;
1260 if (shortName.indexOf(File.separatorChar) > -1)
1262 shortName = shortName
1263 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
1265 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file,
1268 statusBar.setText(MessageManager.formatMessage(
1269 "label.successfully_saved_to_file_in_format", new Object[]
1275 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1276 Runnable cancelAction = new Runnable()
1281 lastSaveSuccessful = false;
1284 Runnable outputAction = new Runnable()
1289 // todo defer this to inside formatSequences (or later)
1290 AlignmentExportData exportData = viewport
1291 .getAlignExportData(options);
1292 String output = new FormatAdapter(alignPanel, options)
1293 .formatSequences(format, exportData.getAlignment(),
1294 exportData.getOmitHidden(),
1295 exportData.getStartEndPostions(),
1296 viewport.getAlignment().getHiddenColumns());
1299 lastSaveSuccessful = false;
1303 // create backupfiles object and get new temp filename destination
1304 boolean doBackup = BackupFiles.getEnabled();
1305 BackupFiles backupfiles = null;
1309 "ALIGNFRAME making backupfiles object for " + file);
1310 backupfiles = new BackupFiles(file);
1314 String tempFilePath = doBackup ? backupfiles.getTempFilePath()
1316 Console.trace("ALIGNFRAME setting PrintWriter");
1317 PrintWriter out = new PrintWriter(new FileWriter(tempFilePath));
1319 if (backupfiles != null)
1321 Console.trace("ALIGNFRAME about to write to temp file "
1322 + backupfiles.getTempFilePath());
1326 Console.trace("ALIGNFRAME about to close file");
1328 Console.trace("ALIGNFRAME closed file");
1329 AlignFrame.this.setTitle(file);
1330 statusBar.setText(MessageManager.formatMessage(
1331 "label.successfully_saved_to_file_in_format",
1333 { fileName, format.getName() }));
1334 lastSaveSuccessful = true;
1335 } catch (IOException e)
1337 lastSaveSuccessful = false;
1339 "ALIGNFRAME Something happened writing the temp file");
1340 Console.error(e.getMessage());
1341 Console.debug(Cache.getStackTraceString(e));
1342 } catch (Exception ex)
1344 lastSaveSuccessful = false;
1346 "ALIGNFRAME Something unexpected happened writing the temp file");
1347 Console.error(ex.getMessage());
1348 Console.debug(Cache.getStackTraceString(ex));
1353 backupfiles.setWriteSuccess(lastSaveSuccessful);
1354 Console.debug("ALIGNFRAME writing temp file was "
1355 + (lastSaveSuccessful ? "" : "NOT ") + "successful");
1356 // do the backup file roll and rename the temp file to actual file
1358 "ALIGNFRAME about to rollBackupsAndRenameTempFile");
1359 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1361 "ALIGNFRAME performed rollBackupsAndRenameTempFile "
1362 + (lastSaveSuccessful ? "" : "un")
1370 * show dialog with export options if applicable; else just do it
1372 if (AlignExportOptions.isNeeded(viewport, format))
1374 AlignExportOptions choices = new AlignExportOptions(
1375 alignPanel.getAlignViewport(), format, options);
1376 choices.setResponseAction(0, outputAction);
1377 choices.setResponseAction(1, cancelAction);
1378 choices.showDialog();
1387 * Outputs the alignment to textbox in the requested format, if necessary
1388 * first prompting the user for whether to include hidden regions or
1391 * @param fileFormatName
1394 protected void outputText_actionPerformed(String fileFormatName)
1396 FileFormatI fileFormat = FileFormats.getInstance()
1397 .forName(fileFormatName);
1398 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1399 Runnable outputAction = new Runnable()
1404 // todo defer this to inside formatSequences (or later)
1405 AlignmentExportData exportData = viewport
1406 .getAlignExportData(options);
1407 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1408 cap.setForInput(null);
1411 FileFormatI format = fileFormat;
1412 cap.setText(new FormatAdapter(alignPanel, options)
1413 .formatSequences(format, exportData.getAlignment(),
1414 exportData.getOmitHidden(),
1415 exportData.getStartEndPostions(),
1416 viewport.getAlignment().getHiddenColumns()));
1417 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1418 "label.alignment_output_command", new Object[]
1419 { fileFormat.getName() }), 600, 500);
1420 } catch (OutOfMemoryError oom)
1422 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1430 * show dialog with export options if applicable; else just do it
1432 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1434 AlignExportOptions choices = new AlignExportOptions(
1435 alignPanel.getAlignViewport(), fileFormat, options);
1436 choices.setResponseAction(0, outputAction);
1437 choices.showDialog();
1452 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1454 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1455 htmlSVG.exportHTML(null);
1459 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1461 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1462 bjs.exportHTML(null);
1465 public void createImageMap(File file, String image)
1467 alignPanel.makePNGImageMap(file, image);
1471 * Creates a PNG image of the alignment and writes it to the given file. If
1472 * the file is null, the user is prompted to choose a file.
1477 public void createPNG(File f)
1479 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1483 * Creates an EPS image of the alignment and writes it to the given file. If
1484 * the file is null, the user is prompted to choose a file.
1489 public void createEPS(File f)
1491 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1495 * Creates an SVG image of the alignment and writes it to the given file. If
1496 * the file is null, the user is prompted to choose a file.
1501 public void createSVG(File f)
1503 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1507 public void pageSetup_actionPerformed(ActionEvent e)
1509 PrinterJob printJob = PrinterJob.getPrinterJob();
1510 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1520 public void printMenuItem_actionPerformed(ActionEvent e)
1522 // Putting in a thread avoids Swing painting problems
1523 PrintThread thread = new PrintThread(alignPanel);
1528 public void exportFeatures_actionPerformed(ActionEvent e)
1530 new AnnotationExporter(alignPanel).exportFeatures();
1534 public void exportAnnotations_actionPerformed(ActionEvent e)
1536 new AnnotationExporter(alignPanel).exportAnnotations();
1540 public void associatedData_actionPerformed(ActionEvent e)
1542 final JalviewFileChooser chooser = new JalviewFileChooser(
1543 Cache.getProperty("LAST_DIRECTORY"));
1544 chooser.setFileView(new JalviewFileView());
1545 String tooltip = MessageManager
1546 .getString("label.load_jalview_annotations");
1547 chooser.setDialogTitle(tooltip);
1548 chooser.setToolTipText(tooltip);
1549 chooser.setResponseHandler(0, new Runnable()
1554 String choice = chooser.getSelectedFile().getPath();
1555 Cache.setProperty("LAST_DIRECTORY", choice);
1556 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1560 chooser.showOpenDialog(this);
1564 * Close the current view or all views in the alignment frame. If the frame
1565 * only contains one view then the alignment will be removed from memory.
1567 * @param closeAllTabs
1570 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1572 if (alignPanels != null && alignPanels.size() < 2)
1574 closeAllTabs = true;
1579 if (alignPanels != null)
1583 if (this.isClosed())
1585 // really close all the windows - otherwise wait till
1586 // setClosed(true) is called
1587 for (int i = 0; i < alignPanels.size(); i++)
1589 AlignmentPanel ap = alignPanels.get(i);
1596 closeView(alignPanel);
1601 if (featureSettings != null && featureSettings.isOpen())
1603 featureSettings.close();
1604 featureSettings = null;
1607 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1608 * be called recursively, with the frame now in 'closed' state
1610 this.setClosed(true);
1612 } catch (Exception ex)
1614 ex.printStackTrace();
1619 * Close the specified panel and close up tabs appropriately.
1621 * @param panelToClose
1623 public void closeView(AlignmentPanel panelToClose)
1625 int index = tabbedPane.getSelectedIndex();
1626 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1627 alignPanels.remove(panelToClose);
1628 panelToClose.closePanel();
1629 panelToClose = null;
1631 tabbedPane.removeTabAt(closedindex);
1632 tabbedPane.validate();
1634 if (index > closedindex || index == tabbedPane.getTabCount())
1636 // modify currently selected tab index if necessary.
1640 this.tabSelectionChanged(index);
1646 void updateEditMenuBar()
1649 if (viewport.getHistoryList().size() > 0)
1651 undoMenuItem.setEnabled(true);
1652 CommandI command = viewport.getHistoryList().peek();
1653 undoMenuItem.setText(MessageManager
1654 .formatMessage("label.undo_command", new Object[]
1655 { command.getDescription() }));
1659 undoMenuItem.setEnabled(false);
1660 undoMenuItem.setText(MessageManager.getString("action.undo"));
1663 if (viewport.getRedoList().size() > 0)
1665 redoMenuItem.setEnabled(true);
1667 CommandI command = viewport.getRedoList().peek();
1668 redoMenuItem.setText(MessageManager
1669 .formatMessage("label.redo_command", new Object[]
1670 { command.getDescription() }));
1674 redoMenuItem.setEnabled(false);
1675 redoMenuItem.setText(MessageManager.getString("action.redo"));
1680 public void addHistoryItem(CommandI command)
1682 if (command.getSize() > 0)
1684 viewport.addToHistoryList(command);
1685 viewport.clearRedoList();
1686 updateEditMenuBar();
1687 viewport.updateHiddenColumns();
1688 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1689 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1690 // viewport.getColumnSelection()
1691 // .getHiddenColumns().size() > 0);
1697 * @return alignment objects for all views
1699 AlignmentI[] getViewAlignments()
1701 if (alignPanels != null)
1703 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1705 for (AlignmentPanel ap : alignPanels)
1707 als[i++] = ap.av.getAlignment();
1711 if (viewport != null)
1713 return new AlignmentI[] { viewport.getAlignment() };
1725 protected void undoMenuItem_actionPerformed(ActionEvent e)
1727 if (viewport.getHistoryList().isEmpty())
1731 CommandI command = viewport.getHistoryList().pop();
1732 viewport.addToRedoList(command);
1733 command.undoCommand(getViewAlignments());
1735 AlignmentViewport originalSource = getOriginatingSource(command);
1736 updateEditMenuBar();
1738 if (originalSource != null)
1740 if (originalSource != viewport)
1743 "Implementation worry: mismatch of viewport origin for undo");
1745 originalSource.updateHiddenColumns();
1746 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1748 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1749 // viewport.getColumnSelection()
1750 // .getHiddenColumns().size() > 0);
1751 originalSource.firePropertyChange("alignment", null,
1752 originalSource.getAlignment().getSequences());
1763 protected void redoMenuItem_actionPerformed(ActionEvent e)
1765 if (viewport.getRedoList().size() < 1)
1770 CommandI command = viewport.getRedoList().pop();
1771 viewport.addToHistoryList(command);
1772 command.doCommand(getViewAlignments());
1774 AlignmentViewport originalSource = getOriginatingSource(command);
1775 updateEditMenuBar();
1777 if (originalSource != null)
1780 if (originalSource != viewport)
1783 "Implementation worry: mismatch of viewport origin for redo");
1785 originalSource.updateHiddenColumns();
1786 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1788 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1789 // viewport.getColumnSelection()
1790 // .getHiddenColumns().size() > 0);
1791 originalSource.firePropertyChange("alignment", null,
1792 originalSource.getAlignment().getSequences());
1796 AlignmentViewport getOriginatingSource(CommandI command)
1798 AlignmentViewport originalSource = null;
1799 // For sequence removal and addition, we need to fire
1800 // the property change event FROM the viewport where the
1801 // original alignment was altered
1802 AlignmentI al = null;
1803 if (command instanceof EditCommand)
1805 EditCommand editCommand = (EditCommand) command;
1806 al = editCommand.getAlignment();
1807 List<Component> comps = PaintRefresher.components
1808 .get(viewport.getSequenceSetId());
1810 for (Component comp : comps)
1812 if (comp instanceof AlignmentPanel)
1814 if (al == ((AlignmentPanel) comp).av.getAlignment())
1816 originalSource = ((AlignmentPanel) comp).av;
1823 if (originalSource == null)
1825 // The original view is closed, we must validate
1826 // the current view against the closed view first
1829 PaintRefresher.validateSequences(al, viewport.getAlignment());
1832 originalSource = viewport;
1835 return originalSource;
1839 * Calls AlignmentI.moveSelectedSequencesByOne with current sequence selection
1840 * or the sequence under cursor in keyboard mode
1845 public void moveSelectedSequences(boolean up)
1847 SequenceGroup sg = viewport.getSelectionGroup();
1851 if (viewport.cursorMode)
1853 sg = new SequenceGroup();
1854 sg.addSequence(viewport.getAlignment().getSequenceAt(
1855 alignPanel.getSeqPanel().seqCanvas.cursorY), false);
1863 if (sg.getSize() < 1)
1868 // TODO: JAL-3733 - add an event to the undo buffer for this !
1870 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1871 viewport.getHiddenRepSequences(), up);
1872 alignPanel.paintAlignment(true, false);
1875 synchronized void slideSequences(boolean right, int size)
1877 List<SequenceI> sg = new ArrayList<>();
1878 if (viewport.cursorMode)
1880 sg.add(viewport.getAlignment()
1881 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1883 else if (viewport.getSelectionGroup() != null
1884 && viewport.getSelectionGroup().getSize() != viewport
1885 .getAlignment().getHeight())
1887 sg = viewport.getSelectionGroup()
1888 .getSequences(viewport.getHiddenRepSequences());
1896 List<SequenceI> invertGroup = new ArrayList<>();
1898 for (SequenceI seq : viewport.getAlignment().getSequences())
1900 if (!sg.contains(seq))
1902 invertGroup.add(seq);
1906 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1908 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1909 for (int i = 0; i < invertGroup.size(); i++)
1911 seqs2[i] = invertGroup.get(i);
1914 SlideSequencesCommand ssc;
1917 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1918 viewport.getGapCharacter());
1922 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1923 viewport.getGapCharacter());
1926 int groupAdjustment = 0;
1927 if (ssc.getGapsInsertedBegin() && right)
1929 if (viewport.cursorMode)
1931 alignPanel.getSeqPanel().moveCursor(size, 0);
1935 groupAdjustment = size;
1938 else if (!ssc.getGapsInsertedBegin() && !right)
1940 if (viewport.cursorMode)
1942 alignPanel.getSeqPanel().moveCursor(-size, 0);
1946 groupAdjustment = -size;
1950 if (groupAdjustment != 0)
1952 viewport.getSelectionGroup().setStartRes(
1953 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1954 viewport.getSelectionGroup().setEndRes(
1955 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1959 * just extend the last slide command if compatible; but not if in
1960 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1962 boolean appendHistoryItem = false;
1963 Deque<CommandI> historyList = viewport.getHistoryList();
1964 boolean inSplitFrame = getSplitViewContainer() != null;
1965 if (!inSplitFrame && historyList != null && historyList.size() > 0
1966 && historyList.peek() instanceof SlideSequencesCommand)
1968 appendHistoryItem = ssc.appendSlideCommand(
1969 (SlideSequencesCommand) historyList.peek());
1972 if (!appendHistoryItem)
1974 addHistoryItem(ssc);
1987 protected void copy_actionPerformed()
1989 if (viewport.getSelectionGroup() == null)
1993 // TODO: preserve the ordering of displayed alignment annotation in any
1994 // internal paste (particularly sequence associated annotation)
1995 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1996 String[] omitHidden = null;
1998 if (viewport.hasHiddenColumns())
2000 omitHidden = viewport.getViewAsString(true);
2003 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2004 seqs, omitHidden, null);
2006 StringSelection ss = new StringSelection(output);
2010 jalview.gui.Desktop.internalCopy = true;
2011 // Its really worth setting the clipboard contents
2012 // to empty before setting the large StringSelection!!
2013 Toolkit.getDefaultToolkit().getSystemClipboard()
2014 .setContents(new StringSelection(""), null);
2016 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2018 } catch (OutOfMemoryError er)
2020 new OOMWarning("copying region", er);
2024 HiddenColumns hiddenColumns = null;
2025 if (viewport.hasHiddenColumns())
2027 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2028 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2030 // create new HiddenColumns object with copy of hidden regions
2031 // between startRes and endRes, offset by startRes
2032 hiddenColumns = new HiddenColumns(
2033 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2034 hiddenCutoff, hiddenOffset);
2037 Desktop.jalviewClipboard = new Object[] { seqs,
2038 viewport.getAlignment().getDataset(), hiddenColumns };
2039 setStatus(MessageManager.formatMessage(
2040 "label.copied_sequences_to_clipboard", new Object[]
2041 { Integer.valueOf(seqs.length).toString() }));
2051 protected void pasteNew_actionPerformed(ActionEvent e)
2063 protected void pasteThis_actionPerformed(ActionEvent e)
2069 * Paste contents of Jalview clipboard
2071 * @param newAlignment
2072 * true to paste to a new alignment, otherwise add to this.
2074 void paste(boolean newAlignment)
2076 boolean externalPaste = true;
2079 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2080 Transferable contents = c.getContents(this);
2082 if (contents == null)
2091 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2092 if (str.length() < 1)
2097 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2099 } catch (OutOfMemoryError er)
2101 new OOMWarning("Out of memory pasting sequences!!", er);
2105 SequenceI[] sequences;
2106 boolean annotationAdded = false;
2107 AlignmentI alignment = null;
2109 if (Desktop.jalviewClipboard != null)
2111 // The clipboard was filled from within Jalview, we must use the
2113 // And dataset from the copied alignment
2114 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2115 // be doubly sure that we create *new* sequence objects.
2116 sequences = new SequenceI[newseq.length];
2117 for (int i = 0; i < newseq.length; i++)
2119 sequences[i] = new Sequence(newseq[i]);
2121 alignment = new Alignment(sequences);
2122 externalPaste = false;
2126 // parse the clipboard as an alignment.
2127 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2129 sequences = alignment.getSequencesArray();
2133 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2139 if (Desktop.jalviewClipboard != null)
2141 // dataset is inherited
2142 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2146 // new dataset is constructed
2147 alignment.setDataset(null);
2149 alwidth = alignment.getWidth() + 1;
2153 AlignmentI pastedal = alignment; // preserve pasted alignment object
2154 // Add pasted sequences and dataset into existing alignment.
2155 alignment = viewport.getAlignment();
2156 alwidth = alignment.getWidth() + 1;
2157 // decide if we need to import sequences from an existing dataset
2158 boolean importDs = Desktop.jalviewClipboard != null
2159 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2160 // importDs==true instructs us to copy over new dataset sequences from
2161 // an existing alignment
2162 Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2164 // minimum dataset set
2166 for (int i = 0; i < sequences.length; i++)
2170 newDs.addElement(null);
2172 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2174 if (importDs && ds != null)
2176 if (!newDs.contains(ds))
2178 newDs.setElementAt(ds, i);
2179 ds = new Sequence(ds);
2180 // update with new dataset sequence
2181 sequences[i].setDatasetSequence(ds);
2185 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2190 // copy and derive new dataset sequence
2191 sequences[i] = sequences[i].deriveSequence();
2192 alignment.getDataset()
2193 .addSequence(sequences[i].getDatasetSequence());
2194 // TODO: avoid creation of duplicate dataset sequences with a
2195 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2197 alignment.addSequence(sequences[i]); // merges dataset
2201 newDs.clear(); // tidy up
2203 if (alignment.getAlignmentAnnotation() != null)
2205 for (AlignmentAnnotation alan : alignment
2206 .getAlignmentAnnotation())
2208 if (alan.graphGroup > fgroup)
2210 fgroup = alan.graphGroup;
2214 if (pastedal.getAlignmentAnnotation() != null)
2216 // Add any annotation attached to alignment.
2217 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2218 for (int i = 0; i < alann.length; i++)
2220 annotationAdded = true;
2221 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2223 AlignmentAnnotation newann = new AlignmentAnnotation(
2225 if (newann.graphGroup > -1)
2227 if (newGraphGroups.size() <= newann.graphGroup
2228 || newGraphGroups.get(newann.graphGroup) == null)
2230 for (int q = newGraphGroups
2231 .size(); q <= newann.graphGroup; q++)
2233 newGraphGroups.add(q, null);
2235 newGraphGroups.set(newann.graphGroup,
2236 Integer.valueOf(++fgroup));
2238 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2242 newann.padAnnotation(alwidth);
2243 alignment.addAnnotation(newann);
2253 addHistoryItem(new EditCommand(
2254 MessageManager.getString("label.add_sequences"),
2255 Action.PASTE, sequences, 0, alignment.getWidth(),
2258 // Add any annotations attached to sequences
2259 for (int i = 0; i < sequences.length; i++)
2261 if (sequences[i].getAnnotation() != null)
2263 AlignmentAnnotation newann;
2264 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2266 annotationAdded = true;
2267 newann = sequences[i].getAnnotation()[a];
2268 newann.adjustForAlignment();
2269 newann.padAnnotation(alwidth);
2270 if (newann.graphGroup > -1)
2272 if (newann.graphGroup > -1)
2274 if (newGraphGroups.size() <= newann.graphGroup
2275 || newGraphGroups.get(newann.graphGroup) == null)
2277 for (int q = newGraphGroups
2278 .size(); q <= newann.graphGroup; q++)
2280 newGraphGroups.add(q, null);
2282 newGraphGroups.set(newann.graphGroup,
2283 Integer.valueOf(++fgroup));
2285 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2289 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2293 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2301 // propagate alignment changed.
2302 viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2303 if (annotationAdded)
2305 // Duplicate sequence annotation in all views.
2306 AlignmentI[] alview = this.getViewAlignments();
2307 for (int i = 0; i < sequences.length; i++)
2309 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2314 for (int avnum = 0; avnum < alview.length; avnum++)
2316 if (alview[avnum] != alignment)
2318 // duplicate in a view other than the one with input focus
2319 int avwidth = alview[avnum].getWidth() + 1;
2320 // this relies on sann being preserved after we
2321 // modify the sequence's annotation array for each duplication
2322 for (int a = 0; a < sann.length; a++)
2324 AlignmentAnnotation newann = new AlignmentAnnotation(
2326 sequences[i].addAlignmentAnnotation(newann);
2327 newann.padAnnotation(avwidth);
2328 alview[avnum].addAnnotation(newann); // annotation was
2329 // duplicated earlier
2330 // TODO JAL-1145 graphGroups are not updated for sequence
2331 // annotation added to several views. This may cause
2333 alview[avnum].setAnnotationIndex(newann, a);
2338 buildSortByAnnotationScoresMenu();
2340 viewport.firePropertyChange("alignment", null,
2341 alignment.getSequences());
2342 if (alignPanels != null)
2344 for (AlignmentPanel ap : alignPanels)
2346 ap.validateAnnotationDimensions(false);
2351 alignPanel.validateAnnotationDimensions(false);
2357 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2359 String newtitle = new String("Copied sequences");
2361 if (Desktop.jalviewClipboard != null
2362 && Desktop.jalviewClipboard[2] != null)
2364 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2365 af.viewport.setHiddenColumns(hc);
2368 // >>>This is a fix for the moment, until a better solution is
2370 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2371 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2372 .getFeatureRenderer());
2374 // TODO: maintain provenance of an alignment, rather than just make the
2375 // title a concatenation of operations.
2378 if (title.startsWith("Copied sequences"))
2384 newtitle = newtitle.concat("- from " + title);
2389 newtitle = new String("Pasted sequences");
2392 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2397 } catch (Exception ex)
2399 ex.printStackTrace();
2400 System.out.println("Exception whilst pasting: " + ex);
2401 // could be anything being pasted in here
2407 protected void expand_newalign(ActionEvent e)
2411 AlignmentI alignment = AlignmentUtils
2412 .expandContext(getViewport().getAlignment(), -1);
2413 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2415 String newtitle = new String("Flanking alignment");
2417 if (Desktop.jalviewClipboard != null
2418 && Desktop.jalviewClipboard[2] != null)
2420 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2421 af.viewport.setHiddenColumns(hc);
2424 // >>>This is a fix for the moment, until a better solution is
2426 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2427 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2428 .getFeatureRenderer());
2430 // TODO: maintain provenance of an alignment, rather than just make the
2431 // title a concatenation of operations.
2433 if (title.startsWith("Copied sequences"))
2439 newtitle = newtitle.concat("- from " + title);
2443 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2445 } catch (Exception ex)
2447 ex.printStackTrace();
2448 System.out.println("Exception whilst pasting: " + ex);
2449 // could be anything being pasted in here
2450 } catch (OutOfMemoryError oom)
2452 new OOMWarning("Viewing flanking region of alignment", oom);
2457 * Action Cut (delete and copy) the selected region
2460 protected void cut_actionPerformed()
2462 copy_actionPerformed();
2463 delete_actionPerformed();
2467 * Performs menu option to Delete the currently selected region
2470 protected void delete_actionPerformed()
2473 SequenceGroup sg = viewport.getSelectionGroup();
2479 Runnable okAction = new Runnable()
2484 SequenceI[] cut = sg.getSequences()
2485 .toArray(new SequenceI[sg.getSize()]);
2487 addHistoryItem(new EditCommand(
2488 MessageManager.getString("label.cut_sequences"), Action.CUT,
2489 cut, sg.getStartRes(),
2490 sg.getEndRes() - sg.getStartRes() + 1,
2491 viewport.getAlignment()));
2493 viewport.setSelectionGroup(null);
2494 viewport.sendSelection();
2495 viewport.getAlignment().deleteGroup(sg);
2497 viewport.firePropertyChange("alignment", null,
2498 viewport.getAlignment().getSequences());
2499 if (viewport.getAlignment().getHeight() < 1)
2503 AlignFrame.this.setClosed(true);
2504 } catch (Exception ex)
2512 * If the cut affects all sequences, prompt for confirmation
2514 boolean wholeHeight = sg.getSize() == viewport.getAlignment()
2516 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2517 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2518 if (wholeHeight && wholeWidth)
2520 JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.desktop);
2521 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2522 Object[] options = new Object[] {
2523 MessageManager.getString("action.ok"),
2524 MessageManager.getString("action.cancel") };
2525 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2526 MessageManager.getString("label.delete_all"),
2527 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2528 options, options[0]);
2543 protected void deleteGroups_actionPerformed(ActionEvent e)
2545 if (avc.deleteGroups())
2547 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2548 alignPanel.updateAnnotation();
2549 alignPanel.paintAlignment(true, true);
2560 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2562 SequenceGroup sg = new SequenceGroup(
2563 viewport.getAlignment().getSequences());
2565 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2566 viewport.setSelectionGroup(sg);
2567 viewport.isSelectionGroupChanged(true);
2568 viewport.sendSelection();
2569 // JAL-2034 - should delegate to
2570 // alignPanel to decide if overview needs
2572 alignPanel.paintAlignment(false, false);
2573 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2583 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2585 if (viewport.cursorMode)
2587 alignPanel.getSeqPanel().keyboardNo1 = null;
2588 alignPanel.getSeqPanel().keyboardNo2 = null;
2590 viewport.setSelectionGroup(null);
2591 viewport.getColumnSelection().clear();
2592 viewport.setSearchResults(null);
2593 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2594 // JAL-2034 - should delegate to
2595 // alignPanel to decide if overview needs
2597 alignPanel.paintAlignment(false, false);
2598 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2599 viewport.sendSelection();
2609 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2611 SequenceGroup sg = viewport.getSelectionGroup();
2615 selectAllSequenceMenuItem_actionPerformed(null);
2620 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2622 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2624 // JAL-2034 - should delegate to
2625 // alignPanel to decide if overview needs
2628 alignPanel.paintAlignment(true, false);
2629 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2630 viewport.sendSelection();
2634 public void invertColSel_actionPerformed(ActionEvent e)
2636 viewport.invertColumnSelection();
2637 alignPanel.paintAlignment(true, false);
2638 viewport.sendSelection();
2648 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2650 trimAlignment(true);
2660 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2662 trimAlignment(false);
2665 void trimAlignment(boolean trimLeft)
2667 ColumnSelection colSel = viewport.getColumnSelection();
2670 if (!colSel.isEmpty())
2674 column = colSel.getMin();
2678 column = colSel.getMax();
2682 if (viewport.getSelectionGroup() != null)
2684 seqs = viewport.getSelectionGroup()
2685 .getSequencesAsArray(viewport.getHiddenRepSequences());
2689 seqs = viewport.getAlignment().getSequencesArray();
2692 TrimRegionCommand trimRegion;
2695 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2696 column, viewport.getAlignment());
2697 viewport.getRanges().setStartRes(0);
2701 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2702 column, viewport.getAlignment());
2705 setStatus(MessageManager.formatMessage("label.removed_columns",
2707 { Integer.valueOf(trimRegion.getSize()).toString() }));
2709 addHistoryItem(trimRegion);
2711 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2713 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2714 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2716 viewport.getAlignment().deleteGroup(sg);
2720 viewport.firePropertyChange("alignment", null,
2721 viewport.getAlignment().getSequences());
2732 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2734 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2737 if (viewport.getSelectionGroup() != null)
2739 seqs = viewport.getSelectionGroup()
2740 .getSequencesAsArray(viewport.getHiddenRepSequences());
2741 start = viewport.getSelectionGroup().getStartRes();
2742 end = viewport.getSelectionGroup().getEndRes();
2746 seqs = viewport.getAlignment().getSequencesArray();
2749 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2750 "Remove Gapped Columns", seqs, start, end,
2751 viewport.getAlignment());
2753 addHistoryItem(removeGapCols);
2755 setStatus(MessageManager.formatMessage("label.removed_empty_columns",
2757 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2759 // This is to maintain viewport position on first residue
2760 // of first sequence
2761 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2762 ViewportRanges ranges = viewport.getRanges();
2763 int startRes = seq.findPosition(ranges.getStartRes());
2764 // ShiftList shifts;
2765 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2766 // edit.alColumnChanges=shifts.getInverse();
2767 // if (viewport.hasHiddenColumns)
2768 // viewport.getColumnSelection().compensateForEdits(shifts);
2769 ranges.setStartRes(seq.findIndex(startRes) - 1);
2770 viewport.firePropertyChange("alignment", null,
2771 viewport.getAlignment().getSequences());
2782 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2784 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2787 if (viewport.getSelectionGroup() != null)
2789 seqs = viewport.getSelectionGroup()
2790 .getSequencesAsArray(viewport.getHiddenRepSequences());
2791 start = viewport.getSelectionGroup().getStartRes();
2792 end = viewport.getSelectionGroup().getEndRes();
2796 seqs = viewport.getAlignment().getSequencesArray();
2799 // This is to maintain viewport position on first residue
2800 // of first sequence
2801 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2802 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2804 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2805 viewport.getAlignment()));
2807 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2809 viewport.firePropertyChange("alignment", null,
2810 viewport.getAlignment().getSequences());
2821 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2823 viewport.setPadGaps(padGapsMenuitem.isSelected());
2824 viewport.firePropertyChange("alignment", null,
2825 viewport.getAlignment().getSequences());
2829 * Opens a Finder dialog
2834 public void findMenuItem_actionPerformed(ActionEvent e)
2836 new Finder(alignPanel, false, null);
2840 * Create a new view of the current alignment.
2843 public void newView_actionPerformed(ActionEvent e)
2845 newView(null, true);
2849 * Creates and shows a new view of the current alignment.
2852 * title of newly created view; if null, one will be generated
2853 * @param copyAnnotation
2854 * if true then duplicate all annnotation, groups and settings
2855 * @return new alignment panel, already displayed.
2857 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2860 * Create a new AlignmentPanel (with its own, new Viewport)
2862 AlignmentPanel newap = new jalview.project.Jalview2XML()
2863 .copyAlignPanel(alignPanel);
2864 if (!copyAnnotation)
2867 * remove all groups and annotation except for the automatic stuff
2869 newap.av.getAlignment().deleteAllGroups();
2870 newap.av.getAlignment().deleteAllAnnotations(false);
2873 newap.av.setGatherViewsHere(false);
2875 if (viewport.getViewName() == null)
2877 viewport.setViewName(
2878 MessageManager.getString("label.view_name_original"));
2882 * Views share the same edits undo and redo stacks
2884 newap.av.setHistoryList(viewport.getHistoryList());
2885 newap.av.setRedoList(viewport.getRedoList());
2888 * copy any visualisation settings that are not saved in the project
2890 newap.av.setColourAppliesToAllGroups(
2891 viewport.getColourAppliesToAllGroups());
2894 * Views share the same mappings; need to deregister any new mappings
2895 * created by copyAlignPanel, and register the new reference to the shared
2898 newap.av.replaceMappings(viewport.getAlignment());
2901 * start up cDNA consensus (if applicable) now mappings are in place
2903 if (newap.av.initComplementConsensus())
2905 newap.refresh(true); // adjust layout of annotations
2908 newap.av.setViewName(getNewViewName(viewTitle));
2910 addAlignmentPanel(newap, true);
2911 newap.alignmentChanged();
2913 if (alignPanels.size() == 2)
2915 viewport.setGatherViewsHere(true);
2917 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2922 * Make a new name for the view, ensuring it is unique within the current
2923 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2924 * these now use viewId. Unique view names are still desirable for usability.)
2929 protected String getNewViewName(String viewTitle)
2931 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2932 boolean addFirstIndex = false;
2933 if (viewTitle == null || viewTitle.trim().length() == 0)
2935 viewTitle = MessageManager.getString("action.view");
2936 addFirstIndex = true;
2940 index = 1;// we count from 1 if given a specific name
2942 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2944 List<Component> comps = PaintRefresher.components
2945 .get(viewport.getSequenceSetId());
2947 List<String> existingNames = getExistingViewNames(comps);
2949 while (existingNames.contains(newViewName))
2951 newViewName = viewTitle + " " + (++index);
2957 * Returns a list of distinct view names found in the given list of
2958 * components. View names are held on the viewport of an AlignmentPanel.
2963 protected List<String> getExistingViewNames(List<Component> comps)
2965 List<String> existingNames = new ArrayList<>();
2966 for (Component comp : comps)
2968 if (comp instanceof AlignmentPanel)
2970 AlignmentPanel ap = (AlignmentPanel) comp;
2971 if (!existingNames.contains(ap.av.getViewName()))
2973 existingNames.add(ap.av.getViewName());
2977 return existingNames;
2981 * Explode tabbed views into separate windows.
2984 public void expandViews_actionPerformed(ActionEvent e)
2986 Desktop.explodeViews(this);
2990 * Gather views in separate windows back into a tabbed presentation.
2993 public void gatherViews_actionPerformed(ActionEvent e)
2995 Desktop.instance.gatherViews(this);
3005 public void font_actionPerformed(ActionEvent e)
3007 new FontChooser(alignPanel);
3017 protected void seqLimit_actionPerformed(ActionEvent e)
3019 viewport.setShowJVSuffix(seqLimits.isSelected());
3021 alignPanel.getIdPanel().getIdCanvas()
3022 .setPreferredSize(alignPanel.calculateIdWidth());
3023 alignPanel.paintAlignment(true, false);
3027 public void idRightAlign_actionPerformed(ActionEvent e)
3029 viewport.setRightAlignIds(idRightAlign.isSelected());
3030 alignPanel.paintAlignment(false, false);
3034 public void centreColumnLabels_actionPerformed(ActionEvent e)
3036 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3037 alignPanel.paintAlignment(false, false);
3043 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3046 protected void followHighlight_actionPerformed()
3049 * Set the 'follow' flag on the Viewport (and scroll to position if now
3052 final boolean state = this.followHighlightMenuItem.getState();
3053 viewport.setFollowHighlight(state);
3056 alignPanel.scrollToPosition(viewport.getSearchResults());
3067 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3069 viewport.setColourText(colourTextMenuItem.isSelected());
3070 alignPanel.paintAlignment(false, false);
3080 public void wrapMenuItem_actionPerformed(ActionEvent e)
3082 scaleAbove.setVisible(wrapMenuItem.isSelected());
3083 scaleLeft.setVisible(wrapMenuItem.isSelected());
3084 scaleRight.setVisible(wrapMenuItem.isSelected());
3085 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3086 alignPanel.updateLayout();
3090 public void showAllSeqs_actionPerformed(ActionEvent e)
3092 viewport.showAllHiddenSeqs();
3096 public void showAllColumns_actionPerformed(ActionEvent e)
3098 viewport.showAllHiddenColumns();
3099 alignPanel.paintAlignment(true, true);
3100 viewport.sendSelection();
3104 public void hideSelSequences_actionPerformed(ActionEvent e)
3106 viewport.hideAllSelectedSeqs();
3110 * called by key handler and the hide all/show all menu items
3115 protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3118 boolean hide = false;
3119 SequenceGroup sg = viewport.getSelectionGroup();
3120 if (!toggleSeqs && !toggleCols)
3122 // Hide everything by the current selection - this is a hack - we do the
3123 // invert and then hide
3124 // first check that there will be visible columns after the invert.
3125 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3126 && sg.getStartRes() <= sg.getEndRes()))
3128 // now invert the sequence set, if required - empty selection implies
3129 // that no hiding is required.
3132 invertSequenceMenuItem_actionPerformed(null);
3133 sg = viewport.getSelectionGroup();
3137 viewport.expandColSelection(sg, true);
3138 // finally invert the column selection and get the new sequence
3140 invertColSel_actionPerformed(null);
3147 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3149 hideSelSequences_actionPerformed(null);
3152 else if (!(toggleCols && viewport.hasSelectedColumns()))
3154 showAllSeqs_actionPerformed(null);
3160 if (viewport.hasSelectedColumns())
3162 hideSelColumns_actionPerformed(null);
3165 viewport.setSelectionGroup(sg);
3170 showAllColumns_actionPerformed(null);
3179 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3180 * event.ActionEvent)
3183 public void hideAllButSelection_actionPerformed(ActionEvent e)
3185 toggleHiddenRegions(false, false);
3186 viewport.sendSelection();
3193 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3197 public void hideAllSelection_actionPerformed(ActionEvent e)
3199 SequenceGroup sg = viewport.getSelectionGroup();
3200 viewport.expandColSelection(sg, false);
3201 viewport.hideAllSelectedSeqs();
3202 viewport.hideSelectedColumns();
3203 alignPanel.updateLayout();
3204 alignPanel.paintAlignment(true, true);
3205 viewport.sendSelection();
3212 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3216 public void showAllhidden_actionPerformed(ActionEvent e)
3218 viewport.showAllHiddenColumns();
3219 viewport.showAllHiddenSeqs();
3220 alignPanel.paintAlignment(true, true);
3221 viewport.sendSelection();
3225 public void hideSelColumns_actionPerformed(ActionEvent e)
3227 viewport.hideSelectedColumns();
3228 alignPanel.updateLayout();
3229 alignPanel.paintAlignment(true, true);
3230 viewport.sendSelection();
3234 public void hiddenMarkers_actionPerformed(ActionEvent e)
3236 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3247 protected void scaleAbove_actionPerformed(ActionEvent e)
3249 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3250 alignPanel.updateLayout();
3251 alignPanel.paintAlignment(true, false);
3261 protected void scaleLeft_actionPerformed(ActionEvent e)
3263 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3264 alignPanel.updateLayout();
3265 alignPanel.paintAlignment(true, false);
3275 protected void scaleRight_actionPerformed(ActionEvent e)
3277 viewport.setScaleRightWrapped(scaleRight.isSelected());
3278 alignPanel.updateLayout();
3279 alignPanel.paintAlignment(true, false);
3289 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3291 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3292 alignPanel.paintAlignment(false, false);
3302 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3304 viewport.setShowText(viewTextMenuItem.isSelected());
3305 alignPanel.paintAlignment(false, false);
3315 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3317 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3318 alignPanel.paintAlignment(false, false);
3321 public FeatureSettings featureSettings;
3324 public FeatureSettingsControllerI getFeatureSettingsUI()
3326 return featureSettings;
3330 public void featureSettings_actionPerformed(ActionEvent e)
3332 showFeatureSettingsUI();
3336 public FeatureSettingsControllerI showFeatureSettingsUI()
3338 if (featureSettings != null)
3340 featureSettings.closeOldSettings();
3341 featureSettings = null;
3343 if (!showSeqFeatures.isSelected())
3345 // make sure features are actually displayed
3346 showSeqFeatures.setSelected(true);
3347 showSeqFeatures_actionPerformed(null);
3349 featureSettings = new FeatureSettings(this);
3350 return featureSettings;
3354 * Set or clear 'Show Sequence Features'
3360 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3362 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3363 alignPanel.paintAlignment(true, true);
3367 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3368 * the annotations panel as a whole.
3370 * The options to show/hide all annotations should be enabled when the panel
3371 * is shown, and disabled when the panel is hidden.
3376 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3378 final boolean setVisible = annotationPanelMenuItem.isSelected();
3379 viewport.setShowAnnotation(setVisible);
3380 this.showAllSeqAnnotations.setEnabled(setVisible);
3381 this.hideAllSeqAnnotations.setEnabled(setVisible);
3382 this.showAllAlAnnotations.setEnabled(setVisible);
3383 this.hideAllAlAnnotations.setEnabled(setVisible);
3384 alignPanel.updateLayout();
3388 public void alignmentProperties()
3391 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3394 String content = MessageManager.formatMessage("label.html_content",
3396 { contents.toString() });
3399 if (Platform.isJS())
3401 JLabel textLabel = new JLabel();
3402 textLabel.setText(content);
3403 textLabel.setBackground(Color.WHITE);
3405 pane = new JPanel(new BorderLayout());
3406 ((JPanel) pane).setOpaque(true);
3407 pane.setBackground(Color.WHITE);
3408 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3417 JEditorPane editPane = new JEditorPane("text/html", "");
3418 editPane.setEditable(false);
3419 editPane.setText(content);
3423 JInternalFrame frame = new JInternalFrame();
3425 frame.getContentPane().add(new JScrollPane(pane));
3427 Desktop.addInternalFrame(frame, MessageManager
3428 .formatMessage("label.alignment_properties", new Object[]
3429 { getTitle() }), 500, 400);
3439 public void overviewMenuItem_actionPerformed(ActionEvent e)
3441 if (alignPanel.overviewPanel != null)
3446 JInternalFrame frame = new JInternalFrame();
3447 final OverviewPanel overview = new OverviewPanel(alignPanel);
3448 frame.setContentPane(overview);
3449 Desktop.addInternalFrame(frame, MessageManager
3450 .formatMessage("label.overview_params", new Object[]
3451 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3454 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3455 frame.addInternalFrameListener(
3456 new javax.swing.event.InternalFrameAdapter()
3459 public void internalFrameClosed(
3460 javax.swing.event.InternalFrameEvent evt)
3463 alignPanel.setOverviewPanel(null);
3466 if (getKeyListeners().length > 0)
3468 frame.addKeyListener(getKeyListeners()[0]);
3471 alignPanel.setOverviewPanel(overview);
3475 public void textColour_actionPerformed()
3477 new TextColourChooser().chooseColour(alignPanel, null);
3481 * public void covariationColour_actionPerformed() {
3483 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3487 public void annotationColour_actionPerformed()
3489 new AnnotationColourChooser(viewport, alignPanel);
3493 public void annotationColumn_actionPerformed(ActionEvent e)
3495 new AnnotationColumnChooser(viewport, alignPanel);
3499 * Action on the user checking or unchecking the option to apply the selected
3500 * colour scheme to all groups. If unchecked, groups may have their own
3501 * independent colour schemes.
3506 public void applyToAllGroups_actionPerformed(boolean selected)
3508 viewport.setColourAppliesToAllGroups(selected);
3512 * Action on user selecting a colour from the colour menu
3515 * the name (not the menu item label!) of the colour scheme
3518 public void changeColour_actionPerformed(String name)
3521 * 'User Defined' opens a panel to configure or load a
3522 * user-defined colour scheme
3524 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3526 new UserDefinedColours(alignPanel);
3531 * otherwise set the chosen colour scheme (or null for 'None')
3533 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3534 viewport, viewport.getAlignment(),
3535 viewport.getHiddenRepSequences());
3540 * Actions on setting or changing the alignment colour scheme
3545 public void changeColour(ColourSchemeI cs)
3547 // TODO: pull up to controller method
3548 ColourMenuHelper.setColourSelected(colourMenu, cs);
3550 viewport.setGlobalColourScheme(cs);
3552 alignPanel.paintAlignment(true, true);
3556 * Show the PID threshold slider panel
3559 protected void modifyPID_actionPerformed()
3561 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3562 alignPanel.getViewName());
3563 SliderPanel.showPIDSlider();
3567 * Show the Conservation slider panel
3570 protected void modifyConservation_actionPerformed()
3572 SliderPanel.setConservationSlider(alignPanel,
3573 viewport.getResidueShading(), alignPanel.getViewName());
3574 SliderPanel.showConservationSlider();
3578 * Action on selecting or deselecting (Colour) By Conservation
3581 public void conservationMenuItem_actionPerformed(boolean selected)
3583 modifyConservation.setEnabled(selected);
3584 viewport.setConservationSelected(selected);
3585 viewport.getResidueShading().setConservationApplied(selected);
3587 changeColour(viewport.getGlobalColourScheme());
3590 modifyConservation_actionPerformed();
3594 SliderPanel.hideConservationSlider();
3599 * Action on selecting or deselecting (Colour) Above PID Threshold
3602 public void abovePIDThreshold_actionPerformed(boolean selected)
3604 modifyPID.setEnabled(selected);
3605 viewport.setAbovePIDThreshold(selected);
3608 viewport.getResidueShading().setThreshold(0,
3609 viewport.isIgnoreGapsConsensus());
3612 changeColour(viewport.getGlobalColourScheme());
3615 modifyPID_actionPerformed();
3619 SliderPanel.hidePIDSlider();
3630 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3632 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3633 AlignmentSorter.sortByPID(viewport.getAlignment(),
3634 viewport.getAlignment().getSequenceAt(0));
3635 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3636 viewport.getAlignment()));
3637 alignPanel.paintAlignment(true, false);
3647 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3649 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3650 AlignmentSorter.sortByID(viewport.getAlignment());
3652 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3653 alignPanel.paintAlignment(true, false);
3663 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3665 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3666 AlignmentSorter.sortByLength(viewport.getAlignment());
3667 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3668 viewport.getAlignment()));
3669 alignPanel.paintAlignment(true, false);
3679 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3681 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3682 AlignmentSorter.sortByGroup(viewport.getAlignment());
3683 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3684 viewport.getAlignment()));
3686 alignPanel.paintAlignment(true, false);
3696 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3698 new RedundancyPanel(alignPanel, this);
3708 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3710 if ((viewport.getSelectionGroup() == null)
3711 || (viewport.getSelectionGroup().getSize() < 2))
3713 JvOptionPane.showInternalMessageDialog(this,
3714 MessageManager.getString(
3715 "label.you_must_select_least_two_sequences"),
3716 MessageManager.getString("label.invalid_selection"),
3717 JvOptionPane.WARNING_MESSAGE);
3721 JInternalFrame frame = new JInternalFrame();
3722 frame.setContentPane(new PairwiseAlignPanel(viewport));
3723 Desktop.addInternalFrame(frame,
3724 MessageManager.getString("action.pairwise_alignment"), 600,
3730 public void autoCalculate_actionPerformed(ActionEvent e)
3732 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3733 if (viewport.autoCalculateConsensus)
3735 viewport.firePropertyChange("alignment", null,
3736 viewport.getAlignment().getSequences());
3741 public void sortByTreeOption_actionPerformed(ActionEvent e)
3743 viewport.sortByTree = sortByTree.isSelected();
3747 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3749 viewport.followSelection = listenToViewSelections.isSelected();
3753 * Constructs a tree panel and adds it to the desktop
3762 void newTreePanel(TreeModel tree, String treeAlgo,
3763 String substitutionMatrix)
3765 String frameTitle = "";
3768 boolean onSelection = false;
3769 if (viewport.getSelectionGroup() != null
3770 && viewport.getSelectionGroup().getSize() > 0)
3772 SequenceGroup sg = viewport.getSelectionGroup();
3774 /* Decide if the selection is a column region */
3775 for (SequenceI _s : sg.getSequences()) // port this to Archaeopteryx?
3777 if (_s.getLength() < sg.getEndRes())
3779 JvOptionPane.showMessageDialog(Desktop.desktop,
3780 MessageManager.getString(
3781 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3782 MessageManager.getString(
3783 "label.sequences_selection_not_aligned"),
3784 JvOptionPane.WARNING_MESSAGE);
3793 if (viewport.getAlignment().getHeight() < 2)
3799 tp = new TreePanel(alignPanel, tree, treeAlgo, substitutionMatrix);
3800 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3802 frameTitle += " from ";
3804 if (viewport.getViewName() != null)
3806 frameTitle += viewport.getViewName() + " of ";
3809 frameTitle += this.title;
3811 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3822 public void addSortByOrderMenuItem(String title,
3823 final AlignmentOrder order)
3825 final JMenuItem item = new JMenuItem(MessageManager
3826 .formatMessage("action.by_title_param", new Object[]
3829 item.addActionListener(new java.awt.event.ActionListener()
3832 public void actionPerformed(ActionEvent e)
3834 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3836 // TODO: JBPNote - have to map order entries to curent SequenceI
3838 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3840 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3841 viewport.getAlignment()));
3843 alignPanel.paintAlignment(true, false);
3849 * Add a new sort by annotation score menu item
3852 * the menu to add the option to
3854 * the label used to retrieve scores for each sequence on the
3857 public void addSortByAnnotScoreMenuItem(JMenu sort,
3858 final String scoreLabel)
3860 final JMenuItem item = new JMenuItem(scoreLabel);
3862 item.addActionListener(new java.awt.event.ActionListener()
3865 public void actionPerformed(ActionEvent e)
3867 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3868 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3869 viewport.getAlignment());// ,viewport.getSelectionGroup());
3870 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3871 viewport.getAlignment()));
3872 alignPanel.paintAlignment(true, false);
3878 * last hash for alignment's annotation array - used to minimise cost of
3881 protected int _annotationScoreVectorHash;
3884 * search the alignment and rebuild the sort by annotation score submenu the
3885 * last alignment annotation vector hash is stored to minimize cost of
3886 * rebuilding in subsequence calls.
3890 public void buildSortByAnnotationScoresMenu()
3892 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3897 if (viewport.getAlignment().getAlignmentAnnotation()
3898 .hashCode() != _annotationScoreVectorHash)
3900 sortByAnnotScore.removeAll();
3901 // almost certainly a quicker way to do this - but we keep it simple
3902 Hashtable<String, String> scoreSorts = new Hashtable<>();
3903 AlignmentAnnotation aann[];
3904 for (SequenceI sqa : viewport.getAlignment().getSequences())
3906 aann = sqa.getAnnotation();
3907 for (int i = 0; aann != null && i < aann.length; i++)
3909 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3911 scoreSorts.put(aann[i].label, aann[i].label);
3915 Enumeration<String> labels = scoreSorts.keys();
3916 while (labels.hasMoreElements())
3918 addSortByAnnotScoreMenuItem(sortByAnnotScore, labels.nextElement());
3920 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3923 _annotationScoreVectorHash = viewport.getAlignment()
3924 .getAlignmentAnnotation().hashCode();
3929 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3930 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3931 * call. Listeners are added to remove the menu item when the treePanel is
3932 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3936 public void buildTreeSortMenu()
3938 sortByTreeMenu.removeAll();
3940 List<Component> comps = PaintRefresher.components
3941 .get(viewport.getSequenceSetId());
3942 List<TreePanel> treePanels = new ArrayList<>();
3943 for (Component comp : comps)
3945 if (comp instanceof TreePanel)
3947 treePanels.add((TreePanel) comp);
3951 if (treePanels.size() < 1)
3953 sortByTreeMenu.setVisible(false);
3957 sortByTreeMenu.setVisible(true);
3959 for (final TreePanel tp : treePanels)
3961 final JMenuItem item = new JMenuItem(tp.getTitle());
3962 item.addActionListener(new java.awt.event.ActionListener()
3965 public void actionPerformed(ActionEvent e)
3968 tp.sortByTree_actionPerformed();
3969 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3974 sortByTreeMenu.add(item);
3978 public boolean sortBy(AlignmentOrder alorder, String undoname)
3980 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3981 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3982 if (undoname != null)
3984 addHistoryItem(new OrderCommand(undoname, oldOrder,
3985 viewport.getAlignment()));
3987 alignPanel.paintAlignment(true, false);
3992 * Work out whether the whole set of sequences or just the selected set will
3993 * be submitted for multiple alignment.
3996 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3998 // Now, check we have enough sequences
3999 AlignmentView msa = null;
4001 if ((viewport.getSelectionGroup() != null)
4002 && (viewport.getSelectionGroup().getSize() > 1))
4004 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4005 // some common interface!
4007 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4008 * SequenceI[sz = seqs.getSize(false)];
4010 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4011 * seqs.getSequenceAt(i); }
4013 msa = viewport.getAlignmentView(true);
4015 else if (viewport.getSelectionGroup() != null
4016 && viewport.getSelectionGroup().getSize() == 1)
4018 int option = JvOptionPane.showConfirmDialog(this,
4019 MessageManager.getString("warn.oneseq_msainput_selection"),
4020 MessageManager.getString("label.invalid_selection"),
4021 JvOptionPane.OK_CANCEL_OPTION);
4022 if (option == JvOptionPane.OK_OPTION)
4024 msa = viewport.getAlignmentView(false);
4029 msa = viewport.getAlignmentView(false);
4035 * Decides what is submitted to a secondary structure prediction service: the
4036 * first sequence in the alignment, or in the current selection, or, if the
4037 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4038 * region or the whole alignment. (where the first sequence in the set is the
4039 * one that the prediction will be for).
4041 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4043 AlignmentView seqs = null;
4045 if ((viewport.getSelectionGroup() != null)
4046 && (viewport.getSelectionGroup().getSize() > 0))
4048 seqs = viewport.getAlignmentView(true);
4052 seqs = viewport.getAlignmentView(false);
4054 // limit sequences - JBPNote in future - could spawn multiple prediction
4056 // TODO: viewport.getAlignment().isAligned is a global state - the local
4057 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4058 if (!viewport.getAlignment().isAligned(false))
4060 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4061 // TODO: if seqs.getSequences().length>1 then should really have warned
4075 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4081 protected void loadTreeUrlItem_actionPerformed(ActionEvent e)
4087 protected void loadTreeBaseStudy_actionPerformed(ActionEvent e)
4094 protected void loadTreeOfLife_actionPerformed(ActionEvent e)
4101 protected void loadTreeFam_actionPerformed(ActionEvent e)
4108 protected void loadTreePfam_actionPerformed(ActionEvent e)
4115 protected void loadTreeBase_actionPerformed(ActionEvent e)
4122 public void chooseTreeFile()
4124 // Pick the tree file
4125 JalviewFileChooser chooser = new JalviewFileChooser(
4126 Cache.getProperty("LAST_DIRECTORY"));
4127 chooser.setFileView(new JalviewFileView());
4128 chooser.setDialogTitle(
4129 MessageManager.getString("label.select_tree_file")); // modify
4130 chooser.setToolTipText(
4131 MessageManager.getString("label.load_tree_for_sequence_set"));
4132 for (SupportedTreeFileFilter treeFormat : SupportedTreeFileFilter
4135 chooser.setFileFilter(treeFormat.getTreeFilter());
4138 chooser.setResponseHandler(0, new Runnable()
4143 String filePath = chooser.getSelectedFile().getPath();
4144 Cache.setProperty("LAST_DIRECTORY", filePath);
4145 TreeParser treeParser = null;
4147 treeParser = new TreeParser(filePath);
4148 treeParser.loadTree(viewport);
4149 } catch (Exception ex)
4151 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4153 .getString("label.problem_reading_tree_file"),
4154 JvOptionPane.WARNING_MESSAGE);
4155 ex.printStackTrace();
4157 // TODO: handle any other warnings from treeParser ?
4158 // if (treeParser != null && treeParser.fin.hasWarningMessage())
4160 // JvOptionPane.showMessageDialog(Desktop.desktop,
4161 // fin.getWarningMessage(),
4162 // MessageManager.getString(
4163 // "label.possible_problem_with_tree_file"),
4164 // JvOptionPane.WARNING_MESSAGE);
4168 chooser.showOpenDialog(this);
4172 * Break up and move to TreeParser?
4174 public void chooseTreeUrl()
4177 JLabel label = new JLabel(
4178 MessageManager.getString("label.tree_url_example"));
4179 // add "example" button
4180 final JComboBox<String> history = new JComboBox<>();
4182 JPanel panel = new JPanel(new GridLayout(2, 1));
4185 history.setPreferredSize(new Dimension(400, 20));
4186 history.setEditable(true);
4187 history.addItem("http://www.");
4189 String historyItems = jalview.bin.Cache.getProperty("RECENT_URL");
4193 if (historyItems != null)
4195 st = new StringTokenizer(historyItems, "\t");
4197 while (st.hasMoreTokens())
4199 history.addItem(st.nextToken());
4203 int reply = JvOptionPane.showInternalConfirmDialog(this, panel,
4204 MessageManager.getString("label.load_tree_url"),
4205 JvOptionPane.OK_CANCEL_OPTION);
4207 if (reply == JvOptionPane.OK_OPTION)
4210 String urlString = history.getSelectedItem().toString();
4215 FileFormatI format = null;
4217 format = new IdentifyFile().identify(urlString, DataSourceType.URL);
4218 // add actual use for the format identification (jalview .jar files)
4219 treeUrl = new URL(urlString);
4220 AptxInit.createInstanceFromUrl(treeUrl, viewport);
4222 } catch (IOException | RuntimeException e)
4224 JvOptionPane.showMessageDialog(this, MessageManager.formatMessage(
4225 "exception.failed_to_read_data_from_source", new String[]
4227 MessageManager.getString("label.url_not_found"),
4228 JvOptionPane.ERROR_MESSAGE);
4229 e.printStackTrace();
4238 public void chooseTreeDb()
4242 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4244 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4247 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4248 int h, int x, int y)
4250 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4254 * Add a treeviewer for the tree extracted from a Newick file object to the
4255 * current alignment view
4262 * Associated alignment input data (or null)
4271 * @return TreePanel handle
4273 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4274 AlignmentView input, int w, int h, int x, int y)
4276 TreePanel tp = null;
4282 if (nf.getTree() != null)
4284 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4290 tp.setLocation(x, y);
4293 Desktop.addInternalFrame(tp, treeTitle, w, h);
4295 } catch (Exception ex)
4297 ex.printStackTrace();
4303 private boolean buildingMenu = false;
4306 * Generates menu items and listener event actions for web service clients
4309 public void BuildWebServiceMenu()
4311 while (buildingMenu)
4315 System.err.println("Waiting for building menu to finish.");
4317 } catch (Exception e)
4321 final AlignFrame me = this;
4322 buildingMenu = true;
4323 new Thread(new Runnable()
4328 final List<JMenuItem> legacyItems = new ArrayList<>();
4331 // System.err.println("Building ws menu again "
4332 // + Thread.currentThread());
4333 // TODO: add support for context dependent disabling of services based
4335 // alignment and current selection
4336 // TODO: add additional serviceHandle parameter to specify abstract
4338 // class independently of AbstractName
4339 // TODO: add in rediscovery GUI function to restart discoverer
4340 // TODO: group services by location as well as function and/or
4342 // object broker mechanism.
4343 final Vector<JMenu> wsmenu = new Vector<>();
4344 final IProgressIndicator af = me;
4347 * do not i18n these strings - they are hard-coded in class
4348 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4349 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4351 final JMenu msawsmenu = new JMenu("Alignment");
4352 final JMenu secstrmenu = new JMenu(
4353 "Secondary Structure Prediction");
4354 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4355 final JMenu analymenu = new JMenu("Analysis");
4356 final JMenu dismenu = new JMenu("Protein Disorder");
4357 final JMenu phylogenmenu = new JMenu("Phylogenetic inference");
4359 // JAL-940 - only show secondary structure prediction services from
4360 // the legacy server
4361 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4363 Discoverer.services != null && (Discoverer.services.size() > 0))
4365 // TODO: refactor to allow list of AbstractName/Handler bindings to
4367 // stored or retrieved from elsewhere
4368 // No MSAWS used any more:
4369 // Vector msaws = null; // (Vector)
4370 // Discoverer.services.get("MsaWS");
4371 Vector<ServiceHandle> secstrpr = Discoverer.services
4373 if (secstrpr != null)
4375 // Add any secondary structure prediction services
4376 for (int i = 0, j = secstrpr.size(); i < j; i++)
4378 final ext.vamsas.ServiceHandle sh = secstrpr.get(i);
4379 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4380 .getServiceClient(sh);
4381 int p = secstrmenu.getItemCount();
4382 impl.attachWSMenuEntry(secstrmenu, me);
4383 int q = secstrmenu.getItemCount();
4384 for (int litm = p; litm < q; litm++)
4386 legacyItems.add(secstrmenu.getItem(litm));
4392 // Add all submenus in the order they should appear on the web
4394 wsmenu.add(msawsmenu);
4395 wsmenu.add(secstrmenu);
4396 wsmenu.add(dismenu);
4397 wsmenu.add(analymenu);
4398 wsmenu.add(phylogenmenu);
4399 // No search services yet
4400 // wsmenu.add(seqsrchmenu);
4402 javax.swing.SwingUtilities.invokeLater(new Runnable()
4409 webService.removeAll();
4410 // first, add discovered services onto the webservices menu
4411 if (wsmenu.size() > 0)
4413 for (int i = 0, j = wsmenu.size(); i < j; i++)
4415 webService.add(wsmenu.get(i));
4420 webService.add(me.webServiceNoServices);
4422 // TODO: move into separate menu builder class.
4424 // logic for 2.11.1.4 is
4425 // always look to see if there is a discover. if there isn't
4426 // we can't show any Jws2 services
4427 // if there are services available, show them - regardless of
4428 // the 'show JWS2 preference'
4429 // if the discoverer is running then say so
4430 // otherwise offer to trigger discovery if 'show JWS2' is not
4432 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4433 if (jws2servs != null)
4435 if (jws2servs.hasServices())
4437 jws2servs.attachWSMenuEntry(webService, me);
4438 for (Jws2Instance sv : jws2servs.getServices())
4440 if (sv.description.toLowerCase(Locale.ROOT)
4443 for (JMenuItem jmi : legacyItems)
4445 jmi.setVisible(false);
4451 if (jws2servs.isRunning())
4453 JMenuItem tm = new JMenuItem(
4454 "Still discovering JABA Services");
4455 tm.setEnabled(false);
4458 else if (!Cache.getDefault("SHOW_JWS2_SERVICES", true))
4460 JMenuItem enableJws2 = new JMenuItem(
4461 "Discover Web Services");
4462 enableJws2.setToolTipText(
4463 "Select to start JABA Web Service discovery (or enable option in Web Service preferences)");
4464 enableJws2.setEnabled(true);
4465 enableJws2.addActionListener(new ActionListener()
4469 public void actionPerformed(ActionEvent e)
4471 // start service discoverer, but ignore preference
4472 Desktop.instance.startServiceDiscovery(false,
4476 webService.add(enableJws2);
4480 build_urlServiceMenu(me.webService);
4481 build_fetchdbmenu(webService);
4482 for (JMenu item : wsmenu)
4484 if (item.getItemCount() == 0)
4486 item.setEnabled(false);
4490 item.setEnabled(true);
4493 } catch (Exception e)
4496 "Exception during web service menu building process.",
4501 } catch (Exception e)
4504 buildingMenu = false;
4506 }, "BuildWebServiceThread").start();
4511 * construct any groupURL type service menu entries.
4515 protected void build_urlServiceMenu(JMenu webService)
4517 // TODO: remove this code when 2.7 is released
4518 // DEBUG - alignmentView
4520 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4521 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4523 * @Override public void actionPerformed(ActionEvent e) {
4524 * jalview.datamodel.AlignmentView
4525 * .testSelectionViews(af.viewport.getAlignment(),
4526 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4528 * }); webService.add(testAlView);
4530 // TODO: refactor to RestClient discoverer and merge menu entries for
4531 // rest-style services with other types of analysis/calculation service
4532 // SHmmr test client - still being implemented.
4533 // DEBUG - alignmentView
4535 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4538 client.attachWSMenuEntry(
4539 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4545 * Searches the alignment sequences for xRefs and builds the Show
4546 * Cross-References menu (formerly called Show Products), with database
4547 * sources for which cross-references are found (protein sources for a
4548 * nucleotide alignment and vice versa)
4550 * @return true if Show Cross-references menu should be enabled
4552 public boolean canShowProducts()
4554 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4555 AlignmentI dataset = viewport.getAlignment().getDataset();
4557 showProducts.removeAll();
4558 final boolean dna = viewport.getAlignment().isNucleotide();
4560 if (seqs == null || seqs.length == 0)
4562 // nothing to see here.
4566 boolean showp = false;
4569 List<String> ptypes = new CrossRef(seqs, dataset)
4570 .findXrefSourcesForSequences(dna);
4572 for (final String source : ptypes)
4575 final AlignFrame af = this;
4576 JMenuItem xtype = new JMenuItem(source);
4577 xtype.addActionListener(new ActionListener()
4580 public void actionPerformed(ActionEvent e)
4582 showProductsFor(af.viewport.getSequenceSelection(), dna,
4586 showProducts.add(xtype);
4588 showProducts.setVisible(showp);
4589 showProducts.setEnabled(showp);
4590 } catch (Exception e)
4593 "canShowProducts threw an exception - please report to help@jalview.org",
4601 * Finds and displays cross-references for the selected sequences (protein
4602 * products for nucleotide sequences, dna coding sequences for peptides).
4605 * the sequences to show cross-references for
4607 * true if from a nucleotide alignment (so showing proteins)
4609 * the database to show cross-references for
4611 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4612 final String source)
4614 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this),
4615 "CrossReferencesThread")
4620 * Construct and display a new frame containing the translation of this
4621 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4624 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4626 AlignmentI al = null;
4629 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4631 al = dna.translateCdna(codeTable);
4632 } catch (Exception ex)
4634 Console.error("Exception during translation. Please report this !",
4636 final String msg = MessageManager.getString(
4637 "label.error_when_translating_sequences_submit_bug_report");
4638 final String errorTitle = MessageManager
4639 .getString("label.implementation_error")
4640 + MessageManager.getString("label.translation_failed");
4641 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4642 JvOptionPane.ERROR_MESSAGE);
4645 if (al == null || al.getHeight() == 0)
4647 final String msg = MessageManager.getString(
4648 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4649 final String errorTitle = MessageManager
4650 .getString("label.translation_failed");
4651 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4652 JvOptionPane.WARNING_MESSAGE);
4656 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4657 af.setFileFormat(this.currentFileFormat);
4658 final String newTitle = MessageManager
4659 .formatMessage("label.translation_of_params", new Object[]
4660 { this.getTitle(), codeTable.getId() });
4661 af.setTitle(newTitle);
4662 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4664 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4665 viewport.openSplitFrame(af, new Alignment(seqs));
4669 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4676 * Set the file format
4680 public void setFileFormat(FileFormatI format)
4682 this.currentFileFormat = format;
4686 * Try to load a features file onto the alignment.
4689 * contents or path to retrieve file or a File object
4691 * access mode of file (see jalview.io.AlignFile)
4692 * @return true if features file was parsed correctly.
4694 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4697 return avc.parseFeaturesFile(file, sourceType,
4698 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4703 public void refreshFeatureUI(boolean enableIfNecessary)
4705 // note - currently this is only still here rather than in the controller
4706 // because of the featureSettings hard reference that is yet to be
4708 if (enableIfNecessary)
4710 viewport.setShowSequenceFeatures(true);
4711 showSeqFeatures.setSelected(true);
4717 public void dragEnter(DropTargetDragEvent evt)
4722 public void dragExit(DropTargetEvent evt)
4727 public void dragOver(DropTargetDragEvent evt)
4732 public void dropActionChanged(DropTargetDragEvent evt)
4737 public void drop(DropTargetDropEvent evt)
4739 // JAL-1552 - acceptDrop required before getTransferable call for
4740 // Java's Transferable for native dnd
4741 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4742 Transferable t = evt.getTransferable();
4744 final AlignFrame thisaf = this;
4745 final List<Object> files = new ArrayList<>();
4746 List<DataSourceType> protocols = new ArrayList<>();
4750 Desktop.transferFromDropTarget(files, protocols, evt, t);
4751 } catch (Exception e)
4753 e.printStackTrace();
4757 new Thread(new Runnable()
4764 // check to see if any of these files have names matching sequences
4767 SequenceIdMatcher idm = new SequenceIdMatcher(
4768 viewport.getAlignment().getSequencesArray());
4770 * Object[] { String,SequenceI}
4772 ArrayList<Object[]> filesmatched = new ArrayList<>();
4773 ArrayList<Object> filesnotmatched = new ArrayList<>();
4774 for (int i = 0; i < files.size(); i++)
4777 Object file = files.get(i);
4778 String fileName = file.toString();
4780 DataSourceType protocol = (file instanceof File
4781 ? DataSourceType.FILE
4782 : FormatAdapter.checkProtocol(fileName));
4783 if (protocol == DataSourceType.FILE)
4786 if (file instanceof File)
4789 Platform.cacheFileData(fl);
4793 fl = new File(fileName);
4795 pdbfn = fl.getName();
4797 else if (protocol == DataSourceType.URL)
4799 URL url = new URL(fileName);
4800 pdbfn = url.getFile();
4802 if (pdbfn.length() > 0)
4804 // attempt to find a match in the alignment
4805 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4806 int l = 0, c = pdbfn.indexOf(".");
4807 while (mtch == null && c != -1)
4812 } while ((c = pdbfn.indexOf(".", l)) > l);
4815 pdbfn = pdbfn.substring(0, l);
4817 mtch = idm.findAllIdMatches(pdbfn);
4824 type = new IdentifyFile().identify(file, protocol);
4825 } catch (Exception ex)
4829 if (type != null && type.isStructureFile())
4831 filesmatched.add(new Object[] { file, protocol, mtch });
4835 // File wasn't named like one of the sequences or wasn't a PDB
4837 filesnotmatched.add(file);
4841 if (filesmatched.size() > 0)
4843 boolean autoAssociate = Cache
4844 .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4847 String msg = MessageManager.formatMessage(
4848 "label.automatically_associate_structure_files_with_sequences_same_name",
4850 { Integer.valueOf(filesmatched.size())
4852 String ttl = MessageManager.getString(
4853 "label.automatically_associate_structure_files_by_name");
4854 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4855 ttl, JvOptionPane.YES_NO_OPTION);
4856 autoAssociate = choice == JvOptionPane.YES_OPTION;
4860 for (Object[] fm : filesmatched)
4862 // try and associate
4863 // TODO: may want to set a standard ID naming formalism for
4864 // associating PDB files which have no IDs.
4865 for (SequenceI toassoc : (SequenceI[]) fm[2])
4867 PDBEntry pe = new AssociatePdbFileWithSeq()
4868 .associatePdbWithSeq(fm[0].toString(),
4869 (DataSourceType) fm[1], toassoc, false,
4873 System.err.println("Associated file : "
4874 + (fm[0].toString()) + " with "
4875 + toassoc.getDisplayId(true));
4879 // TODO: do we need to update overview ? only if features are
4881 alignPanel.paintAlignment(true, false);
4887 * add declined structures as sequences
4889 for (Object[] o : filesmatched)
4891 filesnotmatched.add(o[0]);
4895 if (filesnotmatched.size() > 0)
4897 if (assocfiles > 0 && (Cache.getDefault(
4898 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4899 || JvOptionPane.showConfirmDialog(thisaf,
4900 "<html>" + MessageManager.formatMessage(
4901 "label.ignore_unmatched_dropped_files_info",
4904 filesnotmatched.size())
4907 MessageManager.getString(
4908 "label.ignore_unmatched_dropped_files"),
4909 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4913 for (Object fn : filesnotmatched)
4915 loadJalviewDataFile(fn, null, null, null);
4919 } catch (Exception ex)
4921 ex.printStackTrace();
4924 }, "DropFileThread").start();
4929 * Attempt to load a "dropped" file or URL string, by testing in turn for
4931 * <li>an Annotation file</li>
4932 * <li>a JNet file</li>
4933 * <li>a features file</li>
4934 * <li>else try to interpret as an alignment file</li>
4938 * either a filename or a URL string.
4940 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4941 FileFormatI format, SequenceI assocSeq)
4943 // BH 2018 was String file
4946 if (sourceType == null)
4948 sourceType = FormatAdapter.checkProtocol(file);
4950 // if the file isn't identified, or not positively identified as some
4951 // other filetype (PFAM is default unidentified alignment file type) then
4952 // try to parse as annotation.
4953 boolean isAnnotation = (format == null
4954 || FileFormat.Pfam.equals(format))
4955 ? new AnnotationFile().annotateAlignmentView(viewport,
4961 // first see if its a T-COFFEE score file
4962 TCoffeeScoreFile tcf = null;
4965 tcf = new TCoffeeScoreFile(file, sourceType);
4968 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4972 new TCoffeeColourScheme(viewport.getAlignment()));
4973 isAnnotation = true;
4974 setStatus(MessageManager.getString(
4975 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4979 // some problem - if no warning its probable that the ID matching
4980 // process didn't work
4981 JvOptionPane.showMessageDialog(Desktop.desktop,
4982 tcf.getWarningMessage() == null
4983 ? MessageManager.getString(
4984 "label.check_file_matches_sequence_ids_alignment")
4985 : tcf.getWarningMessage(),
4986 MessageManager.getString(
4987 "label.problem_reading_tcoffee_score_file"),
4988 JvOptionPane.WARNING_MESSAGE);
4995 } catch (Exception x)
4998 "Exception when processing data source as T-COFFEE score file",
5004 // try to see if its a JNet 'concise' style annotation file *before*
5006 // try to parse it as a features file
5009 format = new IdentifyFile().identify(file, sourceType);
5011 if (FileFormat.ScoreMatrix == format)
5013 ScoreMatrixFile sm = new ScoreMatrixFile(
5014 new FileParse(file, sourceType));
5016 // todo: i18n this message
5017 setStatus(MessageManager.formatMessage(
5018 "label.successfully_loaded_matrix",
5019 sm.getMatrixName()));
5021 else if (FileFormat.Jnet.equals(format))
5023 JPredFile predictions = new JPredFile(file, sourceType);
5024 new JnetAnnotationMaker();
5025 JnetAnnotationMaker.add_annotation(predictions,
5026 viewport.getAlignment(), 0, false);
5027 viewport.getAlignment().setupJPredAlignment();
5028 isAnnotation = true;
5030 // else if (IdentifyFile.FeaturesFile.equals(format))
5031 else if (FileFormat.Features.equals(format))
5033 if (parseFeaturesFile(file, sourceType))
5035 SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
5036 if (splitFrame != null)
5038 splitFrame.repaint();
5042 alignPanel.paintAlignment(true, true);
5048 new FileLoader().LoadFile(viewport, file, sourceType, format);
5055 alignPanel.adjustAnnotationHeight();
5056 viewport.updateSequenceIdColours();
5057 buildSortByAnnotationScoresMenu();
5058 alignPanel.paintAlignment(true, true);
5060 } catch (Exception ex)
5062 ex.printStackTrace();
5063 } catch (OutOfMemoryError oom)
5068 } catch (Exception x)
5073 + (sourceType != null
5074 ? (sourceType == DataSourceType.PASTE
5076 : "using " + sourceType + " from "
5080 ? "(parsing as '" + format + "' file)"
5082 oom, Desktop.desktop);
5087 * Method invoked by the ChangeListener on the tabbed pane, in other words
5088 * when a different tabbed pane is selected by the user or programmatically.
5091 public void tabSelectionChanged(int index)
5095 alignPanel = alignPanels.get(index);
5096 viewport = alignPanel.av;
5097 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5098 setMenusFromViewport(viewport);
5099 if (featureSettings != null && featureSettings.isOpen()
5100 && featureSettings.fr.getViewport() != viewport)
5102 if (viewport.isShowSequenceFeatures())
5104 // refresh the featureSettings to reflect UI change
5105 showFeatureSettingsUI();
5109 // close feature settings for this view.
5110 featureSettings.close();
5117 * 'focus' any colour slider that is open to the selected viewport
5119 if (viewport.getConservationSelected())
5121 SliderPanel.setConservationSlider(alignPanel,
5122 viewport.getResidueShading(), alignPanel.getViewName());
5126 SliderPanel.hideConservationSlider();
5128 if (viewport.getAbovePIDThreshold())
5130 SliderPanel.setPIDSliderSource(alignPanel,
5131 viewport.getResidueShading(), alignPanel.getViewName());
5135 SliderPanel.hidePIDSlider();
5139 * If there is a frame linked to this one in a SplitPane, switch it to the
5140 * same view tab index. No infinite recursion of calls should happen, since
5141 * tabSelectionChanged() should not get invoked on setting the selected
5142 * index to an unchanged value. Guard against setting an invalid index
5143 * before the new view peer tab has been created.
5145 final AlignViewportI peer = viewport.getCodingComplement();
5148 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
5149 .getAlignPanel().alignFrame;
5150 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5152 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5158 * On right mouse click on view tab, prompt for and set new view name.
5161 public void tabbedPane_mousePressed(MouseEvent e)
5163 if (e.isPopupTrigger())
5165 String msg = MessageManager.getString("label.enter_view_name");
5166 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
5167 String reply = JvOptionPane.showInputDialog(msg, ttl);
5171 viewport.setViewName(reply);
5172 // TODO warn if reply is in getExistingViewNames()?
5173 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5178 public AlignViewport getCurrentView()
5184 * Open the dialog for regex description parsing.
5187 protected void extractScores_actionPerformed(ActionEvent e)
5189 ParseProperties pp = new jalview.analysis.ParseProperties(
5190 viewport.getAlignment());
5191 // TODO: verify regex and introduce GUI dialog for version 2.5
5192 // if (pp.getScoresFromDescription("col", "score column ",
5193 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5195 if (pp.getScoresFromDescription("description column",
5196 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5198 buildSortByAnnotationScoresMenu();
5206 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5210 protected void showDbRefs_actionPerformed(ActionEvent e)
5212 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5218 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5222 protected void showNpFeats_actionPerformed(ActionEvent e)
5224 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5228 * find the viewport amongst the tabs in this alignment frame and close that
5233 public boolean closeView(AlignViewportI av)
5237 this.closeMenuItem_actionPerformed(false);
5240 Component[] comp = tabbedPane.getComponents();
5241 for (int i = 0; comp != null && i < comp.length; i++)
5243 if (comp[i] instanceof AlignmentPanel)
5245 if (((AlignmentPanel) comp[i]).av == av)
5248 closeView((AlignmentPanel) comp[i]);
5256 protected void build_fetchdbmenu(JMenu webService)
5258 // Temporary hack - DBRef Fetcher always top level ws entry.
5259 // TODO We probably want to store a sequence database checklist in
5260 // preferences and have checkboxes.. rather than individual sources selected
5262 final JMenu rfetch = new JMenu(
5263 MessageManager.getString("action.fetch_db_references"));
5264 rfetch.setToolTipText(MessageManager.getString(
5265 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5266 webService.add(rfetch);
5268 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5269 MessageManager.getString("option.trim_retrieved_seqs"));
5270 trimrs.setToolTipText(
5271 MessageManager.getString("label.trim_retrieved_sequences"));
5273 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5274 trimrs.addActionListener(new ActionListener()
5277 public void actionPerformed(ActionEvent e)
5279 trimrs.setSelected(trimrs.isSelected());
5280 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5281 Boolean.valueOf(trimrs.isSelected()).toString());
5285 JMenuItem fetchr = new JMenuItem(
5286 MessageManager.getString("label.standard_databases"));
5287 fetchr.setToolTipText(
5288 MessageManager.getString("label.fetch_embl_uniprot"));
5289 fetchr.addActionListener(new ActionListener()
5293 public void actionPerformed(ActionEvent e)
5295 new Thread(new Runnable()
5300 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5301 .getAlignment().isNucleotide();
5302 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5303 alignPanel.av.getSequenceSelection(),
5304 alignPanel.alignFrame, null,
5305 alignPanel.alignFrame.featureSettings, isNucleotide);
5306 dbRefFetcher.addListener(new FetchFinishedListenerI()
5309 public void finished()
5312 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5313 .getFeatureSettingsModels())
5316 alignPanel.av.mergeFeaturesStyle(srcSettings);
5318 AlignFrame.this.setMenusForViewport();
5321 dbRefFetcher.fetchDBRefs(false);
5323 }, "BuildFetchDBMenuThread").start();
5329 new Thread(new Runnable()
5334 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5335 .getSequenceFetcherSingleton();
5336 javax.swing.SwingUtilities.invokeLater(new Runnable()
5341 String[] dbclasses = sf.getNonAlignmentSources();
5342 List<DbSourceProxy> otherdb;
5343 JMenu dfetch = new JMenu();
5344 JMenu ifetch = new JMenu();
5345 JMenuItem fetchr = null;
5346 int comp = 0, icomp = 0, mcomp = 15;
5347 String mname = null;
5349 for (String dbclass : dbclasses)
5351 otherdb = sf.getSourceProxy(dbclass);
5352 // add a single entry for this class, or submenu allowing 'fetch
5354 if (otherdb == null || otherdb.size() < 1)
5360 mname = "From " + dbclass;
5362 if (otherdb.size() == 1)
5364 final DbSourceProxy[] dassource = otherdb
5365 .toArray(new DbSourceProxy[0]);
5366 DbSourceProxy src = otherdb.get(0);
5367 fetchr = new JMenuItem(src.getDbSource());
5368 fetchr.addActionListener(new ActionListener()
5372 public void actionPerformed(ActionEvent e)
5374 new Thread(new Runnable()
5380 boolean isNucleotide = alignPanel.alignFrame
5381 .getViewport().getAlignment()
5383 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5384 alignPanel.av.getSequenceSelection(),
5385 alignPanel.alignFrame, dassource,
5386 alignPanel.alignFrame.featureSettings,
5389 .addListener(new FetchFinishedListenerI()
5392 public void finished()
5394 FeatureSettingsModelI srcSettings = dassource[0]
5395 .getFeatureColourScheme();
5396 alignPanel.av.mergeFeaturesStyle(
5398 AlignFrame.this.setMenusForViewport();
5401 dbRefFetcher.fetchDBRefs(false);
5407 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5408 MessageManager.formatMessage(
5409 "label.fetch_retrieve_from", new Object[]
5410 { src.getDbName() })));
5416 final DbSourceProxy[] dassource = otherdb
5417 .toArray(new DbSourceProxy[0]);
5419 DbSourceProxy src = otherdb.get(0);
5420 fetchr = new JMenuItem(MessageManager
5421 .formatMessage("label.fetch_all_param", new Object[]
5422 { src.getDbSource() }));
5423 fetchr.addActionListener(new ActionListener()
5426 public void actionPerformed(ActionEvent e)
5428 new Thread(new Runnable()
5434 boolean isNucleotide = alignPanel.alignFrame
5435 .getViewport().getAlignment()
5437 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5438 alignPanel.av.getSequenceSelection(),
5439 alignPanel.alignFrame, dassource,
5440 alignPanel.alignFrame.featureSettings,
5443 .addListener(new FetchFinishedListenerI()
5446 public void finished()
5448 AlignFrame.this.setMenusForViewport();
5451 dbRefFetcher.fetchDBRefs(false);
5457 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5458 MessageManager.formatMessage(
5459 "label.fetch_retrieve_from_all_sources",
5461 { Integer.valueOf(otherdb.size())
5463 src.getDbSource(), src.getDbName() })));
5466 // and then build the rest of the individual menus
5467 ifetch = new JMenu(MessageManager.formatMessage(
5468 "label.source_from_db_source", new Object[]
5469 { src.getDbSource() }));
5471 String imname = null;
5473 for (DbSourceProxy sproxy : otherdb)
5475 String dbname = sproxy.getDbName();
5476 String sname = dbname.length() > 5
5477 ? dbname.substring(0, 5) + "..."
5479 String msname = dbname.length() > 10
5480 ? dbname.substring(0, 10) + "..."
5484 imname = MessageManager
5485 .formatMessage("label.from_msname", new Object[]
5488 fetchr = new JMenuItem(msname);
5489 final DbSourceProxy[] dassrc = { sproxy };
5490 fetchr.addActionListener(new ActionListener()
5494 public void actionPerformed(ActionEvent e)
5496 new Thread(new Runnable()
5502 boolean isNucleotide = alignPanel.alignFrame
5503 .getViewport().getAlignment()
5505 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5506 alignPanel.av.getSequenceSelection(),
5507 alignPanel.alignFrame, dassrc,
5508 alignPanel.alignFrame.featureSettings,
5511 .addListener(new FetchFinishedListenerI()
5514 public void finished()
5516 AlignFrame.this.setMenusForViewport();
5519 dbRefFetcher.fetchDBRefs(false);
5525 fetchr.setToolTipText(
5526 "<html>" + MessageManager.formatMessage(
5527 "label.fetch_retrieve_from", new Object[]
5531 if (++icomp >= mcomp || i == (otherdb.size()))
5533 ifetch.setText(MessageManager.formatMessage(
5534 "label.source_to_target", imname, sname));
5536 ifetch = new JMenu();
5544 if (comp >= mcomp || dbi >= (dbclasses.length))
5546 dfetch.setText(MessageManager.formatMessage(
5547 "label.source_to_target", mname, dbclass));
5549 dfetch = new JMenu();
5562 * Left justify the whole alignment.
5565 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5567 AlignmentI al = viewport.getAlignment();
5569 viewport.firePropertyChange("alignment", null, al);
5573 * Right justify the whole alignment.
5576 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5578 AlignmentI al = viewport.getAlignment();
5580 viewport.firePropertyChange("alignment", null, al);
5584 public void setShowSeqFeatures(boolean b)
5586 showSeqFeatures.setSelected(b);
5587 viewport.setShowSequenceFeatures(b);
5594 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5595 * awt.event.ActionEvent)
5598 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5600 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5601 alignPanel.paintAlignment(false, false);
5608 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5612 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5614 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5615 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5623 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5624 * .event.ActionEvent)
5627 protected void showGroupConservation_actionPerformed(ActionEvent e)
5629 viewport.setShowGroupConservation(showGroupConservation.getState());
5630 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5637 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5638 * .event.ActionEvent)
5641 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5643 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5644 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5651 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5652 * .event.ActionEvent)
5655 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5657 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5658 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5662 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5664 showSequenceLogo.setState(true);
5665 viewport.setShowSequenceLogo(true);
5666 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5667 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5671 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5673 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5680 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5681 * .event.ActionEvent)
5684 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5686 if (avc.makeGroupsFromSelection())
5688 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5689 alignPanel.updateAnnotation();
5690 alignPanel.paintAlignment(true,
5691 viewport.needToUpdateStructureViews());
5695 public void clearAlignmentSeqRep()
5697 // TODO refactor alignmentseqrep to controller
5698 if (viewport.getAlignment().hasSeqrep())
5700 viewport.getAlignment().setSeqrep(null);
5701 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5702 alignPanel.updateAnnotation();
5703 alignPanel.paintAlignment(true, true);
5708 protected void createGroup_actionPerformed(ActionEvent e)
5710 if (avc.createGroup())
5712 if (applyAutoAnnotationSettings.isSelected())
5714 alignPanel.updateAnnotation(true, false);
5716 alignPanel.alignmentChanged();
5721 protected void unGroup_actionPerformed(ActionEvent e)
5725 alignPanel.alignmentChanged();
5730 * make the given alignmentPanel the currently selected tab
5732 * @param alignmentPanel
5734 public void setDisplayedView(AlignmentPanel alignmentPanel)
5736 if (!viewport.getSequenceSetId()
5737 .equals(alignmentPanel.av.getSequenceSetId()))
5739 throw new Error(MessageManager.getString(
5740 "error.implementation_error_cannot_show_view_alignment_frame"));
5742 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5743 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5745 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5750 * Action on selection of menu options to Show or Hide annotations.
5753 * @param forSequences
5754 * update sequence-related annotations
5755 * @param forAlignment
5756 * update non-sequence-related annotations
5759 protected void setAnnotationsVisibility(boolean visible,
5760 boolean forSequences, boolean forAlignment)
5762 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5763 .getAlignmentAnnotation();
5768 for (AlignmentAnnotation aa : anns)
5771 * don't display non-positional annotations on an alignment
5773 if (aa.annotations == null)
5777 boolean apply = (aa.sequenceRef == null && forAlignment)
5778 || (aa.sequenceRef != null && forSequences);
5781 aa.visible = visible;
5784 alignPanel.validateAnnotationDimensions(true);
5785 alignPanel.alignmentChanged();
5789 * Store selected annotation sort order for the view and repaint.
5792 protected void sortAnnotations_actionPerformed()
5794 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5796 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5797 alignPanel.paintAlignment(false, false);
5802 * @return alignment panels in this alignment frame
5804 public List<? extends AlignmentViewPanel> getAlignPanels()
5806 // alignPanels is never null
5807 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5812 * Open a new alignment window, with the cDNA associated with this (protein)
5813 * alignment, aligned as is the protein.
5815 protected void viewAsCdna_actionPerformed()
5817 // TODO no longer a menu action - refactor as required
5818 final AlignmentI alignment = getViewport().getAlignment();
5819 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5820 if (mappings == null)
5824 List<SequenceI> cdnaSeqs = new ArrayList<>();
5825 for (SequenceI aaSeq : alignment.getSequences())
5827 for (AlignedCodonFrame acf : mappings)
5829 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5833 * There is a cDNA mapping for this protein sequence - add to new
5834 * alignment. It will share the same dataset sequence as other mapped
5835 * cDNA (no new mappings need to be created).
5837 final Sequence newSeq = new Sequence(dnaSeq);
5838 newSeq.setDatasetSequence(dnaSeq);
5839 cdnaSeqs.add(newSeq);
5843 if (cdnaSeqs.size() == 0)
5845 // show a warning dialog no mapped cDNA
5848 AlignmentI cdna = new Alignment(
5849 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5850 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5851 AlignFrame.DEFAULT_HEIGHT);
5852 cdna.alignAs(alignment);
5853 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5855 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5856 AlignFrame.DEFAULT_HEIGHT);
5860 * Set visibility of dna/protein complement view (available when shown in a
5866 protected void showComplement_actionPerformed(boolean show)
5868 SplitContainerI sf = getSplitViewContainer();
5871 sf.setComplementVisible(this, show);
5876 * Generate the reverse (optionally complemented) of the selected sequences,
5877 * and add them to the alignment
5880 protected void showReverse_actionPerformed(boolean complement)
5882 AlignmentI al = null;
5885 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5886 al = dna.reverseCdna(complement);
5887 viewport.addAlignment(al, "");
5888 addHistoryItem(new EditCommand(
5889 MessageManager.getString("label.add_sequences"), Action.PASTE,
5890 al.getSequencesArray(), 0, al.getWidth(),
5891 viewport.getAlignment()));
5892 } catch (Exception ex)
5894 System.err.println(ex.getMessage());
5900 * Try to run a script in the Groovy console, having first ensured that this
5901 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5902 * be targeted at this alignment.
5905 protected void runGroovy_actionPerformed()
5907 Jalview.setCurrentAlignFrame(this);
5908 groovy.ui.Console console = Desktop.getGroovyConsole();
5909 if (console != null)
5913 console.runScript();
5914 } catch (Exception ex)
5916 System.err.println((ex.toString()));
5917 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5918 MessageManager.getString("label.couldnt_run_groovy_script"),
5919 MessageManager.getString("label.groovy_support_failed"),
5920 JvOptionPane.ERROR_MESSAGE);
5925 System.err.println("Can't run Groovy script as console not found");
5930 * Hides columns containing (or not containing) a specified feature, provided
5931 * that would not leave all columns hidden
5933 * @param featureType
5934 * @param columnsContaining
5937 public boolean hideFeatureColumns(String featureType,
5938 boolean columnsContaining)
5940 boolean notForHiding = avc.markColumnsContainingFeatures(
5941 columnsContaining, false, false, featureType);
5944 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5945 false, featureType))
5947 getViewport().hideSelectedColumns();
5955 protected void selectHighlightedColumns_actionPerformed(
5956 ActionEvent actionEvent)
5958 // include key modifier check in case user selects from menu
5959 avc.markHighlightedColumns(
5960 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5961 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5962 | ActionEvent.CTRL_MASK)) != 0);
5966 * Rebuilds the Colour menu, including any user-defined colours which have
5967 * been loaded either on startup or during the session
5969 public void buildColourMenu()
5971 colourMenu.removeAll();
5973 colourMenu.add(applyToAllGroups);
5974 colourMenu.add(textColour);
5975 colourMenu.addSeparator();
5977 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5978 viewport.getAlignment(), false);
5980 colourMenu.add(annotationColour);
5981 bg.add(annotationColour);
5982 colourMenu.addSeparator();
5983 colourMenu.add(conservationMenuItem);
5984 colourMenu.add(modifyConservation);
5985 colourMenu.add(abovePIDThreshold);
5986 colourMenu.add(modifyPID);
5988 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5989 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5993 * Open a dialog (if not already open) that allows the user to select and
5994 * calculate PCA or Tree analysis
5996 protected void openTreePcaDialog()
5998 if (alignPanel.getCalculationDialog() == null)
6000 new CalculationChooser(AlignFrame.this);
6005 protected void loadVcf_actionPerformed()
6007 JalviewFileChooser chooser = new JalviewFileChooser(
6008 Cache.getProperty("LAST_DIRECTORY"));
6009 chooser.setFileView(new JalviewFileView());
6010 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
6011 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
6012 final AlignFrame us = this;
6013 chooser.setResponseHandler(0, new Runnable()
6018 String choice = chooser.getSelectedFile().getPath();
6019 Cache.setProperty("LAST_DIRECTORY", choice);
6020 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
6021 new VCFLoader(choice).loadVCF(seqs, us);
6024 chooser.showOpenDialog(null);
6028 private Rectangle lastFeatureSettingsBounds = null;
6031 public void setFeatureSettingsGeometry(Rectangle bounds)
6033 lastFeatureSettingsBounds = bounds;
6037 public Rectangle getFeatureSettingsGeometry()
6039 return lastFeatureSettingsBounds;
6043 class PrintThread extends Thread
6047 public PrintThread(AlignmentPanel ap)
6052 static PageFormat pf;
6057 PrinterJob printJob = PrinterJob.getPrinterJob();
6061 printJob.setPrintable(ap, pf);
6065 printJob.setPrintable(ap);
6068 if (printJob.printDialog())
6073 } catch (Exception PrintException)
6075 PrintException.printStackTrace();