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.client.api.WebServiceDiscovererI;
119 import jalview.ws2.client.slivka.SlivkaWSDiscoverer;
120 import jalview.ws2.gui.WebServicesMenuManager;
122 import java.io.IOException;
123 import java.util.HashSet;
124 import java.util.Set;
126 import javax.swing.JFileChooser;
127 import javax.swing.JOptionPane;
129 import java.awt.BorderLayout;
130 import java.awt.Color;
131 import java.awt.Component;
132 import java.awt.Dimension;
133 import java.awt.Rectangle;
134 import java.awt.Toolkit;
135 import java.awt.datatransfer.Clipboard;
136 import java.awt.datatransfer.DataFlavor;
137 import java.awt.datatransfer.StringSelection;
138 import java.awt.datatransfer.Transferable;
139 import java.awt.dnd.DnDConstants;
140 import java.awt.dnd.DropTargetDragEvent;
141 import java.awt.dnd.DropTargetDropEvent;
142 import java.awt.dnd.DropTargetEvent;
143 import java.awt.dnd.DropTargetListener;
144 import java.awt.event.ActionEvent;
145 import java.awt.event.ActionListener;
146 import java.awt.event.FocusAdapter;
147 import java.awt.event.FocusEvent;
148 import java.awt.event.ItemEvent;
149 import java.awt.event.ItemListener;
150 import java.awt.event.KeyAdapter;
151 import java.awt.event.KeyEvent;
152 import java.awt.event.MouseEvent;
153 import java.awt.print.PageFormat;
154 import java.awt.print.PrinterJob;
155 import java.beans.PropertyChangeEvent;
156 import java.beans.PropertyChangeListener;
158 import java.io.FileWriter;
159 import java.io.PrintWriter;
161 import java.util.ArrayList;
162 import java.util.Arrays;
163 import java.util.Collection;
164 import java.util.Deque;
165 import java.util.Enumeration;
166 import java.util.Hashtable;
167 import java.util.List;
168 import java.util.Vector;
170 import javax.swing.ButtonGroup;
171 import javax.swing.JCheckBoxMenuItem;
172 import javax.swing.JComponent;
173 import javax.swing.JEditorPane;
174 import javax.swing.JInternalFrame;
175 import javax.swing.JLabel;
176 import javax.swing.JLayeredPane;
177 import javax.swing.JMenu;
178 import javax.swing.JMenuItem;
179 import javax.swing.JPanel;
180 import javax.swing.JScrollPane;
181 import javax.swing.SwingUtilities;
182 import javax.swing.event.InternalFrameAdapter;
183 import javax.swing.event.InternalFrameEvent;
185 import ext.vamsas.ServiceHandle;
191 * @version $Revision$
193 @SuppressWarnings("serial")
194 public class AlignFrame extends GAlignFrame
195 implements DropTargetListener, IProgressIndicator,
196 AlignViewControllerGuiI, ColourChangeListener, ServiceChangeListener
199 public static int frameCount;
201 public static final int DEFAULT_WIDTH = 700;
203 public static final int DEFAULT_HEIGHT = 500;
206 * The currently displayed panel (selected tabbed view if more than one)
208 public AlignmentPanel alignPanel;
210 AlignViewport viewport;
212 public AlignViewControllerI avc;
214 List<AlignmentPanel> alignPanels = new ArrayList<>();
217 * Last format used to load or save alignments in this window
219 FileFormatI currentFileFormat = null;
222 * Current filename for this alignment
224 String fileName = null;
227 * TODO: remove reference to 'FileObject' in AlignFrame - not correct mapping
233 private DataSourceType protocol ;
236 * Creates a new AlignFrame object with specific width and height.
242 public AlignFrame(AlignmentI al, int width, int height)
244 this(al, null, width, height);
248 * Creates a new AlignFrame object with specific width, height and
254 * @param sequenceSetId
256 public AlignFrame(AlignmentI al, int width, int height,
257 String sequenceSetId)
259 this(al, null, width, height, sequenceSetId);
263 * Creates a new AlignFrame object with specific width, height and
269 * @param sequenceSetId
272 public AlignFrame(AlignmentI al, int width, int height,
273 String sequenceSetId, String viewId)
275 this(al, null, width, height, sequenceSetId, viewId);
279 * new alignment window with hidden columns
283 * @param hiddenColumns
284 * ColumnSelection or null
286 * Width of alignment frame
290 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
293 this(al, hiddenColumns, width, height, null);
297 * Create alignment frame for al with hiddenColumns, a specific width and
298 * height, and specific sequenceId
301 * @param hiddenColumns
304 * @param sequenceSetId
307 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
308 int height, String sequenceSetId)
310 this(al, hiddenColumns, width, height, sequenceSetId, null);
314 * Create alignment frame for al with hiddenColumns, a specific width and
315 * height, and specific sequenceId
318 * @param hiddenColumns
321 * @param sequenceSetId
326 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
327 int height, String sequenceSetId, String viewId)
332 setSize(width, height);
334 if (al.getDataset() == null)
339 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
341 // JalviewJS needs to distinguish a new panel from an old one in init()
342 // alignPanel = new AlignmentPanel(this, viewport);
343 // addAlignmentPanel(alignPanel, true);
347 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
348 HiddenColumns hiddenColumns, int width, int height)
350 setSize(width, height);
352 if (al.getDataset() == null)
357 viewport = new AlignViewport(al, hiddenColumns);
359 if (hiddenSeqs != null && hiddenSeqs.length > 0)
361 viewport.hideSequence(hiddenSeqs);
363 // alignPanel = new AlignmentPanel(this, viewport);
364 // addAlignmentPanel(alignPanel, true);
369 * Make a new AlignFrame from existing alignmentPanels
376 public AlignFrame(AlignmentPanel ap)
380 // addAlignmentPanel(ap, false);
385 * initalise the alignframe from the underlying viewport data and the
391 boolean newPanel = (alignPanel == null);
392 viewport.setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
397 // need to set this up front if NOANNOTATION is
398 // used in conjunction with SHOWOVERVIEW.
400 // I have not determined if this is appropriate for
401 // Jalview/Java, as it means we are setting this flag
402 // for all subsequent AlignFrames. For now, at least,
403 // I am setting it to be JalviewJS-only.
405 boolean showAnnotation = Jalview.getInstance().getShowAnnotation();
406 viewport.setShowAnnotation(showAnnotation);
408 alignPanel = new AlignmentPanel(this, viewport);
410 addAlignmentPanel(alignPanel, newPanel);
412 // setBackground(Color.white); // BH 2019
414 if (!Jalview.isHeadlessMode())
416 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
418 statusPanel.setVisible(Jalview.getInstance().getShowStatus());
419 alignFrameMenuBar.setVisible(Jalview.getInstance().getAllowMenuBar());
422 avc = new jalview.controller.AlignViewController(this, viewport,
424 if (viewport.getAlignmentConservationAnnotation() == null)
426 // BLOSUM62Colour.setEnabled(false);
427 conservationMenuItem.setEnabled(false);
428 modifyConservation.setEnabled(false);
429 // PIDColour.setEnabled(false);
430 // abovePIDThreshold.setEnabled(false);
431 // modifyPID.setEnabled(false);
434 String sortby = jalview.bin.Cache.getDefault(Preferences.SORT_ALIGNMENT,
437 if (sortby.equals("Id"))
439 sortIDMenuItem_actionPerformed(null);
441 else if (sortby.equals("Pairwise Identity"))
443 sortPairwiseMenuItem_actionPerformed(null);
448 // this.alignPanel.av
449 // .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
451 setMenusFromViewport(viewport);
452 buildSortByAnnotationScoresMenu();
453 calculateTree.addActionListener(new ActionListener()
457 public void actionPerformed(ActionEvent e)
464 if (Desktop.getDesktopPane() != null)
466 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
467 addServiceListeners();
468 if (!Platform.isJS())
474 if (viewport.getWrapAlignment())
476 wrapMenuItem_actionPerformed(null);
479 if (jalview.bin.Cache.getDefault(Preferences.SHOW_OVERVIEW, false))
481 this.overviewMenuItem_actionPerformed(null);
486 final List<AlignmentPanel> selviews = new ArrayList<>();
487 final List<AlignmentPanel> origview = new ArrayList<>();
488 final String menuLabel = MessageManager
489 .getString("label.copy_format_from");
490 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
491 new ViewSetProvider()
495 public AlignmentPanel[] getAllAlignmentPanels()
498 origview.add(alignPanel);
499 // make an array of all alignment panels except for this one
500 List<AlignmentPanel> aps = new ArrayList<>(
501 Arrays.asList(Desktop.getAlignmentPanels(null)));
502 aps.remove(AlignFrame.this.alignPanel);
503 return aps.toArray(new AlignmentPanel[aps.size()]);
505 }, selviews, new ItemListener()
509 public void itemStateChanged(ItemEvent e)
511 if (origview.size() > 0)
513 final AlignmentPanel ap = origview.get(0);
516 * Copy the ViewStyle of the selected panel to 'this one'.
517 * Don't change value of 'scaleProteinAsCdna' unless copying
520 ViewStyleI vs = selviews.get(0).getAlignViewport()
522 boolean fromSplitFrame = selviews.get(0)
523 .getAlignViewport().getCodingComplement() != null;
526 vs.setScaleProteinAsCdna(ap.getAlignViewport()
527 .getViewStyle().isScaleProteinAsCdna());
529 ap.getAlignViewport().setViewStyle(vs);
532 * Also rescale ViewStyle of SplitFrame complement if there is
533 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
534 * the whole ViewStyle (allow cDNA protein to have different
537 AlignViewportI complement = ap.getAlignViewport()
538 .getCodingComplement();
539 if (complement != null && vs.isScaleProteinAsCdna())
541 AlignFrame af = Desktop.getAlignFrameFor(complement);
542 ((SplitFrame) af.getSplitViewContainer())
544 af.setMenusForViewport();
548 ap.setSelected(true);
549 ap.alignFrame.setMenusForViewport();
554 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
555 .indexOf("devel") > -1
556 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
557 .indexOf("test") > -1)
559 formatMenu.add(vsel);
561 addFocusListener(new FocusAdapter()
565 public void focusGained(FocusEvent e)
567 Jalview.setCurrentAlignFrame(AlignFrame.this);
574 * Change the filename and format for the alignment, and enable the 'reload'
575 * button functionality.
584 public void setFileName(String file, FileFormatI format)
587 setFileFormat(format);
588 reload.setEnabled(true);
594 * @param file from SwingJS; may contain bytes -- for reload
595 * @param protocol from SwingJS; may be RELATIVE_URL
598 public void setFile(String fileName, File file, DataSourceType protocol, FileFormatI format)
600 this.fileName = fileName;
601 this.fileObject = file;
602 this.protocol = protocol;
603 setFileFormat(format);
604 reload.setEnabled(true);
608 * JavaScript will have this, maybe others. More dependable than a file name
609 * and maintains a reference to the actual bytes loaded.
614 public void setFileObject(File file)
616 this.fileObject = file;
620 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
624 void addKeyListener()
626 addKeyListener(new KeyAdapter()
630 public void keyPressed(KeyEvent evt)
632 if (viewport.cursorMode
633 && ((evt.getKeyCode() >= KeyEvent.VK_0
634 && evt.getKeyCode() <= KeyEvent.VK_9)
635 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
636 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
637 && Character.isDigit(evt.getKeyChar()))
639 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
642 switch (evt.getKeyCode())
645 case KeyEvent.VK_ESCAPE: // escape key
646 // alignPanel.deselectAllSequences();
647 alignPanel.deselectAllSequences();
651 case KeyEvent.VK_DOWN:
652 if (evt.isAltDown() || !viewport.cursorMode)
654 moveSelectedSequences(false);
656 if (viewport.cursorMode)
658 alignPanel.getSeqPanel().moveCursor(0, 1);
663 if (evt.isAltDown() || !viewport.cursorMode)
665 moveSelectedSequences(true);
667 if (viewport.cursorMode)
669 alignPanel.getSeqPanel().moveCursor(0, -1);
674 case KeyEvent.VK_LEFT:
675 if (evt.isAltDown() || !viewport.cursorMode)
677 slideSequences(false,
678 alignPanel.getSeqPanel().getKeyboardNo1());
682 alignPanel.getSeqPanel().moveCursor(-1, 0);
687 case KeyEvent.VK_RIGHT:
688 if (evt.isAltDown() || !viewport.cursorMode)
690 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
694 alignPanel.getSeqPanel().moveCursor(1, 0);
698 case KeyEvent.VK_SPACE:
699 if (viewport.cursorMode)
701 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
702 || evt.isShiftDown() || evt.isAltDown());
706 // case KeyEvent.VK_A:
707 // if (viewport.cursorMode)
709 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
710 // //System.out.println("A");
714 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
715 * System.out.println("closing bracket"); } break;
717 case KeyEvent.VK_DELETE:
718 case KeyEvent.VK_BACK_SPACE:
719 if (!viewport.cursorMode)
721 cut_actionPerformed();
725 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
726 || evt.isShiftDown() || evt.isAltDown());
732 if (viewport.cursorMode)
734 alignPanel.getSeqPanel().setCursorRow();
738 if (viewport.cursorMode && !evt.isControlDown())
740 alignPanel.getSeqPanel().setCursorColumn();
744 if (viewport.cursorMode)
746 alignPanel.getSeqPanel().setCursorPosition();
750 case KeyEvent.VK_ENTER:
751 case KeyEvent.VK_COMMA:
752 if (viewport.cursorMode)
754 alignPanel.getSeqPanel().setCursorRowAndColumn();
759 if (viewport.cursorMode)
761 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
765 if (viewport.cursorMode)
767 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
772 viewport.cursorMode = !viewport.cursorMode;
773 setStatus(MessageManager
774 .formatMessage("label.keyboard_editing_mode", new String[]
775 { (viewport.cursorMode ? "on" : "off") }));
776 if (viewport.cursorMode)
778 ViewportRanges ranges = viewport.getRanges();
779 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
781 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
784 alignPanel.getSeqPanel().seqCanvas.repaint();
790 Help.showHelpWindow();
791 } catch (Exception ex)
793 ex.printStackTrace();
798 boolean toggleSeqs = !evt.isControlDown();
799 boolean toggleCols = !evt.isShiftDown();
800 toggleHiddenRegions(toggleSeqs, toggleCols);
805 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
806 boolean modifyExisting = true; // always modify, don't clear
807 // evt.isShiftDown();
808 boolean invertHighlighted = evt.isAltDown();
809 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
813 case KeyEvent.VK_PAGE_UP:
814 viewport.getRanges().pageUp();
816 case KeyEvent.VK_PAGE_DOWN:
817 viewport.getRanges().pageDown();
823 public void keyReleased(KeyEvent evt)
825 switch (evt.getKeyCode())
827 case KeyEvent.VK_LEFT:
828 if (evt.isAltDown() || !viewport.cursorMode)
830 viewport.notifyAlignment();
834 case KeyEvent.VK_RIGHT:
835 if (evt.isAltDown() || !viewport.cursorMode)
837 viewport.notifyAlignment();
845 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
847 ap.alignFrame = this;
848 avc = new jalview.controller.AlignViewController(this, viewport,
853 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
855 int aSize = alignPanels.size();
857 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
859 if (aSize == 1 && ap.av.getViewName() == null)
861 this.getContentPane().add(ap, BorderLayout.CENTER);
867 setInitialTabVisible();
870 expandViews.setEnabled(true);
871 gatherViews.setEnabled(true);
872 tabbedPane.addTab(ap.av.getViewName(), ap);
874 ap.setVisible(false);
879 if (ap.av.isPadGaps())
881 ap.av.getAlignment().padGaps();
883 if (Jalview.getInstance().getStartCalculations())
885 ap.av.updateConservation(ap);
886 ap.av.updateConsensus(ap);
887 ap.av.updateStrucConsensus(ap);
888 ap.av.initInformationWorker(ap);
893 public void setInitialTabVisible()
895 expandViews.setEnabled(true);
896 gatherViews.setEnabled(true);
897 tabbedPane.setVisible(true);
898 AlignmentPanel first = alignPanels.get(0);
899 tabbedPane.addTab(first.av.getViewName(), first);
900 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
903 public AlignViewport getViewport()
909 public void servicesChanged(WSDiscovererI discoverer,
910 Collection<? extends ServiceWithParameters> services)
912 buildWebServicesMenu();
915 private WebServiceDiscovererI.ServicesChangeListener slivkaServiceChangeListener =
916 (discoverer, services) -> {
917 // run when slivka services change
918 var menu = AlignFrame.this.slivkaMenu;
919 menu.setServices(discoverer);
920 menu.setInProgress(discoverer.isRunning());
921 menu.setNoServices(services.isEmpty() && discoverer.isDone());
924 /* Set up intrinsic listeners for dynamically generated GUI bits. */
925 private void addServiceListeners()
927 if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
929 WebServiceDiscovererI discoverer = SlivkaWSDiscoverer.getInstance();
930 discoverer.addServicesChangeListener(slivkaServiceChangeListener);
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().removeServicesChangeListener(slivkaServiceChangeListener);
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();
4649 private WebServicesMenuManager slivkaMenu = new WebServicesMenuManager("slivka", this);
4652 * Schedule the web services menu rebuild to the event dispatch thread.
4654 public void buildWebServicesMenu()
4656 SwingUtilities.invokeLater(() -> {
4657 Cache.log.info("Rebuiling WS menu");
4658 webService.removeAll();
4659 if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
4661 Cache.log.info("Building web service menu for slivka");
4662 SlivkaWSDiscoverer discoverer = SlivkaWSDiscoverer.getInstance();
4663 slivkaMenu.setServices(discoverer);
4664 slivkaMenu.setInProgress(discoverer.isRunning());
4665 slivkaMenu.setNoServices(discoverer.isDone() && !discoverer.hasServices());
4666 webService.add(slivkaMenu.getMenu());
4668 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4670 WSDiscovererI jws2servs = Jws2Discoverer.getInstance();
4671 JMenu submenu = new JMenu("JABAWS");
4672 buildLegacyWebServicesMenu(submenu);
4673 buildWebServicesMenu(jws2servs, submenu);
4674 webService.add(submenu);
4676 build_urlServiceMenu(webService);
4677 build_fetchdbmenu(webService);
4681 private void buildLegacyWebServicesMenu(JMenu menu)
4683 JMenu secstrmenu = new JMenu("Secondary Structure Prediction");
4684 if (Discoverer.getServices() != null && Discoverer.getServices().size() > 0)
4686 var secstrpred = Discoverer.getServices().get("SecStrPred");
4687 if (secstrpred != null)
4689 for (ext.vamsas.ServiceHandle sh : secstrpred)
4691 var menuProvider = Discoverer.getServiceClient(sh);
4692 menuProvider.attachWSMenuEntry(secstrmenu, this);
4696 menu.add(secstrmenu);
4700 * Constructs the web services menu for the given discoverer under the
4701 * specified menu. This method must be called on the EDT
4704 * the discoverer used to build the menu
4706 * parent component which the elements will be attached to
4708 private void buildWebServicesMenu(WSDiscovererI discoverer, JMenu menu)
4710 if (discoverer.hasServices())
4712 PreferredServiceRegistry.getRegistry().populateWSMenuEntry(
4713 discoverer.getServices(), sv -> buildWebServicesMenu(), menu,
4716 if (discoverer.isRunning())
4718 JMenuItem item = new JMenuItem("Service discovery in progress.");
4719 item.setEnabled(false);
4722 else if (!discoverer.hasServices())
4724 JMenuItem item = new JMenuItem("No services available.");
4725 item.setEnabled(false);
4731 * construct any groupURL type service menu entries.
4736 protected void build_urlServiceMenu(JMenu webService)
4738 // TODO: remove this code when 2.7 is released
4739 // DEBUG - alignmentView
4741 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4742 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4744 * public void actionPerformed(ActionEvent e) {
4745 * jalview.datamodel.AlignmentView
4746 * .testSelectionViews(af.viewport.getAlignment(),
4747 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4749 * }); webService.add(testAlView);
4751 // TODO: refactor to RestClient discoverer and merge menu entries for
4752 // rest-style services with other types of analysis/calculation service
4753 // SHmmr test client - still being implemented.
4754 // DEBUG - alignmentView
4756 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4759 client.attachWSMenuEntry(
4760 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4766 * Searches the alignment sequences for xRefs and builds the Show
4767 * Cross-References menu (formerly called Show Products), with database
4768 * sources for which cross-references are found (protein sources for a
4769 * nucleotide alignment and vice versa)
4771 * @return true if Show Cross-references menu should be enabled
4774 public boolean canShowProducts()
4776 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4777 AlignmentI dataset = viewport.getAlignment().getDataset();
4779 showProducts.removeAll();
4780 final boolean dna = viewport.getAlignment().isNucleotide();
4782 if (seqs == null || seqs.length == 0)
4784 // nothing to see here.
4788 boolean showp = false;
4791 List<String> ptypes = new CrossRef(seqs, dataset)
4792 .findXrefSourcesForSequences(dna);
4794 for (final String source : ptypes)
4797 final AlignFrame af = this;
4798 JMenuItem xtype = new JMenuItem(source);
4799 xtype.addActionListener(new ActionListener()
4803 public void actionPerformed(ActionEvent e)
4805 showProductsFor(af.viewport.getSequenceSelection(), dna,
4809 showProducts.add(xtype);
4811 showProducts.setVisible(showp);
4812 showProducts.setEnabled(showp);
4813 } catch (Exception e)
4816 "canShowProducts threw an exception - please report to help@jalview.org",
4824 * Finds and displays cross-references for the selected sequences (protein
4825 * products for nucleotide sequences, dna coding sequences for peptides).
4828 * the sequences to show cross-references for
4830 * true if from a nucleotide alignment (so showing proteins)
4832 * the database to show cross-references for
4835 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4836 final String source)
4838 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4843 * Construct and display a new frame containing the translation of this
4844 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4848 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4850 AlignmentI al = null;
4853 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4855 al = dna.translateCdna(codeTable);
4856 } catch (Exception ex)
4858 jalview.bin.Cache.log.error(
4859 "Exception during translation. Please report this !", ex);
4860 final String msg = MessageManager.getString(
4861 "label.error_when_translating_sequences_submit_bug_report");
4862 final String errorTitle = MessageManager
4863 .getString("label.implementation_error")
4864 + MessageManager.getString("label.translation_failed");
4865 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4866 errorTitle, JvOptionPane.ERROR_MESSAGE);
4869 if (al == null || al.getHeight() == 0)
4871 final String msg = MessageManager.getString(
4872 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4873 final String errorTitle = MessageManager
4874 .getString("label.translation_failed");
4875 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4876 errorTitle, JvOptionPane.WARNING_MESSAGE);
4880 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4881 af.setFileFormat(this.currentFileFormat);
4882 final String newTitle = MessageManager
4883 .formatMessage("label.translation_of_params", new Object[]
4884 { this.getTitle(), codeTable.getId() });
4885 af.setTitle(newTitle);
4886 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4888 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4889 AlignViewport.openSplitFrame(this, af, new Alignment(seqs));
4893 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4900 * Set the file format
4905 public void setFileFormat(FileFormatI format)
4907 this.currentFileFormat = format;
4911 * Try to load a features file onto the alignment.
4914 * contents or path to retrieve file or a File object
4916 * access mode of file (see jalview.io.AlignFile)
4917 * @return true if features file was parsed correctly.
4920 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4923 return avc.parseFeaturesFile(file, sourceType,
4924 Cache.getDefault(Preferences.RELAXEDSEQIDMATCHING, false));
4929 public void refreshFeatureUI(boolean enableIfNecessary)
4931 // note - currently this is only still here rather than in the controller
4932 // because of the featureSettings hard reference that is yet to be
4934 if (enableIfNecessary)
4936 viewport.setShowSequenceFeatures(true);
4937 showSeqFeatures.setSelected(true);
4943 public void dragEnter(DropTargetDragEvent evt)
4948 public void dragExit(DropTargetEvent evt)
4953 public void dragOver(DropTargetDragEvent evt)
4958 public void dropActionChanged(DropTargetDragEvent evt)
4963 public void drop(DropTargetDropEvent evt)
4965 // JAL-1552 - acceptDrop required before getTransferable call for
4966 // Java's Transferable for native dnd
4967 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4968 Transferable t = evt.getTransferable();
4970 final List<Object> files = new ArrayList<>();
4971 List<DataSourceType> protocols = new ArrayList<>();
4975 Desktop.transferFromDropTarget(files, protocols, evt, t);
4976 if (files.size() > 0)
4978 new Thread(new Runnable()
4984 loadDroppedFiles(files, protocols, evt, t);
4988 } catch (Exception e)
4990 e.printStackTrace();
4994 protected void loadDroppedFiles(List<Object> files,
4995 List<DataSourceType> protocols, DropTargetDropEvent evt,
5000 // check to see if any of these files have names matching sequences
5003 SequenceIdMatcher idm = new SequenceIdMatcher(
5004 viewport.getAlignment().getSequencesArray());
5006 * Object[] { String,SequenceI}
5008 ArrayList<Object[]> filesmatched = new ArrayList<>();
5009 ArrayList<Object> filesnotmatched = new ArrayList<>();
5010 for (int i = 0; i < files.size(); i++)
5013 Object fileObj = files.get(i);
5014 String fileName = fileObj.toString();
5016 DataSourceType protocol = (fileObj instanceof File
5017 ? DataSourceType.FILE
5018 : FormatAdapter.checkProtocol(fileName));
5019 if (protocol == DataSourceType.FILE)
5022 if (fileObj instanceof File)
5024 file = (File) fileObj;
5025 Platform.cacheFileData(file);
5029 file = new File(fileName);
5031 pdbfn = file.getName();
5033 else if (protocol == DataSourceType.URL)
5035 URL url = new URL(fileName);
5036 pdbfn = url.getFile();
5038 if (pdbfn.length() > 0)
5040 // attempt to find a match in the alignment
5041 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5042 int l = 0, c = pdbfn.indexOf(".");
5043 while (mtch == null && c != -1)
5048 } while ((c = pdbfn.indexOf(".", l)) > l);
5051 pdbfn = pdbfn.substring(0, l);
5053 mtch = idm.findAllIdMatches(pdbfn);
5060 type = new IdentifyFile().identify(fileObj, protocol);
5061 } catch (Exception ex)
5065 if (type != null && type.isStructureFile())
5067 filesmatched.add(new Object[] { fileObj, protocol, mtch });
5071 // File wasn't named like one of the sequences or wasn't a PDB
5073 filesnotmatched.add(fileObj);
5077 if (filesmatched.size() > 0)
5079 boolean autoAssociate = Cache
5080 .getDefault(Preferences.AUTOASSOCIATE_PDBANDSEQS, false);
5083 String msg = MessageManager.formatMessage(
5084 "label.automatically_associate_structure_files_with_sequences_same_name",
5086 { Integer.valueOf(filesmatched.size()).toString() });
5087 String ttl = MessageManager.getString(
5088 "label.automatically_associate_structure_files_by_name");
5089 int choice = JvOptionPane.showConfirmDialog(this, msg, ttl,
5090 JvOptionPane.YES_NO_OPTION);
5091 autoAssociate = choice == JvOptionPane.YES_OPTION;
5095 for (Object[] fm : filesmatched)
5097 // try and associate
5098 // TODO: may want to set a standard ID naming formalism for
5099 // associating PDB files which have no IDs.
5100 for (SequenceI toassoc : (SequenceI[]) fm[2])
5102 PDBEntry pe = AssociatePdbFileWithSeq.associatePdbWithSeq(
5103 fm[0].toString(), (DataSourceType) fm[1], toassoc,
5107 System.err.println("Associated file : " + (fm[0].toString())
5108 + " with " + toassoc.getDisplayId(true));
5112 // TODO: do we need to update overview ? only if features are
5114 alignPanel.paintAlignment(true, false);
5120 * add declined structures as sequences
5122 for (Object[] o : filesmatched)
5124 filesnotmatched.add(o[0]);
5128 if (filesnotmatched.size() > 0)
5130 if (assocfiles > 0 && (Cache
5131 .getDefault("AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
5132 || JvOptionPane.showConfirmDialog(this,
5133 "<html>" + MessageManager.formatMessage(
5134 "label.ignore_unmatched_dropped_files_info",
5136 { Integer.valueOf(filesnotmatched.size())
5139 MessageManager.getString(
5140 "label.ignore_unmatched_dropped_files"),
5141 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
5145 for (Object fn : filesnotmatched)
5147 loadJalviewDataFile(fn, null, null, null);
5151 } catch (Exception ex)
5153 ex.printStackTrace();
5158 * Attempt to load a "dropped" file or URL string, by testing in turn for
5160 * <li>an Annotation file</li>
5161 * <li>a JNet file</li>
5162 * <li>a features file</li>
5163 * <li>else try to interpret as an alignment file</li>
5167 * either a filename or a URL string.
5168 * @throws InterruptedException
5169 * @throws IOException
5172 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
5173 FileFormatI format, SequenceI assocSeq)
5175 // BH 2018 was String file
5178 if (sourceType == null)
5180 sourceType = FormatAdapter.checkProtocol(file);
5182 // if the file isn't identified, or not positively identified as some
5183 // other filetype (PFAM is default unidentified alignment file type) then
5184 // try to parse as annotation.
5185 boolean isAnnotation = (format == null
5186 || FileFormat.Pfam.equals(format))
5187 ? new AnnotationFile().annotateAlignmentView(viewport,
5193 // first see if its a T-COFFEE score file
5194 TCoffeeScoreFile tcf = null;
5197 tcf = new TCoffeeScoreFile(file, sourceType);
5200 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5204 new TCoffeeColourScheme(viewport.getAlignment()));
5205 isAnnotation = true;
5206 setStatus(MessageManager.getString(
5207 "label.successfully_pasted_tcoffee_scores_to_alignment"));
5211 // some problem - if no warning its probable that the ID matching
5212 // process didn't work
5213 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
5214 tcf.getWarningMessage() == null
5215 ? MessageManager.getString(
5216 "label.check_file_matches_sequence_ids_alignment")
5217 : tcf.getWarningMessage(),
5218 MessageManager.getString(
5219 "label.problem_reading_tcoffee_score_file"),
5220 JvOptionPane.WARNING_MESSAGE);
5227 } catch (Exception x)
5230 "Exception when processing data source as T-COFFEE score file",
5236 // try to see if its a JNet 'concise' style annotation file *before*
5238 // try to parse it as a features file
5241 format = new IdentifyFile().identify(file, sourceType);
5243 if (FileFormat.ScoreMatrix == format)
5245 ScoreMatrixFile sm = new ScoreMatrixFile(
5246 new FileParse(file, sourceType));
5248 // todo: i18n this message
5249 setStatus(MessageManager.formatMessage(
5250 "label.successfully_loaded_matrix",
5251 sm.getMatrixName()));
5253 else if (FileFormat.Jnet.equals(format))
5255 JPredFile predictions = new JPredFile(file, sourceType);
5256 new JnetAnnotationMaker();
5257 JnetAnnotationMaker.add_annotation(predictions,
5258 viewport.getAlignment(), 0, false);
5259 viewport.getAlignment().setupJPredAlignment();
5260 isAnnotation = true;
5262 // else if (IdentifyFile.FeaturesFile.equals(format))
5263 else if (FileFormat.Features.equals(format))
5265 if (parseFeaturesFile(file, sourceType))
5267 SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
5268 if (splitFrame != null)
5270 splitFrame.repaint();
5274 alignPanel.paintAlignment(true, true);
5280 new FileLoader().LoadFile(viewport, file, sourceType, format);
5286 updateForAnnotations();
5288 } catch (Exception ex)
5290 ex.printStackTrace();
5291 } catch (OutOfMemoryError oom)
5296 } catch (Exception x)
5301 + (sourceType != null
5302 ? (sourceType == DataSourceType.PASTE
5304 : "using " + sourceType + " from "
5308 ? "(parsing as '" + format + "' file)"
5310 oom, Desktop.getDesktopPane());
5315 * Do all updates necessary after an annotation file such as jnet. Also called
5316 * from Jalview.loadAppletParams for "annotations", "jnetFile"
5319 public void updateForAnnotations()
5321 alignPanel.adjustAnnotationHeight();
5322 viewport.updateSequenceIdColours();
5323 buildSortByAnnotationScoresMenu();
5324 alignPanel.paintAlignment(true, true);
5328 * Change the display state for the given feature groups -- Added by BH from
5332 * list of group strings
5334 * visible or invisible
5337 public void setFeatureGroupState(String[] groups, boolean state)
5339 jalview.api.FeatureRenderer fr = null;
5340 viewport.setShowSequenceFeatures(true);
5341 if (alignPanel != null
5342 && (fr = alignPanel.getFeatureRenderer()) != null)
5345 fr.setGroupVisibility(Arrays.asList(groups), state);
5346 alignPanel.getSeqPanel().seqCanvas.repaint();
5347 if (alignPanel.overviewPanel != null)
5349 alignPanel.overviewPanel.updateOverviewImage();
5355 * Method invoked by the ChangeListener on the tabbed pane, in other words
5356 * when a different tabbed pane is selected by the user or programmatically.
5360 public void tabSelectionChanged(int index)
5364 alignPanel = alignPanels.get(index);
5365 viewport = alignPanel.av;
5366 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5367 setMenusFromViewport(viewport);
5368 if (featureSettings != null && featureSettings.isOpen()
5369 && featureSettings.fr.getViewport() != viewport)
5371 if (viewport.isShowSequenceFeatures())
5373 // refresh the featureSettings to reflect UI change
5374 showFeatureSettingsUI();
5378 // close feature settings for this view.
5379 featureSettings.close();
5386 * 'focus' any colour slider that is open to the selected viewport
5388 if (viewport.getConservationSelected())
5390 SliderPanel.setConservationSlider(alignPanel,
5391 viewport.getResidueShading(), alignPanel.getViewName());
5395 SliderPanel.hideConservationSlider();
5397 if (viewport.getAbovePIDThreshold())
5399 SliderPanel.setPIDSliderSource(alignPanel,
5400 viewport.getResidueShading(), alignPanel.getViewName());
5404 SliderPanel.hidePIDSlider();
5408 * If there is a frame linked to this one in a SplitPane, switch it to the
5409 * same view tab index. No infinite recursion of calls should happen, since
5410 * tabSelectionChanged() should not get invoked on setting the selected
5411 * index to an unchanged value. Guard against setting an invalid index
5412 * before the new view peer tab has been created.
5414 final AlignViewportI peer = viewport.getCodingComplement();
5417 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
5418 .getAlignPanel().alignFrame;
5419 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5421 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5427 * On right mouse click on view tab, prompt for and set new view name.
5431 public void tabbedPane_mousePressed(MouseEvent e)
5433 if (e.isPopupTrigger())
5435 String msg = MessageManager.getString("label.enter_view_name");
5436 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
5437 String reply = JvOptionPane.showInputDialog(msg, ttl);
5441 viewport.setViewName(reply);
5442 // TODO warn if reply is in getExistingViewNames()?
5443 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5448 public AlignViewport getCurrentView()
5454 * Open the dialog for regex description parsing.
5458 protected void extractScores_actionPerformed(ActionEvent e)
5460 ParseProperties pp = new jalview.analysis.ParseProperties(
5461 viewport.getAlignment());
5462 // TODO: verify regex and introduce GUI dialog for version 2.5
5463 // if (pp.getScoresFromDescription("col", "score column ",
5464 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5466 if (pp.getScoresFromDescription("description column",
5467 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5469 buildSortByAnnotationScoresMenu();
5477 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5482 protected void showDbRefs_actionPerformed(ActionEvent e)
5484 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5490 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5495 protected void showNpFeats_actionPerformed(ActionEvent e)
5497 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5501 * find the viewport amongst the tabs in this alignment frame and close that
5507 public boolean closeView(AlignViewportI av)
5511 this.closeMenuItem_actionPerformed(false);
5514 Component[] comp = tabbedPane.getComponents();
5515 for (int i = 0; comp != null && i < comp.length; i++)
5517 if (comp[i] instanceof AlignmentPanel)
5519 if (((AlignmentPanel) comp[i]).av == av)
5522 closeView((AlignmentPanel) comp[i]);
5530 protected void build_fetchdbmenu(JMenu webService)
5532 // Temporary hack - DBRef Fetcher always top level ws entry.
5533 // TODO We probably want to store a sequence database checklist in
5534 // preferences and have checkboxes.. rather than individual sources selected
5536 final JMenu rfetch = new JMenu(
5537 MessageManager.getString("action.fetch_db_references"));
5538 rfetch.setToolTipText(MessageManager.getString(
5539 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5540 webService.add(rfetch);
5542 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5543 MessageManager.getString("option.trim_retrieved_seqs"));
5544 trimrs.setToolTipText(
5545 MessageManager.getString("label.trim_retrieved_sequences"));
5547 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5548 trimrs.addActionListener(new ActionListener()
5552 public void actionPerformed(ActionEvent e)
5554 trimrs.setSelected(trimrs.isSelected());
5555 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5556 Boolean.valueOf(trimrs.isSelected()).toString());
5560 JMenuItem fetchr = new JMenuItem(
5561 MessageManager.getString("label.standard_databases"));
5562 fetchr.setToolTipText(
5563 MessageManager.getString("label.fetch_embl_uniprot"));
5564 fetchr.addActionListener(new ActionListener()
5568 public void actionPerformed(ActionEvent e)
5570 new Thread(new Runnable()
5576 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5577 .getAlignment().isNucleotide();
5578 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5579 alignPanel.av.getSequenceSelection(),
5580 alignPanel.alignFrame, null,
5581 alignPanel.alignFrame.featureSettings, isNucleotide);
5582 dbRefFetcher.addListener(new FetchFinishedListenerI()
5586 public void finished()
5589 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5590 .getFeatureSettingsModels())
5593 alignPanel.av.mergeFeaturesStyle(srcSettings);
5595 AlignFrame.this.setMenusForViewport();
5598 dbRefFetcher.fetchDBRefs(false);
5606 new Thread(new Runnable()
5613 // final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5614 // .getSequenceFetcherSingleton();
5615 javax.swing.SwingUtilities.invokeLater(new Runnable()
5621 jalview.ws.SequenceFetcher sf = jalview.ws.SequenceFetcher
5623 String[] dbclasses = sf.getNonAlignmentSources();
5624 List<DbSourceProxy> otherdb;
5625 JMenu dfetch = new JMenu();
5626 JMenu ifetch = new JMenu();
5627 JMenuItem fetchr = null;
5628 int comp = 0, icomp = 0, mcomp = 15;
5629 String mname = null;
5631 for (String dbclass : dbclasses)
5633 otherdb = sf.getSourceProxy(dbclass);
5634 // add a single entry for this class, or submenu allowing 'fetch
5636 if (otherdb == null || otherdb.size() < 1)
5642 mname = "From " + dbclass;
5644 if (otherdb.size() == 1)
5646 DbSourceProxy src = otherdb.get(0);
5647 DbSourceProxy[] dassource = new DbSourceProxy[] { src };
5648 fetchr = new JMenuItem(src.getDbSource());
5649 fetchr.addActionListener(new ActionListener()
5653 public void actionPerformed(ActionEvent e)
5655 new Thread(new Runnable()
5661 boolean isNucleotide = alignPanel.alignFrame
5662 .getViewport().getAlignment()
5664 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5665 alignPanel.av.getSequenceSelection(),
5666 alignPanel.alignFrame, dassource,
5667 alignPanel.alignFrame.featureSettings,
5670 .addListener(new FetchFinishedListenerI()
5674 public void finished()
5676 FeatureSettingsModelI srcSettings = dassource[0]
5677 .getFeatureColourScheme();
5678 alignPanel.av.mergeFeaturesStyle(
5680 AlignFrame.this.setMenusForViewport();
5683 dbRefFetcher.fetchDBRefs(false);
5689 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5690 MessageManager.formatMessage(
5691 "label.fetch_retrieve_from", new Object[]
5692 { src.getDbName() })));
5698 final DbSourceProxy[] dassource = otherdb
5699 .toArray(new DbSourceProxy[0]);
5701 DbSourceProxy src = otherdb.get(0);
5702 fetchr = new JMenuItem(MessageManager
5703 .formatMessage("label.fetch_all_param", new Object[]
5704 { src.getDbSource() }));
5705 fetchr.addActionListener(new ActionListener()
5709 public void actionPerformed(ActionEvent e)
5711 new Thread(new Runnable()
5717 boolean isNucleotide = alignPanel.alignFrame
5718 .getViewport().getAlignment()
5720 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5721 alignPanel.av.getSequenceSelection(),
5722 alignPanel.alignFrame, dassource,
5723 alignPanel.alignFrame.featureSettings,
5726 .addListener(new FetchFinishedListenerI()
5730 public void finished()
5732 AlignFrame.this.setMenusForViewport();
5735 dbRefFetcher.fetchDBRefs(false);
5741 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5742 MessageManager.formatMessage(
5743 "label.fetch_retrieve_from_all_sources",
5745 { Integer.valueOf(otherdb.size())
5747 src.getDbSource(), src.getDbName() })));
5750 // and then build the rest of the individual menus
5751 ifetch = new JMenu(MessageManager.formatMessage(
5752 "label.source_from_db_source", new Object[]
5753 { src.getDbSource() }));
5755 String imname = null;
5757 for (DbSourceProxy sproxy : otherdb)
5759 String dbname = sproxy.getDbName();
5760 String sname = dbname.length() > 5
5761 ? dbname.substring(0, 5) + "..."
5763 String msname = dbname.length() > 10
5764 ? dbname.substring(0, 10) + "..."
5768 imname = MessageManager
5769 .formatMessage("label.from_msname", new Object[]
5772 fetchr = new JMenuItem(msname);
5773 final DbSourceProxy[] dassrc = { sproxy };
5774 fetchr.addActionListener(new ActionListener()
5778 public void actionPerformed(ActionEvent e)
5780 new Thread(new Runnable()
5786 boolean isNucleotide = alignPanel.alignFrame
5787 .getViewport().getAlignment()
5789 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5790 alignPanel.av.getSequenceSelection(),
5791 alignPanel.alignFrame, dassrc,
5792 alignPanel.alignFrame.featureSettings,
5795 .addListener(new FetchFinishedListenerI()
5799 public void finished()
5801 AlignFrame.this.setMenusForViewport();
5804 dbRefFetcher.fetchDBRefs(false);
5810 fetchr.setToolTipText(
5811 "<html>" + MessageManager.formatMessage(
5812 "label.fetch_retrieve_from", new Object[]
5816 if (++icomp >= mcomp || i == (otherdb.size()))
5818 ifetch.setText(MessageManager.formatMessage(
5819 "label.source_to_target", imname, sname));
5821 ifetch = new JMenu();
5829 if (comp >= mcomp || dbi >= (dbclasses.length))
5831 dfetch.setText(MessageManager.formatMessage(
5832 "label.source_to_target", mname, dbclass));
5834 dfetch = new JMenu();
5847 * Left justify the whole alignment.
5851 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5853 viewport.getAlignment().justify(false);
5854 viewport.notifyAlignment();
5858 * Right justify the whole alignment.
5862 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5864 viewport.getAlignment().justify(true);
5865 viewport.notifyAlignment();
5869 public void setShowSeqFeatures(boolean b)
5871 showSeqFeatures.setSelected(b);
5872 viewport.setShowSequenceFeatures(b);
5879 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5880 * awt.event.ActionEvent)
5884 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5886 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5887 alignPanel.paintAlignment(false, false);
5894 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5899 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5901 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5902 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5910 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5911 * .event.ActionEvent)
5915 protected void showGroupConservation_actionPerformed(ActionEvent e)
5917 viewport.setShowGroupConservation(showGroupConservation.getState());
5918 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5925 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5926 * .event.ActionEvent)
5930 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5932 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5933 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5940 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5941 * .event.ActionEvent)
5945 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5947 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5948 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5952 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5954 showSequenceLogo.setState(true);
5955 viewport.setShowSequenceLogo(true);
5956 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5957 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5961 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5963 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5970 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5971 * .event.ActionEvent)
5975 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5977 if (avc.makeGroupsFromSelection())
5979 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5980 alignPanel.updateAnnotation();
5981 alignPanel.paintAlignment(true,
5982 viewport.needToUpdateStructureViews());
5986 public void clearAlignmentSeqRep()
5988 // TODO refactor alignmentseqrep to controller
5989 if (viewport.getAlignment().hasSeqrep())
5991 viewport.getAlignment().setSeqrep(null);
5992 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5993 alignPanel.updateAnnotation();
5994 alignPanel.paintAlignment(true, true);
5999 protected void createGroup_actionPerformed(ActionEvent e)
6001 if (avc.createGroup())
6003 if (applyAutoAnnotationSettings.isSelected())
6005 alignPanel.updateAnnotation(true, false);
6007 alignPanel.alignmentChanged();
6012 protected void unGroup_actionPerformed(ActionEvent e)
6016 alignPanel.alignmentChanged();
6021 * make the given alignmentPanel the currently selected tab
6023 * @param alignmentPanel
6026 public void setDisplayedView(AlignmentPanel alignmentPanel)
6028 if (!viewport.getSequenceSetId()
6029 .equals(alignmentPanel.av.getSequenceSetId()))
6031 throw new Error(MessageManager.getString(
6032 "error.implementation_error_cannot_show_view_alignment_frame"));
6034 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
6035 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
6037 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
6042 * Action on selection of menu options to Show or Hide annotations.
6045 * @param forSequences
6046 * update sequence-related annotations
6047 * @param forAlignment
6048 * update non-sequence-related annotations
6052 protected void setAnnotationsVisibility(boolean visible,
6053 boolean forSequences, boolean forAlignment)
6055 AlignmentAnnotation[] anns = alignPanel.getAlignment()
6056 .getAlignmentAnnotation();
6061 for (AlignmentAnnotation aa : anns)
6064 * don't display non-positional annotations on an alignment
6066 if (aa.annotations == null)
6070 boolean apply = (aa.sequenceRef == null && forAlignment)
6071 || (aa.sequenceRef != null && forSequences);
6074 aa.visible = visible;
6077 alignPanel.validateAnnotationDimensions(true);
6078 alignPanel.alignmentChanged();
6082 * Store selected annotation sort order for the view and repaint.
6086 protected void sortAnnotations_actionPerformed()
6088 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
6090 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
6091 alignPanel.paintAlignment(false, false);
6096 * @return alignment panels in this alignment frame
6099 public List<? extends AlignmentViewPanel> getAlignPanels()
6101 // alignPanels is never null
6102 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
6107 * Open a new alignment window, with the cDNA associated with this (protein)
6108 * alignment, aligned as is the protein.
6111 protected void viewAsCdna_actionPerformed()
6113 // TODO no longer a menu action - refactor as required
6114 final AlignmentI alignment = getViewport().getAlignment();
6115 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
6116 if (mappings == null)
6120 List<SequenceI> cdnaSeqs = new ArrayList<>();
6121 for (SequenceI aaSeq : alignment.getSequences())
6123 for (AlignedCodonFrame acf : mappings)
6125 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
6129 * There is a cDNA mapping for this protein sequence - add to new
6130 * alignment. It will share the same dataset sequence as other mapped
6131 * cDNA (no new mappings need to be created).
6133 final Sequence newSeq = new Sequence(dnaSeq);
6134 newSeq.setDatasetSequence(dnaSeq);
6135 cdnaSeqs.add(newSeq);
6139 if (cdnaSeqs.size() == 0)
6141 // show a warning dialog no mapped cDNA
6144 AlignmentI cdna = new Alignment(
6145 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
6146 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
6147 AlignFrame.DEFAULT_HEIGHT);
6148 cdna.alignAs(alignment);
6149 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
6151 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
6152 AlignFrame.DEFAULT_HEIGHT);
6156 * Set visibility of dna/protein complement view (available when shown in a
6163 protected void showComplement_actionPerformed(boolean show)
6165 SplitContainerI sf = getSplitViewContainer();
6168 sf.setComplementVisible(this, show);
6173 * Generate the reverse (optionally complemented) of the selected sequences,
6174 * and add them to the alignment
6178 protected void showReverse_actionPerformed(boolean complement)
6180 AlignmentI al = null;
6183 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
6184 al = dna.reverseCdna(complement);
6185 viewport.addAlignment(al, "");
6186 addHistoryItem(new EditCommand(
6187 MessageManager.getString("label.add_sequences"), Action.PASTE,
6188 al.getSequencesArray(), 0, al.getWidth(),
6189 viewport.getAlignment()));
6190 } catch (Exception ex)
6192 System.err.println(ex.getMessage());
6198 * Try to run a script in the Groovy console, having first ensured that this
6199 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
6200 * be targeted at this alignment.
6204 protected void runGroovy_actionPerformed()
6206 Jalview.setCurrentAlignFrame(this);
6207 groovy.ui.Console console = Desktop.getGroovyConsole();
6208 if (console != null)
6212 console.runScript();
6213 } catch (Exception ex)
6215 System.err.println((ex.toString()));
6216 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
6217 MessageManager.getString("label.couldnt_run_groovy_script"),
6218 MessageManager.getString("label.groovy_support_failed"),
6219 JvOptionPane.ERROR_MESSAGE);
6224 System.err.println("Can't run Groovy script as console not found");
6229 * Hides columns containing (or not containing) a specified feature, provided
6230 * that would not leave all columns hidden
6232 * @param featureType
6233 * @param columnsContaining
6237 public boolean hideFeatureColumns(String featureType,
6238 boolean columnsContaining)
6240 boolean notForHiding = avc.markColumnsContainingFeatures(
6241 columnsContaining, false, false, featureType);
6244 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
6245 false, featureType))
6247 getViewport().hideSelectedColumns();
6255 protected void selectHighlightedColumns_actionPerformed(
6256 ActionEvent actionEvent)
6258 // include key modifier check in case user selects from menu
6259 avc.markHighlightedColumns(
6260 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
6261 (actionEvent.getModifiers() & (ActionEvent.META_MASK
6262 | ActionEvent.CTRL_MASK)) != 0);
6266 * Rebuilds the Colour menu, including any user-defined colours which have
6267 * been loaded either on startup or during the session
6270 public void buildColourMenu()
6272 colourMenu.removeAll();
6274 colourMenu.add(applyToAllGroups);
6275 colourMenu.add(textColour);
6276 colourMenu.addSeparator();
6278 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
6279 viewport.getAlignment(), false);
6281 colourMenu.add(annotationColour);
6282 bg.add(annotationColour);
6283 colourMenu.addSeparator();
6284 colourMenu.add(conservationMenuItem);
6285 colourMenu.add(modifyConservation);
6286 colourMenu.add(abovePIDThreshold);
6287 colourMenu.add(modifyPID);
6289 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
6290 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
6294 * Open a dialog (if not already open) that allows the user to select and
6295 * calculate PCA or Tree analysis
6298 protected void openTreePcaDialog()
6300 if (alignPanel.getCalculationDialog() == null)
6302 new CalculationChooser(AlignFrame.this);
6307 * Sets the status of the HMMER menu
6309 public void updateHMMERStatus()
6311 hmmerMenu.setEnabled(HmmerCommand.isHmmerAvailable());
6315 protected void loadVcf_actionPerformed()
6317 JalviewFileChooser chooser = new JalviewFileChooser(
6318 Cache.getProperty("LAST_DIRECTORY"));
6319 chooser.setFileView(new JalviewFileView());
6320 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
6321 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
6322 final AlignFrame us = this;
6323 chooser.setResponseHandler(0, new Runnable()
6329 String choice = chooser.getSelectedFile().getPath();
6330 Cache.setProperty("LAST_DIRECTORY", choice);
6331 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
6332 new VCFLoader(choice).loadVCF(seqs, us);
6335 chooser.showOpenDialog(null);
6339 private Rectangle lastFeatureSettingsBounds = null;
6342 public void setFeatureSettingsGeometry(Rectangle bounds)
6344 lastFeatureSettingsBounds = bounds;
6348 public Rectangle getFeatureSettingsGeometry()
6350 return lastFeatureSettingsBounds;
6353 public void scrollTo(int row, int column)
6355 alignPanel.getSeqPanel().scrollTo(row, column);
6358 public void scrollToRow(int row)
6360 alignPanel.getSeqPanel().scrollToRow(row);
6363 public void scrollToColumn(int column)
6365 alignPanel.getSeqPanel().scrollToColumn(column);
6369 * BH 2019 from JalviewLite
6371 * get sequence feature groups that are hidden or shown
6378 public String[] getFeatureGroupsOfState(boolean visible)
6380 jalview.api.FeatureRenderer fr = null;
6381 if (alignPanel != null
6382 && (fr = alignPanel.getFeatureRenderer()) != null)
6384 List<String> gps = fr.getGroups(visible);
6385 String[] _gps = gps.toArray(new String[gps.size()]);
6393 * @return list of feature groups on the view
6396 public String[] getFeatureGroups()
6398 jalview.api.FeatureRenderer fr = null;
6399 if (alignPanel != null
6400 && (fr = alignPanel.getFeatureRenderer()) != null)
6402 List<String> gps = fr.getFeatureGroups();
6403 String[] _gps = gps.toArray(new String[gps.size()]);
6409 public void select(SequenceGroup sel, ColumnSelection csel,
6410 HiddenColumns hidden)
6412 alignPanel.getSeqPanel().selection(sel, csel, hidden, null);
6420 static class PrintThread extends Thread
6424 public PrintThread(AlignmentPanel ap)
6429 static PageFormat pf;
6434 PrinterJob printJob = PrinterJob.getPrinterJob();
6438 printJob.setPrintable(ap, pf);
6442 printJob.setPrintable(ap);
6445 if (printJob.printDialog())
6450 } catch (Exception PrintException)
6452 PrintException.printStackTrace();