2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AlignmentSorter;
24 import jalview.analysis.AlignmentUtils;
25 import jalview.analysis.CrossRef;
26 import jalview.analysis.Dna;
27 import jalview.analysis.GeneticCodeI;
28 import jalview.analysis.ParseProperties;
29 import jalview.analysis.SequenceIdMatcher;
30 import jalview.api.AlignExportSettingsI;
31 import jalview.api.AlignViewControllerGuiI;
32 import jalview.api.AlignViewControllerI;
33 import jalview.api.AlignViewportI;
34 import jalview.api.AlignmentViewPanel;
35 import jalview.api.FeatureSettingsControllerI;
36 import jalview.api.FeatureSettingsModelI;
37 import jalview.api.SplitContainerI;
38 import jalview.api.ViewStyleI;
39 import jalview.api.analysis.SimilarityParamsI;
40 import jalview.bin.Cache;
41 import jalview.bin.Jalview;
42 import jalview.commands.CommandI;
43 import jalview.commands.EditCommand;
44 import jalview.commands.EditCommand.Action;
45 import jalview.commands.OrderCommand;
46 import jalview.commands.RemoveGapColCommand;
47 import jalview.commands.RemoveGapsCommand;
48 import jalview.commands.SlideSequencesCommand;
49 import jalview.commands.TrimRegionCommand;
50 import jalview.datamodel.AlignExportSettingsAdapter;
51 import jalview.datamodel.AlignedCodonFrame;
52 import jalview.datamodel.Alignment;
53 import jalview.datamodel.AlignmentAnnotation;
54 import jalview.datamodel.AlignmentExportData;
55 import jalview.datamodel.AlignmentI;
56 import jalview.datamodel.AlignmentOrder;
57 import jalview.datamodel.AlignmentView;
58 import jalview.datamodel.ColumnSelection;
59 import jalview.datamodel.HiddenColumns;
60 import jalview.datamodel.PDBEntry;
61 import jalview.datamodel.SeqCigar;
62 import jalview.datamodel.Sequence;
63 import jalview.datamodel.SequenceGroup;
64 import jalview.datamodel.SequenceI;
65 import jalview.gui.ColourMenuHelper.ColourChangeListener;
66 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
67 import jalview.hmmer.HMMAlign;
68 import jalview.hmmer.HMMBuild;
69 import jalview.hmmer.HMMERParamStore;
70 import jalview.hmmer.HMMERPreset;
71 import jalview.hmmer.HMMSearch;
72 import jalview.hmmer.HmmerCommand;
73 import jalview.hmmer.JackHMMER;
74 import jalview.io.AlignmentProperties;
75 import jalview.io.AnnotationFile;
76 import jalview.io.BackupFiles;
77 import jalview.io.BioJsHTMLOutput;
78 import jalview.io.DataSourceType;
79 import jalview.io.FileFormat;
80 import jalview.io.FileFormatI;
81 import jalview.io.FileFormats;
82 import jalview.io.FileLoader;
83 import jalview.io.FileParse;
84 import jalview.io.FormatAdapter;
85 import jalview.io.HtmlSvgOutput;
86 import jalview.io.IdentifyFile;
87 import jalview.io.JPredFile;
88 import jalview.io.JalviewFileChooser;
89 import jalview.io.JalviewFileView;
90 import jalview.io.JnetAnnotationMaker;
91 import jalview.io.NewickFile;
92 import jalview.io.ScoreMatrixFile;
93 import jalview.io.TCoffeeScoreFile;
94 import jalview.io.vcf.VCFLoader;
95 import jalview.jbgui.GAlignFrame;
96 import jalview.project.Jalview2XML;
97 import jalview.schemes.ColourSchemeI;
98 import jalview.schemes.ColourSchemes;
99 import jalview.schemes.ResidueColourScheme;
100 import jalview.schemes.TCoffeeColourScheme;
101 import jalview.util.ImageMaker.TYPE;
102 import jalview.util.MessageManager;
103 import jalview.util.Platform;
104 import jalview.viewmodel.AlignmentViewport;
105 import jalview.viewmodel.ViewportRanges;
106 import jalview.ws.DBRefFetcher;
107 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
108 import jalview.ws.ServiceChangeListener;
109 import jalview.ws.WSDiscovererI;
110 import jalview.ws.api.ServiceWithParameters;
111 import jalview.ws.jws1.Discoverer;
112 import jalview.ws.jws2.Jws2Discoverer;
113 import jalview.ws.jws2.PreferredServiceRegistry;
114 import jalview.ws.params.ArgumentI;
115 import jalview.ws.params.ParamDatastoreI;
116 import jalview.ws.params.WsParamSetI;
117 import jalview.ws.seqfetcher.DbSourceProxy;
118 import jalview.ws2.WebServiceDiscoverer;
119 import jalview.ws2.WebServiceI;
120 import jalview.ws2.operations.Operation;
121 import jalview.ws2.slivka.SlivkaWSDiscoverer;
123 import java.io.IOException;
124 import java.util.HashSet;
125 import java.util.Set;
127 import javax.swing.JFileChooser;
128 import javax.swing.JOptionPane;
130 import java.awt.BorderLayout;
131 import java.awt.Color;
132 import java.awt.Component;
133 import java.awt.Dimension;
134 import java.awt.Rectangle;
135 import java.awt.Toolkit;
136 import java.awt.datatransfer.Clipboard;
137 import java.awt.datatransfer.DataFlavor;
138 import java.awt.datatransfer.StringSelection;
139 import java.awt.datatransfer.Transferable;
140 import java.awt.dnd.DnDConstants;
141 import java.awt.dnd.DropTargetDragEvent;
142 import java.awt.dnd.DropTargetDropEvent;
143 import java.awt.dnd.DropTargetEvent;
144 import java.awt.dnd.DropTargetListener;
145 import java.awt.event.ActionEvent;
146 import java.awt.event.ActionListener;
147 import java.awt.event.FocusAdapter;
148 import java.awt.event.FocusEvent;
149 import java.awt.event.ItemEvent;
150 import java.awt.event.ItemListener;
151 import java.awt.event.KeyAdapter;
152 import java.awt.event.KeyEvent;
153 import java.awt.event.MouseEvent;
154 import java.awt.print.PageFormat;
155 import java.awt.print.PrinterJob;
156 import java.beans.PropertyChangeEvent;
157 import java.beans.PropertyChangeListener;
159 import java.io.FileWriter;
160 import java.io.PrintWriter;
162 import java.util.ArrayList;
163 import java.util.Arrays;
164 import java.util.Collection;
165 import java.util.Deque;
166 import java.util.Enumeration;
167 import java.util.Hashtable;
168 import java.util.List;
169 import java.util.Vector;
171 import javax.swing.ButtonGroup;
172 import javax.swing.JCheckBoxMenuItem;
173 import javax.swing.JComponent;
174 import javax.swing.JEditorPane;
175 import javax.swing.JInternalFrame;
176 import javax.swing.JLabel;
177 import javax.swing.JLayeredPane;
178 import javax.swing.JMenu;
179 import javax.swing.JMenuItem;
180 import javax.swing.JPanel;
181 import javax.swing.JScrollPane;
182 import javax.swing.SwingUtilities;
183 import javax.swing.event.InternalFrameAdapter;
184 import javax.swing.event.InternalFrameEvent;
186 import ext.vamsas.ServiceHandle;
192 * @version $Revision$
194 @SuppressWarnings("serial")
195 public class AlignFrame extends GAlignFrame
196 implements DropTargetListener, IProgressIndicator,
197 AlignViewControllerGuiI, ColourChangeListener, ServiceChangeListener,
198 WebServiceDiscoverer.ServiceChangeListener
201 public static int frameCount;
203 public static final int DEFAULT_WIDTH = 700;
205 public static final int DEFAULT_HEIGHT = 500;
208 * The currently displayed panel (selected tabbed view if more than one)
210 public AlignmentPanel alignPanel;
212 AlignViewport viewport;
214 public AlignViewControllerI avc;
216 List<AlignmentPanel> alignPanels = new ArrayList<>();
219 * Last format used to load or save alignments in this window
221 FileFormatI currentFileFormat = null;
224 * Current filename for this alignment
226 String fileName = null;
229 * TODO: remove reference to 'FileObject' in AlignFrame - not correct mapping
235 private DataSourceType protocol ;
238 * Creates a new AlignFrame object with specific width and height.
244 public AlignFrame(AlignmentI al, int width, int height)
246 this(al, null, width, height);
250 * Creates a new AlignFrame object with specific width, height and
256 * @param sequenceSetId
258 public AlignFrame(AlignmentI al, int width, int height,
259 String sequenceSetId)
261 this(al, null, width, height, sequenceSetId);
265 * Creates a new AlignFrame object with specific width, height and
271 * @param sequenceSetId
274 public AlignFrame(AlignmentI al, int width, int height,
275 String sequenceSetId, String viewId)
277 this(al, null, width, height, sequenceSetId, viewId);
281 * new alignment window with hidden columns
285 * @param hiddenColumns
286 * ColumnSelection or null
288 * Width of alignment frame
292 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
295 this(al, hiddenColumns, width, height, null);
299 * Create alignment frame for al with hiddenColumns, a specific width and
300 * height, and specific sequenceId
303 * @param hiddenColumns
306 * @param sequenceSetId
309 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
310 int height, String sequenceSetId)
312 this(al, hiddenColumns, width, height, sequenceSetId, null);
316 * Create alignment frame for al with hiddenColumns, a specific width and
317 * height, and specific sequenceId
320 * @param hiddenColumns
323 * @param sequenceSetId
328 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
329 int height, String sequenceSetId, String viewId)
334 setSize(width, height);
336 if (al.getDataset() == null)
341 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
343 // JalviewJS needs to distinguish a new panel from an old one in init()
344 // alignPanel = new AlignmentPanel(this, viewport);
345 // addAlignmentPanel(alignPanel, true);
349 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
350 HiddenColumns hiddenColumns, int width, int height)
352 setSize(width, height);
354 if (al.getDataset() == null)
359 viewport = new AlignViewport(al, hiddenColumns);
361 if (hiddenSeqs != null && hiddenSeqs.length > 0)
363 viewport.hideSequence(hiddenSeqs);
365 // alignPanel = new AlignmentPanel(this, viewport);
366 // addAlignmentPanel(alignPanel, true);
371 * Make a new AlignFrame from existing alignmentPanels
378 public AlignFrame(AlignmentPanel ap)
382 // addAlignmentPanel(ap, false);
387 * initalise the alignframe from the underlying viewport data and the
393 boolean newPanel = (alignPanel == null);
394 viewport.setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
399 // need to set this up front if NOANNOTATION is
400 // used in conjunction with SHOWOVERVIEW.
402 // I have not determined if this is appropriate for
403 // Jalview/Java, as it means we are setting this flag
404 // for all subsequent AlignFrames. For now, at least,
405 // I am setting it to be JalviewJS-only.
407 boolean showAnnotation = Jalview.getInstance().getShowAnnotation();
408 viewport.setShowAnnotation(showAnnotation);
410 alignPanel = new AlignmentPanel(this, viewport);
412 addAlignmentPanel(alignPanel, newPanel);
414 // setBackground(Color.white); // BH 2019
416 if (!Jalview.isHeadlessMode())
418 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
420 statusPanel.setVisible(Jalview.getInstance().getShowStatus());
421 alignFrameMenuBar.setVisible(Jalview.getInstance().getAllowMenuBar());
424 avc = new jalview.controller.AlignViewController(this, viewport,
426 if (viewport.getAlignmentConservationAnnotation() == null)
428 // BLOSUM62Colour.setEnabled(false);
429 conservationMenuItem.setEnabled(false);
430 modifyConservation.setEnabled(false);
431 // PIDColour.setEnabled(false);
432 // abovePIDThreshold.setEnabled(false);
433 // modifyPID.setEnabled(false);
436 String sortby = jalview.bin.Cache.getDefault(Preferences.SORT_ALIGNMENT,
439 if (sortby.equals("Id"))
441 sortIDMenuItem_actionPerformed(null);
443 else if (sortby.equals("Pairwise Identity"))
445 sortPairwiseMenuItem_actionPerformed(null);
450 // this.alignPanel.av
451 // .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
453 setMenusFromViewport(viewport);
454 buildSortByAnnotationScoresMenu();
455 calculateTree.addActionListener(new ActionListener()
459 public void actionPerformed(ActionEvent e)
466 if (Desktop.getDesktopPane() != null)
468 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
469 addServiceListeners();
470 if (!Platform.isJS())
476 if (viewport.getWrapAlignment())
478 wrapMenuItem_actionPerformed(null);
481 if (jalview.bin.Cache.getDefault(Preferences.SHOW_OVERVIEW, false))
483 this.overviewMenuItem_actionPerformed(null);
488 final List<AlignmentPanel> selviews = new ArrayList<>();
489 final List<AlignmentPanel> origview = new ArrayList<>();
490 final String menuLabel = MessageManager
491 .getString("label.copy_format_from");
492 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
493 new ViewSetProvider()
497 public AlignmentPanel[] getAllAlignmentPanels()
500 origview.add(alignPanel);
501 // make an array of all alignment panels except for this one
502 List<AlignmentPanel> aps = new ArrayList<>(
503 Arrays.asList(Desktop.getAlignmentPanels(null)));
504 aps.remove(AlignFrame.this.alignPanel);
505 return aps.toArray(new AlignmentPanel[aps.size()]);
507 }, selviews, new ItemListener()
511 public void itemStateChanged(ItemEvent e)
513 if (origview.size() > 0)
515 final AlignmentPanel ap = origview.get(0);
518 * Copy the ViewStyle of the selected panel to 'this one'.
519 * Don't change value of 'scaleProteinAsCdna' unless copying
522 ViewStyleI vs = selviews.get(0).getAlignViewport()
524 boolean fromSplitFrame = selviews.get(0)
525 .getAlignViewport().getCodingComplement() != null;
528 vs.setScaleProteinAsCdna(ap.getAlignViewport()
529 .getViewStyle().isScaleProteinAsCdna());
531 ap.getAlignViewport().setViewStyle(vs);
534 * Also rescale ViewStyle of SplitFrame complement if there is
535 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
536 * the whole ViewStyle (allow cDNA protein to have different
539 AlignViewportI complement = ap.getAlignViewport()
540 .getCodingComplement();
541 if (complement != null && vs.isScaleProteinAsCdna())
543 AlignFrame af = Desktop.getAlignFrameFor(complement);
544 ((SplitFrame) af.getSplitViewContainer())
546 af.setMenusForViewport();
550 ap.setSelected(true);
551 ap.alignFrame.setMenusForViewport();
556 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
557 .indexOf("devel") > -1
558 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
559 .indexOf("test") > -1)
561 formatMenu.add(vsel);
563 addFocusListener(new FocusAdapter()
567 public void focusGained(FocusEvent e)
569 Jalview.setCurrentAlignFrame(AlignFrame.this);
576 * Change the filename and format for the alignment, and enable the 'reload'
577 * button functionality.
586 public void setFileName(String file, FileFormatI format)
589 setFileFormat(format);
590 reload.setEnabled(true);
596 * @param file from SwingJS; may contain bytes -- for reload
597 * @param protocol from SwingJS; may be RELATIVE_URL
600 public void setFile(String fileName, File file, DataSourceType protocol, FileFormatI format)
602 this.fileName = fileName;
603 this.fileObject = file;
604 this.protocol = protocol;
605 setFileFormat(format);
606 reload.setEnabled(true);
610 * JavaScript will have this, maybe others. More dependable than a file name
611 * and maintains a reference to the actual bytes loaded.
616 public void setFileObject(File file)
618 this.fileObject = file;
622 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
626 void addKeyListener()
628 addKeyListener(new KeyAdapter()
632 public void keyPressed(KeyEvent evt)
634 if (viewport.cursorMode
635 && ((evt.getKeyCode() >= KeyEvent.VK_0
636 && evt.getKeyCode() <= KeyEvent.VK_9)
637 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
638 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
639 && Character.isDigit(evt.getKeyChar()))
641 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
644 switch (evt.getKeyCode())
647 case KeyEvent.VK_ESCAPE: // escape key
648 // alignPanel.deselectAllSequences();
649 alignPanel.deselectAllSequences();
653 case KeyEvent.VK_DOWN:
654 if (evt.isAltDown() || !viewport.cursorMode)
656 moveSelectedSequences(false);
658 if (viewport.cursorMode)
660 alignPanel.getSeqPanel().moveCursor(0, 1);
665 if (evt.isAltDown() || !viewport.cursorMode)
667 moveSelectedSequences(true);
669 if (viewport.cursorMode)
671 alignPanel.getSeqPanel().moveCursor(0, -1);
676 case KeyEvent.VK_LEFT:
677 if (evt.isAltDown() || !viewport.cursorMode)
679 slideSequences(false,
680 alignPanel.getSeqPanel().getKeyboardNo1());
684 alignPanel.getSeqPanel().moveCursor(-1, 0);
689 case KeyEvent.VK_RIGHT:
690 if (evt.isAltDown() || !viewport.cursorMode)
692 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
696 alignPanel.getSeqPanel().moveCursor(1, 0);
700 case KeyEvent.VK_SPACE:
701 if (viewport.cursorMode)
703 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
704 || evt.isShiftDown() || evt.isAltDown());
708 // case KeyEvent.VK_A:
709 // if (viewport.cursorMode)
711 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
712 // //System.out.println("A");
716 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
717 * System.out.println("closing bracket"); } break;
719 case KeyEvent.VK_DELETE:
720 case KeyEvent.VK_BACK_SPACE:
721 if (!viewport.cursorMode)
723 cut_actionPerformed();
727 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
728 || evt.isShiftDown() || evt.isAltDown());
734 if (viewport.cursorMode)
736 alignPanel.getSeqPanel().setCursorRow();
740 if (viewport.cursorMode && !evt.isControlDown())
742 alignPanel.getSeqPanel().setCursorColumn();
746 if (viewport.cursorMode)
748 alignPanel.getSeqPanel().setCursorPosition();
752 case KeyEvent.VK_ENTER:
753 case KeyEvent.VK_COMMA:
754 if (viewport.cursorMode)
756 alignPanel.getSeqPanel().setCursorRowAndColumn();
761 if (viewport.cursorMode)
763 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
767 if (viewport.cursorMode)
769 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
774 viewport.cursorMode = !viewport.cursorMode;
775 setStatus(MessageManager
776 .formatMessage("label.keyboard_editing_mode", new String[]
777 { (viewport.cursorMode ? "on" : "off") }));
778 if (viewport.cursorMode)
780 ViewportRanges ranges = viewport.getRanges();
781 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
783 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
786 alignPanel.getSeqPanel().seqCanvas.repaint();
792 Help.showHelpWindow();
793 } catch (Exception ex)
795 ex.printStackTrace();
800 boolean toggleSeqs = !evt.isControlDown();
801 boolean toggleCols = !evt.isShiftDown();
802 toggleHiddenRegions(toggleSeqs, toggleCols);
807 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
808 boolean modifyExisting = true; // always modify, don't clear
809 // evt.isShiftDown();
810 boolean invertHighlighted = evt.isAltDown();
811 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
815 case KeyEvent.VK_PAGE_UP:
816 viewport.getRanges().pageUp();
818 case KeyEvent.VK_PAGE_DOWN:
819 viewport.getRanges().pageDown();
825 public void keyReleased(KeyEvent evt)
827 switch (evt.getKeyCode())
829 case KeyEvent.VK_LEFT:
830 if (evt.isAltDown() || !viewport.cursorMode)
832 viewport.notifyAlignment();
836 case KeyEvent.VK_RIGHT:
837 if (evt.isAltDown() || !viewport.cursorMode)
839 viewport.notifyAlignment();
847 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
849 ap.alignFrame = this;
850 avc = new jalview.controller.AlignViewController(this, viewport,
855 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
857 int aSize = alignPanels.size();
859 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
861 if (aSize == 1 && ap.av.getViewName() == null)
863 this.getContentPane().add(ap, BorderLayout.CENTER);
869 setInitialTabVisible();
872 expandViews.setEnabled(true);
873 gatherViews.setEnabled(true);
874 tabbedPane.addTab(ap.av.getViewName(), ap);
876 ap.setVisible(false);
881 if (ap.av.isPadGaps())
883 ap.av.getAlignment().padGaps();
885 if (Jalview.getInstance().getStartCalculations())
887 ap.av.updateConservation(ap);
888 ap.av.updateConsensus(ap);
889 ap.av.updateStrucConsensus(ap);
890 ap.av.initInformationWorker(ap);
895 public void setInitialTabVisible()
897 expandViews.setEnabled(true);
898 gatherViews.setEnabled(true);
899 tabbedPane.setVisible(true);
900 AlignmentPanel first = alignPanels.get(0);
901 tabbedPane.addTab(first.av.getViewName(), first);
902 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
905 public AlignViewport getViewport()
911 public void servicesChanged(WSDiscovererI discoverer,
912 Collection<? extends ServiceWithParameters> services)
914 buildWebServicesMenu();
918 public void servicesChanged(WebServiceDiscoverer discoverer,
919 Collection<? extends WebServiceI> services)
921 buildWebServicesMenu();
924 /* Set up intrinsic listeners for dynamically generated GUI bits. */
925 private void addServiceListeners()
927 if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
929 WebServiceDiscoverer discoverer = SlivkaWSDiscoverer.getInstance();
930 discoverer.addServiceChangeListener((disc, srvcs) -> buildWebServicesMenu());
932 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
934 WSDiscovererI discoverer = Jws2Discoverer.getInstance();
935 discoverer.addServiceChangeListener(this);
937 // legacy event listener for compatibility with jws1
938 PropertyChangeListener legacyListener = (changeEvent) -> {
939 buildWebServicesMenu();
941 Desktop.getInstance().addJalviewPropertyChangeListener("services",legacyListener);
943 addInternalFrameListener(new InternalFrameAdapter() {
945 public void internalFrameClosed(InternalFrameEvent e) {
946 System.out.println("deregistering discoverer listener");
947 // SlivkaWSDiscoverer.getInstance().removeServiceChangeListener(AlignFrame.this);
948 Jws2Discoverer.getInstance().removeServiceChangeListener(AlignFrame.this);
949 Desktop.getInstance().removeJalviewPropertyChangeListener("services", legacyListener);
950 closeMenuItem_actionPerformed(true);
953 buildWebServicesMenu();
957 * Configure menu items that vary according to whether the alignment is
958 * nucleotide or protein
961 public void setGUINucleotide()
963 AlignmentI al = getViewport().getAlignment();
964 boolean nucleotide = al.isNucleotide();
966 loadVcf.setVisible(nucleotide);
967 showTranslation.setVisible(nucleotide);
968 showReverse.setVisible(nucleotide);
969 showReverseComplement.setVisible(nucleotide);
970 conservationMenuItem.setEnabled(!nucleotide);
972 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
973 showGroupConservation.setEnabled(!nucleotide);
975 showComplementMenuItem
976 .setText(nucleotide ? MessageManager.getString("label.protein")
977 : MessageManager.getString("label.nucleotide"));
981 * set up menus for the current viewport. This may be called after any
982 * operation that affects the data in the current view (selection changed,
983 * etc) to update the menus to reflect the new state.
987 public void setMenusForViewport()
989 setMenusFromViewport(viewport);
993 * Need to call this method when tabs are selected for multiple views, or when
994 * loading from Jalview2XML.java
1000 public void setMenusFromViewport(AlignViewport av)
1002 padGapsMenuitem.setSelected(av.isPadGaps());
1003 colourTextMenuItem.setSelected(av.isShowColourText());
1004 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
1005 modifyPID.setEnabled(abovePIDThreshold.isSelected());
1006 conservationMenuItem.setSelected(av.getConservationSelected());
1007 modifyConservation.setEnabled(conservationMenuItem.isSelected());
1008 seqLimits.setSelected(av.getShowJVSuffix());
1009 idRightAlign.setSelected(av.isRightAlignIds());
1010 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
1011 renderGapsMenuItem.setSelected(av.isRenderGaps());
1012 wrapMenuItem.setSelected(av.getWrapAlignment());
1013 scaleAbove.setVisible(av.getWrapAlignment());
1014 scaleLeft.setVisible(av.getWrapAlignment());
1015 scaleRight.setVisible(av.getWrapAlignment());
1016 annotationPanelMenuItem.setState(av.isShowAnnotation());
1017 // Show/hide annotations only enabled if annotation panel is shown
1018 syncAnnotationMenuItems(av.isShowAnnotation());
1019 viewBoxesMenuItem.setSelected(av.getShowBoxes());
1020 viewTextMenuItem.setSelected(av.getShowText());
1021 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
1022 showGroupConsensus.setSelected(av.isShowGroupConsensus());
1023 showGroupConservation.setSelected(av.isShowGroupConservation());
1024 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
1025 showSequenceLogo.setSelected(av.isShowSequenceLogo());
1026 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
1027 showInformationHistogram.setSelected(av.isShowInformationHistogram());
1028 showHMMSequenceLogo.setSelected(av.isShowHMMSequenceLogo());
1029 normaliseHMMSequenceLogo.setSelected(av.isNormaliseHMMSequenceLogo());
1031 ColourMenuHelper.setColourSelected(colourMenu,
1032 av.getGlobalColourScheme());
1034 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
1035 hiddenMarkers.setState(av.getShowHiddenMarkers());
1036 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
1037 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
1038 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
1040 .setSelected(av.getAutoCalculateConsensusAndConservation());
1041 sortByTree.setSelected(av.sortByTree);
1042 listenToViewSelections.setSelected(av.followSelection);
1044 showProducts.setEnabled(canShowProducts());
1045 setGroovyEnabled(Desktop.getGroovyConsole() != null);
1047 updateEditMenuBar();
1051 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
1056 public void setGroovyEnabled(boolean b)
1058 runGroovy.setEnabled(b);
1061 private IProgressIndicator progressBar;
1066 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
1070 public void setProgressBar(String message, long id)
1072 progressBar.setProgressBar(message, id);
1076 public void removeProgressBar(long id)
1078 progressBar.removeProgressBar(id);
1082 public void registerHandler(final long id,
1083 final IProgressIndicatorHandler handler)
1085 progressBar.registerHandler(id, handler);
1090 * @return true if any progress bars are still active
1094 public boolean operationInProgress()
1096 return progressBar.operationInProgress();
1100 * Sets the text of the status bar. Note that setting a null or empty value
1101 * will cause the status bar to be hidden, with possibly undesirable flicker
1102 * of the screen layout.
1106 public void setStatus(String text)
1108 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1112 * Added so Castor Mapping file can obtain Jalview Version
1115 public String getVersion()
1117 return jalview.bin.Cache.getProperty("VERSION");
1120 public FeatureRenderer getFeatureRenderer()
1122 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1126 public void fetchSequence_actionPerformed()
1128 new SequenceFetcher(this);
1132 public void addFromFile_actionPerformed(ActionEvent e)
1134 Desktop.getInstance().inputLocalFileMenuItem_actionPerformed(viewport);
1138 public void hmmBuild_actionPerformed(boolean withDefaults)
1140 if (!alignmentIsSufficient(1))
1146 * get default parameters, and optionally show a dialog
1147 * to allow them to be modified
1149 ParamDatastoreI store = HMMERParamStore.forBuild(viewport);
1150 List<ArgumentI> args = store.getServiceParameters();
1154 WsParamSetI set = new HMMERPreset();
1155 WsJobParameters params = new WsJobParameters(store, set, args);
1156 params.showRunDialog().thenAccept((startJob) -> {
1159 var args2 = params.getJobParams();
1160 new Thread(new HMMBuild(this, args2)).start();
1166 new Thread(new HMMBuild(this, args)).start();
1171 public void hmmAlign_actionPerformed(boolean withDefaults)
1173 if (!(checkForHMM() && alignmentIsSufficient(2)))
1179 * get default parameters, and optionally show a dialog
1180 * to allow them to be modified
1182 ParamDatastoreI store = HMMERParamStore.forAlign(viewport);
1183 List<ArgumentI> args = store.getServiceParameters();
1187 WsParamSetI set = new HMMERPreset();
1188 WsJobParameters params = new WsJobParameters(store, set, args);
1189 params.showRunDialog().thenAccept((startJob) -> {
1192 var args2 = params.getJobParams();
1193 new Thread(new HMMAlign(this, args2)).start();
1199 new Thread(new HMMAlign(this, args)).start();
1204 public void hmmSearch_actionPerformed(boolean withDefaults)
1212 * get default parameters, and (if requested) show
1213 * dialog to allow modification
1215 ParamDatastoreI store = HMMERParamStore.forSearch(viewport);
1216 List<ArgumentI> args = store.getServiceParameters();
1220 WsParamSetI set = new HMMERPreset();
1221 WsJobParameters params = new WsJobParameters(store, set, args);
1222 params.showRunDialog().thenAccept((startJob) -> {
1225 var args2 = params.getJobParams();
1226 new Thread(new HMMSearch(this, args2)).start();
1227 alignPanel.repaint();
1233 new Thread(new HMMSearch(this, args)).start();
1234 alignPanel.repaint();
1239 public void jackhmmer_actionPerformed(boolean withDefaults)
1243 * get default parameters, and (if requested) show
1244 * dialog to allow modification
1247 ParamDatastoreI store = HMMERParamStore.forJackhmmer(viewport);
1248 List<ArgumentI> args = store.getServiceParameters();
1252 WsParamSetI set = new HMMERPreset();
1253 WsJobParameters params = new WsJobParameters(store, set, args);
1254 params.showRunDialog().thenAccept((startJob) -> {
1257 var args2 = params.getJobParams();
1258 new Thread(new JackHMMER(this, args2)).start();
1259 alignPanel.repaint();
1265 new Thread(new JackHMMER(this, args)).start();
1266 alignPanel.repaint();
1271 * Checks if the alignment has at least one hidden Markov model, if not shows
1272 * a dialog advising to run hmmbuild or load an HMM profile
1276 private boolean checkForHMM()
1278 if (viewport.getAlignment().getHmmSequences().isEmpty())
1280 JOptionPane.showMessageDialog(this,
1281 MessageManager.getString("warn.no_hmm"));
1288 protected void filterByEValue_actionPerformed()
1290 viewport.filterByEvalue(inputDouble("Enter E-Value Cutoff"));
1294 protected void filterByScore_actionPerformed()
1296 viewport.filterByScore(inputDouble("Enter Bit Score Threshold"));
1299 private double inputDouble(String message)
1303 while (d == null || d <= 0)
1305 str = JOptionPane.showInputDialog(this.alignPanel, message);
1308 d = Double.valueOf(str);
1309 } catch (NumberFormatException e)
1317 * Checks if the alignment contains the required number of sequences.
1322 public boolean alignmentIsSufficient(int required)
1324 if (getViewport().getSequenceSelection().length < required)
1326 JOptionPane.showMessageDialog(this,
1327 MessageManager.getString("label.not_enough_sequences"));
1334 * Opens a file browser and adds the selected file, if in Fasta, Stockholm or
1335 * Pfam format, to the list held under preference key "HMMSEARCH_DBS" (as a
1336 * comma-separated list)
1339 public void addDatabase_actionPerformed() throws IOException
1341 if (Cache.getProperty(Preferences.HMMSEARCH_DBS) == null)
1343 Cache.setProperty(Preferences.HMMSEARCH_DBS, "");
1346 String path = openFileChooser(false);
1347 if (path != null && new File(path).exists())
1349 IdentifyFile identifier = new IdentifyFile();
1350 FileFormatI format = identifier.identify(path, DataSourceType.FILE);
1351 if (format == FileFormat.Fasta || format == FileFormat.Stockholm
1352 || format == FileFormat.Pfam)
1354 String currentDbPaths = Cache
1355 .getProperty(Preferences.HMMSEARCH_DBS);
1356 currentDbPaths += Preferences.COMMA + path;
1357 Cache.setProperty(Preferences.HMMSEARCH_DBS, currentDbPaths);
1361 JOptionPane.showMessageDialog(this,
1362 MessageManager.getString("warn.invalid_format"));
1368 * Opens a file chooser, optionally restricted to selecting folders
1369 * (directories) only. Answers the path to the selected file or folder, or
1370 * null if none is chosen.
1375 protected String openFileChooser(boolean forFolder)
1377 // TODO duplicates GPreferences method - relocate to JalviewFileChooser?
1378 String choice = null;
1379 JFileChooser chooser = new JFileChooser();
1382 chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1384 chooser.setDialogTitle(
1385 MessageManager.getString("label.open_local_file"));
1386 chooser.setToolTipText(MessageManager.getString("action.open"));
1388 int value = chooser.showOpenDialog(this);
1390 if (value == JFileChooser.APPROVE_OPTION)
1392 choice = chooser.getSelectedFile().getPath();
1398 public void reload_actionPerformed(ActionEvent e)
1400 if (fileName == null && fileObject == null)
1404 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1405 // originating file's format
1406 // TODO: work out how to recover feature settings for correct view(s) when
1407 // file is reloaded.
1408 if (FileFormat.Jalview.equals(currentFileFormat))
1410 JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
1411 for (int i = 0; i < frames.length; i++)
1413 if (frames[i] instanceof AlignFrame && frames[i] != this
1414 && ((AlignFrame) frames[i]).fileName != null
1415 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1419 frames[i].setSelected(true);
1420 Desktop.getInstance().closeAssociatedWindows();
1421 } catch (java.beans.PropertyVetoException ex)
1427 Desktop.getInstance().closeAssociatedWindows();
1429 FileLoader loader = new FileLoader();
1430 // DataSourceType protocol = fileName.startsWith("http:")
1431 // ? DataSourceType.URL
1432 // : DataSourceType.FILE;
1433 loader.LoadFile(viewport, (fileObject == null ? fileName : fileObject), protocol, currentFileFormat);
1437 Rectangle bounds = this.getBounds();
1439 FileLoader loader = new FileLoader();
1441 AlignFrame newframe = null;
1443 if (fileObject == null)
1445 newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1450 newframe = loader.LoadFileWaitTillLoaded(fileObject,
1451 DataSourceType.FILE, currentFileFormat);
1454 newframe.setBounds(bounds);
1455 if (featureSettings != null && featureSettings.isShowing())
1457 final Rectangle fspos = featureSettings.frame.getBounds();
1458 // TODO: need a 'show feature settings' function that takes bounds -
1459 // need to refactor Desktop.addFrame
1460 newframe.featureSettings_actionPerformed(null);
1461 final FeatureSettings nfs = newframe.featureSettings;
1462 SwingUtilities.invokeLater(new Runnable()
1468 nfs.frame.setBounds(fspos);
1471 this.featureSettings.close();
1472 this.featureSettings = null;
1474 this.closeMenuItem_actionPerformed(true);
1480 public void addFromText_actionPerformed(ActionEvent e)
1482 Desktop.getInstance()
1483 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1487 public void addFromURL_actionPerformed(ActionEvent e)
1489 Desktop.getInstance().inputURLMenuItem_actionPerformed(viewport);
1493 public void save_actionPerformed(ActionEvent e)
1495 if (fileName == null || (currentFileFormat == null)
1496 || fileName.startsWith("http"))
1498 saveAs_actionPerformed();
1502 saveAlignment(fileName, currentFileFormat);
1507 * Saves the alignment to a file with a name chosen by the user, if necessary
1508 * warning if a file would be overwritten
1512 public void saveAs_actionPerformed()
1514 String format = currentFileFormat == null ? null
1515 : currentFileFormat.getName();
1516 JalviewFileChooser chooser = JalviewFileChooser
1517 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1519 chooser.setFileView(new JalviewFileView());
1520 chooser.setDialogTitle(
1521 MessageManager.getString("label.save_alignment_to_file"));
1522 chooser.setToolTipText(MessageManager.getString("action.save"));
1524 int value = chooser.showSaveDialog(this);
1526 if (value != JalviewFileChooser.APPROVE_OPTION)
1530 currentFileFormat = chooser.getSelectedFormat();
1531 // todo is this (2005) test now obsolete - value is never null?
1532 while (currentFileFormat == null)
1534 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
1536 .getString("label.select_file_format_before_saving"),
1537 MessageManager.getString("label.file_format_not_specified"),
1538 JvOptionPane.WARNING_MESSAGE);
1539 currentFileFormat = chooser.getSelectedFormat();
1540 value = chooser.showSaveDialog(this);
1541 if (value != JalviewFileChooser.APPROVE_OPTION)
1547 fileName = chooser.getSelectedFile().getPath();
1549 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1550 Cache.setProperty("LAST_DIRECTORY", fileName);
1551 saveAlignment(fileName, currentFileFormat);
1554 boolean lastSaveSuccessful = false;
1556 FileFormatI lastFormatSaved;
1558 String lastFilenameSaved;
1561 * Raise a dialog or status message for the last call to saveAlignment.
1563 * @return true if last call to saveAlignment(file, format) was successful.
1566 public boolean isSaveAlignmentSuccessful()
1569 if (!lastSaveSuccessful)
1571 JvOptionPane.showInternalMessageDialog(this, MessageManager
1572 .formatMessage("label.couldnt_save_file", new Object[]
1573 { lastFilenameSaved }),
1574 MessageManager.getString("label.error_saving_file"),
1575 JvOptionPane.WARNING_MESSAGE);
1580 setStatus(MessageManager.formatMessage(
1581 "label.successfully_saved_to_file_in_format", new Object[]
1582 { lastFilenameSaved, lastFormatSaved }));
1585 return lastSaveSuccessful;
1589 * Saves the alignment to the specified file path, in the specified format,
1590 * which may be an alignment format, or Jalview project format. If the
1591 * alignment has hidden regions, or the format is one capable of including
1592 * non-sequence data (features, annotations, groups), then the user may be
1593 * prompted to specify what to include in the output.
1599 public void saveAlignment(String file, FileFormatI format)
1601 lastSaveSuccessful = true;
1602 lastFilenameSaved = file;
1603 lastFormatSaved = format;
1605 if (FileFormat.Jalview.equals(format))
1607 String shortName = title;
1608 if (shortName.indexOf(File.separatorChar) > -1)
1610 shortName = shortName
1611 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
1613 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file,
1616 statusBar.setText(MessageManager.formatMessage(
1617 "label.successfully_saved_to_file_in_format", new Object[]
1618 { fileName, format }));
1623 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1624 Runnable cancelAction = new Runnable()
1630 lastSaveSuccessful = false;
1633 Runnable outputAction = new Runnable()
1639 // todo defer this to inside formatSequences (or later)
1640 AlignmentExportData exportData = viewport
1641 .getAlignExportData(options);
1642 String output = new FormatAdapter(alignPanel, options)
1643 .formatSequences(format, exportData.getAlignment(),
1644 exportData.getOmitHidden(),
1645 exportData.getStartEndPostions(),
1646 viewport.getAlignment().getHiddenColumns());
1649 lastSaveSuccessful = false;
1653 // create backupfiles object and get new temp filename destination
1654 boolean doBackup = BackupFiles.getEnabled();
1655 BackupFiles backupfiles = doBackup ? new BackupFiles(file) : null;
1658 String tempFilePath = doBackup ? backupfiles.getTempFilePath()
1660 PrintWriter out = new PrintWriter(new FileWriter(tempFilePath));
1664 AlignFrame.this.setTitle(file);
1665 statusBar.setText(MessageManager.formatMessage(
1666 "label.successfully_saved_to_file_in_format",
1668 { fileName, format.getName() }));
1669 lastSaveSuccessful = true;
1670 } catch (Exception ex)
1672 lastSaveSuccessful = false;
1673 ex.printStackTrace();
1678 backupfiles.setWriteSuccess(lastSaveSuccessful);
1679 // do the backup file roll and rename the temp file to actual file
1680 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1687 * show dialog with export options if applicable; else just do it
1689 if (AlignExportOptions.isNeeded(viewport, format))
1691 AlignExportOptions choices = new AlignExportOptions(
1692 alignPanel.getAlignViewport(), format, options);
1693 choices.setResponseAction(0, outputAction);
1694 choices.setResponseAction(1, cancelAction);
1695 choices.showDialog();
1704 * Outputs the alignment to textbox in the requested format, if necessary
1705 * first prompting the user for whether to include hidden regions or
1708 * @param fileFormatName
1712 protected void outputText_actionPerformed(String fileFormatName)
1714 FileFormatI fileFormat = FileFormats.getInstance()
1715 .forName(fileFormatName);
1716 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1717 Runnable outputAction = new Runnable()
1723 // todo defer this to inside formatSequences (or later)
1724 AlignmentExportData exportData = viewport
1725 .getAlignExportData(options);
1726 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1727 cap.setForInput(null);
1730 FileFormatI format = fileFormat;
1731 cap.setText(new FormatAdapter(alignPanel, options)
1732 .formatSequences(format, exportData.getAlignment(),
1733 exportData.getOmitHidden(),
1734 exportData.getStartEndPostions(),
1735 viewport.getAlignment().getHiddenColumns()));
1736 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1737 "label.alignment_output_command", new Object[]
1738 { fileFormat.getName() }), 600, 500);
1739 } catch (OutOfMemoryError oom)
1741 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1749 * show dialog with export options if applicable; else just do it
1751 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1753 AlignExportOptions choices = new AlignExportOptions(
1754 alignPanel.getAlignViewport(), fileFormat, options);
1755 choices.setResponseAction(0, outputAction);
1756 choices.showDialog();
1772 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1774 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1775 htmlSVG.exportHTML(null);
1779 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1781 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1782 bjs.exportHTML(null);
1787 public void createImageMap(File file, String image)
1789 alignPanel.makePNGImageMap(file, image);
1793 * Creates a PNG image of the alignment and writes it to the given file. If
1794 * the file is null, the user is prompted to choose a file.
1800 public void createPNG(File f)
1802 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1806 * Creates an EPS image of the alignment and writes it to the given file. If
1807 * the file is null, the user is prompted to choose a file.
1813 public void createEPS(File f)
1815 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1819 * Creates an SVG image of the alignment and writes it to the given file. If
1820 * the file is null, the user is prompted to choose a file.
1826 public void createSVG(File f)
1828 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1832 public void pageSetup_actionPerformed(ActionEvent e)
1834 PrinterJob printJob = PrinterJob.getPrinterJob();
1835 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1846 public void printMenuItem_actionPerformed(ActionEvent e)
1848 // Putting in a thread avoids Swing painting problems
1849 PrintThread thread = new PrintThread(alignPanel);
1854 public void exportFeatures_actionPerformed(ActionEvent e)
1856 new AnnotationExporter(alignPanel).exportFeatures();
1860 public void exportAnnotations_actionPerformed(ActionEvent e)
1862 new AnnotationExporter(alignPanel).exportAnnotations();
1866 public void associatedData_actionPerformed(ActionEvent e)
1867 throws IOException, InterruptedException
1869 final JalviewFileChooser chooser = new JalviewFileChooser(
1870 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1871 chooser.setFileView(new JalviewFileView());
1872 String tooltip = MessageManager
1873 .getString("label.load_jalview_annotations");
1874 chooser.setDialogTitle(tooltip);
1875 chooser.setToolTipText(tooltip);
1876 chooser.setResponseHandler(0, new Runnable()
1882 String choice = chooser.getSelectedFile().getPath();
1883 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1884 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1888 chooser.showOpenDialog(this);
1892 * Close the current view or all views in the alignment frame. If the frame
1893 * only contains one view then the alignment will be removed from memory.
1895 * @param closeAllTabs
1899 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1901 if (alignPanels != null && alignPanels.size() < 2)
1903 closeAllTabs = true;
1908 if (alignPanels != null)
1912 if (this.isClosed())
1914 // really close all the windows - otherwise wait till
1915 // setClosed(true) is called
1916 for (int i = 0; i < alignPanels.size(); i++)
1918 AlignmentPanel ap = alignPanels.get(i);
1925 closeView(alignPanel);
1930 if (featureSettings != null && featureSettings.isOpen())
1932 featureSettings.close();
1933 featureSettings = null;
1936 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1937 * be called recursively, with the frame now in 'closed' state
1939 this.setClosed(true);
1941 } catch (Exception ex)
1943 ex.printStackTrace();
1948 * Close the specified panel and close up tabs appropriately.
1950 * @param panelToClose
1953 public void closeView(AlignmentPanel panelToClose)
1955 int index = tabbedPane.getSelectedIndex();
1956 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1957 alignPanels.remove(panelToClose);
1958 panelToClose.closePanel();
1959 panelToClose = null;
1961 tabbedPane.removeTabAt(closedindex);
1962 tabbedPane.validate();
1964 if (index > closedindex || index == tabbedPane.getTabCount())
1966 // modify currently selected tab index if necessary.
1970 this.tabSelectionChanged(index);
1977 void updateEditMenuBar()
1980 if (viewport.getHistoryList().size() > 0)
1982 undoMenuItem.setEnabled(true);
1983 CommandI command = viewport.getHistoryList().peek();
1984 undoMenuItem.setText(MessageManager
1985 .formatMessage("label.undo_command", new Object[]
1986 { command.getDescription() }));
1990 undoMenuItem.setEnabled(false);
1991 undoMenuItem.setText(MessageManager.getString("action.undo"));
1994 if (viewport.getRedoList().size() > 0)
1996 redoMenuItem.setEnabled(true);
1998 CommandI command = viewport.getRedoList().peek();
1999 redoMenuItem.setText(MessageManager
2000 .formatMessage("label.redo_command", new Object[]
2001 { command.getDescription() }));
2005 redoMenuItem.setEnabled(false);
2006 redoMenuItem.setText(MessageManager.getString("action.redo"));
2011 public void addHistoryItem(CommandI command)
2013 if (command.getSize() > 0)
2015 viewport.addToHistoryList(command);
2016 viewport.clearRedoList();
2017 updateEditMenuBar();
2018 viewport.updateHiddenColumns();
2019 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
2020 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2021 // viewport.getColumnSelection()
2022 // .getHiddenColumns().size() > 0);
2028 * @return alignment objects for all views
2031 AlignmentI[] getViewAlignments()
2033 if (alignPanels != null)
2035 AlignmentI[] als = new AlignmentI[alignPanels.size()];
2037 for (AlignmentPanel ap : alignPanels)
2039 als[i++] = ap.av.getAlignment();
2043 if (viewport != null)
2045 return new AlignmentI[] { viewport.getAlignment() };
2058 protected void undoMenuItem_actionPerformed(ActionEvent e)
2060 if (viewport.getHistoryList().isEmpty())
2064 CommandI command = viewport.getHistoryList().pop();
2065 viewport.addToRedoList(command);
2066 command.undoCommand(getViewAlignments());
2068 AlignmentViewport originalSource = getOriginatingSource(command);
2069 updateEditMenuBar();
2071 if (originalSource != null)
2073 if (originalSource != viewport)
2076 "Implementation worry: mismatch of viewport origin for undo");
2078 originalSource.updateHiddenColumns();
2079 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
2081 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2082 // viewport.getColumnSelection()
2083 // .getHiddenColumns().size() > 0);
2084 originalSource.notifyAlignment();
2097 protected void redoMenuItem_actionPerformed(ActionEvent e)
2099 if (viewport.getRedoList().size() < 1)
2104 CommandI command = viewport.getRedoList().pop();
2105 viewport.addToHistoryList(command);
2106 command.doCommand(getViewAlignments());
2108 AlignmentViewport originalSource = getOriginatingSource(command);
2109 updateEditMenuBar();
2111 if (originalSource != null)
2114 if (originalSource != viewport)
2117 "Implementation worry: mismatch of viewport origin for redo");
2119 originalSource.updateHiddenColumns();
2120 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
2122 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2123 // viewport.getColumnSelection()
2124 // .getHiddenColumns().size() > 0);
2125 originalSource.notifyAlignment();
2130 AlignmentViewport getOriginatingSource(CommandI command)
2132 AlignmentViewport originalSource = null;
2133 // For sequence removal and addition, we need to fire
2134 // the property change event FROM the viewport where the
2135 // original alignment was altered
2136 AlignmentI al = null;
2137 if (command instanceof EditCommand)
2139 EditCommand editCommand = (EditCommand) command;
2140 al = editCommand.getAlignment();
2141 List<Component> comps = PaintRefresher.components
2142 .get(viewport.getSequenceSetId());
2144 for (Component comp : comps)
2146 if (comp instanceof AlignmentPanel)
2148 if (al == ((AlignmentPanel) comp).av.getAlignment())
2150 originalSource = ((AlignmentPanel) comp).av;
2157 if (originalSource == null)
2159 // The original view is closed, we must validate
2160 // the current view against the closed view first
2163 PaintRefresher.validateSequences(al, viewport.getAlignment());
2166 originalSource = viewport;
2169 return originalSource;
2179 public void moveSelectedSequences(boolean up)
2181 SequenceGroup sg = viewport.getSelectionGroup();
2187 viewport.getAlignment().moveSelectedSequencesByOne(sg,
2188 viewport.getHiddenRepSequences(), up);
2189 alignPanel.paintAlignment(true, false);
2192 synchronized void slideSequences(boolean right, int size)
2194 List<SequenceI> sg = new ArrayList<>();
2195 if (viewport.cursorMode)
2197 sg.add(viewport.getAlignment()
2198 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
2200 else if (viewport.getSelectionGroup() != null
2201 && viewport.getSelectionGroup().getSize() != viewport
2202 .getAlignment().getHeight())
2204 sg = viewport.getSelectionGroup()
2205 .getSequences(viewport.getHiddenRepSequences());
2213 List<SequenceI> invertGroup = new ArrayList<>();
2215 for (SequenceI seq : viewport.getAlignment().getSequences())
2217 if (!sg.contains(seq))
2219 invertGroup.add(seq);
2223 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
2225 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
2226 for (int i = 0; i < invertGroup.size(); i++)
2228 seqs2[i] = invertGroup.get(i);
2231 SlideSequencesCommand ssc;
2234 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
2235 viewport.getGapCharacter());
2239 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
2240 viewport.getGapCharacter());
2243 int groupAdjustment = 0;
2244 if (ssc.getGapsInsertedBegin() && right)
2246 if (viewport.cursorMode)
2248 alignPanel.getSeqPanel().moveCursor(size, 0);
2252 groupAdjustment = size;
2255 else if (!ssc.getGapsInsertedBegin() && !right)
2257 if (viewport.cursorMode)
2259 alignPanel.getSeqPanel().moveCursor(-size, 0);
2263 groupAdjustment = -size;
2267 if (groupAdjustment != 0)
2269 viewport.getSelectionGroup().setStartRes(
2270 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
2271 viewport.getSelectionGroup().setEndRes(
2272 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
2276 * just extend the last slide command if compatible; but not if in
2277 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
2279 boolean appendHistoryItem = false;
2280 Deque<CommandI> historyList = viewport.getHistoryList();
2281 boolean inSplitFrame = getSplitViewContainer() != null;
2282 if (!inSplitFrame && historyList != null && historyList.size() > 0
2283 && historyList.peek() instanceof SlideSequencesCommand)
2285 appendHistoryItem = ssc.appendSlideCommand(
2286 (SlideSequencesCommand) historyList.peek());
2289 if (!appendHistoryItem)
2291 addHistoryItem(ssc);
2305 protected void copy_actionPerformed()
2307 if (viewport.getSelectionGroup() == null)
2311 // TODO: preserve the ordering of displayed alignment annotation in any
2312 // internal paste (particularly sequence associated annotation)
2313 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2314 String[] omitHidden = null;
2316 if (viewport.hasHiddenColumns())
2318 omitHidden = viewport.getViewAsString(true);
2321 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2322 seqs, omitHidden, null);
2324 StringSelection ss = new StringSelection(output);
2326 Desktop d = Desktop.getInstance();
2329 d.internalCopy = true;
2330 // Its really worth setting the clipboard contents
2331 // to empty before setting the large StringSelection!!
2332 Toolkit.getDefaultToolkit().getSystemClipboard()
2333 .setContents(new StringSelection(""), null);
2335 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2336 Desktop.getInstance());
2337 } catch (OutOfMemoryError er)
2339 new OOMWarning("copying region", er);
2343 HiddenColumns hiddenColumns = null;
2344 if (viewport.hasHiddenColumns())
2346 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2347 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2349 // create new HiddenColumns object with copy of hidden regions
2350 // between startRes and endRes, offset by startRes
2351 hiddenColumns = new HiddenColumns(
2352 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2353 hiddenCutoff, hiddenOffset);
2356 d.jalviewClipboard = new Object[] { seqs,
2357 viewport.getAlignment().getDataset(), hiddenColumns };
2358 setStatus(MessageManager.formatMessage(
2359 "label.copied_sequences_to_clipboard", new Object[]
2360 { Integer.valueOf(seqs.length).toString() }));
2368 * @throws InterruptedException
2369 * @throws IOException
2373 protected void pasteNew_actionPerformed(ActionEvent e)
2374 throws IOException, InterruptedException
2384 * @throws InterruptedException
2385 * @throws IOException
2389 protected void pasteThis_actionPerformed(ActionEvent e)
2390 throws IOException, InterruptedException
2396 * Paste contents of Jalview clipboard
2398 * @param newAlignment
2399 * true to paste to a new alignment, otherwise add to this.
2400 * @throws InterruptedException
2401 * @throws IOException
2403 void paste(boolean newAlignment) throws IOException, InterruptedException
2405 boolean externalPaste = true;
2408 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2409 Transferable contents = c.getContents(this);
2411 if (contents == null)
2420 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2421 if (str.length() < 1)
2426 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2428 } catch (OutOfMemoryError er)
2430 new OOMWarning("Out of memory pasting sequences!!", er);
2434 SequenceI[] sequences;
2435 boolean annotationAdded = false;
2436 AlignmentI alignment = null;
2438 Desktop d = Desktop.getInstance();
2440 if (d.jalviewClipboard != null)
2442 // The clipboard was filled from within Jalview, we must use the
2444 // And dataset from the copied alignment
2445 SequenceI[] newseq = (SequenceI[]) d.jalviewClipboard[0];
2446 // be doubly sure that we create *new* sequence objects.
2447 sequences = new SequenceI[newseq.length];
2448 for (int i = 0; i < newseq.length; i++)
2450 sequences[i] = new Sequence(newseq[i]);
2452 alignment = new Alignment(sequences);
2453 externalPaste = false;
2457 // parse the clipboard as an alignment.
2458 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2460 sequences = alignment.getSequencesArray();
2464 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2470 if (d.jalviewClipboard != null)
2472 // dataset is inherited
2473 alignment.setDataset((Alignment) d.jalviewClipboard[1]);
2477 // new dataset is constructed
2478 alignment.setDataset(null);
2480 alwidth = alignment.getWidth() + 1;
2484 AlignmentI pastedal = alignment; // preserve pasted alignment object
2485 // Add pasted sequences and dataset into existing alignment.
2486 alignment = viewport.getAlignment();
2487 alwidth = alignment.getWidth() + 1;
2488 // decide if we need to import sequences from an existing dataset
2489 boolean importDs = d.jalviewClipboard != null
2490 && d.jalviewClipboard[1] != alignment.getDataset();
2491 // importDs==true instructs us to copy over new dataset sequences from
2492 // an existing alignment
2493 Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2495 // minimum dataset set
2497 for (int i = 0; i < sequences.length; i++)
2501 newDs.addElement(null);
2503 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2505 if (importDs && ds != null)
2507 if (!newDs.contains(ds))
2509 newDs.setElementAt(ds, i);
2510 ds = new Sequence(ds);
2511 // update with new dataset sequence
2512 sequences[i].setDatasetSequence(ds);
2516 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2521 // copy and derive new dataset sequence
2522 sequences[i] = sequences[i].deriveSequence();
2523 alignment.getDataset()
2524 .addSequence(sequences[i].getDatasetSequence());
2525 // TODO: avoid creation of duplicate dataset sequences with a
2526 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2528 alignment.addSequence(sequences[i]); // merges dataset
2532 newDs.clear(); // tidy up
2534 if (alignment.getAlignmentAnnotation() != null)
2536 for (AlignmentAnnotation alan : alignment
2537 .getAlignmentAnnotation())
2539 if (alan.graphGroup > fgroup)
2541 fgroup = alan.graphGroup;
2545 if (pastedal.getAlignmentAnnotation() != null)
2547 // Add any annotation attached to alignment.
2548 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2549 for (int i = 0; i < alann.length; i++)
2551 annotationAdded = true;
2552 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2554 AlignmentAnnotation newann = new AlignmentAnnotation(
2556 if (newann.graphGroup > -1)
2558 if (newGraphGroups.size() <= newann.graphGroup
2559 || newGraphGroups.get(newann.graphGroup) == null)
2561 for (int q = newGraphGroups
2562 .size(); q <= newann.graphGroup; q++)
2564 newGraphGroups.add(q, null);
2566 newGraphGroups.set(newann.graphGroup,
2567 Integer.valueOf(++fgroup));
2569 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2573 newann.padAnnotation(alwidth);
2574 alignment.addAnnotation(newann);
2584 addHistoryItem(new EditCommand(
2585 MessageManager.getString("label.add_sequences"),
2586 Action.PASTE, sequences, 0, alignment.getWidth(),
2589 // Add any annotations attached to sequences
2590 for (int i = 0; i < sequences.length; i++)
2592 if (sequences[i].getAnnotation() != null)
2594 AlignmentAnnotation newann;
2595 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2597 annotationAdded = true;
2598 newann = sequences[i].getAnnotation()[a];
2599 newann.adjustForAlignment();
2600 newann.padAnnotation(alwidth);
2601 if (newann.graphGroup > -1)
2603 if (newann.graphGroup > -1)
2605 if (newGraphGroups.size() <= newann.graphGroup
2606 || newGraphGroups.get(newann.graphGroup) == null)
2608 for (int q = newGraphGroups
2609 .size(); q <= newann.graphGroup; q++)
2611 newGraphGroups.add(q, null);
2613 newGraphGroups.set(newann.graphGroup,
2614 Integer.valueOf(++fgroup));
2616 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2620 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2624 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2632 // propagate alignment changed.
2633 viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2634 if (annotationAdded)
2636 // Duplicate sequence annotation in all views.
2637 AlignmentI[] alview = this.getViewAlignments();
2638 for (int i = 0; i < sequences.length; i++)
2640 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2645 for (int avnum = 0; avnum < alview.length; avnum++)
2647 if (alview[avnum] != alignment)
2649 // duplicate in a view other than the one with input focus
2650 int avwidth = alview[avnum].getWidth() + 1;
2651 // this relies on sann being preserved after we
2652 // modify the sequence's annotation array for each duplication
2653 for (int a = 0; a < sann.length; a++)
2655 AlignmentAnnotation newann = new AlignmentAnnotation(
2657 sequences[i].addAlignmentAnnotation(newann);
2658 newann.padAnnotation(avwidth);
2659 alview[avnum].addAnnotation(newann); // annotation was
2660 // duplicated earlier
2661 // TODO JAL-1145 graphGroups are not updated for sequence
2662 // annotation added to several views. This may cause
2664 alview[avnum].setAnnotationIndex(newann, a);
2669 buildSortByAnnotationScoresMenu();
2671 viewport.notifyAlignment();
2672 if (alignPanels != null)
2674 for (AlignmentPanel ap : alignPanels)
2676 ap.validateAnnotationDimensions(false);
2681 alignPanel.validateAnnotationDimensions(false);
2687 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2689 String newtitle = new String("Copied sequences");
2691 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2693 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2694 af.viewport.setHiddenColumns(hc);
2697 // >>>This is a fix for the moment, until a better solution is
2699 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2700 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2701 .getFeatureRenderer());
2703 // TODO: maintain provenance of an alignment, rather than just make the
2704 // title a concatenation of operations.
2707 if (title.startsWith("Copied sequences"))
2713 newtitle = newtitle.concat("- from " + title);
2718 newtitle = new String("Pasted sequences");
2721 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2726 } catch (Exception ex)
2728 ex.printStackTrace();
2729 System.out.println("Exception whilst pasting: " + ex);
2730 // could be anything being pasted in here
2735 protected void expand_newalign(ActionEvent e)
2739 AlignmentI alignment = AlignmentUtils
2740 .expandContext(getViewport().getAlignment(), -1);
2741 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2743 String newtitle = new String("Flanking alignment");
2744 Desktop d = Desktop.getInstance();
2745 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2747 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2748 af.viewport.setHiddenColumns(hc);
2751 // >>>This is a fix for the moment, until a better solution is
2753 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2754 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2755 .getFeatureRenderer());
2757 // TODO: maintain provenance of an alignment, rather than just make the
2758 // title a concatenation of operations.
2760 if (title.startsWith("Copied sequences"))
2766 newtitle = newtitle.concat("- from " + title);
2770 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2772 } catch (Exception ex)
2774 ex.printStackTrace();
2775 System.out.println("Exception whilst pasting: " + ex);
2776 // could be anything being pasted in here
2777 } catch (OutOfMemoryError oom)
2779 new OOMWarning("Viewing flanking region of alignment", oom);
2784 * Action Cut (delete and copy) the selected region
2788 protected void cut_actionPerformed()
2790 copy_actionPerformed();
2791 delete_actionPerformed();
2795 * Performs menu option to Delete the currently selected region
2799 protected void delete_actionPerformed()
2802 SequenceGroup sg = viewport.getSelectionGroup();
2808 Runnable okAction = new Runnable()
2814 SequenceI[] cut = sg.getSequences()
2815 .toArray(new SequenceI[sg.getSize()]);
2817 addHistoryItem(new EditCommand(
2818 MessageManager.getString("label.cut_sequences"), Action.CUT,
2819 cut, sg.getStartRes(),
2820 sg.getEndRes() - sg.getStartRes() + 1,
2821 viewport.getAlignment()));
2823 viewport.setSelectionGroup(null);
2824 viewport.sendSelection();
2825 viewport.getAlignment().deleteGroup(sg);
2827 viewport.notifyAlignment();
2829 if (viewport.getAlignment().getHeight() < 1)
2833 AlignFrame.this.setClosed(true);
2834 } catch (Exception ex)
2844 * If the cut affects all sequences, prompt for confirmation
2846 boolean wholeHeight = sg.getSize() == viewport.getAlignment()
2848 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2849 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2850 if (wholeHeight && wholeWidth)
2852 JvOptionPane dialog = JvOptionPane
2853 .newOptionDialog(Desktop.getDesktopPane());
2854 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2855 Object[] options = new Object[] {
2856 MessageManager.getString("action.ok"),
2857 MessageManager.getString("action.cancel") };
2858 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2859 MessageManager.getString("label.delete_all"),
2860 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2861 options, options[0]);
2877 protected void deleteGroups_actionPerformed(ActionEvent e)
2879 if (avc.deleteGroups())
2881 updateAll(viewport.getSequenceSetId());
2885 private void updateAll(String id)
2889 // this will force a non-fast repaint of both the IdPanel and SeqPanel
2890 alignPanel.getIdPanel().getIdCanvas().setNoFastPaint();
2891 alignPanel.getSeqPanel().seqCanvas.setNoFastPaint();
2892 alignPanel.repaint();
2897 PaintRefresher.Refresh(this, id);
2898 alignPanel.paintAlignment(true, true);
2900 alignPanel.updateAnnotation();
2911 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2913 alignPanel.selectAllSequences();
2924 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2926 alignPanel.deselectAllSequences();
2937 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2939 SequenceGroup sg = viewport.getSelectionGroup();
2943 alignPanel.selectAllSequences();
2948 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2950 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2952 // JAL-2034 - should delegate to
2953 // alignPanel to decide if overview needs
2956 alignPanel.paintAlignment(true, false);
2957 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2958 viewport.sendSelection();
2962 public void invertColSel_actionPerformed(ActionEvent e)
2964 viewport.invertColumnSelection();
2965 alignPanel.paintAlignment(true, false);
2966 viewport.sendSelection();
2977 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2979 trimAlignment(true);
2990 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2992 trimAlignment(false);
2995 void trimAlignment(boolean trimLeft)
2997 ColumnSelection colSel = viewport.getColumnSelection();
3000 if (!colSel.isEmpty())
3004 column = colSel.getMin();
3008 column = colSel.getMax();
3012 if (viewport.getSelectionGroup() != null)
3014 seqs = viewport.getSelectionGroup()
3015 .getSequencesAsArray(viewport.getHiddenRepSequences());
3019 seqs = viewport.getAlignment().getSequencesArray();
3022 TrimRegionCommand trimRegion;
3025 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
3026 column, viewport.getAlignment());
3027 viewport.getRanges().setStartRes(0);
3031 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
3032 column, viewport.getAlignment());
3035 setStatus(MessageManager.formatMessage("label.removed_columns",
3037 { Integer.valueOf(trimRegion.getSize()).toString() }));
3039 addHistoryItem(trimRegion);
3041 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3043 if ((trimLeft && !sg.adjustForRemoveLeft(column))
3044 || (!trimLeft && !sg.adjustForRemoveRight(column)))
3046 viewport.getAlignment().deleteGroup(sg);
3050 viewport.notifyAlignment();
3063 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
3065 int start = 0, end = viewport.getAlignment().getWidth() - 1;
3068 if (viewport.getSelectionGroup() != null)
3070 seqs = viewport.getSelectionGroup()
3071 .getSequencesAsArray(viewport.getHiddenRepSequences());
3072 start = viewport.getSelectionGroup().getStartRes();
3073 end = viewport.getSelectionGroup().getEndRes();
3077 seqs = viewport.getAlignment().getSequencesArray();
3080 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
3081 "Remove Gapped Columns", seqs, start, end,
3082 viewport.getAlignment());
3084 addHistoryItem(removeGapCols);
3086 setStatus(MessageManager.formatMessage("label.removed_empty_columns",
3088 { Integer.valueOf(removeGapCols.getSize()).toString() }));
3090 // This is to maintain viewport position on first residue
3091 // of first sequence
3092 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3093 ViewportRanges ranges = viewport.getRanges();
3094 int startRes = seq.findPosition(ranges.getStartRes());
3095 // ShiftList shifts;
3096 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
3097 // edit.alColumnChanges=shifts.getInverse();
3098 // if (viewport.hasHiddenColumns)
3099 // viewport.getColumnSelection().compensateForEdits(shifts);
3100 ranges.setStartRes(seq.findIndex(startRes) - 1);
3101 viewport.notifyAlignment();
3114 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
3116 int start = 0, end = viewport.getAlignment().getWidth() - 1;
3119 if (viewport.getSelectionGroup() != null)
3121 seqs = viewport.getSelectionGroup()
3122 .getSequencesAsArray(viewport.getHiddenRepSequences());
3123 start = viewport.getSelectionGroup().getStartRes();
3124 end = viewport.getSelectionGroup().getEndRes();
3128 seqs = viewport.getAlignment().getSequencesArray();
3131 // This is to maintain viewport position on first residue
3132 // of first sequence
3133 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3134 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
3136 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
3137 viewport.getAlignment()));
3139 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
3140 viewport.notifyAlignment();
3152 public void padGapsMenuitem_actionPerformed(ActionEvent e)
3154 viewport.setPadGaps(padGapsMenuitem.isSelected());
3155 viewport.notifyAlignment();
3167 public void findMenuItem_actionPerformed(ActionEvent e)
3173 * Create a new view of the current alignment.
3177 public void newView_actionPerformed(ActionEvent e)
3179 newView(null, true);
3183 * Creates and shows a new view of the current alignment.
3186 * title of newly created view; if null, one will be generated
3187 * @param copyAnnotation
3188 * if true then duplicate all annnotation, groups and settings
3189 * @return new alignment panel, already displayed.
3192 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
3195 * Create a new AlignmentPanel (with its own, new Viewport)
3197 AlignmentPanel newap = new jalview.project.Jalview2XML()
3198 .copyAlignPanel(alignPanel);
3199 if (!copyAnnotation)
3202 * remove all groups and annotation except for the automatic stuff
3204 newap.av.getAlignment().deleteAllGroups();
3205 newap.av.getAlignment().deleteAllAnnotations(false);
3208 newap.av.setGatherViewsHere(false);
3210 if (viewport.getViewName() == null)
3212 viewport.setViewName(
3213 MessageManager.getString("label.view_name_original"));
3217 * Views share the same edits undo and redo stacks
3219 newap.av.setHistoryList(viewport.getHistoryList());
3220 newap.av.setRedoList(viewport.getRedoList());
3223 * copy any visualisation settings that are not saved in the project
3225 newap.av.setColourAppliesToAllGroups(
3226 viewport.getColourAppliesToAllGroups());
3229 * Views share the same mappings; need to deregister any new mappings
3230 * created by copyAlignPanel, and register the new reference to the shared
3233 newap.av.replaceMappings(viewport.getAlignment());
3236 * start up cDNA consensus (if applicable) now mappings are in place
3238 if (newap.av.initComplementConsensus())
3240 newap.refresh(true); // adjust layout of annotations
3243 newap.av.setViewName(getNewViewName(viewTitle));
3245 addAlignmentPanel(newap, true);
3246 newap.alignmentChanged();
3248 if (alignPanels.size() == 2)
3250 viewport.setGatherViewsHere(true);
3252 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
3257 * Make a new name for the view, ensuring it is unique within the current
3258 * sequenceSetId. (This used to be essential for Jalview Project archives, but
3259 * these now use viewId. Unique view names are still desirable for usability.)
3265 protected String getNewViewName(String viewTitle)
3267 int index = Desktop.getViewCount(viewport.getSequenceSetId());
3268 boolean addFirstIndex = false;
3269 if (viewTitle == null || viewTitle.trim().length() == 0)
3271 viewTitle = MessageManager.getString("action.view");
3272 addFirstIndex = true;
3276 index = 1;// we count from 1 if given a specific name
3278 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
3280 List<Component> comps = PaintRefresher.components
3281 .get(viewport.getSequenceSetId());
3283 List<String> existingNames = getExistingViewNames(comps);
3285 while (existingNames.contains(newViewName))
3287 newViewName = viewTitle + " " + (++index);
3293 * Returns a list of distinct view names found in the given list of
3294 * components. View names are held on the viewport of an AlignmentPanel.
3300 protected List<String> getExistingViewNames(List<Component> comps)
3302 List<String> existingNames = new ArrayList<>();
3303 for (Component comp : comps)
3305 if (comp instanceof AlignmentPanel)
3307 AlignmentPanel ap = (AlignmentPanel) comp;
3308 if (!existingNames.contains(ap.av.getViewName()))
3310 existingNames.add(ap.av.getViewName());
3314 return existingNames;
3318 * Explode tabbed views into separate windows.
3322 public void expandViews_actionPerformed(ActionEvent e)
3324 Desktop.explodeViews(this);
3328 * Gather views in separate windows back into a tabbed presentation.
3332 public void gatherViews_actionPerformed(ActionEvent e)
3334 Desktop.getInstance().gatherViews(this);
3345 public void font_actionPerformed(ActionEvent e)
3347 new FontChooser(alignPanel);
3358 protected void seqLimit_actionPerformed(ActionEvent e)
3360 viewport.setShowJVSuffix(seqLimits.isSelected());
3362 alignPanel.getIdPanel().getIdCanvas()
3363 .setPreferredSize(alignPanel.calculateIdWidth());
3364 alignPanel.paintAlignment(true, false);
3368 public void idRightAlign_actionPerformed(ActionEvent e)
3370 viewport.setRightAlignIds(idRightAlign.isSelected());
3371 alignPanel.paintAlignment(false, false);
3375 public void centreColumnLabels_actionPerformed(ActionEvent e)
3377 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3378 alignPanel.paintAlignment(false, false);
3384 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3388 protected void followHighlight_actionPerformed()
3391 * Set the 'follow' flag on the Viewport (and scroll to position if now
3394 final boolean state = this.followHighlightMenuItem.getState();
3395 viewport.setFollowHighlight(state);
3398 alignPanel.scrollToPosition(viewport.getSearchResults());
3410 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3412 viewport.setColourText(colourTextMenuItem.isSelected());
3413 alignPanel.paintAlignment(false, false);
3424 public void wrapMenuItem_actionPerformed(ActionEvent e)
3426 scaleAbove.setVisible(wrapMenuItem.isSelected());
3427 scaleLeft.setVisible(wrapMenuItem.isSelected());
3428 scaleRight.setVisible(wrapMenuItem.isSelected());
3429 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3430 alignPanel.updateLayout();
3434 public void showAllSeqs_actionPerformed(ActionEvent e)
3436 viewport.showAllHiddenSeqs();
3440 public void showAllColumns_actionPerformed(ActionEvent e)
3442 viewport.showAllHiddenColumns();
3443 alignPanel.paintAlignment(true, true);
3444 viewport.sendSelection();
3448 public void hideSelSequences_actionPerformed(ActionEvent e)
3450 viewport.hideAllSelectedSeqs();
3454 * called by key handler and the hide all/show all menu items
3460 protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3463 boolean hide = false;
3464 SequenceGroup sg = viewport.getSelectionGroup();
3465 if (!toggleSeqs && !toggleCols)
3467 // Hide everything by the current selection - this is a hack - we do the
3468 // invert and then hide
3469 // first check that there will be visible columns after the invert.
3470 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3471 && sg.getStartRes() <= sg.getEndRes()))
3473 // now invert the sequence set, if required - empty selection implies
3474 // that no hiding is required.
3477 invertSequenceMenuItem_actionPerformed(null);
3478 sg = viewport.getSelectionGroup();
3482 viewport.expandColSelection(sg, true);
3483 // finally invert the column selection and get the new sequence
3485 invertColSel_actionPerformed(null);
3492 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3494 hideSelSequences_actionPerformed(null);
3497 else if (!(toggleCols && viewport.hasSelectedColumns()))
3499 showAllSeqs_actionPerformed(null);
3505 if (viewport.hasSelectedColumns())
3507 hideSelColumns_actionPerformed(null);
3510 viewport.setSelectionGroup(sg);
3515 showAllColumns_actionPerformed(null);
3524 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3525 * event.ActionEvent)
3529 public void hideAllButSelection_actionPerformed(ActionEvent e)
3531 toggleHiddenRegions(false, false);
3532 viewport.sendSelection();
3539 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3544 public void hideAllSelection_actionPerformed(ActionEvent e)
3546 SequenceGroup sg = viewport.getSelectionGroup();
3547 viewport.expandColSelection(sg, false);
3548 viewport.hideAllSelectedSeqs();
3549 viewport.hideSelectedColumns();
3550 alignPanel.updateLayout();
3551 alignPanel.paintAlignment(true, true);
3552 viewport.sendSelection();
3559 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3564 public void showAllhidden_actionPerformed(ActionEvent e)
3566 viewport.showAllHiddenColumns();
3567 viewport.showAllHiddenSeqs();
3568 alignPanel.paintAlignment(true, true);
3569 viewport.sendSelection();
3573 public void hideSelColumns_actionPerformed(ActionEvent e)
3575 viewport.hideSelectedColumns();
3576 alignPanel.updateLayout();
3577 alignPanel.paintAlignment(true, true);
3578 viewport.sendSelection();
3582 public void hiddenMarkers_actionPerformed(ActionEvent e)
3584 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3596 protected void scaleAbove_actionPerformed(ActionEvent e)
3598 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3599 alignPanel.updateLayout();
3600 alignPanel.paintAlignment(true, false);
3611 protected void scaleLeft_actionPerformed(ActionEvent e)
3613 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3614 alignPanel.updateLayout();
3615 alignPanel.paintAlignment(true, false);
3626 protected void scaleRight_actionPerformed(ActionEvent e)
3628 viewport.setScaleRightWrapped(scaleRight.isSelected());
3629 alignPanel.updateLayout();
3630 alignPanel.paintAlignment(true, false);
3641 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3643 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3644 alignPanel.paintAlignment(false, false);
3655 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3657 viewport.setShowText(viewTextMenuItem.isSelected());
3658 alignPanel.paintAlignment(false, false);
3669 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3671 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3672 alignPanel.paintAlignment(false, false);
3675 public FeatureSettings featureSettings;
3678 public FeatureSettingsControllerI getFeatureSettingsUI()
3680 return featureSettings;
3684 public void featureSettings_actionPerformed(ActionEvent e)
3686 showFeatureSettingsUI();
3690 public FeatureSettingsControllerI showFeatureSettingsUI()
3692 if (featureSettings != null)
3694 featureSettings.closeOldSettings();
3695 featureSettings = null;
3697 if (!showSeqFeatures.isSelected())
3699 // make sure features are actually displayed
3700 showSeqFeatures.setSelected(true);
3701 showSeqFeatures_actionPerformed(null);
3703 featureSettings = new FeatureSettings(this);
3704 return featureSettings;
3708 * Set or clear 'Show Sequence Features'
3715 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3717 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3718 alignPanel.paintAlignment(true, true);
3722 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3723 * the annotations panel as a whole.
3725 * The options to show/hide all annotations should be enabled when the panel
3726 * is shown, and disabled when the panel is hidden.
3732 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3734 final boolean setVisible = annotationPanelMenuItem.isSelected();
3735 viewport.setShowAnnotation(setVisible);
3736 syncAnnotationMenuItems(setVisible);
3737 alignPanel.updateLayout();
3739 SwingUtilities.invokeLater(new Runnable() {
3744 alignPanel.updateScrollBarsFromRanges();
3750 private void syncAnnotationMenuItems(boolean setVisible)
3752 showAllSeqAnnotations.setEnabled(setVisible);
3753 hideAllSeqAnnotations.setEnabled(setVisible);
3754 showAllAlAnnotations.setEnabled(setVisible);
3755 hideAllAlAnnotations.setEnabled(setVisible);
3759 public void alignmentProperties()
3762 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3765 String content = MessageManager.formatMessage("label.html_content",
3767 { contents.toString() });
3770 if (Platform.isJS())
3772 JLabel textLabel = new JLabel();
3773 textLabel.setText(content);
3774 textLabel.setBackground(Color.WHITE);
3776 pane = new JPanel(new BorderLayout());
3777 ((JPanel) pane).setOpaque(true);
3778 pane.setBackground(Color.WHITE);
3779 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3788 JEditorPane editPane = new JEditorPane("text/html", "");
3789 editPane.setEditable(false);
3790 editPane.setText(content);
3794 JInternalFrame frame = new JInternalFrame();
3796 frame.getContentPane().add(new JScrollPane(pane));
3798 Desktop.addInternalFrame(frame, MessageManager
3799 .formatMessage("label.alignment_properties", new Object[]
3800 { getTitle() }), 500, 400);
3811 public void overviewMenuItem_actionPerformed(ActionEvent e)
3813 if (alignPanel.overviewPanel != null)
3818 JInternalFrame frame = new JInternalFrame();
3820 // BH 2019.07.26 we allow for an embedded
3821 // undecorated overview with defined size
3822 frame.setName(Platform.getAppID("overview"));
3824 Dimension dim = Platform.getDimIfEmbedded(frame, -1, -1);
3825 if (dim != null && dim.width == 0)
3827 dim = null; // hidden, not embedded
3829 OverviewPanel overview = new OverviewPanel(alignPanel, dim);
3831 frame.setContentPane(overview);
3834 dim = new Dimension();
3835 // was frame.getSize(), but that is 0,0 at this point;
3839 // we are imbedding, and so we have an undecorated frame
3840 // and we can set the the frame dimensions accordingly.
3842 // allowing for unresizable option using, style="resize:none"
3843 boolean resizable = (Platform.getEmbeddedAttribute(frame,
3844 "resize") != "none");
3845 Desktop.addInternalFrame(frame, MessageManager
3846 .formatMessage("label.overview_params", new Object[]
3847 { this.getTitle() }), Desktop.FRAME_MAKE_VISIBLE, dim.width,
3848 dim.height, resizable, Desktop.FRAME_ALLOW_ANY_SIZE);
3850 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3851 frame.addInternalFrameListener(
3852 new javax.swing.event.InternalFrameAdapter()
3856 public void internalFrameClosed(
3857 javax.swing.event.InternalFrameEvent evt)
3860 alignPanel.setOverviewPanel(null);
3863 if (getKeyListeners().length > 0)
3865 frame.addKeyListener(getKeyListeners()[0]);
3868 alignPanel.setOverviewPanel(overview);
3872 public void textColour_actionPerformed()
3874 new TextColourChooser().chooseColour(alignPanel, null);
3878 * public void covariationColour_actionPerformed() {
3880 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3885 public void annotationColour_actionPerformed()
3887 new AnnotationColourChooser(viewport, alignPanel);
3891 public void annotationColumn_actionPerformed(ActionEvent e)
3893 new AnnotationColumnChooser(viewport, alignPanel);
3897 * Action on the user checking or unchecking the option to apply the selected
3898 * colour scheme to all groups. If unchecked, groups may have their own
3899 * independent colour schemes.
3905 public void applyToAllGroups_actionPerformed(boolean selected)
3907 viewport.setColourAppliesToAllGroups(selected);
3911 * Action on user selecting a colour from the colour menu
3914 * the name (not the menu item label!) of the colour scheme
3918 public void changeColour_actionPerformed(String name)
3921 * 'User Defined' opens a panel to configure or load a
3922 * user-defined colour scheme
3924 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3926 new UserDefinedColours(alignPanel);
3931 * otherwise set the chosen colour scheme (or null for 'None')
3933 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3934 viewport, viewport.getAlignment(),
3935 viewport.getHiddenRepSequences());
3940 * Actions on setting or changing the alignment colour scheme
3946 public void changeColour(ColourSchemeI cs)
3948 // TODO: pull up to controller method
3949 ColourMenuHelper.setColourSelected(colourMenu, cs);
3951 viewport.setGlobalColourScheme(cs);
3953 alignPanel.paintAlignment(true, true);
3957 * Show the PID threshold slider panel
3961 protected void modifyPID_actionPerformed()
3963 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3964 alignPanel.getViewName());
3965 SliderPanel.showPIDSlider();
3969 * Show the Conservation slider panel
3973 protected void modifyConservation_actionPerformed()
3975 SliderPanel.setConservationSlider(alignPanel,
3976 viewport.getResidueShading(), alignPanel.getViewName());
3977 SliderPanel.showConservationSlider();
3981 * Action on selecting or deselecting (Colour) By Conservation
3985 public void conservationMenuItem_actionPerformed(boolean selected)
3987 modifyConservation.setEnabled(selected);
3988 viewport.setConservationSelected(selected);
3989 viewport.getResidueShading().setConservationApplied(selected);
3991 changeColour(viewport.getGlobalColourScheme());
3994 modifyConservation_actionPerformed();
3998 SliderPanel.hideConservationSlider();
4003 * Action on selecting or deselecting (Colour) Above PID Threshold
4007 public void abovePIDThreshold_actionPerformed(boolean selected)
4009 modifyPID.setEnabled(selected);
4010 viewport.setAbovePIDThreshold(selected);
4013 viewport.getResidueShading().setThreshold(0,
4014 viewport.isIgnoreGapsConsensus());
4017 changeColour(viewport.getGlobalColourScheme());
4020 modifyPID_actionPerformed();
4024 SliderPanel.hidePIDSlider();
4036 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
4038 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4039 AlignmentSorter.sortByPID(viewport.getAlignment(),
4040 viewport.getAlignment().getSequenceAt(0));
4041 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
4042 viewport.getAlignment()));
4043 alignPanel.paintAlignment(true, false);
4054 public void sortIDMenuItem_actionPerformed(ActionEvent e)
4056 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4057 AlignmentSorter.sortByID(viewport.getAlignment());
4059 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
4060 alignPanel.paintAlignment(true, false);
4071 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
4073 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4074 AlignmentSorter.sortByLength(viewport.getAlignment());
4075 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
4076 viewport.getAlignment()));
4077 alignPanel.paintAlignment(true, false);
4088 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
4090 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4091 AlignmentSorter.sortByGroup(viewport.getAlignment());
4092 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4093 viewport.getAlignment()));
4095 alignPanel.paintAlignment(true, false);
4099 public void sortEValueMenuItem_actionPerformed(ActionEvent e)
4101 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4102 AlignmentSorter.sortByEValue(viewport.getAlignment());
4103 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4104 viewport.getAlignment()));
4105 alignPanel.paintAlignment(true, false);
4110 public void sortBitScoreMenuItem_actionPerformed(ActionEvent e)
4112 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4113 AlignmentSorter.sortByBitScore(viewport.getAlignment());
4114 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4115 viewport.getAlignment()));
4116 alignPanel.paintAlignment(true, false);
4128 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
4130 new RedundancyPanel(alignPanel, this);
4141 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
4143 if ((viewport.getSelectionGroup() == null)
4144 || (viewport.getSelectionGroup().getSize() < 2))
4146 JvOptionPane.showInternalMessageDialog(this,
4147 MessageManager.getString(
4148 "label.you_must_select_least_two_sequences"),
4149 MessageManager.getString("label.invalid_selection"),
4150 JvOptionPane.WARNING_MESSAGE);
4154 JInternalFrame frame = new JInternalFrame();
4155 frame.setContentPane(new PairwiseAlignPanel(viewport));
4156 Desktop.addInternalFrame(frame,
4157 MessageManager.getString("action.pairwise_alignment"), 600,
4163 public void autoCalculate_actionPerformed(ActionEvent e)
4165 viewport.setAutoCalculateConsensusAndConservation(
4166 autoCalculate.isSelected());
4167 if (viewport.getAutoCalculateConsensusAndConservation())
4169 // viewport.autoCalculateConsensus = autoCalculate.isSelected();
4170 // if (viewport.autoCalculateConsensus)
4172 viewport.notifyAlignment();
4177 public void sortByTreeOption_actionPerformed(ActionEvent e)
4179 viewport.sortByTree = sortByTree.isSelected();
4183 protected void listenToViewSelections_actionPerformed(ActionEvent e)
4185 viewport.followSelection = listenToViewSelections.isSelected();
4189 * Constructs a tree panel and adds it to the desktop
4192 * tree type (NJ or AV)
4194 * name of score model used to compute the tree
4196 * parameters for the distance or similarity calculation
4199 void newTreePanel(String type, String modelName,
4200 SimilarityParamsI options)
4202 String frameTitle = "";
4205 boolean onSelection = false;
4206 if (viewport.getSelectionGroup() != null
4207 && viewport.getSelectionGroup().getSize() > 0)
4209 SequenceGroup sg = viewport.getSelectionGroup();
4211 /* Decide if the selection is a column region */
4212 for (SequenceI _s : sg.getSequences())
4214 if (_s.getLength() < sg.getEndRes())
4216 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4217 MessageManager.getString(
4218 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
4219 MessageManager.getString(
4220 "label.sequences_selection_not_aligned"),
4221 JvOptionPane.WARNING_MESSAGE);
4230 if (viewport.getAlignment().getHeight() < 2)
4236 tp = new TreePanel(alignPanel, type, modelName, options);
4237 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
4239 frameTitle += " from ";
4241 if (viewport.getViewName() != null)
4243 frameTitle += viewport.getViewName() + " of ";
4246 frameTitle += this.title;
4248 Dimension dim = Platform.getDimIfEmbedded(tp, 600, 500);
4249 Desktop.addInternalFrame(tp, frameTitle, dim.width, dim.height);
4261 public void addSortByOrderMenuItem(String title,
4262 final AlignmentOrder order)
4264 final JMenuItem item = new JMenuItem(MessageManager
4265 .formatMessage("action.by_title_param", new Object[]
4268 item.addActionListener(new java.awt.event.ActionListener()
4272 public void actionPerformed(ActionEvent e)
4274 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4276 // TODO: JBPNote - have to map order entries to curent SequenceI
4278 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4280 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
4281 viewport.getAlignment()));
4283 alignPanel.paintAlignment(true, false);
4289 * Add a new sort by annotation score menu item
4292 * the menu to add the option to
4294 * the label used to retrieve scores for each sequence on the
4298 public void addSortByAnnotScoreMenuItem(JMenu sort,
4299 final String scoreLabel)
4301 final JMenuItem item = new JMenuItem(scoreLabel);
4303 item.addActionListener(new java.awt.event.ActionListener()
4307 public void actionPerformed(ActionEvent e)
4309 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4310 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4311 viewport.getAlignment());// ,viewport.getSelectionGroup());
4312 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4313 viewport.getAlignment()));
4314 alignPanel.paintAlignment(true, false);
4320 * last hash for alignment's annotation array - used to minimise cost of
4323 protected int _annotationScoreVectorHash;
4326 * search the alignment and rebuild the sort by annotation score submenu the
4327 * last alignment annotation vector hash is stored to minimize cost of
4328 * rebuilding in subsequence calls.
4333 public void buildSortByAnnotationScoresMenu()
4335 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4340 if (viewport.getAlignment().getAlignmentAnnotation()
4341 .hashCode() == _annotationScoreVectorHash)
4346 sortByAnnotScore.removeAll();
4347 Set<String> scoreSorts = new HashSet<>();
4348 for (SequenceI sqa : viewport.getAlignment().getSequences())
4350 AlignmentAnnotation[] anns = sqa.getAnnotation();
4351 for (int i = 0; anns != null && i < anns.length; i++)
4353 AlignmentAnnotation aa = anns[i];
4354 if (aa != null && aa.hasScore() && aa.sequenceRef != null)
4356 scoreSorts.add(aa.label);
4360 for (String label : scoreSorts)
4362 addSortByAnnotScoreMenuItem(sortByAnnotScore, label);
4364 sortByAnnotScore.setVisible(!scoreSorts.isEmpty());
4366 _annotationScoreVectorHash = viewport.getAlignment()
4367 .getAlignmentAnnotation().hashCode();
4371 * Enable (or, if desired, make visible) the By Tree
4372 * submenu only if it has at least one element (or will have).
4376 protected void enableSortMenuOptions()
4378 List<TreePanel> treePanels = getTreePanels();
4379 sortByTreeMenu.setEnabled(!treePanels.isEmpty());
4383 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4384 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4385 * call. Listeners are added to remove the menu item when the treePanel is
4386 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4391 public void buildTreeSortMenu()
4393 sortByTreeMenu.removeAll();
4395 List<TreePanel> treePanels = getTreePanels();
4397 for (final TreePanel tp : treePanels)
4399 final JMenuItem item = new JMenuItem(tp.getTitle());
4400 item.addActionListener(new java.awt.event.ActionListener()
4404 public void actionPerformed(ActionEvent e)
4406 tp.sortByTree_actionPerformed();
4407 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4412 sortByTreeMenu.add(item);
4416 private List<TreePanel> getTreePanels()
4418 List<Component> comps = PaintRefresher.components
4419 .get(viewport.getSequenceSetId());
4420 List<TreePanel> treePanels = new ArrayList<>();
4421 for (Component comp : comps)
4423 if (comp instanceof TreePanel)
4425 treePanels.add((TreePanel) comp);
4431 public boolean sortBy(AlignmentOrder alorder, String undoname)
4433 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4434 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4435 if (undoname != null)
4437 addHistoryItem(new OrderCommand(undoname, oldOrder,
4438 viewport.getAlignment()));
4440 alignPanel.paintAlignment(true, false);
4445 * Work out whether the whole set of sequences or just the selected set will
4446 * be submitted for multiple alignment.
4450 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4452 // Now, check we have enough sequences
4453 AlignmentView msa = null;
4455 if ((viewport.getSelectionGroup() != null)
4456 && (viewport.getSelectionGroup().getSize() > 1))
4458 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4459 // some common interface!
4461 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4462 * SequenceI[sz = seqs.getSize(false)];
4464 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4465 * seqs.getSequenceAt(i); }
4467 msa = viewport.getAlignmentView(true);
4469 else if (viewport.getSelectionGroup() != null
4470 && viewport.getSelectionGroup().getSize() == 1)
4472 int option = JvOptionPane.showConfirmDialog(this,
4473 MessageManager.getString("warn.oneseq_msainput_selection"),
4474 MessageManager.getString("label.invalid_selection"),
4475 JvOptionPane.OK_CANCEL_OPTION);
4476 if (option == JvOptionPane.OK_OPTION)
4478 msa = viewport.getAlignmentView(false);
4483 msa = viewport.getAlignmentView(false);
4489 * Decides what is submitted to a secondary structure prediction service: the
4490 * first sequence in the alignment, or in the current selection, or, if the
4491 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4492 * region or the whole alignment. (where the first sequence in the set is the
4493 * one that the prediction will be for).
4496 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4498 AlignmentView seqs = null;
4500 if ((viewport.getSelectionGroup() != null)
4501 && (viewport.getSelectionGroup().getSize() > 0))
4503 seqs = viewport.getAlignmentView(true);
4507 seqs = viewport.getAlignmentView(false);
4509 // limit sequences - JBPNote in future - could spawn multiple prediction
4511 // TODO: viewport.getAlignment().isAligned is a global state - the local
4512 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4513 if (!viewport.getAlignment().isAligned(false))
4515 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4516 // TODO: if seqs.getSequences().length>1 then should really have warned
4531 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4533 // Pick the tree file
4534 JalviewFileChooser chooser = new JalviewFileChooser(
4535 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4536 chooser.setFileView(new JalviewFileView());
4537 chooser.setDialogTitle(
4538 MessageManager.getString("label.select_newick_like_tree_file"));
4539 chooser.setToolTipText(
4540 MessageManager.getString("label.load_tree_file"));
4542 chooser.setResponseHandler(0, new Runnable()
4548 String filePath = chooser.getSelectedFile().getPath();
4549 Cache.setProperty("LAST_DIRECTORY", filePath);
4550 NewickFile fin = null;
4553 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4554 DataSourceType.FILE));
4555 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4556 } catch (Exception ex)
4558 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4561 .getString("label.problem_reading_tree_file"),
4562 JvOptionPane.WARNING_MESSAGE);
4563 ex.printStackTrace();
4565 if (fin != null && fin.hasWarningMessage())
4567 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4568 fin.getWarningMessage(),
4569 MessageManager.getString(
4570 "label.possible_problem_with_tree_file"),
4571 JvOptionPane.WARNING_MESSAGE);
4575 chooser.showOpenDialog(this);
4578 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4580 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4583 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4584 int h, int x, int y)
4586 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4590 * Add a treeviewer for the tree extracted from a Newick file object to the
4591 * current alignment view
4598 * Associated alignment input data (or null)
4607 * @return TreePanel handle
4610 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4611 AlignmentView input, int w, int h, int x, int y)
4613 TreePanel tp = null;
4619 if (nf.getTree() != null)
4621 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4622 Dimension dim = Platform.getDimIfEmbedded(tp, -1, -1);
4625 dim = new Dimension(w, h);
4629 // no offset, either
4632 tp.setSize(dim.width, dim.height);
4636 tp.setLocation(x, y);
4639 Desktop.addInternalFrame(tp, treeTitle, dim.width, dim.height);
4641 } catch (Exception ex)
4643 ex.printStackTrace();
4650 * Schedule the web services menu rebuild to the event dispatch thread.
4652 public void buildWebServicesMenu()
4654 SwingUtilities.invokeLater(() -> {
4655 Cache.log.info("Rebuiling WS menu");
4656 webService.removeAll();
4657 if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
4659 Cache.log.info("Building web service menu for slivka");
4660 SlivkaWSDiscoverer discoverer = SlivkaWSDiscoverer.getInstance();
4661 JMenu submenu = new JMenu("Slivka");
4662 buildWebServicesMenu(discoverer, submenu);
4663 webService.add(submenu);
4665 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4667 WSDiscovererI jws2servs = Jws2Discoverer.getInstance();
4668 JMenu submenu = new JMenu("JABAWS");
4669 buildLegacyWebServicesMenu(submenu);
4670 buildWebServicesMenu(jws2servs, submenu);
4671 webService.add(submenu);
4673 build_fetchdbmenu(webService);
4677 private void buildLegacyWebServicesMenu(JMenu menu)
4679 JMenu secstrmenu = new JMenu("Secondary Structure Prediction");
4680 if (Discoverer.getServices() != null && Discoverer.getServices().size() > 0)
4682 var secstrpred = Discoverer.getServices().get("SecStrPred");
4683 if (secstrpred != null)
4685 for (ext.vamsas.ServiceHandle sh : secstrpred)
4687 var menuProvider = Discoverer.getServiceClient(sh);
4688 menuProvider.attachWSMenuEntry(secstrmenu, this);
4692 menu.add(secstrmenu);
4696 * Constructs the web services menu for the given discoverer under the
4697 * specified menu. This method must be called on the EDT
4700 * the discoverer used to build the menu
4702 * parent component which the elements will be attached to
4704 private void buildWebServicesMenu(WSDiscovererI discoverer, JMenu menu)
4706 if (discoverer.hasServices())
4708 PreferredServiceRegistry.getRegistry().populateWSMenuEntry(
4709 discoverer.getServices(), sv -> buildWebServicesMenu(), menu,
4712 if (discoverer.isRunning())
4714 JMenuItem item = new JMenuItem("Service discovery in progress.");
4715 item.setEnabled(false);
4718 else if (!discoverer.hasServices())
4720 JMenuItem item = new JMenuItem("No services available.");
4721 item.setEnabled(false);
4726 private void buildWebServicesMenu(WebServiceDiscoverer discoverer, JMenu menu)
4728 if (discoverer.hasServices())
4730 for (WebServiceI service : discoverer.getServices())
4732 for (Operation op : service.getOperations())
4734 JMenu atpoint = JvSwingUtils.findOrCreateMenu(menu, op.getTypeName());
4735 op.getMenuBuilder().buildMenu(atpoint, this);
4739 if (discoverer.isRunning())
4741 JMenuItem item = new JMenuItem("Service discovery in progress.");
4742 item.setEnabled(false);
4745 else if (!discoverer.hasServices())
4747 JMenuItem item = new JMenuItem("No services available.");
4748 item.setEnabled(false);
4754 * construct any groupURL type service menu entries.
4759 protected void build_urlServiceMenu(JMenu webService)
4761 // TODO: remove this code when 2.7 is released
4762 // DEBUG - alignmentView
4764 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4765 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4767 * public void actionPerformed(ActionEvent e) {
4768 * jalview.datamodel.AlignmentView
4769 * .testSelectionViews(af.viewport.getAlignment(),
4770 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4772 * }); webService.add(testAlView);
4774 // TODO: refactor to RestClient discoverer and merge menu entries for
4775 // rest-style services with other types of analysis/calculation service
4776 // SHmmr test client - still being implemented.
4777 // DEBUG - alignmentView
4779 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4782 client.attachWSMenuEntry(
4783 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4789 * Searches the alignment sequences for xRefs and builds the Show
4790 * Cross-References menu (formerly called Show Products), with database
4791 * sources for which cross-references are found (protein sources for a
4792 * nucleotide alignment and vice versa)
4794 * @return true if Show Cross-references menu should be enabled
4797 public boolean canShowProducts()
4799 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4800 AlignmentI dataset = viewport.getAlignment().getDataset();
4802 showProducts.removeAll();
4803 final boolean dna = viewport.getAlignment().isNucleotide();
4805 if (seqs == null || seqs.length == 0)
4807 // nothing to see here.
4811 boolean showp = false;
4814 List<String> ptypes = new CrossRef(seqs, dataset)
4815 .findXrefSourcesForSequences(dna);
4817 for (final String source : ptypes)
4820 final AlignFrame af = this;
4821 JMenuItem xtype = new JMenuItem(source);
4822 xtype.addActionListener(new ActionListener()
4826 public void actionPerformed(ActionEvent e)
4828 showProductsFor(af.viewport.getSequenceSelection(), dna,
4832 showProducts.add(xtype);
4834 showProducts.setVisible(showp);
4835 showProducts.setEnabled(showp);
4836 } catch (Exception e)
4839 "canShowProducts threw an exception - please report to help@jalview.org",
4847 * Finds and displays cross-references for the selected sequences (protein
4848 * products for nucleotide sequences, dna coding sequences for peptides).
4851 * the sequences to show cross-references for
4853 * true if from a nucleotide alignment (so showing proteins)
4855 * the database to show cross-references for
4858 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4859 final String source)
4861 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4866 * Construct and display a new frame containing the translation of this
4867 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4871 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4873 AlignmentI al = null;
4876 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4878 al = dna.translateCdna(codeTable);
4879 } catch (Exception ex)
4881 jalview.bin.Cache.log.error(
4882 "Exception during translation. Please report this !", ex);
4883 final String msg = MessageManager.getString(
4884 "label.error_when_translating_sequences_submit_bug_report");
4885 final String errorTitle = MessageManager
4886 .getString("label.implementation_error")
4887 + MessageManager.getString("label.translation_failed");
4888 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4889 errorTitle, JvOptionPane.ERROR_MESSAGE);
4892 if (al == null || al.getHeight() == 0)
4894 final String msg = MessageManager.getString(
4895 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4896 final String errorTitle = MessageManager
4897 .getString("label.translation_failed");
4898 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4899 errorTitle, JvOptionPane.WARNING_MESSAGE);
4903 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4904 af.setFileFormat(this.currentFileFormat);
4905 final String newTitle = MessageManager
4906 .formatMessage("label.translation_of_params", new Object[]
4907 { this.getTitle(), codeTable.getId() });
4908 af.setTitle(newTitle);
4909 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4911 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4912 AlignViewport.openSplitFrame(this, af, new Alignment(seqs));
4916 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4923 * Set the file format
4928 public void setFileFormat(FileFormatI format)
4930 this.currentFileFormat = format;
4934 * Try to load a features file onto the alignment.
4937 * contents or path to retrieve file or a File object
4939 * access mode of file (see jalview.io.AlignFile)
4940 * @return true if features file was parsed correctly.
4943 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4946 return avc.parseFeaturesFile(file, sourceType,
4947 Cache.getDefault(Preferences.RELAXEDSEQIDMATCHING, false));
4952 public void refreshFeatureUI(boolean enableIfNecessary)
4954 // note - currently this is only still here rather than in the controller
4955 // because of the featureSettings hard reference that is yet to be
4957 if (enableIfNecessary)
4959 viewport.setShowSequenceFeatures(true);
4960 showSeqFeatures.setSelected(true);
4966 public void dragEnter(DropTargetDragEvent evt)
4971 public void dragExit(DropTargetEvent evt)
4976 public void dragOver(DropTargetDragEvent evt)
4981 public void dropActionChanged(DropTargetDragEvent evt)
4986 public void drop(DropTargetDropEvent evt)
4988 // JAL-1552 - acceptDrop required before getTransferable call for
4989 // Java's Transferable for native dnd
4990 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4991 Transferable t = evt.getTransferable();
4993 final List<Object> files = new ArrayList<>();
4994 List<DataSourceType> protocols = new ArrayList<>();
4998 Desktop.transferFromDropTarget(files, protocols, evt, t);
4999 if (files.size() > 0)
5001 new Thread(new Runnable()
5007 loadDroppedFiles(files, protocols, evt, t);
5011 } catch (Exception e)
5013 e.printStackTrace();
5017 protected void loadDroppedFiles(List<Object> files,
5018 List<DataSourceType> protocols, DropTargetDropEvent evt,
5023 // check to see if any of these files have names matching sequences
5026 SequenceIdMatcher idm = new SequenceIdMatcher(
5027 viewport.getAlignment().getSequencesArray());
5029 * Object[] { String,SequenceI}
5031 ArrayList<Object[]> filesmatched = new ArrayList<>();
5032 ArrayList<Object> filesnotmatched = new ArrayList<>();
5033 for (int i = 0; i < files.size(); i++)
5036 Object fileObj = files.get(i);
5037 String fileName = fileObj.toString();
5039 DataSourceType protocol = (fileObj instanceof File
5040 ? DataSourceType.FILE
5041 : FormatAdapter.checkProtocol(fileName));
5042 if (protocol == DataSourceType.FILE)
5045 if (fileObj instanceof File)
5047 file = (File) fileObj;
5048 Platform.cacheFileData(file);
5052 file = new File(fileName);
5054 pdbfn = file.getName();
5056 else if (protocol == DataSourceType.URL)
5058 URL url = new URL(fileName);
5059 pdbfn = url.getFile();
5061 if (pdbfn.length() > 0)
5063 // attempt to find a match in the alignment
5064 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5065 int l = 0, c = pdbfn.indexOf(".");
5066 while (mtch == null && c != -1)
5071 } while ((c = pdbfn.indexOf(".", l)) > l);
5074 pdbfn = pdbfn.substring(0, l);
5076 mtch = idm.findAllIdMatches(pdbfn);
5083 type = new IdentifyFile().identify(fileObj, protocol);
5084 } catch (Exception ex)
5088 if (type != null && type.isStructureFile())
5090 filesmatched.add(new Object[] { fileObj, protocol, mtch });
5094 // File wasn't named like one of the sequences or wasn't a PDB
5096 filesnotmatched.add(fileObj);
5100 if (filesmatched.size() > 0)
5102 boolean autoAssociate = Cache
5103 .getDefault(Preferences.AUTOASSOCIATE_PDBANDSEQS, false);
5106 String msg = MessageManager.formatMessage(
5107 "label.automatically_associate_structure_files_with_sequences_same_name",
5109 { Integer.valueOf(filesmatched.size()).toString() });
5110 String ttl = MessageManager.getString(
5111 "label.automatically_associate_structure_files_by_name");
5112 int choice = JvOptionPane.showConfirmDialog(this, msg, ttl,
5113 JvOptionPane.YES_NO_OPTION);
5114 autoAssociate = choice == JvOptionPane.YES_OPTION;
5118 for (Object[] fm : filesmatched)
5120 // try and associate
5121 // TODO: may want to set a standard ID naming formalism for
5122 // associating PDB files which have no IDs.
5123 for (SequenceI toassoc : (SequenceI[]) fm[2])
5125 PDBEntry pe = AssociatePdbFileWithSeq.associatePdbWithSeq(
5126 fm[0].toString(), (DataSourceType) fm[1], toassoc,
5130 System.err.println("Associated file : " + (fm[0].toString())
5131 + " with " + toassoc.getDisplayId(true));
5135 // TODO: do we need to update overview ? only if features are
5137 alignPanel.paintAlignment(true, false);
5143 * add declined structures as sequences
5145 for (Object[] o : filesmatched)
5147 filesnotmatched.add(o[0]);
5151 if (filesnotmatched.size() > 0)
5153 if (assocfiles > 0 && (Cache
5154 .getDefault("AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
5155 || JvOptionPane.showConfirmDialog(this,
5156 "<html>" + MessageManager.formatMessage(
5157 "label.ignore_unmatched_dropped_files_info",
5159 { Integer.valueOf(filesnotmatched.size())
5162 MessageManager.getString(
5163 "label.ignore_unmatched_dropped_files"),
5164 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
5168 for (Object fn : filesnotmatched)
5170 loadJalviewDataFile(fn, null, null, null);
5174 } catch (Exception ex)
5176 ex.printStackTrace();
5181 * Attempt to load a "dropped" file or URL string, by testing in turn for
5183 * <li>an Annotation file</li>
5184 * <li>a JNet file</li>
5185 * <li>a features file</li>
5186 * <li>else try to interpret as an alignment file</li>
5190 * either a filename or a URL string.
5191 * @throws InterruptedException
5192 * @throws IOException
5195 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
5196 FileFormatI format, SequenceI assocSeq)
5198 // BH 2018 was String file
5201 if (sourceType == null)
5203 sourceType = FormatAdapter.checkProtocol(file);
5205 // if the file isn't identified, or not positively identified as some
5206 // other filetype (PFAM is default unidentified alignment file type) then
5207 // try to parse as annotation.
5208 boolean isAnnotation = (format == null
5209 || FileFormat.Pfam.equals(format))
5210 ? new AnnotationFile().annotateAlignmentView(viewport,
5216 // first see if its a T-COFFEE score file
5217 TCoffeeScoreFile tcf = null;
5220 tcf = new TCoffeeScoreFile(file, sourceType);
5223 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5227 new TCoffeeColourScheme(viewport.getAlignment()));
5228 isAnnotation = true;
5229 setStatus(MessageManager.getString(
5230 "label.successfully_pasted_tcoffee_scores_to_alignment"));
5234 // some problem - if no warning its probable that the ID matching
5235 // process didn't work
5236 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
5237 tcf.getWarningMessage() == null
5238 ? MessageManager.getString(
5239 "label.check_file_matches_sequence_ids_alignment")
5240 : tcf.getWarningMessage(),
5241 MessageManager.getString(
5242 "label.problem_reading_tcoffee_score_file"),
5243 JvOptionPane.WARNING_MESSAGE);
5250 } catch (Exception x)
5253 "Exception when processing data source as T-COFFEE score file",
5259 // try to see if its a JNet 'concise' style annotation file *before*
5261 // try to parse it as a features file
5264 format = new IdentifyFile().identify(file, sourceType);
5266 if (FileFormat.ScoreMatrix == format)
5268 ScoreMatrixFile sm = new ScoreMatrixFile(
5269 new FileParse(file, sourceType));
5271 // todo: i18n this message
5272 setStatus(MessageManager.formatMessage(
5273 "label.successfully_loaded_matrix",
5274 sm.getMatrixName()));
5276 else if (FileFormat.Jnet.equals(format))
5278 JPredFile predictions = new JPredFile(file, sourceType);
5279 new JnetAnnotationMaker();
5280 JnetAnnotationMaker.add_annotation(predictions,
5281 viewport.getAlignment(), 0, false);
5282 viewport.getAlignment().setupJPredAlignment();
5283 isAnnotation = true;
5285 // else if (IdentifyFile.FeaturesFile.equals(format))
5286 else if (FileFormat.Features.equals(format))
5288 if (parseFeaturesFile(file, sourceType))
5290 SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
5291 if (splitFrame != null)
5293 splitFrame.repaint();
5297 alignPanel.paintAlignment(true, true);
5303 new FileLoader().LoadFile(viewport, file, sourceType, format);
5309 updateForAnnotations();
5311 } catch (Exception ex)
5313 ex.printStackTrace();
5314 } catch (OutOfMemoryError oom)
5319 } catch (Exception x)
5324 + (sourceType != null
5325 ? (sourceType == DataSourceType.PASTE
5327 : "using " + sourceType + " from "
5331 ? "(parsing as '" + format + "' file)"
5333 oom, Desktop.getDesktopPane());
5338 * Do all updates necessary after an annotation file such as jnet. Also called
5339 * from Jalview.loadAppletParams for "annotations", "jnetFile"
5342 public void updateForAnnotations()
5344 alignPanel.adjustAnnotationHeight();
5345 viewport.updateSequenceIdColours();
5346 buildSortByAnnotationScoresMenu();
5347 alignPanel.paintAlignment(true, true);
5351 * Change the display state for the given feature groups -- Added by BH from
5355 * list of group strings
5357 * visible or invisible
5360 public void setFeatureGroupState(String[] groups, boolean state)
5362 jalview.api.FeatureRenderer fr = null;
5363 viewport.setShowSequenceFeatures(true);
5364 if (alignPanel != null
5365 && (fr = alignPanel.getFeatureRenderer()) != null)
5368 fr.setGroupVisibility(Arrays.asList(groups), state);
5369 alignPanel.getSeqPanel().seqCanvas.repaint();
5370 if (alignPanel.overviewPanel != null)
5372 alignPanel.overviewPanel.updateOverviewImage();
5378 * Method invoked by the ChangeListener on the tabbed pane, in other words
5379 * when a different tabbed pane is selected by the user or programmatically.
5383 public void tabSelectionChanged(int index)
5387 alignPanel = alignPanels.get(index);
5388 viewport = alignPanel.av;
5389 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5390 setMenusFromViewport(viewport);
5391 if (featureSettings != null && featureSettings.isOpen()
5392 && featureSettings.fr.getViewport() != viewport)
5394 if (viewport.isShowSequenceFeatures())
5396 // refresh the featureSettings to reflect UI change
5397 showFeatureSettingsUI();
5401 // close feature settings for this view.
5402 featureSettings.close();
5409 * 'focus' any colour slider that is open to the selected viewport
5411 if (viewport.getConservationSelected())
5413 SliderPanel.setConservationSlider(alignPanel,
5414 viewport.getResidueShading(), alignPanel.getViewName());
5418 SliderPanel.hideConservationSlider();
5420 if (viewport.getAbovePIDThreshold())
5422 SliderPanel.setPIDSliderSource(alignPanel,
5423 viewport.getResidueShading(), alignPanel.getViewName());
5427 SliderPanel.hidePIDSlider();
5431 * If there is a frame linked to this one in a SplitPane, switch it to the
5432 * same view tab index. No infinite recursion of calls should happen, since
5433 * tabSelectionChanged() should not get invoked on setting the selected
5434 * index to an unchanged value. Guard against setting an invalid index
5435 * before the new view peer tab has been created.
5437 final AlignViewportI peer = viewport.getCodingComplement();
5440 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
5441 .getAlignPanel().alignFrame;
5442 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5444 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5450 * On right mouse click on view tab, prompt for and set new view name.
5454 public void tabbedPane_mousePressed(MouseEvent e)
5456 if (e.isPopupTrigger())
5458 String msg = MessageManager.getString("label.enter_view_name");
5459 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
5460 String reply = JvOptionPane.showInputDialog(msg, ttl);
5464 viewport.setViewName(reply);
5465 // TODO warn if reply is in getExistingViewNames()?
5466 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5471 public AlignViewport getCurrentView()
5477 * Open the dialog for regex description parsing.
5481 protected void extractScores_actionPerformed(ActionEvent e)
5483 ParseProperties pp = new jalview.analysis.ParseProperties(
5484 viewport.getAlignment());
5485 // TODO: verify regex and introduce GUI dialog for version 2.5
5486 // if (pp.getScoresFromDescription("col", "score column ",
5487 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5489 if (pp.getScoresFromDescription("description column",
5490 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5492 buildSortByAnnotationScoresMenu();
5500 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5505 protected void showDbRefs_actionPerformed(ActionEvent e)
5507 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5513 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5518 protected void showNpFeats_actionPerformed(ActionEvent e)
5520 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5524 * find the viewport amongst the tabs in this alignment frame and close that
5530 public boolean closeView(AlignViewportI av)
5534 this.closeMenuItem_actionPerformed(false);
5537 Component[] comp = tabbedPane.getComponents();
5538 for (int i = 0; comp != null && i < comp.length; i++)
5540 if (comp[i] instanceof AlignmentPanel)
5542 if (((AlignmentPanel) comp[i]).av == av)
5545 closeView((AlignmentPanel) comp[i]);
5553 protected void build_fetchdbmenu(JMenu webService)
5555 // Temporary hack - DBRef Fetcher always top level ws entry.
5556 // TODO We probably want to store a sequence database checklist in
5557 // preferences and have checkboxes.. rather than individual sources selected
5559 final JMenu rfetch = new JMenu(
5560 MessageManager.getString("action.fetch_db_references"));
5561 rfetch.setToolTipText(MessageManager.getString(
5562 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5563 webService.add(rfetch);
5565 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5566 MessageManager.getString("option.trim_retrieved_seqs"));
5567 trimrs.setToolTipText(
5568 MessageManager.getString("label.trim_retrieved_sequences"));
5570 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5571 trimrs.addActionListener(new ActionListener()
5575 public void actionPerformed(ActionEvent e)
5577 trimrs.setSelected(trimrs.isSelected());
5578 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5579 Boolean.valueOf(trimrs.isSelected()).toString());
5583 JMenuItem fetchr = new JMenuItem(
5584 MessageManager.getString("label.standard_databases"));
5585 fetchr.setToolTipText(
5586 MessageManager.getString("label.fetch_embl_uniprot"));
5587 fetchr.addActionListener(new ActionListener()
5591 public void actionPerformed(ActionEvent e)
5593 new Thread(new Runnable()
5599 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5600 .getAlignment().isNucleotide();
5601 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5602 alignPanel.av.getSequenceSelection(),
5603 alignPanel.alignFrame, null,
5604 alignPanel.alignFrame.featureSettings, isNucleotide);
5605 dbRefFetcher.addListener(new FetchFinishedListenerI()
5609 public void finished()
5612 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5613 .getFeatureSettingsModels())
5616 alignPanel.av.mergeFeaturesStyle(srcSettings);
5618 AlignFrame.this.setMenusForViewport();
5621 dbRefFetcher.fetchDBRefs(false);
5629 new Thread(new Runnable()
5636 // final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5637 // .getSequenceFetcherSingleton();
5638 javax.swing.SwingUtilities.invokeLater(new Runnable()
5644 jalview.ws.SequenceFetcher sf = jalview.ws.SequenceFetcher
5646 String[] dbclasses = sf.getNonAlignmentSources();
5647 List<DbSourceProxy> otherdb;
5648 JMenu dfetch = new JMenu();
5649 JMenu ifetch = new JMenu();
5650 JMenuItem fetchr = null;
5651 int comp = 0, icomp = 0, mcomp = 15;
5652 String mname = null;
5654 for (String dbclass : dbclasses)
5656 otherdb = sf.getSourceProxy(dbclass);
5657 // add a single entry for this class, or submenu allowing 'fetch
5659 if (otherdb == null || otherdb.size() < 1)
5665 mname = "From " + dbclass;
5667 if (otherdb.size() == 1)
5669 DbSourceProxy src = otherdb.get(0);
5670 DbSourceProxy[] dassource = new DbSourceProxy[] { src };
5671 fetchr = new JMenuItem(src.getDbSource());
5672 fetchr.addActionListener(new ActionListener()
5676 public void actionPerformed(ActionEvent e)
5678 new Thread(new Runnable()
5684 boolean isNucleotide = alignPanel.alignFrame
5685 .getViewport().getAlignment()
5687 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5688 alignPanel.av.getSequenceSelection(),
5689 alignPanel.alignFrame, dassource,
5690 alignPanel.alignFrame.featureSettings,
5693 .addListener(new FetchFinishedListenerI()
5697 public void finished()
5699 FeatureSettingsModelI srcSettings = dassource[0]
5700 .getFeatureColourScheme();
5701 alignPanel.av.mergeFeaturesStyle(
5703 AlignFrame.this.setMenusForViewport();
5706 dbRefFetcher.fetchDBRefs(false);
5712 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5713 MessageManager.formatMessage(
5714 "label.fetch_retrieve_from", new Object[]
5715 { src.getDbName() })));
5721 final DbSourceProxy[] dassource = otherdb
5722 .toArray(new DbSourceProxy[0]);
5724 DbSourceProxy src = otherdb.get(0);
5725 fetchr = new JMenuItem(MessageManager
5726 .formatMessage("label.fetch_all_param", new Object[]
5727 { src.getDbSource() }));
5728 fetchr.addActionListener(new ActionListener()
5732 public void actionPerformed(ActionEvent e)
5734 new Thread(new Runnable()
5740 boolean isNucleotide = alignPanel.alignFrame
5741 .getViewport().getAlignment()
5743 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5744 alignPanel.av.getSequenceSelection(),
5745 alignPanel.alignFrame, dassource,
5746 alignPanel.alignFrame.featureSettings,
5749 .addListener(new FetchFinishedListenerI()
5753 public void finished()
5755 AlignFrame.this.setMenusForViewport();
5758 dbRefFetcher.fetchDBRefs(false);
5764 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5765 MessageManager.formatMessage(
5766 "label.fetch_retrieve_from_all_sources",
5768 { Integer.valueOf(otherdb.size())
5770 src.getDbSource(), src.getDbName() })));
5773 // and then build the rest of the individual menus
5774 ifetch = new JMenu(MessageManager.formatMessage(
5775 "label.source_from_db_source", new Object[]
5776 { src.getDbSource() }));
5778 String imname = null;
5780 for (DbSourceProxy sproxy : otherdb)
5782 String dbname = sproxy.getDbName();
5783 String sname = dbname.length() > 5
5784 ? dbname.substring(0, 5) + "..."
5786 String msname = dbname.length() > 10
5787 ? dbname.substring(0, 10) + "..."
5791 imname = MessageManager
5792 .formatMessage("label.from_msname", new Object[]
5795 fetchr = new JMenuItem(msname);
5796 final DbSourceProxy[] dassrc = { sproxy };
5797 fetchr.addActionListener(new ActionListener()
5801 public void actionPerformed(ActionEvent e)
5803 new Thread(new Runnable()
5809 boolean isNucleotide = alignPanel.alignFrame
5810 .getViewport().getAlignment()
5812 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5813 alignPanel.av.getSequenceSelection(),
5814 alignPanel.alignFrame, dassrc,
5815 alignPanel.alignFrame.featureSettings,
5818 .addListener(new FetchFinishedListenerI()
5822 public void finished()
5824 AlignFrame.this.setMenusForViewport();
5827 dbRefFetcher.fetchDBRefs(false);
5833 fetchr.setToolTipText(
5834 "<html>" + MessageManager.formatMessage(
5835 "label.fetch_retrieve_from", new Object[]
5839 if (++icomp >= mcomp || i == (otherdb.size()))
5841 ifetch.setText(MessageManager.formatMessage(
5842 "label.source_to_target", imname, sname));
5844 ifetch = new JMenu();
5852 if (comp >= mcomp || dbi >= (dbclasses.length))
5854 dfetch.setText(MessageManager.formatMessage(
5855 "label.source_to_target", mname, dbclass));
5857 dfetch = new JMenu();
5870 * Left justify the whole alignment.
5874 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5876 viewport.getAlignment().justify(false);
5877 viewport.notifyAlignment();
5881 * Right justify the whole alignment.
5885 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5887 viewport.getAlignment().justify(true);
5888 viewport.notifyAlignment();
5892 public void setShowSeqFeatures(boolean b)
5894 showSeqFeatures.setSelected(b);
5895 viewport.setShowSequenceFeatures(b);
5902 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5903 * awt.event.ActionEvent)
5907 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5909 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5910 alignPanel.paintAlignment(false, false);
5917 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5922 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5924 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5925 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5933 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5934 * .event.ActionEvent)
5938 protected void showGroupConservation_actionPerformed(ActionEvent e)
5940 viewport.setShowGroupConservation(showGroupConservation.getState());
5941 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5948 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5949 * .event.ActionEvent)
5953 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5955 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5956 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5963 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5964 * .event.ActionEvent)
5968 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5970 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5971 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5975 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5977 showSequenceLogo.setState(true);
5978 viewport.setShowSequenceLogo(true);
5979 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5980 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5984 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5986 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5993 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5994 * .event.ActionEvent)
5998 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
6000 if (avc.makeGroupsFromSelection())
6002 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
6003 alignPanel.updateAnnotation();
6004 alignPanel.paintAlignment(true,
6005 viewport.needToUpdateStructureViews());
6009 public void clearAlignmentSeqRep()
6011 // TODO refactor alignmentseqrep to controller
6012 if (viewport.getAlignment().hasSeqrep())
6014 viewport.getAlignment().setSeqrep(null);
6015 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
6016 alignPanel.updateAnnotation();
6017 alignPanel.paintAlignment(true, true);
6022 protected void createGroup_actionPerformed(ActionEvent e)
6024 if (avc.createGroup())
6026 if (applyAutoAnnotationSettings.isSelected())
6028 alignPanel.updateAnnotation(true, false);
6030 alignPanel.alignmentChanged();
6035 protected void unGroup_actionPerformed(ActionEvent e)
6039 alignPanel.alignmentChanged();
6044 * make the given alignmentPanel the currently selected tab
6046 * @param alignmentPanel
6049 public void setDisplayedView(AlignmentPanel alignmentPanel)
6051 if (!viewport.getSequenceSetId()
6052 .equals(alignmentPanel.av.getSequenceSetId()))
6054 throw new Error(MessageManager.getString(
6055 "error.implementation_error_cannot_show_view_alignment_frame"));
6057 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
6058 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
6060 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
6065 * Action on selection of menu options to Show or Hide annotations.
6068 * @param forSequences
6069 * update sequence-related annotations
6070 * @param forAlignment
6071 * update non-sequence-related annotations
6075 protected void setAnnotationsVisibility(boolean visible,
6076 boolean forSequences, boolean forAlignment)
6078 AlignmentAnnotation[] anns = alignPanel.getAlignment()
6079 .getAlignmentAnnotation();
6084 for (AlignmentAnnotation aa : anns)
6087 * don't display non-positional annotations on an alignment
6089 if (aa.annotations == null)
6093 boolean apply = (aa.sequenceRef == null && forAlignment)
6094 || (aa.sequenceRef != null && forSequences);
6097 aa.visible = visible;
6100 alignPanel.validateAnnotationDimensions(true);
6101 alignPanel.alignmentChanged();
6105 * Store selected annotation sort order for the view and repaint.
6109 protected void sortAnnotations_actionPerformed()
6111 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
6113 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
6114 alignPanel.paintAlignment(false, false);
6119 * @return alignment panels in this alignment frame
6122 public List<? extends AlignmentViewPanel> getAlignPanels()
6124 // alignPanels is never null
6125 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
6130 * Open a new alignment window, with the cDNA associated with this (protein)
6131 * alignment, aligned as is the protein.
6134 protected void viewAsCdna_actionPerformed()
6136 // TODO no longer a menu action - refactor as required
6137 final AlignmentI alignment = getViewport().getAlignment();
6138 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
6139 if (mappings == null)
6143 List<SequenceI> cdnaSeqs = new ArrayList<>();
6144 for (SequenceI aaSeq : alignment.getSequences())
6146 for (AlignedCodonFrame acf : mappings)
6148 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
6152 * There is a cDNA mapping for this protein sequence - add to new
6153 * alignment. It will share the same dataset sequence as other mapped
6154 * cDNA (no new mappings need to be created).
6156 final Sequence newSeq = new Sequence(dnaSeq);
6157 newSeq.setDatasetSequence(dnaSeq);
6158 cdnaSeqs.add(newSeq);
6162 if (cdnaSeqs.size() == 0)
6164 // show a warning dialog no mapped cDNA
6167 AlignmentI cdna = new Alignment(
6168 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
6169 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
6170 AlignFrame.DEFAULT_HEIGHT);
6171 cdna.alignAs(alignment);
6172 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
6174 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
6175 AlignFrame.DEFAULT_HEIGHT);
6179 * Set visibility of dna/protein complement view (available when shown in a
6186 protected void showComplement_actionPerformed(boolean show)
6188 SplitContainerI sf = getSplitViewContainer();
6191 sf.setComplementVisible(this, show);
6196 * Generate the reverse (optionally complemented) of the selected sequences,
6197 * and add them to the alignment
6201 protected void showReverse_actionPerformed(boolean complement)
6203 AlignmentI al = null;
6206 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
6207 al = dna.reverseCdna(complement);
6208 viewport.addAlignment(al, "");
6209 addHistoryItem(new EditCommand(
6210 MessageManager.getString("label.add_sequences"), Action.PASTE,
6211 al.getSequencesArray(), 0, al.getWidth(),
6212 viewport.getAlignment()));
6213 } catch (Exception ex)
6215 System.err.println(ex.getMessage());
6221 * Try to run a script in the Groovy console, having first ensured that this
6222 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
6223 * be targeted at this alignment.
6227 protected void runGroovy_actionPerformed()
6229 Jalview.setCurrentAlignFrame(this);
6230 groovy.ui.Console console = Desktop.getGroovyConsole();
6231 if (console != null)
6235 console.runScript();
6236 } catch (Exception ex)
6238 System.err.println((ex.toString()));
6239 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
6240 MessageManager.getString("label.couldnt_run_groovy_script"),
6241 MessageManager.getString("label.groovy_support_failed"),
6242 JvOptionPane.ERROR_MESSAGE);
6247 System.err.println("Can't run Groovy script as console not found");
6252 * Hides columns containing (or not containing) a specified feature, provided
6253 * that would not leave all columns hidden
6255 * @param featureType
6256 * @param columnsContaining
6260 public boolean hideFeatureColumns(String featureType,
6261 boolean columnsContaining)
6263 boolean notForHiding = avc.markColumnsContainingFeatures(
6264 columnsContaining, false, false, featureType);
6267 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
6268 false, featureType))
6270 getViewport().hideSelectedColumns();
6278 protected void selectHighlightedColumns_actionPerformed(
6279 ActionEvent actionEvent)
6281 // include key modifier check in case user selects from menu
6282 avc.markHighlightedColumns(
6283 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
6284 (actionEvent.getModifiers() & (ActionEvent.META_MASK
6285 | ActionEvent.CTRL_MASK)) != 0);
6289 * Rebuilds the Colour menu, including any user-defined colours which have
6290 * been loaded either on startup or during the session
6293 public void buildColourMenu()
6295 colourMenu.removeAll();
6297 colourMenu.add(applyToAllGroups);
6298 colourMenu.add(textColour);
6299 colourMenu.addSeparator();
6301 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
6302 viewport.getAlignment(), false);
6304 colourMenu.add(annotationColour);
6305 bg.add(annotationColour);
6306 colourMenu.addSeparator();
6307 colourMenu.add(conservationMenuItem);
6308 colourMenu.add(modifyConservation);
6309 colourMenu.add(abovePIDThreshold);
6310 colourMenu.add(modifyPID);
6312 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
6313 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
6317 * Open a dialog (if not already open) that allows the user to select and
6318 * calculate PCA or Tree analysis
6321 protected void openTreePcaDialog()
6323 if (alignPanel.getCalculationDialog() == null)
6325 new CalculationChooser(AlignFrame.this);
6330 * Sets the status of the HMMER menu
6332 public void updateHMMERStatus()
6334 hmmerMenu.setEnabled(HmmerCommand.isHmmerAvailable());
6338 protected void loadVcf_actionPerformed()
6340 JalviewFileChooser chooser = new JalviewFileChooser(
6341 Cache.getProperty("LAST_DIRECTORY"));
6342 chooser.setFileView(new JalviewFileView());
6343 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
6344 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
6345 final AlignFrame us = this;
6346 chooser.setResponseHandler(0, new Runnable()
6352 String choice = chooser.getSelectedFile().getPath();
6353 Cache.setProperty("LAST_DIRECTORY", choice);
6354 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
6355 new VCFLoader(choice).loadVCF(seqs, us);
6358 chooser.showOpenDialog(null);
6362 private Rectangle lastFeatureSettingsBounds = null;
6365 public void setFeatureSettingsGeometry(Rectangle bounds)
6367 lastFeatureSettingsBounds = bounds;
6371 public Rectangle getFeatureSettingsGeometry()
6373 return lastFeatureSettingsBounds;
6376 public void scrollTo(int row, int column)
6378 alignPanel.getSeqPanel().scrollTo(row, column);
6381 public void scrollToRow(int row)
6383 alignPanel.getSeqPanel().scrollToRow(row);
6386 public void scrollToColumn(int column)
6388 alignPanel.getSeqPanel().scrollToColumn(column);
6392 * BH 2019 from JalviewLite
6394 * get sequence feature groups that are hidden or shown
6401 public String[] getFeatureGroupsOfState(boolean visible)
6403 jalview.api.FeatureRenderer fr = null;
6404 if (alignPanel != null
6405 && (fr = alignPanel.getFeatureRenderer()) != null)
6407 List<String> gps = fr.getGroups(visible);
6408 String[] _gps = gps.toArray(new String[gps.size()]);
6416 * @return list of feature groups on the view
6419 public String[] getFeatureGroups()
6421 jalview.api.FeatureRenderer fr = null;
6422 if (alignPanel != null
6423 && (fr = alignPanel.getFeatureRenderer()) != null)
6425 List<String> gps = fr.getFeatureGroups();
6426 String[] _gps = gps.toArray(new String[gps.size()]);
6432 public void select(SequenceGroup sel, ColumnSelection csel,
6433 HiddenColumns hidden)
6435 alignPanel.getSeqPanel().selection(sel, csel, hidden, null);
6443 static class PrintThread extends Thread
6447 public PrintThread(AlignmentPanel ap)
6452 static PageFormat pf;
6457 PrinterJob printJob = PrinterJob.getPrinterJob();
6461 printJob.setPrintable(ap, pf);
6465 printJob.setPrintable(ap);
6468 if (printJob.printDialog())
6473 } catch (Exception PrintException)
6475 PrintException.printStackTrace();