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 addProgressBar(long id, String message)
1078 progressBar.addProgressBar(id, message);
1082 public void removeProgressBar(long id)
1084 progressBar.removeProgressBar(id);
1088 public void registerHandler(final long id,
1089 final IProgressIndicatorHandler handler)
1091 progressBar.registerHandler(id, handler);
1096 * @return true if any progress bars are still active
1100 public boolean operationInProgress()
1102 return progressBar.operationInProgress();
1106 * Sets the text of the status bar. Note that setting a null or empty value
1107 * will cause the status bar to be hidden, with possibly undesirable flicker
1108 * of the screen layout.
1112 public void setStatus(String text)
1114 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1118 * Added so Castor Mapping file can obtain Jalview Version
1121 public String getVersion()
1123 return jalview.bin.Cache.getProperty("VERSION");
1126 public FeatureRenderer getFeatureRenderer()
1128 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1132 public void fetchSequence_actionPerformed()
1134 new SequenceFetcher(this);
1138 public void addFromFile_actionPerformed(ActionEvent e)
1140 Desktop.getInstance().inputLocalFileMenuItem_actionPerformed(viewport);
1144 public void hmmBuild_actionPerformed(boolean withDefaults)
1146 if (!alignmentIsSufficient(1))
1152 * get default parameters, and optionally show a dialog
1153 * to allow them to be modified
1155 ParamDatastoreI store = HMMERParamStore.forBuild(viewport);
1156 List<ArgumentI> args = store.getServiceParameters();
1160 WsParamSetI set = new HMMERPreset();
1161 WsJobParameters params = new WsJobParameters(store, set, args);
1162 params.showRunDialog().thenAccept((startJob) -> {
1165 var args2 = params.getJobParams();
1166 new Thread(new HMMBuild(this, args2)).start();
1172 new Thread(new HMMBuild(this, args)).start();
1177 public void hmmAlign_actionPerformed(boolean withDefaults)
1179 if (!(checkForHMM() && alignmentIsSufficient(2)))
1185 * get default parameters, and optionally show a dialog
1186 * to allow them to be modified
1188 ParamDatastoreI store = HMMERParamStore.forAlign(viewport);
1189 List<ArgumentI> args = store.getServiceParameters();
1193 WsParamSetI set = new HMMERPreset();
1194 WsJobParameters params = new WsJobParameters(store, set, args);
1195 params.showRunDialog().thenAccept((startJob) -> {
1198 var args2 = params.getJobParams();
1199 new Thread(new HMMAlign(this, args2)).start();
1205 new Thread(new HMMAlign(this, args)).start();
1210 public void hmmSearch_actionPerformed(boolean withDefaults)
1218 * get default parameters, and (if requested) show
1219 * dialog to allow modification
1221 ParamDatastoreI store = HMMERParamStore.forSearch(viewport);
1222 List<ArgumentI> args = store.getServiceParameters();
1226 WsParamSetI set = new HMMERPreset();
1227 WsJobParameters params = new WsJobParameters(store, set, args);
1228 params.showRunDialog().thenAccept((startJob) -> {
1231 var args2 = params.getJobParams();
1232 new Thread(new HMMSearch(this, args2)).start();
1233 alignPanel.repaint();
1239 new Thread(new HMMSearch(this, args)).start();
1240 alignPanel.repaint();
1245 public void jackhmmer_actionPerformed(boolean withDefaults)
1249 * get default parameters, and (if requested) show
1250 * dialog to allow modification
1253 ParamDatastoreI store = HMMERParamStore.forJackhmmer(viewport);
1254 List<ArgumentI> args = store.getServiceParameters();
1258 WsParamSetI set = new HMMERPreset();
1259 WsJobParameters params = new WsJobParameters(store, set, args);
1260 params.showRunDialog().thenAccept((startJob) -> {
1263 var args2 = params.getJobParams();
1264 new Thread(new JackHMMER(this, args2)).start();
1265 alignPanel.repaint();
1271 new Thread(new JackHMMER(this, args)).start();
1272 alignPanel.repaint();
1277 * Checks if the alignment has at least one hidden Markov model, if not shows
1278 * a dialog advising to run hmmbuild or load an HMM profile
1282 private boolean checkForHMM()
1284 if (viewport.getAlignment().getHmmSequences().isEmpty())
1286 JOptionPane.showMessageDialog(this,
1287 MessageManager.getString("warn.no_hmm"));
1294 protected void filterByEValue_actionPerformed()
1296 viewport.filterByEvalue(inputDouble("Enter E-Value Cutoff"));
1300 protected void filterByScore_actionPerformed()
1302 viewport.filterByScore(inputDouble("Enter Bit Score Threshold"));
1305 private double inputDouble(String message)
1309 while (d == null || d <= 0)
1311 str = JOptionPane.showInputDialog(this.alignPanel, message);
1314 d = Double.valueOf(str);
1315 } catch (NumberFormatException e)
1323 * Checks if the alignment contains the required number of sequences.
1328 public boolean alignmentIsSufficient(int required)
1330 if (getViewport().getSequenceSelection().length < required)
1332 JOptionPane.showMessageDialog(this,
1333 MessageManager.getString("label.not_enough_sequences"));
1340 * Opens a file browser and adds the selected file, if in Fasta, Stockholm or
1341 * Pfam format, to the list held under preference key "HMMSEARCH_DBS" (as a
1342 * comma-separated list)
1345 public void addDatabase_actionPerformed() throws IOException
1347 if (Cache.getProperty(Preferences.HMMSEARCH_DBS) == null)
1349 Cache.setProperty(Preferences.HMMSEARCH_DBS, "");
1352 String path = openFileChooser(false);
1353 if (path != null && new File(path).exists())
1355 IdentifyFile identifier = new IdentifyFile();
1356 FileFormatI format = identifier.identify(path, DataSourceType.FILE);
1357 if (format == FileFormat.Fasta || format == FileFormat.Stockholm
1358 || format == FileFormat.Pfam)
1360 String currentDbPaths = Cache
1361 .getProperty(Preferences.HMMSEARCH_DBS);
1362 currentDbPaths += Preferences.COMMA + path;
1363 Cache.setProperty(Preferences.HMMSEARCH_DBS, currentDbPaths);
1367 JOptionPane.showMessageDialog(this,
1368 MessageManager.getString("warn.invalid_format"));
1374 * Opens a file chooser, optionally restricted to selecting folders
1375 * (directories) only. Answers the path to the selected file or folder, or
1376 * null if none is chosen.
1381 protected String openFileChooser(boolean forFolder)
1383 // TODO duplicates GPreferences method - relocate to JalviewFileChooser?
1384 String choice = null;
1385 JFileChooser chooser = new JFileChooser();
1388 chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1390 chooser.setDialogTitle(
1391 MessageManager.getString("label.open_local_file"));
1392 chooser.setToolTipText(MessageManager.getString("action.open"));
1394 int value = chooser.showOpenDialog(this);
1396 if (value == JFileChooser.APPROVE_OPTION)
1398 choice = chooser.getSelectedFile().getPath();
1404 public void reload_actionPerformed(ActionEvent e)
1406 if (fileName == null && fileObject == null)
1410 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1411 // originating file's format
1412 // TODO: work out how to recover feature settings for correct view(s) when
1413 // file is reloaded.
1414 if (FileFormat.Jalview.equals(currentFileFormat))
1416 JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
1417 for (int i = 0; i < frames.length; i++)
1419 if (frames[i] instanceof AlignFrame && frames[i] != this
1420 && ((AlignFrame) frames[i]).fileName != null
1421 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1425 frames[i].setSelected(true);
1426 Desktop.getInstance().closeAssociatedWindows();
1427 } catch (java.beans.PropertyVetoException ex)
1433 Desktop.getInstance().closeAssociatedWindows();
1435 FileLoader loader = new FileLoader();
1436 // DataSourceType protocol = fileName.startsWith("http:")
1437 // ? DataSourceType.URL
1438 // : DataSourceType.FILE;
1439 loader.LoadFile(viewport, (fileObject == null ? fileName : fileObject), protocol, currentFileFormat);
1443 Rectangle bounds = this.getBounds();
1445 FileLoader loader = new FileLoader();
1447 AlignFrame newframe = null;
1449 if (fileObject == null)
1451 newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1456 newframe = loader.LoadFileWaitTillLoaded(fileObject,
1457 DataSourceType.FILE, currentFileFormat);
1460 newframe.setBounds(bounds);
1461 if (featureSettings != null && featureSettings.isShowing())
1463 final Rectangle fspos = featureSettings.frame.getBounds();
1464 // TODO: need a 'show feature settings' function that takes bounds -
1465 // need to refactor Desktop.addFrame
1466 newframe.featureSettings_actionPerformed(null);
1467 final FeatureSettings nfs = newframe.featureSettings;
1468 SwingUtilities.invokeLater(new Runnable()
1474 nfs.frame.setBounds(fspos);
1477 this.featureSettings.close();
1478 this.featureSettings = null;
1480 this.closeMenuItem_actionPerformed(true);
1486 public void addFromText_actionPerformed(ActionEvent e)
1488 Desktop.getInstance()
1489 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1493 public void addFromURL_actionPerformed(ActionEvent e)
1495 Desktop.getInstance().inputURLMenuItem_actionPerformed(viewport);
1499 public void save_actionPerformed(ActionEvent e)
1501 if (fileName == null || (currentFileFormat == null)
1502 || fileName.startsWith("http"))
1504 saveAs_actionPerformed();
1508 saveAlignment(fileName, currentFileFormat);
1513 * Saves the alignment to a file with a name chosen by the user, if necessary
1514 * warning if a file would be overwritten
1518 public void saveAs_actionPerformed()
1520 String format = currentFileFormat == null ? null
1521 : currentFileFormat.getName();
1522 JalviewFileChooser chooser = JalviewFileChooser
1523 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1525 chooser.setFileView(new JalviewFileView());
1526 chooser.setDialogTitle(
1527 MessageManager.getString("label.save_alignment_to_file"));
1528 chooser.setToolTipText(MessageManager.getString("action.save"));
1530 int value = chooser.showSaveDialog(this);
1532 if (value != JalviewFileChooser.APPROVE_OPTION)
1536 currentFileFormat = chooser.getSelectedFormat();
1537 // todo is this (2005) test now obsolete - value is never null?
1538 while (currentFileFormat == null)
1540 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
1542 .getString("label.select_file_format_before_saving"),
1543 MessageManager.getString("label.file_format_not_specified"),
1544 JvOptionPane.WARNING_MESSAGE);
1545 currentFileFormat = chooser.getSelectedFormat();
1546 value = chooser.showSaveDialog(this);
1547 if (value != JalviewFileChooser.APPROVE_OPTION)
1553 fileName = chooser.getSelectedFile().getPath();
1555 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1556 Cache.setProperty("LAST_DIRECTORY", fileName);
1557 saveAlignment(fileName, currentFileFormat);
1560 boolean lastSaveSuccessful = false;
1562 FileFormatI lastFormatSaved;
1564 String lastFilenameSaved;
1567 * Raise a dialog or status message for the last call to saveAlignment.
1569 * @return true if last call to saveAlignment(file, format) was successful.
1572 public boolean isSaveAlignmentSuccessful()
1575 if (!lastSaveSuccessful)
1577 JvOptionPane.showInternalMessageDialog(this, MessageManager
1578 .formatMessage("label.couldnt_save_file", new Object[]
1579 { lastFilenameSaved }),
1580 MessageManager.getString("label.error_saving_file"),
1581 JvOptionPane.WARNING_MESSAGE);
1586 setStatus(MessageManager.formatMessage(
1587 "label.successfully_saved_to_file_in_format", new Object[]
1588 { lastFilenameSaved, lastFormatSaved }));
1591 return lastSaveSuccessful;
1595 * Saves the alignment to the specified file path, in the specified format,
1596 * which may be an alignment format, or Jalview project format. If the
1597 * alignment has hidden regions, or the format is one capable of including
1598 * non-sequence data (features, annotations, groups), then the user may be
1599 * prompted to specify what to include in the output.
1605 public void saveAlignment(String file, FileFormatI format)
1607 lastSaveSuccessful = true;
1608 lastFilenameSaved = file;
1609 lastFormatSaved = format;
1611 if (FileFormat.Jalview.equals(format))
1613 String shortName = title;
1614 if (shortName.indexOf(File.separatorChar) > -1)
1616 shortName = shortName
1617 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
1619 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file,
1622 statusBar.setText(MessageManager.formatMessage(
1623 "label.successfully_saved_to_file_in_format", new Object[]
1624 { fileName, format }));
1629 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1630 Runnable cancelAction = new Runnable()
1636 lastSaveSuccessful = false;
1639 Runnable outputAction = new Runnable()
1645 // todo defer this to inside formatSequences (or later)
1646 AlignmentExportData exportData = viewport
1647 .getAlignExportData(options);
1648 String output = new FormatAdapter(alignPanel, options)
1649 .formatSequences(format, exportData.getAlignment(),
1650 exportData.getOmitHidden(),
1651 exportData.getStartEndPostions(),
1652 viewport.getAlignment().getHiddenColumns());
1655 lastSaveSuccessful = false;
1659 // create backupfiles object and get new temp filename destination
1660 boolean doBackup = BackupFiles.getEnabled();
1661 BackupFiles backupfiles = doBackup ? new BackupFiles(file) : null;
1664 String tempFilePath = doBackup ? backupfiles.getTempFilePath()
1666 PrintWriter out = new PrintWriter(new FileWriter(tempFilePath));
1670 AlignFrame.this.setTitle(file);
1671 statusBar.setText(MessageManager.formatMessage(
1672 "label.successfully_saved_to_file_in_format",
1674 { fileName, format.getName() }));
1675 lastSaveSuccessful = true;
1676 } catch (Exception ex)
1678 lastSaveSuccessful = false;
1679 ex.printStackTrace();
1684 backupfiles.setWriteSuccess(lastSaveSuccessful);
1685 // do the backup file roll and rename the temp file to actual file
1686 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1693 * show dialog with export options if applicable; else just do it
1695 if (AlignExportOptions.isNeeded(viewport, format))
1697 AlignExportOptions choices = new AlignExportOptions(
1698 alignPanel.getAlignViewport(), format, options);
1699 choices.setResponseAction(0, outputAction);
1700 choices.setResponseAction(1, cancelAction);
1701 choices.showDialog();
1710 * Outputs the alignment to textbox in the requested format, if necessary
1711 * first prompting the user for whether to include hidden regions or
1714 * @param fileFormatName
1718 protected void outputText_actionPerformed(String fileFormatName)
1720 FileFormatI fileFormat = FileFormats.getInstance()
1721 .forName(fileFormatName);
1722 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1723 Runnable outputAction = new Runnable()
1729 // todo defer this to inside formatSequences (or later)
1730 AlignmentExportData exportData = viewport
1731 .getAlignExportData(options);
1732 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1733 cap.setForInput(null);
1736 FileFormatI format = fileFormat;
1737 cap.setText(new FormatAdapter(alignPanel, options)
1738 .formatSequences(format, exportData.getAlignment(),
1739 exportData.getOmitHidden(),
1740 exportData.getStartEndPostions(),
1741 viewport.getAlignment().getHiddenColumns()));
1742 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1743 "label.alignment_output_command", new Object[]
1744 { fileFormat.getName() }), 600, 500);
1745 } catch (OutOfMemoryError oom)
1747 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1755 * show dialog with export options if applicable; else just do it
1757 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1759 AlignExportOptions choices = new AlignExportOptions(
1760 alignPanel.getAlignViewport(), fileFormat, options);
1761 choices.setResponseAction(0, outputAction);
1762 choices.showDialog();
1778 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1780 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1781 htmlSVG.exportHTML(null);
1785 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1787 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1788 bjs.exportHTML(null);
1793 public void createImageMap(File file, String image)
1795 alignPanel.makePNGImageMap(file, image);
1799 * Creates a PNG image of the alignment and writes it to the given file. If
1800 * the file is null, the user is prompted to choose a file.
1806 public void createPNG(File f)
1808 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1812 * Creates an EPS image of the alignment and writes it to the given file. If
1813 * the file is null, the user is prompted to choose a file.
1819 public void createEPS(File f)
1821 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1825 * Creates an SVG image of the alignment and writes it to the given file. If
1826 * the file is null, the user is prompted to choose a file.
1832 public void createSVG(File f)
1834 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1838 public void pageSetup_actionPerformed(ActionEvent e)
1840 PrinterJob printJob = PrinterJob.getPrinterJob();
1841 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1852 public void printMenuItem_actionPerformed(ActionEvent e)
1854 // Putting in a thread avoids Swing painting problems
1855 PrintThread thread = new PrintThread(alignPanel);
1860 public void exportFeatures_actionPerformed(ActionEvent e)
1862 new AnnotationExporter(alignPanel).exportFeatures();
1866 public void exportAnnotations_actionPerformed(ActionEvent e)
1868 new AnnotationExporter(alignPanel).exportAnnotations();
1872 public void associatedData_actionPerformed(ActionEvent e)
1873 throws IOException, InterruptedException
1875 final JalviewFileChooser chooser = new JalviewFileChooser(
1876 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1877 chooser.setFileView(new JalviewFileView());
1878 String tooltip = MessageManager
1879 .getString("label.load_jalview_annotations");
1880 chooser.setDialogTitle(tooltip);
1881 chooser.setToolTipText(tooltip);
1882 chooser.setResponseHandler(0, new Runnable()
1888 String choice = chooser.getSelectedFile().getPath();
1889 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1890 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1894 chooser.showOpenDialog(this);
1898 * Close the current view or all views in the alignment frame. If the frame
1899 * only contains one view then the alignment will be removed from memory.
1901 * @param closeAllTabs
1905 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1907 if (alignPanels != null && alignPanels.size() < 2)
1909 closeAllTabs = true;
1914 if (alignPanels != null)
1918 if (this.isClosed())
1920 // really close all the windows - otherwise wait till
1921 // setClosed(true) is called
1922 for (int i = 0; i < alignPanels.size(); i++)
1924 AlignmentPanel ap = alignPanels.get(i);
1931 closeView(alignPanel);
1936 if (featureSettings != null && featureSettings.isOpen())
1938 featureSettings.close();
1939 featureSettings = null;
1942 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1943 * be called recursively, with the frame now in 'closed' state
1945 this.setClosed(true);
1947 } catch (Exception ex)
1949 ex.printStackTrace();
1954 * Close the specified panel and close up tabs appropriately.
1956 * @param panelToClose
1959 public void closeView(AlignmentPanel panelToClose)
1961 int index = tabbedPane.getSelectedIndex();
1962 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1963 alignPanels.remove(panelToClose);
1964 panelToClose.closePanel();
1965 panelToClose = null;
1967 tabbedPane.removeTabAt(closedindex);
1968 tabbedPane.validate();
1970 if (index > closedindex || index == tabbedPane.getTabCount())
1972 // modify currently selected tab index if necessary.
1976 this.tabSelectionChanged(index);
1983 void updateEditMenuBar()
1986 if (viewport.getHistoryList().size() > 0)
1988 undoMenuItem.setEnabled(true);
1989 CommandI command = viewport.getHistoryList().peek();
1990 undoMenuItem.setText(MessageManager
1991 .formatMessage("label.undo_command", new Object[]
1992 { command.getDescription() }));
1996 undoMenuItem.setEnabled(false);
1997 undoMenuItem.setText(MessageManager.getString("action.undo"));
2000 if (viewport.getRedoList().size() > 0)
2002 redoMenuItem.setEnabled(true);
2004 CommandI command = viewport.getRedoList().peek();
2005 redoMenuItem.setText(MessageManager
2006 .formatMessage("label.redo_command", new Object[]
2007 { command.getDescription() }));
2011 redoMenuItem.setEnabled(false);
2012 redoMenuItem.setText(MessageManager.getString("action.redo"));
2017 public void addHistoryItem(CommandI command)
2019 if (command.getSize() > 0)
2021 viewport.addToHistoryList(command);
2022 viewport.clearRedoList();
2023 updateEditMenuBar();
2024 viewport.updateHiddenColumns();
2025 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
2026 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2027 // viewport.getColumnSelection()
2028 // .getHiddenColumns().size() > 0);
2034 * @return alignment objects for all views
2037 AlignmentI[] getViewAlignments()
2039 if (alignPanels != null)
2041 AlignmentI[] als = new AlignmentI[alignPanels.size()];
2043 for (AlignmentPanel ap : alignPanels)
2045 als[i++] = ap.av.getAlignment();
2049 if (viewport != null)
2051 return new AlignmentI[] { viewport.getAlignment() };
2064 protected void undoMenuItem_actionPerformed(ActionEvent e)
2066 if (viewport.getHistoryList().isEmpty())
2070 CommandI command = viewport.getHistoryList().pop();
2071 viewport.addToRedoList(command);
2072 command.undoCommand(getViewAlignments());
2074 AlignmentViewport originalSource = getOriginatingSource(command);
2075 updateEditMenuBar();
2077 if (originalSource != null)
2079 if (originalSource != viewport)
2082 "Implementation worry: mismatch of viewport origin for undo");
2084 originalSource.updateHiddenColumns();
2085 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
2087 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2088 // viewport.getColumnSelection()
2089 // .getHiddenColumns().size() > 0);
2090 originalSource.notifyAlignment();
2103 protected void redoMenuItem_actionPerformed(ActionEvent e)
2105 if (viewport.getRedoList().size() < 1)
2110 CommandI command = viewport.getRedoList().pop();
2111 viewport.addToHistoryList(command);
2112 command.doCommand(getViewAlignments());
2114 AlignmentViewport originalSource = getOriginatingSource(command);
2115 updateEditMenuBar();
2117 if (originalSource != null)
2120 if (originalSource != viewport)
2123 "Implementation worry: mismatch of viewport origin for redo");
2125 originalSource.updateHiddenColumns();
2126 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
2128 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2129 // viewport.getColumnSelection()
2130 // .getHiddenColumns().size() > 0);
2131 originalSource.notifyAlignment();
2136 AlignmentViewport getOriginatingSource(CommandI command)
2138 AlignmentViewport originalSource = null;
2139 // For sequence removal and addition, we need to fire
2140 // the property change event FROM the viewport where the
2141 // original alignment was altered
2142 AlignmentI al = null;
2143 if (command instanceof EditCommand)
2145 EditCommand editCommand = (EditCommand) command;
2146 al = editCommand.getAlignment();
2147 List<Component> comps = PaintRefresher.components
2148 .get(viewport.getSequenceSetId());
2150 for (Component comp : comps)
2152 if (comp instanceof AlignmentPanel)
2154 if (al == ((AlignmentPanel) comp).av.getAlignment())
2156 originalSource = ((AlignmentPanel) comp).av;
2163 if (originalSource == null)
2165 // The original view is closed, we must validate
2166 // the current view against the closed view first
2169 PaintRefresher.validateSequences(al, viewport.getAlignment());
2172 originalSource = viewport;
2175 return originalSource;
2185 public void moveSelectedSequences(boolean up)
2187 SequenceGroup sg = viewport.getSelectionGroup();
2193 viewport.getAlignment().moveSelectedSequencesByOne(sg,
2194 viewport.getHiddenRepSequences(), up);
2195 alignPanel.paintAlignment(true, false);
2198 synchronized void slideSequences(boolean right, int size)
2200 List<SequenceI> sg = new ArrayList<>();
2201 if (viewport.cursorMode)
2203 sg.add(viewport.getAlignment()
2204 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
2206 else if (viewport.getSelectionGroup() != null
2207 && viewport.getSelectionGroup().getSize() != viewport
2208 .getAlignment().getHeight())
2210 sg = viewport.getSelectionGroup()
2211 .getSequences(viewport.getHiddenRepSequences());
2219 List<SequenceI> invertGroup = new ArrayList<>();
2221 for (SequenceI seq : viewport.getAlignment().getSequences())
2223 if (!sg.contains(seq))
2225 invertGroup.add(seq);
2229 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
2231 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
2232 for (int i = 0; i < invertGroup.size(); i++)
2234 seqs2[i] = invertGroup.get(i);
2237 SlideSequencesCommand ssc;
2240 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
2241 viewport.getGapCharacter());
2245 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
2246 viewport.getGapCharacter());
2249 int groupAdjustment = 0;
2250 if (ssc.getGapsInsertedBegin() && right)
2252 if (viewport.cursorMode)
2254 alignPanel.getSeqPanel().moveCursor(size, 0);
2258 groupAdjustment = size;
2261 else if (!ssc.getGapsInsertedBegin() && !right)
2263 if (viewport.cursorMode)
2265 alignPanel.getSeqPanel().moveCursor(-size, 0);
2269 groupAdjustment = -size;
2273 if (groupAdjustment != 0)
2275 viewport.getSelectionGroup().setStartRes(
2276 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
2277 viewport.getSelectionGroup().setEndRes(
2278 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
2282 * just extend the last slide command if compatible; but not if in
2283 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
2285 boolean appendHistoryItem = false;
2286 Deque<CommandI> historyList = viewport.getHistoryList();
2287 boolean inSplitFrame = getSplitViewContainer() != null;
2288 if (!inSplitFrame && historyList != null && historyList.size() > 0
2289 && historyList.peek() instanceof SlideSequencesCommand)
2291 appendHistoryItem = ssc.appendSlideCommand(
2292 (SlideSequencesCommand) historyList.peek());
2295 if (!appendHistoryItem)
2297 addHistoryItem(ssc);
2311 protected void copy_actionPerformed()
2313 if (viewport.getSelectionGroup() == null)
2317 // TODO: preserve the ordering of displayed alignment annotation in any
2318 // internal paste (particularly sequence associated annotation)
2319 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2320 String[] omitHidden = null;
2322 if (viewport.hasHiddenColumns())
2324 omitHidden = viewport.getViewAsString(true);
2327 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2328 seqs, omitHidden, null);
2330 StringSelection ss = new StringSelection(output);
2332 Desktop d = Desktop.getInstance();
2335 d.internalCopy = true;
2336 // Its really worth setting the clipboard contents
2337 // to empty before setting the large StringSelection!!
2338 Toolkit.getDefaultToolkit().getSystemClipboard()
2339 .setContents(new StringSelection(""), null);
2341 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2342 Desktop.getInstance());
2343 } catch (OutOfMemoryError er)
2345 new OOMWarning("copying region", er);
2349 HiddenColumns hiddenColumns = null;
2350 if (viewport.hasHiddenColumns())
2352 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2353 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2355 // create new HiddenColumns object with copy of hidden regions
2356 // between startRes and endRes, offset by startRes
2357 hiddenColumns = new HiddenColumns(
2358 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2359 hiddenCutoff, hiddenOffset);
2362 d.jalviewClipboard = new Object[] { seqs,
2363 viewport.getAlignment().getDataset(), hiddenColumns };
2364 setStatus(MessageManager.formatMessage(
2365 "label.copied_sequences_to_clipboard", new Object[]
2366 { Integer.valueOf(seqs.length).toString() }));
2374 * @throws InterruptedException
2375 * @throws IOException
2379 protected void pasteNew_actionPerformed(ActionEvent e)
2380 throws IOException, InterruptedException
2390 * @throws InterruptedException
2391 * @throws IOException
2395 protected void pasteThis_actionPerformed(ActionEvent e)
2396 throws IOException, InterruptedException
2402 * Paste contents of Jalview clipboard
2404 * @param newAlignment
2405 * true to paste to a new alignment, otherwise add to this.
2406 * @throws InterruptedException
2407 * @throws IOException
2409 void paste(boolean newAlignment) throws IOException, InterruptedException
2411 boolean externalPaste = true;
2414 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2415 Transferable contents = c.getContents(this);
2417 if (contents == null)
2426 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2427 if (str.length() < 1)
2432 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2434 } catch (OutOfMemoryError er)
2436 new OOMWarning("Out of memory pasting sequences!!", er);
2440 SequenceI[] sequences;
2441 boolean annotationAdded = false;
2442 AlignmentI alignment = null;
2444 Desktop d = Desktop.getInstance();
2446 if (d.jalviewClipboard != null)
2448 // The clipboard was filled from within Jalview, we must use the
2450 // And dataset from the copied alignment
2451 SequenceI[] newseq = (SequenceI[]) d.jalviewClipboard[0];
2452 // be doubly sure that we create *new* sequence objects.
2453 sequences = new SequenceI[newseq.length];
2454 for (int i = 0; i < newseq.length; i++)
2456 sequences[i] = new Sequence(newseq[i]);
2458 alignment = new Alignment(sequences);
2459 externalPaste = false;
2463 // parse the clipboard as an alignment.
2464 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2466 sequences = alignment.getSequencesArray();
2470 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2476 if (d.jalviewClipboard != null)
2478 // dataset is inherited
2479 alignment.setDataset((Alignment) d.jalviewClipboard[1]);
2483 // new dataset is constructed
2484 alignment.setDataset(null);
2486 alwidth = alignment.getWidth() + 1;
2490 AlignmentI pastedal = alignment; // preserve pasted alignment object
2491 // Add pasted sequences and dataset into existing alignment.
2492 alignment = viewport.getAlignment();
2493 alwidth = alignment.getWidth() + 1;
2494 // decide if we need to import sequences from an existing dataset
2495 boolean importDs = d.jalviewClipboard != null
2496 && d.jalviewClipboard[1] != alignment.getDataset();
2497 // importDs==true instructs us to copy over new dataset sequences from
2498 // an existing alignment
2499 Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2501 // minimum dataset set
2503 for (int i = 0; i < sequences.length; i++)
2507 newDs.addElement(null);
2509 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2511 if (importDs && ds != null)
2513 if (!newDs.contains(ds))
2515 newDs.setElementAt(ds, i);
2516 ds = new Sequence(ds);
2517 // update with new dataset sequence
2518 sequences[i].setDatasetSequence(ds);
2522 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2527 // copy and derive new dataset sequence
2528 sequences[i] = sequences[i].deriveSequence();
2529 alignment.getDataset()
2530 .addSequence(sequences[i].getDatasetSequence());
2531 // TODO: avoid creation of duplicate dataset sequences with a
2532 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2534 alignment.addSequence(sequences[i]); // merges dataset
2538 newDs.clear(); // tidy up
2540 if (alignment.getAlignmentAnnotation() != null)
2542 for (AlignmentAnnotation alan : alignment
2543 .getAlignmentAnnotation())
2545 if (alan.graphGroup > fgroup)
2547 fgroup = alan.graphGroup;
2551 if (pastedal.getAlignmentAnnotation() != null)
2553 // Add any annotation attached to alignment.
2554 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2555 for (int i = 0; i < alann.length; i++)
2557 annotationAdded = true;
2558 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2560 AlignmentAnnotation newann = new AlignmentAnnotation(
2562 if (newann.graphGroup > -1)
2564 if (newGraphGroups.size() <= newann.graphGroup
2565 || newGraphGroups.get(newann.graphGroup) == null)
2567 for (int q = newGraphGroups
2568 .size(); q <= newann.graphGroup; q++)
2570 newGraphGroups.add(q, null);
2572 newGraphGroups.set(newann.graphGroup,
2573 Integer.valueOf(++fgroup));
2575 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2579 newann.padAnnotation(alwidth);
2580 alignment.addAnnotation(newann);
2590 addHistoryItem(new EditCommand(
2591 MessageManager.getString("label.add_sequences"),
2592 Action.PASTE, sequences, 0, alignment.getWidth(),
2595 // Add any annotations attached to sequences
2596 for (int i = 0; i < sequences.length; i++)
2598 if (sequences[i].getAnnotation() != null)
2600 AlignmentAnnotation newann;
2601 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2603 annotationAdded = true;
2604 newann = sequences[i].getAnnotation()[a];
2605 newann.adjustForAlignment();
2606 newann.padAnnotation(alwidth);
2607 if (newann.graphGroup > -1)
2609 if (newann.graphGroup > -1)
2611 if (newGraphGroups.size() <= newann.graphGroup
2612 || newGraphGroups.get(newann.graphGroup) == null)
2614 for (int q = newGraphGroups
2615 .size(); q <= newann.graphGroup; q++)
2617 newGraphGroups.add(q, null);
2619 newGraphGroups.set(newann.graphGroup,
2620 Integer.valueOf(++fgroup));
2622 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2626 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2630 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2638 // propagate alignment changed.
2639 viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2640 if (annotationAdded)
2642 // Duplicate sequence annotation in all views.
2643 AlignmentI[] alview = this.getViewAlignments();
2644 for (int i = 0; i < sequences.length; i++)
2646 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2651 for (int avnum = 0; avnum < alview.length; avnum++)
2653 if (alview[avnum] != alignment)
2655 // duplicate in a view other than the one with input focus
2656 int avwidth = alview[avnum].getWidth() + 1;
2657 // this relies on sann being preserved after we
2658 // modify the sequence's annotation array for each duplication
2659 for (int a = 0; a < sann.length; a++)
2661 AlignmentAnnotation newann = new AlignmentAnnotation(
2663 sequences[i].addAlignmentAnnotation(newann);
2664 newann.padAnnotation(avwidth);
2665 alview[avnum].addAnnotation(newann); // annotation was
2666 // duplicated earlier
2667 // TODO JAL-1145 graphGroups are not updated for sequence
2668 // annotation added to several views. This may cause
2670 alview[avnum].setAnnotationIndex(newann, a);
2675 buildSortByAnnotationScoresMenu();
2677 viewport.notifyAlignment();
2678 if (alignPanels != null)
2680 for (AlignmentPanel ap : alignPanels)
2682 ap.validateAnnotationDimensions(false);
2687 alignPanel.validateAnnotationDimensions(false);
2693 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2695 String newtitle = new String("Copied sequences");
2697 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2699 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2700 af.viewport.setHiddenColumns(hc);
2703 // >>>This is a fix for the moment, until a better solution is
2705 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2706 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2707 .getFeatureRenderer());
2709 // TODO: maintain provenance of an alignment, rather than just make the
2710 // title a concatenation of operations.
2713 if (title.startsWith("Copied sequences"))
2719 newtitle = newtitle.concat("- from " + title);
2724 newtitle = new String("Pasted sequences");
2727 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2732 } catch (Exception ex)
2734 ex.printStackTrace();
2735 System.out.println("Exception whilst pasting: " + ex);
2736 // could be anything being pasted in here
2741 protected void expand_newalign(ActionEvent e)
2745 AlignmentI alignment = AlignmentUtils
2746 .expandContext(getViewport().getAlignment(), -1);
2747 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2749 String newtitle = new String("Flanking alignment");
2750 Desktop d = Desktop.getInstance();
2751 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2753 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2754 af.viewport.setHiddenColumns(hc);
2757 // >>>This is a fix for the moment, until a better solution is
2759 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2760 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2761 .getFeatureRenderer());
2763 // TODO: maintain provenance of an alignment, rather than just make the
2764 // title a concatenation of operations.
2766 if (title.startsWith("Copied sequences"))
2772 newtitle = newtitle.concat("- from " + title);
2776 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2778 } catch (Exception ex)
2780 ex.printStackTrace();
2781 System.out.println("Exception whilst pasting: " + ex);
2782 // could be anything being pasted in here
2783 } catch (OutOfMemoryError oom)
2785 new OOMWarning("Viewing flanking region of alignment", oom);
2790 * Action Cut (delete and copy) the selected region
2794 protected void cut_actionPerformed()
2796 copy_actionPerformed();
2797 delete_actionPerformed();
2801 * Performs menu option to Delete the currently selected region
2805 protected void delete_actionPerformed()
2808 SequenceGroup sg = viewport.getSelectionGroup();
2814 Runnable okAction = new Runnable()
2820 SequenceI[] cut = sg.getSequences()
2821 .toArray(new SequenceI[sg.getSize()]);
2823 addHistoryItem(new EditCommand(
2824 MessageManager.getString("label.cut_sequences"), Action.CUT,
2825 cut, sg.getStartRes(),
2826 sg.getEndRes() - sg.getStartRes() + 1,
2827 viewport.getAlignment()));
2829 viewport.setSelectionGroup(null);
2830 viewport.sendSelection();
2831 viewport.getAlignment().deleteGroup(sg);
2833 viewport.notifyAlignment();
2835 if (viewport.getAlignment().getHeight() < 1)
2839 AlignFrame.this.setClosed(true);
2840 } catch (Exception ex)
2850 * If the cut affects all sequences, prompt for confirmation
2852 boolean wholeHeight = sg.getSize() == viewport.getAlignment()
2854 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2855 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2856 if (wholeHeight && wholeWidth)
2858 JvOptionPane dialog = JvOptionPane
2859 .newOptionDialog(Desktop.getDesktopPane());
2860 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2861 Object[] options = new Object[] {
2862 MessageManager.getString("action.ok"),
2863 MessageManager.getString("action.cancel") };
2864 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2865 MessageManager.getString("label.delete_all"),
2866 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2867 options, options[0]);
2883 protected void deleteGroups_actionPerformed(ActionEvent e)
2885 if (avc.deleteGroups())
2887 updateAll(viewport.getSequenceSetId());
2891 private void updateAll(String id)
2895 // this will force a non-fast repaint of both the IdPanel and SeqPanel
2896 alignPanel.getIdPanel().getIdCanvas().setNoFastPaint();
2897 alignPanel.getSeqPanel().seqCanvas.setNoFastPaint();
2898 alignPanel.repaint();
2903 PaintRefresher.Refresh(this, id);
2904 alignPanel.paintAlignment(true, true);
2906 alignPanel.updateAnnotation();
2917 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2919 alignPanel.selectAllSequences();
2930 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2932 alignPanel.deselectAllSequences();
2943 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2945 SequenceGroup sg = viewport.getSelectionGroup();
2949 alignPanel.selectAllSequences();
2954 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2956 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2958 // JAL-2034 - should delegate to
2959 // alignPanel to decide if overview needs
2962 alignPanel.paintAlignment(true, false);
2963 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2964 viewport.sendSelection();
2968 public void invertColSel_actionPerformed(ActionEvent e)
2970 viewport.invertColumnSelection();
2971 alignPanel.paintAlignment(true, false);
2972 viewport.sendSelection();
2983 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2985 trimAlignment(true);
2996 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2998 trimAlignment(false);
3001 void trimAlignment(boolean trimLeft)
3003 ColumnSelection colSel = viewport.getColumnSelection();
3006 if (!colSel.isEmpty())
3010 column = colSel.getMin();
3014 column = colSel.getMax();
3018 if (viewport.getSelectionGroup() != null)
3020 seqs = viewport.getSelectionGroup()
3021 .getSequencesAsArray(viewport.getHiddenRepSequences());
3025 seqs = viewport.getAlignment().getSequencesArray();
3028 TrimRegionCommand trimRegion;
3031 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
3032 column, viewport.getAlignment());
3033 viewport.getRanges().setStartRes(0);
3037 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
3038 column, viewport.getAlignment());
3041 setStatus(MessageManager.formatMessage("label.removed_columns",
3043 { Integer.valueOf(trimRegion.getSize()).toString() }));
3045 addHistoryItem(trimRegion);
3047 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3049 if ((trimLeft && !sg.adjustForRemoveLeft(column))
3050 || (!trimLeft && !sg.adjustForRemoveRight(column)))
3052 viewport.getAlignment().deleteGroup(sg);
3056 viewport.notifyAlignment();
3069 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
3071 int start = 0, end = viewport.getAlignment().getWidth() - 1;
3074 if (viewport.getSelectionGroup() != null)
3076 seqs = viewport.getSelectionGroup()
3077 .getSequencesAsArray(viewport.getHiddenRepSequences());
3078 start = viewport.getSelectionGroup().getStartRes();
3079 end = viewport.getSelectionGroup().getEndRes();
3083 seqs = viewport.getAlignment().getSequencesArray();
3086 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
3087 "Remove Gapped Columns", seqs, start, end,
3088 viewport.getAlignment());
3090 addHistoryItem(removeGapCols);
3092 setStatus(MessageManager.formatMessage("label.removed_empty_columns",
3094 { Integer.valueOf(removeGapCols.getSize()).toString() }));
3096 // This is to maintain viewport position on first residue
3097 // of first sequence
3098 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3099 ViewportRanges ranges = viewport.getRanges();
3100 int startRes = seq.findPosition(ranges.getStartRes());
3101 // ShiftList shifts;
3102 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
3103 // edit.alColumnChanges=shifts.getInverse();
3104 // if (viewport.hasHiddenColumns)
3105 // viewport.getColumnSelection().compensateForEdits(shifts);
3106 ranges.setStartRes(seq.findIndex(startRes) - 1);
3107 viewport.notifyAlignment();
3120 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
3122 int start = 0, end = viewport.getAlignment().getWidth() - 1;
3125 if (viewport.getSelectionGroup() != null)
3127 seqs = viewport.getSelectionGroup()
3128 .getSequencesAsArray(viewport.getHiddenRepSequences());
3129 start = viewport.getSelectionGroup().getStartRes();
3130 end = viewport.getSelectionGroup().getEndRes();
3134 seqs = viewport.getAlignment().getSequencesArray();
3137 // This is to maintain viewport position on first residue
3138 // of first sequence
3139 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3140 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
3142 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
3143 viewport.getAlignment()));
3145 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
3146 viewport.notifyAlignment();
3158 public void padGapsMenuitem_actionPerformed(ActionEvent e)
3160 viewport.setPadGaps(padGapsMenuitem.isSelected());
3161 viewport.notifyAlignment();
3173 public void findMenuItem_actionPerformed(ActionEvent e)
3179 * Create a new view of the current alignment.
3183 public void newView_actionPerformed(ActionEvent e)
3185 newView(null, true);
3189 * Creates and shows a new view of the current alignment.
3192 * title of newly created view; if null, one will be generated
3193 * @param copyAnnotation
3194 * if true then duplicate all annnotation, groups and settings
3195 * @return new alignment panel, already displayed.
3198 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
3201 * Create a new AlignmentPanel (with its own, new Viewport)
3203 AlignmentPanel newap = new jalview.project.Jalview2XML()
3204 .copyAlignPanel(alignPanel);
3205 if (!copyAnnotation)
3208 * remove all groups and annotation except for the automatic stuff
3210 newap.av.getAlignment().deleteAllGroups();
3211 newap.av.getAlignment().deleteAllAnnotations(false);
3214 newap.av.setGatherViewsHere(false);
3216 if (viewport.getViewName() == null)
3218 viewport.setViewName(
3219 MessageManager.getString("label.view_name_original"));
3223 * Views share the same edits undo and redo stacks
3225 newap.av.setHistoryList(viewport.getHistoryList());
3226 newap.av.setRedoList(viewport.getRedoList());
3229 * copy any visualisation settings that are not saved in the project
3231 newap.av.setColourAppliesToAllGroups(
3232 viewport.getColourAppliesToAllGroups());
3235 * Views share the same mappings; need to deregister any new mappings
3236 * created by copyAlignPanel, and register the new reference to the shared
3239 newap.av.replaceMappings(viewport.getAlignment());
3242 * start up cDNA consensus (if applicable) now mappings are in place
3244 if (newap.av.initComplementConsensus())
3246 newap.refresh(true); // adjust layout of annotations
3249 newap.av.setViewName(getNewViewName(viewTitle));
3251 addAlignmentPanel(newap, true);
3252 newap.alignmentChanged();
3254 if (alignPanels.size() == 2)
3256 viewport.setGatherViewsHere(true);
3258 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
3263 * Make a new name for the view, ensuring it is unique within the current
3264 * sequenceSetId. (This used to be essential for Jalview Project archives, but
3265 * these now use viewId. Unique view names are still desirable for usability.)
3271 protected String getNewViewName(String viewTitle)
3273 int index = Desktop.getViewCount(viewport.getSequenceSetId());
3274 boolean addFirstIndex = false;
3275 if (viewTitle == null || viewTitle.trim().length() == 0)
3277 viewTitle = MessageManager.getString("action.view");
3278 addFirstIndex = true;
3282 index = 1;// we count from 1 if given a specific name
3284 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
3286 List<Component> comps = PaintRefresher.components
3287 .get(viewport.getSequenceSetId());
3289 List<String> existingNames = getExistingViewNames(comps);
3291 while (existingNames.contains(newViewName))
3293 newViewName = viewTitle + " " + (++index);
3299 * Returns a list of distinct view names found in the given list of
3300 * components. View names are held on the viewport of an AlignmentPanel.
3306 protected List<String> getExistingViewNames(List<Component> comps)
3308 List<String> existingNames = new ArrayList<>();
3309 for (Component comp : comps)
3311 if (comp instanceof AlignmentPanel)
3313 AlignmentPanel ap = (AlignmentPanel) comp;
3314 if (!existingNames.contains(ap.av.getViewName()))
3316 existingNames.add(ap.av.getViewName());
3320 return existingNames;
3324 * Explode tabbed views into separate windows.
3328 public void expandViews_actionPerformed(ActionEvent e)
3330 Desktop.explodeViews(this);
3334 * Gather views in separate windows back into a tabbed presentation.
3338 public void gatherViews_actionPerformed(ActionEvent e)
3340 Desktop.getInstance().gatherViews(this);
3351 public void font_actionPerformed(ActionEvent e)
3353 new FontChooser(alignPanel);
3364 protected void seqLimit_actionPerformed(ActionEvent e)
3366 viewport.setShowJVSuffix(seqLimits.isSelected());
3368 alignPanel.getIdPanel().getIdCanvas()
3369 .setPreferredSize(alignPanel.calculateIdWidth());
3370 alignPanel.paintAlignment(true, false);
3374 public void idRightAlign_actionPerformed(ActionEvent e)
3376 viewport.setRightAlignIds(idRightAlign.isSelected());
3377 alignPanel.paintAlignment(false, false);
3381 public void centreColumnLabels_actionPerformed(ActionEvent e)
3383 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3384 alignPanel.paintAlignment(false, false);
3390 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3394 protected void followHighlight_actionPerformed()
3397 * Set the 'follow' flag on the Viewport (and scroll to position if now
3400 final boolean state = this.followHighlightMenuItem.getState();
3401 viewport.setFollowHighlight(state);
3404 alignPanel.scrollToPosition(viewport.getSearchResults());
3416 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3418 viewport.setColourText(colourTextMenuItem.isSelected());
3419 alignPanel.paintAlignment(false, false);
3430 public void wrapMenuItem_actionPerformed(ActionEvent e)
3432 scaleAbove.setVisible(wrapMenuItem.isSelected());
3433 scaleLeft.setVisible(wrapMenuItem.isSelected());
3434 scaleRight.setVisible(wrapMenuItem.isSelected());
3435 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3436 alignPanel.updateLayout();
3440 public void showAllSeqs_actionPerformed(ActionEvent e)
3442 viewport.showAllHiddenSeqs();
3446 public void showAllColumns_actionPerformed(ActionEvent e)
3448 viewport.showAllHiddenColumns();
3449 alignPanel.paintAlignment(true, true);
3450 viewport.sendSelection();
3454 public void hideSelSequences_actionPerformed(ActionEvent e)
3456 viewport.hideAllSelectedSeqs();
3460 * called by key handler and the hide all/show all menu items
3466 protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3469 boolean hide = false;
3470 SequenceGroup sg = viewport.getSelectionGroup();
3471 if (!toggleSeqs && !toggleCols)
3473 // Hide everything by the current selection - this is a hack - we do the
3474 // invert and then hide
3475 // first check that there will be visible columns after the invert.
3476 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3477 && sg.getStartRes() <= sg.getEndRes()))
3479 // now invert the sequence set, if required - empty selection implies
3480 // that no hiding is required.
3483 invertSequenceMenuItem_actionPerformed(null);
3484 sg = viewport.getSelectionGroup();
3488 viewport.expandColSelection(sg, true);
3489 // finally invert the column selection and get the new sequence
3491 invertColSel_actionPerformed(null);
3498 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3500 hideSelSequences_actionPerformed(null);
3503 else if (!(toggleCols && viewport.hasSelectedColumns()))
3505 showAllSeqs_actionPerformed(null);
3511 if (viewport.hasSelectedColumns())
3513 hideSelColumns_actionPerformed(null);
3516 viewport.setSelectionGroup(sg);
3521 showAllColumns_actionPerformed(null);
3530 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3531 * event.ActionEvent)
3535 public void hideAllButSelection_actionPerformed(ActionEvent e)
3537 toggleHiddenRegions(false, false);
3538 viewport.sendSelection();
3545 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3550 public void hideAllSelection_actionPerformed(ActionEvent e)
3552 SequenceGroup sg = viewport.getSelectionGroup();
3553 viewport.expandColSelection(sg, false);
3554 viewport.hideAllSelectedSeqs();
3555 viewport.hideSelectedColumns();
3556 alignPanel.updateLayout();
3557 alignPanel.paintAlignment(true, true);
3558 viewport.sendSelection();
3565 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3570 public void showAllhidden_actionPerformed(ActionEvent e)
3572 viewport.showAllHiddenColumns();
3573 viewport.showAllHiddenSeqs();
3574 alignPanel.paintAlignment(true, true);
3575 viewport.sendSelection();
3579 public void hideSelColumns_actionPerformed(ActionEvent e)
3581 viewport.hideSelectedColumns();
3582 alignPanel.updateLayout();
3583 alignPanel.paintAlignment(true, true);
3584 viewport.sendSelection();
3588 public void hiddenMarkers_actionPerformed(ActionEvent e)
3590 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3602 protected void scaleAbove_actionPerformed(ActionEvent e)
3604 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3605 alignPanel.updateLayout();
3606 alignPanel.paintAlignment(true, false);
3617 protected void scaleLeft_actionPerformed(ActionEvent e)
3619 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3620 alignPanel.updateLayout();
3621 alignPanel.paintAlignment(true, false);
3632 protected void scaleRight_actionPerformed(ActionEvent e)
3634 viewport.setScaleRightWrapped(scaleRight.isSelected());
3635 alignPanel.updateLayout();
3636 alignPanel.paintAlignment(true, false);
3647 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3649 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3650 alignPanel.paintAlignment(false, false);
3661 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3663 viewport.setShowText(viewTextMenuItem.isSelected());
3664 alignPanel.paintAlignment(false, false);
3675 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3677 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3678 alignPanel.paintAlignment(false, false);
3681 public FeatureSettings featureSettings;
3684 public FeatureSettingsControllerI getFeatureSettingsUI()
3686 return featureSettings;
3690 public void featureSettings_actionPerformed(ActionEvent e)
3692 showFeatureSettingsUI();
3696 public FeatureSettingsControllerI showFeatureSettingsUI()
3698 if (featureSettings != null)
3700 featureSettings.closeOldSettings();
3701 featureSettings = null;
3703 if (!showSeqFeatures.isSelected())
3705 // make sure features are actually displayed
3706 showSeqFeatures.setSelected(true);
3707 showSeqFeatures_actionPerformed(null);
3709 featureSettings = new FeatureSettings(this);
3710 return featureSettings;
3714 * Set or clear 'Show Sequence Features'
3721 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3723 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3724 alignPanel.paintAlignment(true, true);
3728 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3729 * the annotations panel as a whole.
3731 * The options to show/hide all annotations should be enabled when the panel
3732 * is shown, and disabled when the panel is hidden.
3738 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3740 final boolean setVisible = annotationPanelMenuItem.isSelected();
3741 viewport.setShowAnnotation(setVisible);
3742 syncAnnotationMenuItems(setVisible);
3743 alignPanel.updateLayout();
3745 SwingUtilities.invokeLater(new Runnable() {
3750 alignPanel.updateScrollBarsFromRanges();
3756 private void syncAnnotationMenuItems(boolean setVisible)
3758 showAllSeqAnnotations.setEnabled(setVisible);
3759 hideAllSeqAnnotations.setEnabled(setVisible);
3760 showAllAlAnnotations.setEnabled(setVisible);
3761 hideAllAlAnnotations.setEnabled(setVisible);
3765 public void alignmentProperties()
3768 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3771 String content = MessageManager.formatMessage("label.html_content",
3773 { contents.toString() });
3776 if (Platform.isJS())
3778 JLabel textLabel = new JLabel();
3779 textLabel.setText(content);
3780 textLabel.setBackground(Color.WHITE);
3782 pane = new JPanel(new BorderLayout());
3783 ((JPanel) pane).setOpaque(true);
3784 pane.setBackground(Color.WHITE);
3785 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3794 JEditorPane editPane = new JEditorPane("text/html", "");
3795 editPane.setEditable(false);
3796 editPane.setText(content);
3800 JInternalFrame frame = new JInternalFrame();
3802 frame.getContentPane().add(new JScrollPane(pane));
3804 Desktop.addInternalFrame(frame, MessageManager
3805 .formatMessage("label.alignment_properties", new Object[]
3806 { getTitle() }), 500, 400);
3817 public void overviewMenuItem_actionPerformed(ActionEvent e)
3819 if (alignPanel.overviewPanel != null)
3824 JInternalFrame frame = new JInternalFrame();
3826 // BH 2019.07.26 we allow for an embedded
3827 // undecorated overview with defined size
3828 frame.setName(Platform.getAppID("overview"));
3830 Dimension dim = Platform.getDimIfEmbedded(frame, -1, -1);
3831 if (dim != null && dim.width == 0)
3833 dim = null; // hidden, not embedded
3835 OverviewPanel overview = new OverviewPanel(alignPanel, dim);
3837 frame.setContentPane(overview);
3840 dim = new Dimension();
3841 // was frame.getSize(), but that is 0,0 at this point;
3845 // we are imbedding, and so we have an undecorated frame
3846 // and we can set the the frame dimensions accordingly.
3848 // allowing for unresizable option using, style="resize:none"
3849 boolean resizable = (Platform.getEmbeddedAttribute(frame,
3850 "resize") != "none");
3851 Desktop.addInternalFrame(frame, MessageManager
3852 .formatMessage("label.overview_params", new Object[]
3853 { this.getTitle() }), Desktop.FRAME_MAKE_VISIBLE, dim.width,
3854 dim.height, resizable, Desktop.FRAME_ALLOW_ANY_SIZE);
3856 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3857 frame.addInternalFrameListener(
3858 new javax.swing.event.InternalFrameAdapter()
3862 public void internalFrameClosed(
3863 javax.swing.event.InternalFrameEvent evt)
3866 alignPanel.setOverviewPanel(null);
3869 if (getKeyListeners().length > 0)
3871 frame.addKeyListener(getKeyListeners()[0]);
3874 alignPanel.setOverviewPanel(overview);
3878 public void textColour_actionPerformed()
3880 new TextColourChooser().chooseColour(alignPanel, null);
3884 * public void covariationColour_actionPerformed() {
3886 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3891 public void annotationColour_actionPerformed()
3893 new AnnotationColourChooser(viewport, alignPanel);
3897 public void annotationColumn_actionPerformed(ActionEvent e)
3899 new AnnotationColumnChooser(viewport, alignPanel);
3903 * Action on the user checking or unchecking the option to apply the selected
3904 * colour scheme to all groups. If unchecked, groups may have their own
3905 * independent colour schemes.
3911 public void applyToAllGroups_actionPerformed(boolean selected)
3913 viewport.setColourAppliesToAllGroups(selected);
3917 * Action on user selecting a colour from the colour menu
3920 * the name (not the menu item label!) of the colour scheme
3924 public void changeColour_actionPerformed(String name)
3927 * 'User Defined' opens a panel to configure or load a
3928 * user-defined colour scheme
3930 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3932 new UserDefinedColours(alignPanel);
3937 * otherwise set the chosen colour scheme (or null for 'None')
3939 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3940 viewport, viewport.getAlignment(),
3941 viewport.getHiddenRepSequences());
3946 * Actions on setting or changing the alignment colour scheme
3952 public void changeColour(ColourSchemeI cs)
3954 // TODO: pull up to controller method
3955 ColourMenuHelper.setColourSelected(colourMenu, cs);
3957 viewport.setGlobalColourScheme(cs);
3959 alignPanel.paintAlignment(true, true);
3963 * Show the PID threshold slider panel
3967 protected void modifyPID_actionPerformed()
3969 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3970 alignPanel.getViewName());
3971 SliderPanel.showPIDSlider();
3975 * Show the Conservation slider panel
3979 protected void modifyConservation_actionPerformed()
3981 SliderPanel.setConservationSlider(alignPanel,
3982 viewport.getResidueShading(), alignPanel.getViewName());
3983 SliderPanel.showConservationSlider();
3987 * Action on selecting or deselecting (Colour) By Conservation
3991 public void conservationMenuItem_actionPerformed(boolean selected)
3993 modifyConservation.setEnabled(selected);
3994 viewport.setConservationSelected(selected);
3995 viewport.getResidueShading().setConservationApplied(selected);
3997 changeColour(viewport.getGlobalColourScheme());
4000 modifyConservation_actionPerformed();
4004 SliderPanel.hideConservationSlider();
4009 * Action on selecting or deselecting (Colour) Above PID Threshold
4013 public void abovePIDThreshold_actionPerformed(boolean selected)
4015 modifyPID.setEnabled(selected);
4016 viewport.setAbovePIDThreshold(selected);
4019 viewport.getResidueShading().setThreshold(0,
4020 viewport.isIgnoreGapsConsensus());
4023 changeColour(viewport.getGlobalColourScheme());
4026 modifyPID_actionPerformed();
4030 SliderPanel.hidePIDSlider();
4042 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
4044 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4045 AlignmentSorter.sortByPID(viewport.getAlignment(),
4046 viewport.getAlignment().getSequenceAt(0));
4047 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
4048 viewport.getAlignment()));
4049 alignPanel.paintAlignment(true, false);
4060 public void sortIDMenuItem_actionPerformed(ActionEvent e)
4062 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4063 AlignmentSorter.sortByID(viewport.getAlignment());
4065 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
4066 alignPanel.paintAlignment(true, false);
4077 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
4079 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4080 AlignmentSorter.sortByLength(viewport.getAlignment());
4081 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
4082 viewport.getAlignment()));
4083 alignPanel.paintAlignment(true, false);
4094 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
4096 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4097 AlignmentSorter.sortByGroup(viewport.getAlignment());
4098 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4099 viewport.getAlignment()));
4101 alignPanel.paintAlignment(true, false);
4105 public void sortEValueMenuItem_actionPerformed(ActionEvent e)
4107 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4108 AlignmentSorter.sortByEValue(viewport.getAlignment());
4109 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4110 viewport.getAlignment()));
4111 alignPanel.paintAlignment(true, false);
4116 public void sortBitScoreMenuItem_actionPerformed(ActionEvent e)
4118 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4119 AlignmentSorter.sortByBitScore(viewport.getAlignment());
4120 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4121 viewport.getAlignment()));
4122 alignPanel.paintAlignment(true, false);
4134 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
4136 new RedundancyPanel(alignPanel, this);
4147 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
4149 if ((viewport.getSelectionGroup() == null)
4150 || (viewport.getSelectionGroup().getSize() < 2))
4152 JvOptionPane.showInternalMessageDialog(this,
4153 MessageManager.getString(
4154 "label.you_must_select_least_two_sequences"),
4155 MessageManager.getString("label.invalid_selection"),
4156 JvOptionPane.WARNING_MESSAGE);
4160 JInternalFrame frame = new JInternalFrame();
4161 frame.setContentPane(new PairwiseAlignPanel(viewport));
4162 Desktop.addInternalFrame(frame,
4163 MessageManager.getString("action.pairwise_alignment"), 600,
4169 public void autoCalculate_actionPerformed(ActionEvent e)
4171 viewport.setAutoCalculateConsensusAndConservation(
4172 autoCalculate.isSelected());
4173 if (viewport.getAutoCalculateConsensusAndConservation())
4175 // viewport.autoCalculateConsensus = autoCalculate.isSelected();
4176 // if (viewport.autoCalculateConsensus)
4178 viewport.notifyAlignment();
4183 public void sortByTreeOption_actionPerformed(ActionEvent e)
4185 viewport.sortByTree = sortByTree.isSelected();
4189 protected void listenToViewSelections_actionPerformed(ActionEvent e)
4191 viewport.followSelection = listenToViewSelections.isSelected();
4195 * Constructs a tree panel and adds it to the desktop
4198 * tree type (NJ or AV)
4200 * name of score model used to compute the tree
4202 * parameters for the distance or similarity calculation
4205 void newTreePanel(String type, String modelName,
4206 SimilarityParamsI options)
4208 String frameTitle = "";
4211 boolean onSelection = false;
4212 if (viewport.getSelectionGroup() != null
4213 && viewport.getSelectionGroup().getSize() > 0)
4215 SequenceGroup sg = viewport.getSelectionGroup();
4217 /* Decide if the selection is a column region */
4218 for (SequenceI _s : sg.getSequences())
4220 if (_s.getLength() < sg.getEndRes())
4222 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4223 MessageManager.getString(
4224 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
4225 MessageManager.getString(
4226 "label.sequences_selection_not_aligned"),
4227 JvOptionPane.WARNING_MESSAGE);
4236 if (viewport.getAlignment().getHeight() < 2)
4242 tp = new TreePanel(alignPanel, type, modelName, options);
4243 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
4245 frameTitle += " from ";
4247 if (viewport.getViewName() != null)
4249 frameTitle += viewport.getViewName() + " of ";
4252 frameTitle += this.title;
4254 Dimension dim = Platform.getDimIfEmbedded(tp, 600, 500);
4255 Desktop.addInternalFrame(tp, frameTitle, dim.width, dim.height);
4267 public void addSortByOrderMenuItem(String title,
4268 final AlignmentOrder order)
4270 final JMenuItem item = new JMenuItem(MessageManager
4271 .formatMessage("action.by_title_param", new Object[]
4274 item.addActionListener(new java.awt.event.ActionListener()
4278 public void actionPerformed(ActionEvent e)
4280 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4282 // TODO: JBPNote - have to map order entries to curent SequenceI
4284 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4286 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
4287 viewport.getAlignment()));
4289 alignPanel.paintAlignment(true, false);
4295 * Add a new sort by annotation score menu item
4298 * the menu to add the option to
4300 * the label used to retrieve scores for each sequence on the
4304 public void addSortByAnnotScoreMenuItem(JMenu sort,
4305 final String scoreLabel)
4307 final JMenuItem item = new JMenuItem(scoreLabel);
4309 item.addActionListener(new java.awt.event.ActionListener()
4313 public void actionPerformed(ActionEvent e)
4315 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4316 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4317 viewport.getAlignment());// ,viewport.getSelectionGroup());
4318 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4319 viewport.getAlignment()));
4320 alignPanel.paintAlignment(true, false);
4326 * last hash for alignment's annotation array - used to minimise cost of
4329 protected int _annotationScoreVectorHash;
4332 * search the alignment and rebuild the sort by annotation score submenu the
4333 * last alignment annotation vector hash is stored to minimize cost of
4334 * rebuilding in subsequence calls.
4339 public void buildSortByAnnotationScoresMenu()
4341 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4346 if (viewport.getAlignment().getAlignmentAnnotation()
4347 .hashCode() == _annotationScoreVectorHash)
4352 sortByAnnotScore.removeAll();
4353 Set<String> scoreSorts = new HashSet<>();
4354 for (SequenceI sqa : viewport.getAlignment().getSequences())
4356 AlignmentAnnotation[] anns = sqa.getAnnotation();
4357 for (int i = 0; anns != null && i < anns.length; i++)
4359 AlignmentAnnotation aa = anns[i];
4360 if (aa != null && aa.hasScore() && aa.sequenceRef != null)
4362 scoreSorts.add(aa.label);
4366 for (String label : scoreSorts)
4368 addSortByAnnotScoreMenuItem(sortByAnnotScore, label);
4370 sortByAnnotScore.setVisible(!scoreSorts.isEmpty());
4372 _annotationScoreVectorHash = viewport.getAlignment()
4373 .getAlignmentAnnotation().hashCode();
4377 * Enable (or, if desired, make visible) the By Tree
4378 * submenu only if it has at least one element (or will have).
4382 protected void enableSortMenuOptions()
4384 List<TreePanel> treePanels = getTreePanels();
4385 sortByTreeMenu.setEnabled(!treePanels.isEmpty());
4389 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4390 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4391 * call. Listeners are added to remove the menu item when the treePanel is
4392 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4397 public void buildTreeSortMenu()
4399 sortByTreeMenu.removeAll();
4401 List<TreePanel> treePanels = getTreePanels();
4403 for (final TreePanel tp : treePanels)
4405 final JMenuItem item = new JMenuItem(tp.getTitle());
4406 item.addActionListener(new java.awt.event.ActionListener()
4410 public void actionPerformed(ActionEvent e)
4412 tp.sortByTree_actionPerformed();
4413 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4418 sortByTreeMenu.add(item);
4422 private List<TreePanel> getTreePanels()
4424 List<Component> comps = PaintRefresher.components
4425 .get(viewport.getSequenceSetId());
4426 List<TreePanel> treePanels = new ArrayList<>();
4427 for (Component comp : comps)
4429 if (comp instanceof TreePanel)
4431 treePanels.add((TreePanel) comp);
4437 public boolean sortBy(AlignmentOrder alorder, String undoname)
4439 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4440 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4441 if (undoname != null)
4443 addHistoryItem(new OrderCommand(undoname, oldOrder,
4444 viewport.getAlignment()));
4446 alignPanel.paintAlignment(true, false);
4451 * Work out whether the whole set of sequences or just the selected set will
4452 * be submitted for multiple alignment.
4456 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4458 // Now, check we have enough sequences
4459 AlignmentView msa = null;
4461 if ((viewport.getSelectionGroup() != null)
4462 && (viewport.getSelectionGroup().getSize() > 1))
4464 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4465 // some common interface!
4467 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4468 * SequenceI[sz = seqs.getSize(false)];
4470 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4471 * seqs.getSequenceAt(i); }
4473 msa = viewport.getAlignmentView(true);
4475 else if (viewport.getSelectionGroup() != null
4476 && viewport.getSelectionGroup().getSize() == 1)
4478 int option = JvOptionPane.showConfirmDialog(this,
4479 MessageManager.getString("warn.oneseq_msainput_selection"),
4480 MessageManager.getString("label.invalid_selection"),
4481 JvOptionPane.OK_CANCEL_OPTION);
4482 if (option == JvOptionPane.OK_OPTION)
4484 msa = viewport.getAlignmentView(false);
4489 msa = viewport.getAlignmentView(false);
4495 * Decides what is submitted to a secondary structure prediction service: the
4496 * first sequence in the alignment, or in the current selection, or, if the
4497 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4498 * region or the whole alignment. (where the first sequence in the set is the
4499 * one that the prediction will be for).
4502 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4504 AlignmentView seqs = null;
4506 if ((viewport.getSelectionGroup() != null)
4507 && (viewport.getSelectionGroup().getSize() > 0))
4509 seqs = viewport.getAlignmentView(true);
4513 seqs = viewport.getAlignmentView(false);
4515 // limit sequences - JBPNote in future - could spawn multiple prediction
4517 // TODO: viewport.getAlignment().isAligned is a global state - the local
4518 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4519 if (!viewport.getAlignment().isAligned(false))
4521 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4522 // TODO: if seqs.getSequences().length>1 then should really have warned
4537 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4539 // Pick the tree file
4540 JalviewFileChooser chooser = new JalviewFileChooser(
4541 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4542 chooser.setFileView(new JalviewFileView());
4543 chooser.setDialogTitle(
4544 MessageManager.getString("label.select_newick_like_tree_file"));
4545 chooser.setToolTipText(
4546 MessageManager.getString("label.load_tree_file"));
4548 chooser.setResponseHandler(0, new Runnable()
4554 String filePath = chooser.getSelectedFile().getPath();
4555 Cache.setProperty("LAST_DIRECTORY", filePath);
4556 NewickFile fin = null;
4559 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4560 DataSourceType.FILE));
4561 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4562 } catch (Exception ex)
4564 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4567 .getString("label.problem_reading_tree_file"),
4568 JvOptionPane.WARNING_MESSAGE);
4569 ex.printStackTrace();
4571 if (fin != null && fin.hasWarningMessage())
4573 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4574 fin.getWarningMessage(),
4575 MessageManager.getString(
4576 "label.possible_problem_with_tree_file"),
4577 JvOptionPane.WARNING_MESSAGE);
4581 chooser.showOpenDialog(this);
4584 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4586 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4589 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4590 int h, int x, int y)
4592 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4596 * Add a treeviewer for the tree extracted from a Newick file object to the
4597 * current alignment view
4604 * Associated alignment input data (or null)
4613 * @return TreePanel handle
4616 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4617 AlignmentView input, int w, int h, int x, int y)
4619 TreePanel tp = null;
4625 if (nf.getTree() != null)
4627 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4628 Dimension dim = Platform.getDimIfEmbedded(tp, -1, -1);
4631 dim = new Dimension(w, h);
4635 // no offset, either
4638 tp.setSize(dim.width, dim.height);
4642 tp.setLocation(x, y);
4645 Desktop.addInternalFrame(tp, treeTitle, dim.width, dim.height);
4647 } catch (Exception ex)
4649 ex.printStackTrace();
4655 private WebServicesMenuManager slivkaMenu = new WebServicesMenuManager("slivka", this);
4658 * Schedule the web services menu rebuild to the event dispatch thread.
4660 public void buildWebServicesMenu()
4662 SwingUtilities.invokeLater(() -> {
4663 Cache.log.info("Rebuiling WS menu");
4664 webService.removeAll();
4665 if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
4667 Cache.log.info("Building web service menu for slivka");
4668 SlivkaWSDiscoverer discoverer = SlivkaWSDiscoverer.getInstance();
4669 slivkaMenu.setServices(discoverer);
4670 slivkaMenu.setInProgress(discoverer.isRunning());
4671 slivkaMenu.setNoServices(discoverer.isDone() && !discoverer.hasServices());
4672 webService.add(slivkaMenu.getMenu());
4674 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4676 WSDiscovererI jws2servs = Jws2Discoverer.getInstance();
4677 JMenu submenu = new JMenu("JABAWS");
4678 buildLegacyWebServicesMenu(submenu);
4679 buildWebServicesMenu(jws2servs, submenu);
4680 webService.add(submenu);
4682 build_urlServiceMenu(webService);
4683 build_fetchdbmenu(webService);
4687 private void buildLegacyWebServicesMenu(JMenu menu)
4689 JMenu secstrmenu = new JMenu("Secondary Structure Prediction");
4690 if (Discoverer.getServices() != null && Discoverer.getServices().size() > 0)
4692 var secstrpred = Discoverer.getServices().get("SecStrPred");
4693 if (secstrpred != null)
4695 for (ext.vamsas.ServiceHandle sh : secstrpred)
4697 var menuProvider = Discoverer.getServiceClient(sh);
4698 menuProvider.attachWSMenuEntry(secstrmenu, this);
4702 menu.add(secstrmenu);
4706 * Constructs the web services menu for the given discoverer under the
4707 * specified menu. This method must be called on the EDT
4710 * the discoverer used to build the menu
4712 * parent component which the elements will be attached to
4714 private void buildWebServicesMenu(WSDiscovererI discoverer, JMenu menu)
4716 if (discoverer.hasServices())
4718 PreferredServiceRegistry.getRegistry().populateWSMenuEntry(
4719 discoverer.getServices(), sv -> buildWebServicesMenu(), menu,
4722 if (discoverer.isRunning())
4724 JMenuItem item = new JMenuItem("Service discovery in progress.");
4725 item.setEnabled(false);
4728 else if (!discoverer.hasServices())
4730 JMenuItem item = new JMenuItem("No services available.");
4731 item.setEnabled(false);
4737 * construct any groupURL type service menu entries.
4742 protected void build_urlServiceMenu(JMenu webService)
4744 // TODO: remove this code when 2.7 is released
4745 // DEBUG - alignmentView
4747 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4748 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4750 * public void actionPerformed(ActionEvent e) {
4751 * jalview.datamodel.AlignmentView
4752 * .testSelectionViews(af.viewport.getAlignment(),
4753 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4755 * }); webService.add(testAlView);
4757 // TODO: refactor to RestClient discoverer and merge menu entries for
4758 // rest-style services with other types of analysis/calculation service
4759 // SHmmr test client - still being implemented.
4760 // DEBUG - alignmentView
4762 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4765 client.attachWSMenuEntry(
4766 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4772 * Searches the alignment sequences for xRefs and builds the Show
4773 * Cross-References menu (formerly called Show Products), with database
4774 * sources for which cross-references are found (protein sources for a
4775 * nucleotide alignment and vice versa)
4777 * @return true if Show Cross-references menu should be enabled
4780 public boolean canShowProducts()
4782 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4783 AlignmentI dataset = viewport.getAlignment().getDataset();
4785 showProducts.removeAll();
4786 final boolean dna = viewport.getAlignment().isNucleotide();
4788 if (seqs == null || seqs.length == 0)
4790 // nothing to see here.
4794 boolean showp = false;
4797 List<String> ptypes = new CrossRef(seqs, dataset)
4798 .findXrefSourcesForSequences(dna);
4800 for (final String source : ptypes)
4803 final AlignFrame af = this;
4804 JMenuItem xtype = new JMenuItem(source);
4805 xtype.addActionListener(new ActionListener()
4809 public void actionPerformed(ActionEvent e)
4811 showProductsFor(af.viewport.getSequenceSelection(), dna,
4815 showProducts.add(xtype);
4817 showProducts.setVisible(showp);
4818 showProducts.setEnabled(showp);
4819 } catch (Exception e)
4822 "canShowProducts threw an exception - please report to help@jalview.org",
4830 * Finds and displays cross-references for the selected sequences (protein
4831 * products for nucleotide sequences, dna coding sequences for peptides).
4834 * the sequences to show cross-references for
4836 * true if from a nucleotide alignment (so showing proteins)
4838 * the database to show cross-references for
4841 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4842 final String source)
4844 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4849 * Construct and display a new frame containing the translation of this
4850 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4854 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4856 AlignmentI al = null;
4859 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4861 al = dna.translateCdna(codeTable);
4862 } catch (Exception ex)
4864 jalview.bin.Cache.log.error(
4865 "Exception during translation. Please report this !", ex);
4866 final String msg = MessageManager.getString(
4867 "label.error_when_translating_sequences_submit_bug_report");
4868 final String errorTitle = MessageManager
4869 .getString("label.implementation_error")
4870 + MessageManager.getString("label.translation_failed");
4871 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4872 errorTitle, JvOptionPane.ERROR_MESSAGE);
4875 if (al == null || al.getHeight() == 0)
4877 final String msg = MessageManager.getString(
4878 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4879 final String errorTitle = MessageManager
4880 .getString("label.translation_failed");
4881 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4882 errorTitle, JvOptionPane.WARNING_MESSAGE);
4886 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4887 af.setFileFormat(this.currentFileFormat);
4888 final String newTitle = MessageManager
4889 .formatMessage("label.translation_of_params", new Object[]
4890 { this.getTitle(), codeTable.getId() });
4891 af.setTitle(newTitle);
4892 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4894 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4895 AlignViewport.openSplitFrame(this, af, new Alignment(seqs));
4899 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4906 * Set the file format
4911 public void setFileFormat(FileFormatI format)
4913 this.currentFileFormat = format;
4917 * Try to load a features file onto the alignment.
4920 * contents or path to retrieve file or a File object
4922 * access mode of file (see jalview.io.AlignFile)
4923 * @return true if features file was parsed correctly.
4926 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4929 return avc.parseFeaturesFile(file, sourceType,
4930 Cache.getDefault(Preferences.RELAXEDSEQIDMATCHING, false));
4935 public void refreshFeatureUI(boolean enableIfNecessary)
4937 // note - currently this is only still here rather than in the controller
4938 // because of the featureSettings hard reference that is yet to be
4940 if (enableIfNecessary)
4942 viewport.setShowSequenceFeatures(true);
4943 showSeqFeatures.setSelected(true);
4949 public void dragEnter(DropTargetDragEvent evt)
4954 public void dragExit(DropTargetEvent evt)
4959 public void dragOver(DropTargetDragEvent evt)
4964 public void dropActionChanged(DropTargetDragEvent evt)
4969 public void drop(DropTargetDropEvent evt)
4971 // JAL-1552 - acceptDrop required before getTransferable call for
4972 // Java's Transferable for native dnd
4973 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4974 Transferable t = evt.getTransferable();
4976 final List<Object> files = new ArrayList<>();
4977 List<DataSourceType> protocols = new ArrayList<>();
4981 Desktop.transferFromDropTarget(files, protocols, evt, t);
4982 if (files.size() > 0)
4984 new Thread(new Runnable()
4990 loadDroppedFiles(files, protocols, evt, t);
4994 } catch (Exception e)
4996 e.printStackTrace();
5000 protected void loadDroppedFiles(List<Object> files,
5001 List<DataSourceType> protocols, DropTargetDropEvent evt,
5006 // check to see if any of these files have names matching sequences
5009 SequenceIdMatcher idm = new SequenceIdMatcher(
5010 viewport.getAlignment().getSequencesArray());
5012 * Object[] { String,SequenceI}
5014 ArrayList<Object[]> filesmatched = new ArrayList<>();
5015 ArrayList<Object> filesnotmatched = new ArrayList<>();
5016 for (int i = 0; i < files.size(); i++)
5019 Object fileObj = files.get(i);
5020 String fileName = fileObj.toString();
5022 DataSourceType protocol = (fileObj instanceof File
5023 ? DataSourceType.FILE
5024 : FormatAdapter.checkProtocol(fileName));
5025 if (protocol == DataSourceType.FILE)
5028 if (fileObj instanceof File)
5030 file = (File) fileObj;
5031 Platform.cacheFileData(file);
5035 file = new File(fileName);
5037 pdbfn = file.getName();
5039 else if (protocol == DataSourceType.URL)
5041 URL url = new URL(fileName);
5042 pdbfn = url.getFile();
5044 if (pdbfn.length() > 0)
5046 // attempt to find a match in the alignment
5047 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5048 int l = 0, c = pdbfn.indexOf(".");
5049 while (mtch == null && c != -1)
5054 } while ((c = pdbfn.indexOf(".", l)) > l);
5057 pdbfn = pdbfn.substring(0, l);
5059 mtch = idm.findAllIdMatches(pdbfn);
5066 type = new IdentifyFile().identify(fileObj, protocol);
5067 } catch (Exception ex)
5071 if (type != null && type.isStructureFile())
5073 filesmatched.add(new Object[] { fileObj, protocol, mtch });
5077 // File wasn't named like one of the sequences or wasn't a PDB
5079 filesnotmatched.add(fileObj);
5083 if (filesmatched.size() > 0)
5085 boolean autoAssociate = Cache
5086 .getDefault(Preferences.AUTOASSOCIATE_PDBANDSEQS, false);
5089 String msg = MessageManager.formatMessage(
5090 "label.automatically_associate_structure_files_with_sequences_same_name",
5092 { Integer.valueOf(filesmatched.size()).toString() });
5093 String ttl = MessageManager.getString(
5094 "label.automatically_associate_structure_files_by_name");
5095 int choice = JvOptionPane.showConfirmDialog(this, msg, ttl,
5096 JvOptionPane.YES_NO_OPTION);
5097 autoAssociate = choice == JvOptionPane.YES_OPTION;
5101 for (Object[] fm : filesmatched)
5103 // try and associate
5104 // TODO: may want to set a standard ID naming formalism for
5105 // associating PDB files which have no IDs.
5106 for (SequenceI toassoc : (SequenceI[]) fm[2])
5108 PDBEntry pe = AssociatePdbFileWithSeq.associatePdbWithSeq(
5109 fm[0].toString(), (DataSourceType) fm[1], toassoc,
5113 System.err.println("Associated file : " + (fm[0].toString())
5114 + " with " + toassoc.getDisplayId(true));
5118 // TODO: do we need to update overview ? only if features are
5120 alignPanel.paintAlignment(true, false);
5126 * add declined structures as sequences
5128 for (Object[] o : filesmatched)
5130 filesnotmatched.add(o[0]);
5134 if (filesnotmatched.size() > 0)
5136 if (assocfiles > 0 && (Cache
5137 .getDefault("AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
5138 || JvOptionPane.showConfirmDialog(this,
5139 "<html>" + MessageManager.formatMessage(
5140 "label.ignore_unmatched_dropped_files_info",
5142 { Integer.valueOf(filesnotmatched.size())
5145 MessageManager.getString(
5146 "label.ignore_unmatched_dropped_files"),
5147 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
5151 for (Object fn : filesnotmatched)
5153 loadJalviewDataFile(fn, null, null, null);
5157 } catch (Exception ex)
5159 ex.printStackTrace();
5164 * Attempt to load a "dropped" file or URL string, by testing in turn for
5166 * <li>an Annotation file</li>
5167 * <li>a JNet file</li>
5168 * <li>a features file</li>
5169 * <li>else try to interpret as an alignment file</li>
5173 * either a filename or a URL string.
5174 * @throws InterruptedException
5175 * @throws IOException
5178 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
5179 FileFormatI format, SequenceI assocSeq)
5181 // BH 2018 was String file
5184 if (sourceType == null)
5186 sourceType = FormatAdapter.checkProtocol(file);
5188 // if the file isn't identified, or not positively identified as some
5189 // other filetype (PFAM is default unidentified alignment file type) then
5190 // try to parse as annotation.
5191 boolean isAnnotation = (format == null
5192 || FileFormat.Pfam.equals(format))
5193 ? new AnnotationFile().annotateAlignmentView(viewport,
5199 // first see if its a T-COFFEE score file
5200 TCoffeeScoreFile tcf = null;
5203 tcf = new TCoffeeScoreFile(file, sourceType);
5206 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5210 new TCoffeeColourScheme(viewport.getAlignment()));
5211 isAnnotation = true;
5212 setStatus(MessageManager.getString(
5213 "label.successfully_pasted_tcoffee_scores_to_alignment"));
5217 // some problem - if no warning its probable that the ID matching
5218 // process didn't work
5219 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
5220 tcf.getWarningMessage() == null
5221 ? MessageManager.getString(
5222 "label.check_file_matches_sequence_ids_alignment")
5223 : tcf.getWarningMessage(),
5224 MessageManager.getString(
5225 "label.problem_reading_tcoffee_score_file"),
5226 JvOptionPane.WARNING_MESSAGE);
5233 } catch (Exception x)
5236 "Exception when processing data source as T-COFFEE score file",
5242 // try to see if its a JNet 'concise' style annotation file *before*
5244 // try to parse it as a features file
5247 format = new IdentifyFile().identify(file, sourceType);
5249 if (FileFormat.ScoreMatrix == format)
5251 ScoreMatrixFile sm = new ScoreMatrixFile(
5252 new FileParse(file, sourceType));
5254 // todo: i18n this message
5255 setStatus(MessageManager.formatMessage(
5256 "label.successfully_loaded_matrix",
5257 sm.getMatrixName()));
5259 else if (FileFormat.Jnet.equals(format))
5261 JPredFile predictions = new JPredFile(file, sourceType);
5262 new JnetAnnotationMaker();
5263 JnetAnnotationMaker.add_annotation(predictions,
5264 viewport.getAlignment(), 0, false);
5265 viewport.getAlignment().setupJPredAlignment();
5266 isAnnotation = true;
5268 // else if (IdentifyFile.FeaturesFile.equals(format))
5269 else if (FileFormat.Features.equals(format))
5271 if (parseFeaturesFile(file, sourceType))
5273 SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
5274 if (splitFrame != null)
5276 splitFrame.repaint();
5280 alignPanel.paintAlignment(true, true);
5286 new FileLoader().LoadFile(viewport, file, sourceType, format);
5292 updateForAnnotations();
5294 } catch (Exception ex)
5296 ex.printStackTrace();
5297 } catch (OutOfMemoryError oom)
5302 } catch (Exception x)
5307 + (sourceType != null
5308 ? (sourceType == DataSourceType.PASTE
5310 : "using " + sourceType + " from "
5314 ? "(parsing as '" + format + "' file)"
5316 oom, Desktop.getDesktopPane());
5321 * Do all updates necessary after an annotation file such as jnet. Also called
5322 * from Jalview.loadAppletParams for "annotations", "jnetFile"
5325 public void updateForAnnotations()
5327 alignPanel.adjustAnnotationHeight();
5328 viewport.updateSequenceIdColours();
5329 buildSortByAnnotationScoresMenu();
5330 alignPanel.paintAlignment(true, true);
5334 * Change the display state for the given feature groups -- Added by BH from
5338 * list of group strings
5340 * visible or invisible
5343 public void setFeatureGroupState(String[] groups, boolean state)
5345 jalview.api.FeatureRenderer fr = null;
5346 viewport.setShowSequenceFeatures(true);
5347 if (alignPanel != null
5348 && (fr = alignPanel.getFeatureRenderer()) != null)
5351 fr.setGroupVisibility(Arrays.asList(groups), state);
5352 alignPanel.getSeqPanel().seqCanvas.repaint();
5353 if (alignPanel.overviewPanel != null)
5355 alignPanel.overviewPanel.updateOverviewImage();
5361 * Method invoked by the ChangeListener on the tabbed pane, in other words
5362 * when a different tabbed pane is selected by the user or programmatically.
5366 public void tabSelectionChanged(int index)
5370 alignPanel = alignPanels.get(index);
5371 viewport = alignPanel.av;
5372 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5373 setMenusFromViewport(viewport);
5374 if (featureSettings != null && featureSettings.isOpen()
5375 && featureSettings.fr.getViewport() != viewport)
5377 if (viewport.isShowSequenceFeatures())
5379 // refresh the featureSettings to reflect UI change
5380 showFeatureSettingsUI();
5384 // close feature settings for this view.
5385 featureSettings.close();
5392 * 'focus' any colour slider that is open to the selected viewport
5394 if (viewport.getConservationSelected())
5396 SliderPanel.setConservationSlider(alignPanel,
5397 viewport.getResidueShading(), alignPanel.getViewName());
5401 SliderPanel.hideConservationSlider();
5403 if (viewport.getAbovePIDThreshold())
5405 SliderPanel.setPIDSliderSource(alignPanel,
5406 viewport.getResidueShading(), alignPanel.getViewName());
5410 SliderPanel.hidePIDSlider();
5414 * If there is a frame linked to this one in a SplitPane, switch it to the
5415 * same view tab index. No infinite recursion of calls should happen, since
5416 * tabSelectionChanged() should not get invoked on setting the selected
5417 * index to an unchanged value. Guard against setting an invalid index
5418 * before the new view peer tab has been created.
5420 final AlignViewportI peer = viewport.getCodingComplement();
5423 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
5424 .getAlignPanel().alignFrame;
5425 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5427 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5433 * On right mouse click on view tab, prompt for and set new view name.
5437 public void tabbedPane_mousePressed(MouseEvent e)
5439 if (e.isPopupTrigger())
5441 String msg = MessageManager.getString("label.enter_view_name");
5442 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
5443 String reply = JvOptionPane.showInputDialog(msg, ttl);
5447 viewport.setViewName(reply);
5448 // TODO warn if reply is in getExistingViewNames()?
5449 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5454 public AlignViewport getCurrentView()
5460 * Open the dialog for regex description parsing.
5464 protected void extractScores_actionPerformed(ActionEvent e)
5466 ParseProperties pp = new jalview.analysis.ParseProperties(
5467 viewport.getAlignment());
5468 // TODO: verify regex and introduce GUI dialog for version 2.5
5469 // if (pp.getScoresFromDescription("col", "score column ",
5470 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5472 if (pp.getScoresFromDescription("description column",
5473 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5475 buildSortByAnnotationScoresMenu();
5483 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5488 protected void showDbRefs_actionPerformed(ActionEvent e)
5490 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5496 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5501 protected void showNpFeats_actionPerformed(ActionEvent e)
5503 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5507 * find the viewport amongst the tabs in this alignment frame and close that
5513 public boolean closeView(AlignViewportI av)
5517 this.closeMenuItem_actionPerformed(false);
5520 Component[] comp = tabbedPane.getComponents();
5521 for (int i = 0; comp != null && i < comp.length; i++)
5523 if (comp[i] instanceof AlignmentPanel)
5525 if (((AlignmentPanel) comp[i]).av == av)
5528 closeView((AlignmentPanel) comp[i]);
5536 protected void build_fetchdbmenu(JMenu webService)
5538 // Temporary hack - DBRef Fetcher always top level ws entry.
5539 // TODO We probably want to store a sequence database checklist in
5540 // preferences and have checkboxes.. rather than individual sources selected
5542 final JMenu rfetch = new JMenu(
5543 MessageManager.getString("action.fetch_db_references"));
5544 rfetch.setToolTipText(MessageManager.getString(
5545 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5546 webService.add(rfetch);
5548 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5549 MessageManager.getString("option.trim_retrieved_seqs"));
5550 trimrs.setToolTipText(
5551 MessageManager.getString("label.trim_retrieved_sequences"));
5553 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5554 trimrs.addActionListener(new ActionListener()
5558 public void actionPerformed(ActionEvent e)
5560 trimrs.setSelected(trimrs.isSelected());
5561 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5562 Boolean.valueOf(trimrs.isSelected()).toString());
5566 JMenuItem fetchr = new JMenuItem(
5567 MessageManager.getString("label.standard_databases"));
5568 fetchr.setToolTipText(
5569 MessageManager.getString("label.fetch_embl_uniprot"));
5570 fetchr.addActionListener(new ActionListener()
5574 public void actionPerformed(ActionEvent e)
5576 new Thread(new Runnable()
5582 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5583 .getAlignment().isNucleotide();
5584 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5585 alignPanel.av.getSequenceSelection(),
5586 alignPanel.alignFrame, null,
5587 alignPanel.alignFrame.featureSettings, isNucleotide);
5588 dbRefFetcher.addListener(new FetchFinishedListenerI()
5592 public void finished()
5595 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5596 .getFeatureSettingsModels())
5599 alignPanel.av.mergeFeaturesStyle(srcSettings);
5601 AlignFrame.this.setMenusForViewport();
5604 dbRefFetcher.fetchDBRefs(false);
5612 new Thread(new Runnable()
5619 // final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5620 // .getSequenceFetcherSingleton();
5621 javax.swing.SwingUtilities.invokeLater(new Runnable()
5627 jalview.ws.SequenceFetcher sf = jalview.ws.SequenceFetcher
5629 String[] dbclasses = sf.getNonAlignmentSources();
5630 List<DbSourceProxy> otherdb;
5631 JMenu dfetch = new JMenu();
5632 JMenu ifetch = new JMenu();
5633 JMenuItem fetchr = null;
5634 int comp = 0, icomp = 0, mcomp = 15;
5635 String mname = null;
5637 for (String dbclass : dbclasses)
5639 otherdb = sf.getSourceProxy(dbclass);
5640 // add a single entry for this class, or submenu allowing 'fetch
5642 if (otherdb == null || otherdb.size() < 1)
5648 mname = "From " + dbclass;
5650 if (otherdb.size() == 1)
5652 DbSourceProxy src = otherdb.get(0);
5653 DbSourceProxy[] dassource = new DbSourceProxy[] { src };
5654 fetchr = new JMenuItem(src.getDbSource());
5655 fetchr.addActionListener(new ActionListener()
5659 public void actionPerformed(ActionEvent e)
5661 new Thread(new Runnable()
5667 boolean isNucleotide = alignPanel.alignFrame
5668 .getViewport().getAlignment()
5670 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5671 alignPanel.av.getSequenceSelection(),
5672 alignPanel.alignFrame, dassource,
5673 alignPanel.alignFrame.featureSettings,
5676 .addListener(new FetchFinishedListenerI()
5680 public void finished()
5682 FeatureSettingsModelI srcSettings = dassource[0]
5683 .getFeatureColourScheme();
5684 alignPanel.av.mergeFeaturesStyle(
5686 AlignFrame.this.setMenusForViewport();
5689 dbRefFetcher.fetchDBRefs(false);
5695 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5696 MessageManager.formatMessage(
5697 "label.fetch_retrieve_from", new Object[]
5698 { src.getDbName() })));
5704 final DbSourceProxy[] dassource = otherdb
5705 .toArray(new DbSourceProxy[0]);
5707 DbSourceProxy src = otherdb.get(0);
5708 fetchr = new JMenuItem(MessageManager
5709 .formatMessage("label.fetch_all_param", new Object[]
5710 { src.getDbSource() }));
5711 fetchr.addActionListener(new ActionListener()
5715 public void actionPerformed(ActionEvent e)
5717 new Thread(new Runnable()
5723 boolean isNucleotide = alignPanel.alignFrame
5724 .getViewport().getAlignment()
5726 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5727 alignPanel.av.getSequenceSelection(),
5728 alignPanel.alignFrame, dassource,
5729 alignPanel.alignFrame.featureSettings,
5732 .addListener(new FetchFinishedListenerI()
5736 public void finished()
5738 AlignFrame.this.setMenusForViewport();
5741 dbRefFetcher.fetchDBRefs(false);
5747 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5748 MessageManager.formatMessage(
5749 "label.fetch_retrieve_from_all_sources",
5751 { Integer.valueOf(otherdb.size())
5753 src.getDbSource(), src.getDbName() })));
5756 // and then build the rest of the individual menus
5757 ifetch = new JMenu(MessageManager.formatMessage(
5758 "label.source_from_db_source", new Object[]
5759 { src.getDbSource() }));
5761 String imname = null;
5763 for (DbSourceProxy sproxy : otherdb)
5765 String dbname = sproxy.getDbName();
5766 String sname = dbname.length() > 5
5767 ? dbname.substring(0, 5) + "..."
5769 String msname = dbname.length() > 10
5770 ? dbname.substring(0, 10) + "..."
5774 imname = MessageManager
5775 .formatMessage("label.from_msname", new Object[]
5778 fetchr = new JMenuItem(msname);
5779 final DbSourceProxy[] dassrc = { sproxy };
5780 fetchr.addActionListener(new ActionListener()
5784 public void actionPerformed(ActionEvent e)
5786 new Thread(new Runnable()
5792 boolean isNucleotide = alignPanel.alignFrame
5793 .getViewport().getAlignment()
5795 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5796 alignPanel.av.getSequenceSelection(),
5797 alignPanel.alignFrame, dassrc,
5798 alignPanel.alignFrame.featureSettings,
5801 .addListener(new FetchFinishedListenerI()
5805 public void finished()
5807 AlignFrame.this.setMenusForViewport();
5810 dbRefFetcher.fetchDBRefs(false);
5816 fetchr.setToolTipText(
5817 "<html>" + MessageManager.formatMessage(
5818 "label.fetch_retrieve_from", new Object[]
5822 if (++icomp >= mcomp || i == (otherdb.size()))
5824 ifetch.setText(MessageManager.formatMessage(
5825 "label.source_to_target", imname, sname));
5827 ifetch = new JMenu();
5835 if (comp >= mcomp || dbi >= (dbclasses.length))
5837 dfetch.setText(MessageManager.formatMessage(
5838 "label.source_to_target", mname, dbclass));
5840 dfetch = new JMenu();
5853 * Left justify the whole alignment.
5857 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5859 viewport.getAlignment().justify(false);
5860 viewport.notifyAlignment();
5864 * Right justify the whole alignment.
5868 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5870 viewport.getAlignment().justify(true);
5871 viewport.notifyAlignment();
5875 public void setShowSeqFeatures(boolean b)
5877 showSeqFeatures.setSelected(b);
5878 viewport.setShowSequenceFeatures(b);
5885 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5886 * awt.event.ActionEvent)
5890 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5892 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5893 alignPanel.paintAlignment(false, false);
5900 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5905 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5907 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5908 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5916 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5917 * .event.ActionEvent)
5921 protected void showGroupConservation_actionPerformed(ActionEvent e)
5923 viewport.setShowGroupConservation(showGroupConservation.getState());
5924 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5931 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5932 * .event.ActionEvent)
5936 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5938 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5939 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5946 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5947 * .event.ActionEvent)
5951 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5953 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5954 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5958 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5960 showSequenceLogo.setState(true);
5961 viewport.setShowSequenceLogo(true);
5962 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5963 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5967 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5969 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5976 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5977 * .event.ActionEvent)
5981 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5983 if (avc.makeGroupsFromSelection())
5985 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5986 alignPanel.updateAnnotation();
5987 alignPanel.paintAlignment(true,
5988 viewport.needToUpdateStructureViews());
5992 public void clearAlignmentSeqRep()
5994 // TODO refactor alignmentseqrep to controller
5995 if (viewport.getAlignment().hasSeqrep())
5997 viewport.getAlignment().setSeqrep(null);
5998 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5999 alignPanel.updateAnnotation();
6000 alignPanel.paintAlignment(true, true);
6005 protected void createGroup_actionPerformed(ActionEvent e)
6007 if (avc.createGroup())
6009 if (applyAutoAnnotationSettings.isSelected())
6011 alignPanel.updateAnnotation(true, false);
6013 alignPanel.alignmentChanged();
6018 protected void unGroup_actionPerformed(ActionEvent e)
6022 alignPanel.alignmentChanged();
6027 * make the given alignmentPanel the currently selected tab
6029 * @param alignmentPanel
6032 public void setDisplayedView(AlignmentPanel alignmentPanel)
6034 if (!viewport.getSequenceSetId()
6035 .equals(alignmentPanel.av.getSequenceSetId()))
6037 throw new Error(MessageManager.getString(
6038 "error.implementation_error_cannot_show_view_alignment_frame"));
6040 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
6041 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
6043 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
6048 * Action on selection of menu options to Show or Hide annotations.
6051 * @param forSequences
6052 * update sequence-related annotations
6053 * @param forAlignment
6054 * update non-sequence-related annotations
6058 protected void setAnnotationsVisibility(boolean visible,
6059 boolean forSequences, boolean forAlignment)
6061 AlignmentAnnotation[] anns = alignPanel.getAlignment()
6062 .getAlignmentAnnotation();
6067 for (AlignmentAnnotation aa : anns)
6070 * don't display non-positional annotations on an alignment
6072 if (aa.annotations == null)
6076 boolean apply = (aa.sequenceRef == null && forAlignment)
6077 || (aa.sequenceRef != null && forSequences);
6080 aa.visible = visible;
6083 alignPanel.validateAnnotationDimensions(true);
6084 alignPanel.alignmentChanged();
6088 * Store selected annotation sort order for the view and repaint.
6092 protected void sortAnnotations_actionPerformed()
6094 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
6096 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
6097 alignPanel.paintAlignment(false, false);
6102 * @return alignment panels in this alignment frame
6105 public List<? extends AlignmentViewPanel> getAlignPanels()
6107 // alignPanels is never null
6108 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
6113 * Open a new alignment window, with the cDNA associated with this (protein)
6114 * alignment, aligned as is the protein.
6117 protected void viewAsCdna_actionPerformed()
6119 // TODO no longer a menu action - refactor as required
6120 final AlignmentI alignment = getViewport().getAlignment();
6121 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
6122 if (mappings == null)
6126 List<SequenceI> cdnaSeqs = new ArrayList<>();
6127 for (SequenceI aaSeq : alignment.getSequences())
6129 for (AlignedCodonFrame acf : mappings)
6131 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
6135 * There is a cDNA mapping for this protein sequence - add to new
6136 * alignment. It will share the same dataset sequence as other mapped
6137 * cDNA (no new mappings need to be created).
6139 final Sequence newSeq = new Sequence(dnaSeq);
6140 newSeq.setDatasetSequence(dnaSeq);
6141 cdnaSeqs.add(newSeq);
6145 if (cdnaSeqs.size() == 0)
6147 // show a warning dialog no mapped cDNA
6150 AlignmentI cdna = new Alignment(
6151 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
6152 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
6153 AlignFrame.DEFAULT_HEIGHT);
6154 cdna.alignAs(alignment);
6155 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
6157 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
6158 AlignFrame.DEFAULT_HEIGHT);
6162 * Set visibility of dna/protein complement view (available when shown in a
6169 protected void showComplement_actionPerformed(boolean show)
6171 SplitContainerI sf = getSplitViewContainer();
6174 sf.setComplementVisible(this, show);
6179 * Generate the reverse (optionally complemented) of the selected sequences,
6180 * and add them to the alignment
6184 protected void showReverse_actionPerformed(boolean complement)
6186 AlignmentI al = null;
6189 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
6190 al = dna.reverseCdna(complement);
6191 viewport.addAlignment(al, "");
6192 addHistoryItem(new EditCommand(
6193 MessageManager.getString("label.add_sequences"), Action.PASTE,
6194 al.getSequencesArray(), 0, al.getWidth(),
6195 viewport.getAlignment()));
6196 } catch (Exception ex)
6198 System.err.println(ex.getMessage());
6204 * Try to run a script in the Groovy console, having first ensured that this
6205 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
6206 * be targeted at this alignment.
6210 protected void runGroovy_actionPerformed()
6212 Jalview.setCurrentAlignFrame(this);
6213 groovy.ui.Console console = Desktop.getGroovyConsole();
6214 if (console != null)
6218 console.runScript();
6219 } catch (Exception ex)
6221 System.err.println((ex.toString()));
6222 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
6223 MessageManager.getString("label.couldnt_run_groovy_script"),
6224 MessageManager.getString("label.groovy_support_failed"),
6225 JvOptionPane.ERROR_MESSAGE);
6230 System.err.println("Can't run Groovy script as console not found");
6235 * Hides columns containing (or not containing) a specified feature, provided
6236 * that would not leave all columns hidden
6238 * @param featureType
6239 * @param columnsContaining
6243 public boolean hideFeatureColumns(String featureType,
6244 boolean columnsContaining)
6246 boolean notForHiding = avc.markColumnsContainingFeatures(
6247 columnsContaining, false, false, featureType);
6250 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
6251 false, featureType))
6253 getViewport().hideSelectedColumns();
6261 protected void selectHighlightedColumns_actionPerformed(
6262 ActionEvent actionEvent)
6264 // include key modifier check in case user selects from menu
6265 avc.markHighlightedColumns(
6266 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
6267 (actionEvent.getModifiers() & (ActionEvent.META_MASK
6268 | ActionEvent.CTRL_MASK)) != 0);
6272 * Rebuilds the Colour menu, including any user-defined colours which have
6273 * been loaded either on startup or during the session
6276 public void buildColourMenu()
6278 colourMenu.removeAll();
6280 colourMenu.add(applyToAllGroups);
6281 colourMenu.add(textColour);
6282 colourMenu.addSeparator();
6284 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
6285 viewport.getAlignment(), false);
6287 colourMenu.add(annotationColour);
6288 bg.add(annotationColour);
6289 colourMenu.addSeparator();
6290 colourMenu.add(conservationMenuItem);
6291 colourMenu.add(modifyConservation);
6292 colourMenu.add(abovePIDThreshold);
6293 colourMenu.add(modifyPID);
6295 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
6296 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
6300 * Open a dialog (if not already open) that allows the user to select and
6301 * calculate PCA or Tree analysis
6304 protected void openTreePcaDialog()
6306 if (alignPanel.getCalculationDialog() == null)
6308 new CalculationChooser(AlignFrame.this);
6313 * Sets the status of the HMMER menu
6315 public void updateHMMERStatus()
6317 hmmerMenu.setEnabled(HmmerCommand.isHmmerAvailable());
6321 protected void loadVcf_actionPerformed()
6323 JalviewFileChooser chooser = new JalviewFileChooser(
6324 Cache.getProperty("LAST_DIRECTORY"));
6325 chooser.setFileView(new JalviewFileView());
6326 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
6327 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
6328 final AlignFrame us = this;
6329 chooser.setResponseHandler(0, new Runnable()
6335 String choice = chooser.getSelectedFile().getPath();
6336 Cache.setProperty("LAST_DIRECTORY", choice);
6337 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
6338 new VCFLoader(choice).loadVCF(seqs, us);
6341 chooser.showOpenDialog(null);
6345 private Rectangle lastFeatureSettingsBounds = null;
6348 public void setFeatureSettingsGeometry(Rectangle bounds)
6350 lastFeatureSettingsBounds = bounds;
6354 public Rectangle getFeatureSettingsGeometry()
6356 return lastFeatureSettingsBounds;
6359 public void scrollTo(int row, int column)
6361 alignPanel.getSeqPanel().scrollTo(row, column);
6364 public void scrollToRow(int row)
6366 alignPanel.getSeqPanel().scrollToRow(row);
6369 public void scrollToColumn(int column)
6371 alignPanel.getSeqPanel().scrollToColumn(column);
6375 * BH 2019 from JalviewLite
6377 * get sequence feature groups that are hidden or shown
6384 public String[] getFeatureGroupsOfState(boolean visible)
6386 jalview.api.FeatureRenderer fr = null;
6387 if (alignPanel != null
6388 && (fr = alignPanel.getFeatureRenderer()) != null)
6390 List<String> gps = fr.getGroups(visible);
6391 String[] _gps = gps.toArray(new String[gps.size()]);
6399 * @return list of feature groups on the view
6402 public String[] getFeatureGroups()
6404 jalview.api.FeatureRenderer fr = null;
6405 if (alignPanel != null
6406 && (fr = alignPanel.getFeatureRenderer()) != null)
6408 List<String> gps = fr.getFeatureGroups();
6409 String[] _gps = gps.toArray(new String[gps.size()]);
6415 public void select(SequenceGroup sel, ColumnSelection csel,
6416 HiddenColumns hidden)
6418 alignPanel.getSeqPanel().selection(sel, csel, hidden, null);
6426 static class PrintThread extends Thread
6430 public PrintThread(AlignmentPanel ap)
6435 static PageFormat pf;
6440 PrinterJob printJob = PrinterJob.getPrinterJob();
6444 printJob.setPrintable(ap, pf);
6448 printJob.setPrintable(ap);
6451 if (printJob.printDialog())
6456 } catch (Exception PrintException)
6458 PrintException.printStackTrace();