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.slivka.SlivkaWSDiscoverer;
119 import jalview.ws2.WebServiceDiscovererI;
120 import jalview.ws2.gui.WebServicesMenuBuilder;
121 import jalview.ws2.operations.Operation;
123 import java.io.IOException;
124 import java.util.HashSet;
125 import java.util.Set;
127 import javax.swing.JFileChooser;
128 import javax.swing.JOptionPane;
130 import java.awt.BorderLayout;
131 import java.awt.Color;
132 import java.awt.Component;
133 import java.awt.Dimension;
134 import java.awt.Rectangle;
135 import java.awt.Toolkit;
136 import java.awt.datatransfer.Clipboard;
137 import java.awt.datatransfer.DataFlavor;
138 import java.awt.datatransfer.StringSelection;
139 import java.awt.datatransfer.Transferable;
140 import java.awt.dnd.DnDConstants;
141 import java.awt.dnd.DropTargetDragEvent;
142 import java.awt.dnd.DropTargetDropEvent;
143 import java.awt.dnd.DropTargetEvent;
144 import java.awt.dnd.DropTargetListener;
145 import java.awt.event.ActionEvent;
146 import java.awt.event.ActionListener;
147 import java.awt.event.FocusAdapter;
148 import java.awt.event.FocusEvent;
149 import java.awt.event.ItemEvent;
150 import java.awt.event.ItemListener;
151 import java.awt.event.KeyAdapter;
152 import java.awt.event.KeyEvent;
153 import java.awt.event.MouseEvent;
154 import java.awt.print.PageFormat;
155 import java.awt.print.PrinterJob;
156 import java.beans.PropertyChangeEvent;
157 import java.beans.PropertyChangeListener;
159 import java.io.FileWriter;
160 import java.io.PrintWriter;
162 import java.util.ArrayList;
163 import java.util.Arrays;
164 import java.util.Collection;
165 import java.util.Deque;
166 import java.util.Enumeration;
167 import java.util.Hashtable;
168 import java.util.List;
169 import java.util.Vector;
171 import javax.swing.ButtonGroup;
172 import javax.swing.JCheckBoxMenuItem;
173 import javax.swing.JComponent;
174 import javax.swing.JEditorPane;
175 import javax.swing.JInternalFrame;
176 import javax.swing.JLabel;
177 import javax.swing.JLayeredPane;
178 import javax.swing.JMenu;
179 import javax.swing.JMenuItem;
180 import javax.swing.JPanel;
181 import javax.swing.JScrollPane;
182 import javax.swing.SwingUtilities;
183 import javax.swing.event.InternalFrameAdapter;
184 import javax.swing.event.InternalFrameEvent;
186 import ext.vamsas.ServiceHandle;
192 * @version $Revision$
194 @SuppressWarnings("serial")
195 public class AlignFrame extends GAlignFrame
196 implements DropTargetListener, IProgressIndicator,
197 AlignViewControllerGuiI, ColourChangeListener, ServiceChangeListener
200 public static int frameCount;
202 public static final int DEFAULT_WIDTH = 700;
204 public static final int DEFAULT_HEIGHT = 500;
207 * The currently displayed panel (selected tabbed view if more than one)
209 public AlignmentPanel alignPanel;
211 AlignViewport viewport;
213 public AlignViewControllerI avc;
215 List<AlignmentPanel> alignPanels = new ArrayList<>();
218 * Last format used to load or save alignments in this window
220 FileFormatI currentFileFormat = null;
223 * Current filename for this alignment
225 String fileName = null;
228 * TODO: remove reference to 'FileObject' in AlignFrame - not correct mapping
234 private DataSourceType protocol ;
237 * Creates a new AlignFrame object with specific width and height.
243 public AlignFrame(AlignmentI al, int width, int height)
245 this(al, null, width, height);
249 * Creates a new AlignFrame object with specific width, height and
255 * @param sequenceSetId
257 public AlignFrame(AlignmentI al, int width, int height,
258 String sequenceSetId)
260 this(al, null, width, height, sequenceSetId);
264 * Creates a new AlignFrame object with specific width, height and
270 * @param sequenceSetId
273 public AlignFrame(AlignmentI al, int width, int height,
274 String sequenceSetId, String viewId)
276 this(al, null, width, height, sequenceSetId, viewId);
280 * new alignment window with hidden columns
284 * @param hiddenColumns
285 * ColumnSelection or null
287 * Width of alignment frame
291 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
294 this(al, hiddenColumns, width, height, null);
298 * Create alignment frame for al with hiddenColumns, a specific width and
299 * height, and specific sequenceId
302 * @param hiddenColumns
305 * @param sequenceSetId
308 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
309 int height, String sequenceSetId)
311 this(al, hiddenColumns, width, height, sequenceSetId, null);
315 * Create alignment frame for al with hiddenColumns, a specific width and
316 * height, and specific sequenceId
319 * @param hiddenColumns
322 * @param sequenceSetId
327 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
328 int height, String sequenceSetId, String viewId)
333 setSize(width, height);
335 if (al.getDataset() == null)
340 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
342 // JalviewJS needs to distinguish a new panel from an old one in init()
343 // alignPanel = new AlignmentPanel(this, viewport);
344 // addAlignmentPanel(alignPanel, true);
348 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
349 HiddenColumns hiddenColumns, int width, int height)
351 setSize(width, height);
353 if (al.getDataset() == null)
358 viewport = new AlignViewport(al, hiddenColumns);
360 if (hiddenSeqs != null && hiddenSeqs.length > 0)
362 viewport.hideSequence(hiddenSeqs);
364 // alignPanel = new AlignmentPanel(this, viewport);
365 // addAlignmentPanel(alignPanel, true);
370 * Make a new AlignFrame from existing alignmentPanels
377 public AlignFrame(AlignmentPanel ap)
381 // addAlignmentPanel(ap, false);
386 * initalise the alignframe from the underlying viewport data and the
392 boolean newPanel = (alignPanel == null);
393 viewport.setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
398 // need to set this up front if NOANNOTATION is
399 // used in conjunction with SHOWOVERVIEW.
401 // I have not determined if this is appropriate for
402 // Jalview/Java, as it means we are setting this flag
403 // for all subsequent AlignFrames. For now, at least,
404 // I am setting it to be JalviewJS-only.
406 boolean showAnnotation = Jalview.getInstance().getShowAnnotation();
407 viewport.setShowAnnotation(showAnnotation);
409 alignPanel = new AlignmentPanel(this, viewport);
411 addAlignmentPanel(alignPanel, newPanel);
413 // setBackground(Color.white); // BH 2019
415 if (!Jalview.isHeadlessMode())
417 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
419 statusPanel.setVisible(Jalview.getInstance().getShowStatus());
420 alignFrameMenuBar.setVisible(Jalview.getInstance().getAllowMenuBar());
423 avc = new jalview.controller.AlignViewController(this, viewport,
425 if (viewport.getAlignmentConservationAnnotation() == null)
427 // BLOSUM62Colour.setEnabled(false);
428 conservationMenuItem.setEnabled(false);
429 modifyConservation.setEnabled(false);
430 // PIDColour.setEnabled(false);
431 // abovePIDThreshold.setEnabled(false);
432 // modifyPID.setEnabled(false);
435 String sortby = jalview.bin.Cache.getDefault(Preferences.SORT_ALIGNMENT,
438 if (sortby.equals("Id"))
440 sortIDMenuItem_actionPerformed(null);
442 else if (sortby.equals("Pairwise Identity"))
444 sortPairwiseMenuItem_actionPerformed(null);
449 // this.alignPanel.av
450 // .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
452 setMenusFromViewport(viewport);
453 buildSortByAnnotationScoresMenu();
454 calculateTree.addActionListener(new ActionListener()
458 public void actionPerformed(ActionEvent e)
465 if (Desktop.getDesktopPane() != null)
467 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
468 addServiceListeners();
469 if (!Platform.isJS())
475 if (viewport.getWrapAlignment())
477 wrapMenuItem_actionPerformed(null);
480 if (jalview.bin.Cache.getDefault(Preferences.SHOW_OVERVIEW, false))
482 this.overviewMenuItem_actionPerformed(null);
487 final List<AlignmentPanel> selviews = new ArrayList<>();
488 final List<AlignmentPanel> origview = new ArrayList<>();
489 final String menuLabel = MessageManager
490 .getString("label.copy_format_from");
491 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
492 new ViewSetProvider()
496 public AlignmentPanel[] getAllAlignmentPanels()
499 origview.add(alignPanel);
500 // make an array of all alignment panels except for this one
501 List<AlignmentPanel> aps = new ArrayList<>(
502 Arrays.asList(Desktop.getAlignmentPanels(null)));
503 aps.remove(AlignFrame.this.alignPanel);
504 return aps.toArray(new AlignmentPanel[aps.size()]);
506 }, selviews, new ItemListener()
510 public void itemStateChanged(ItemEvent e)
512 if (origview.size() > 0)
514 final AlignmentPanel ap = origview.get(0);
517 * Copy the ViewStyle of the selected panel to 'this one'.
518 * Don't change value of 'scaleProteinAsCdna' unless copying
521 ViewStyleI vs = selviews.get(0).getAlignViewport()
523 boolean fromSplitFrame = selviews.get(0)
524 .getAlignViewport().getCodingComplement() != null;
527 vs.setScaleProteinAsCdna(ap.getAlignViewport()
528 .getViewStyle().isScaleProteinAsCdna());
530 ap.getAlignViewport().setViewStyle(vs);
533 * Also rescale ViewStyle of SplitFrame complement if there is
534 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
535 * the whole ViewStyle (allow cDNA protein to have different
538 AlignViewportI complement = ap.getAlignViewport()
539 .getCodingComplement();
540 if (complement != null && vs.isScaleProteinAsCdna())
542 AlignFrame af = Desktop.getAlignFrameFor(complement);
543 ((SplitFrame) af.getSplitViewContainer())
545 af.setMenusForViewport();
549 ap.setSelected(true);
550 ap.alignFrame.setMenusForViewport();
555 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
556 .indexOf("devel") > -1
557 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
558 .indexOf("test") > -1)
560 formatMenu.add(vsel);
562 addFocusListener(new FocusAdapter()
566 public void focusGained(FocusEvent e)
568 Jalview.setCurrentAlignFrame(AlignFrame.this);
575 * Change the filename and format for the alignment, and enable the 'reload'
576 * button functionality.
585 public void setFileName(String file, FileFormatI format)
588 setFileFormat(format);
589 reload.setEnabled(true);
595 * @param file from SwingJS; may contain bytes -- for reload
596 * @param protocol from SwingJS; may be RELATIVE_URL
599 public void setFile(String fileName, File file, DataSourceType protocol, FileFormatI format)
601 this.fileName = fileName;
602 this.fileObject = file;
603 this.protocol = protocol;
604 setFileFormat(format);
605 reload.setEnabled(true);
609 * JavaScript will have this, maybe others. More dependable than a file name
610 * and maintains a reference to the actual bytes loaded.
615 public void setFileObject(File file)
617 this.fileObject = file;
621 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
625 void addKeyListener()
627 addKeyListener(new KeyAdapter()
631 public void keyPressed(KeyEvent evt)
633 if (viewport.cursorMode
634 && ((evt.getKeyCode() >= KeyEvent.VK_0
635 && evt.getKeyCode() <= KeyEvent.VK_9)
636 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
637 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
638 && Character.isDigit(evt.getKeyChar()))
640 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
643 switch (evt.getKeyCode())
646 case KeyEvent.VK_ESCAPE: // escape key
647 // alignPanel.deselectAllSequences();
648 alignPanel.deselectAllSequences();
652 case KeyEvent.VK_DOWN:
653 if (evt.isAltDown() || !viewport.cursorMode)
655 moveSelectedSequences(false);
657 if (viewport.cursorMode)
659 alignPanel.getSeqPanel().moveCursor(0, 1);
664 if (evt.isAltDown() || !viewport.cursorMode)
666 moveSelectedSequences(true);
668 if (viewport.cursorMode)
670 alignPanel.getSeqPanel().moveCursor(0, -1);
675 case KeyEvent.VK_LEFT:
676 if (evt.isAltDown() || !viewport.cursorMode)
678 slideSequences(false,
679 alignPanel.getSeqPanel().getKeyboardNo1());
683 alignPanel.getSeqPanel().moveCursor(-1, 0);
688 case KeyEvent.VK_RIGHT:
689 if (evt.isAltDown() || !viewport.cursorMode)
691 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
695 alignPanel.getSeqPanel().moveCursor(1, 0);
699 case KeyEvent.VK_SPACE:
700 if (viewport.cursorMode)
702 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
703 || evt.isShiftDown() || evt.isAltDown());
707 // case KeyEvent.VK_A:
708 // if (viewport.cursorMode)
710 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
711 // //System.out.println("A");
715 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
716 * System.out.println("closing bracket"); } break;
718 case KeyEvent.VK_DELETE:
719 case KeyEvent.VK_BACK_SPACE:
720 if (!viewport.cursorMode)
722 cut_actionPerformed();
726 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
727 || evt.isShiftDown() || evt.isAltDown());
733 if (viewport.cursorMode)
735 alignPanel.getSeqPanel().setCursorRow();
739 if (viewport.cursorMode && !evt.isControlDown())
741 alignPanel.getSeqPanel().setCursorColumn();
745 if (viewport.cursorMode)
747 alignPanel.getSeqPanel().setCursorPosition();
751 case KeyEvent.VK_ENTER:
752 case KeyEvent.VK_COMMA:
753 if (viewport.cursorMode)
755 alignPanel.getSeqPanel().setCursorRowAndColumn();
760 if (viewport.cursorMode)
762 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
766 if (viewport.cursorMode)
768 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
773 viewport.cursorMode = !viewport.cursorMode;
774 setStatus(MessageManager
775 .formatMessage("label.keyboard_editing_mode", new String[]
776 { (viewport.cursorMode ? "on" : "off") }));
777 if (viewport.cursorMode)
779 ViewportRanges ranges = viewport.getRanges();
780 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
782 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
785 alignPanel.getSeqPanel().seqCanvas.repaint();
791 Help.showHelpWindow();
792 } catch (Exception ex)
794 ex.printStackTrace();
799 boolean toggleSeqs = !evt.isControlDown();
800 boolean toggleCols = !evt.isShiftDown();
801 toggleHiddenRegions(toggleSeqs, toggleCols);
806 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
807 boolean modifyExisting = true; // always modify, don't clear
808 // evt.isShiftDown();
809 boolean invertHighlighted = evt.isAltDown();
810 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
814 case KeyEvent.VK_PAGE_UP:
815 viewport.getRanges().pageUp();
817 case KeyEvent.VK_PAGE_DOWN:
818 viewport.getRanges().pageDown();
824 public void keyReleased(KeyEvent evt)
826 switch (evt.getKeyCode())
828 case KeyEvent.VK_LEFT:
829 if (evt.isAltDown() || !viewport.cursorMode)
831 viewport.notifyAlignment();
835 case KeyEvent.VK_RIGHT:
836 if (evt.isAltDown() || !viewport.cursorMode)
838 viewport.notifyAlignment();
846 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
848 ap.alignFrame = this;
849 avc = new jalview.controller.AlignViewController(this, viewport,
854 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
856 int aSize = alignPanels.size();
858 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
860 if (aSize == 1 && ap.av.getViewName() == null)
862 this.getContentPane().add(ap, BorderLayout.CENTER);
868 setInitialTabVisible();
871 expandViews.setEnabled(true);
872 gatherViews.setEnabled(true);
873 tabbedPane.addTab(ap.av.getViewName(), ap);
875 ap.setVisible(false);
880 if (ap.av.isPadGaps())
882 ap.av.getAlignment().padGaps();
884 if (Jalview.getInstance().getStartCalculations())
886 ap.av.updateConservation(ap);
887 ap.av.updateConsensus(ap);
888 ap.av.updateStrucConsensus(ap);
889 ap.av.initInformationWorker(ap);
894 public void setInitialTabVisible()
896 expandViews.setEnabled(true);
897 gatherViews.setEnabled(true);
898 tabbedPane.setVisible(true);
899 AlignmentPanel first = alignPanels.get(0);
900 tabbedPane.addTab(first.av.getViewName(), first);
901 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
904 public AlignViewport getViewport()
910 public void servicesChanged(WSDiscovererI discoverer,
911 Collection<? extends ServiceWithParameters> services)
913 buildWebServicesMenu();
916 private void servicesChanged(WebServiceDiscovererI discoverer,
917 List<Operation> operations)
919 buildWebServicesMenu();
922 /* Set up intrinsic listeners for dynamically generated GUI bits. */
923 private void addServiceListeners()
925 if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
927 WebServiceDiscovererI discoverer = SlivkaWSDiscoverer.getInstance();
928 discoverer.addOperationsChangeListener(this::servicesChanged);
930 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
932 WSDiscovererI discoverer = Jws2Discoverer.getInstance();
933 discoverer.addServiceChangeListener(this);
935 // legacy event listener for compatibility with jws1
936 PropertyChangeListener legacyListener = (changeEvent) -> {
937 buildWebServicesMenu();
939 Desktop.getInstance().addJalviewPropertyChangeListener("services",legacyListener);
941 addInternalFrameListener(new InternalFrameAdapter() {
943 public void internalFrameClosed(InternalFrameEvent e) {
944 System.out.println("deregistering discoverer listener");
945 SlivkaWSDiscoverer.getInstance().removeOperationsChangeListener(AlignFrame.this::servicesChanged);
946 Jws2Discoverer.getInstance().removeServiceChangeListener(AlignFrame.this);
947 Desktop.getInstance().removeJalviewPropertyChangeListener("services", legacyListener);
948 closeMenuItem_actionPerformed(true);
951 buildWebServicesMenu();
955 * Configure menu items that vary according to whether the alignment is
956 * nucleotide or protein
959 public void setGUINucleotide()
961 AlignmentI al = getViewport().getAlignment();
962 boolean nucleotide = al.isNucleotide();
964 loadVcf.setVisible(nucleotide);
965 showTranslation.setVisible(nucleotide);
966 showReverse.setVisible(nucleotide);
967 showReverseComplement.setVisible(nucleotide);
968 conservationMenuItem.setEnabled(!nucleotide);
970 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
971 showGroupConservation.setEnabled(!nucleotide);
973 showComplementMenuItem
974 .setText(nucleotide ? MessageManager.getString("label.protein")
975 : MessageManager.getString("label.nucleotide"));
979 * set up menus for the current viewport. This may be called after any
980 * operation that affects the data in the current view (selection changed,
981 * etc) to update the menus to reflect the new state.
985 public void setMenusForViewport()
987 setMenusFromViewport(viewport);
991 * Need to call this method when tabs are selected for multiple views, or when
992 * loading from Jalview2XML.java
998 public void setMenusFromViewport(AlignViewport av)
1000 padGapsMenuitem.setSelected(av.isPadGaps());
1001 colourTextMenuItem.setSelected(av.isShowColourText());
1002 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
1003 modifyPID.setEnabled(abovePIDThreshold.isSelected());
1004 conservationMenuItem.setSelected(av.getConservationSelected());
1005 modifyConservation.setEnabled(conservationMenuItem.isSelected());
1006 seqLimits.setSelected(av.getShowJVSuffix());
1007 idRightAlign.setSelected(av.isRightAlignIds());
1008 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
1009 renderGapsMenuItem.setSelected(av.isRenderGaps());
1010 wrapMenuItem.setSelected(av.getWrapAlignment());
1011 scaleAbove.setVisible(av.getWrapAlignment());
1012 scaleLeft.setVisible(av.getWrapAlignment());
1013 scaleRight.setVisible(av.getWrapAlignment());
1014 annotationPanelMenuItem.setState(av.isShowAnnotation());
1015 // Show/hide annotations only enabled if annotation panel is shown
1016 syncAnnotationMenuItems(av.isShowAnnotation());
1017 viewBoxesMenuItem.setSelected(av.getShowBoxes());
1018 viewTextMenuItem.setSelected(av.getShowText());
1019 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
1020 showGroupConsensus.setSelected(av.isShowGroupConsensus());
1021 showGroupConservation.setSelected(av.isShowGroupConservation());
1022 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
1023 showSequenceLogo.setSelected(av.isShowSequenceLogo());
1024 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
1025 showInformationHistogram.setSelected(av.isShowInformationHistogram());
1026 showHMMSequenceLogo.setSelected(av.isShowHMMSequenceLogo());
1027 normaliseHMMSequenceLogo.setSelected(av.isNormaliseHMMSequenceLogo());
1029 ColourMenuHelper.setColourSelected(colourMenu,
1030 av.getGlobalColourScheme());
1032 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
1033 hiddenMarkers.setState(av.getShowHiddenMarkers());
1034 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
1035 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
1036 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
1038 .setSelected(av.getAutoCalculateConsensusAndConservation());
1039 sortByTree.setSelected(av.sortByTree);
1040 listenToViewSelections.setSelected(av.followSelection);
1042 showProducts.setEnabled(canShowProducts());
1043 setGroovyEnabled(Desktop.getGroovyConsole() != null);
1045 updateEditMenuBar();
1049 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
1054 public void setGroovyEnabled(boolean b)
1056 runGroovy.setEnabled(b);
1059 private IProgressIndicator progressBar;
1064 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
1068 public void setProgressBar(String message, long id)
1070 progressBar.setProgressBar(message, id);
1074 public void removeProgressBar(long id)
1076 progressBar.removeProgressBar(id);
1080 public void registerHandler(final long id,
1081 final IProgressIndicatorHandler handler)
1083 progressBar.registerHandler(id, handler);
1088 * @return true if any progress bars are still active
1092 public boolean operationInProgress()
1094 return progressBar.operationInProgress();
1098 * Sets the text of the status bar. Note that setting a null or empty value
1099 * will cause the status bar to be hidden, with possibly undesirable flicker
1100 * of the screen layout.
1104 public void setStatus(String text)
1106 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1110 * Added so Castor Mapping file can obtain Jalview Version
1113 public String getVersion()
1115 return jalview.bin.Cache.getProperty("VERSION");
1118 public FeatureRenderer getFeatureRenderer()
1120 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1124 public void fetchSequence_actionPerformed()
1126 new SequenceFetcher(this);
1130 public void addFromFile_actionPerformed(ActionEvent e)
1132 Desktop.getInstance().inputLocalFileMenuItem_actionPerformed(viewport);
1136 public void hmmBuild_actionPerformed(boolean withDefaults)
1138 if (!alignmentIsSufficient(1))
1144 * get default parameters, and optionally show a dialog
1145 * to allow them to be modified
1147 ParamDatastoreI store = HMMERParamStore.forBuild(viewport);
1148 List<ArgumentI> args = store.getServiceParameters();
1152 WsParamSetI set = new HMMERPreset();
1153 WsJobParameters params = new WsJobParameters(store, set, args);
1154 params.showRunDialog().thenAccept((startJob) -> {
1157 var args2 = params.getJobParams();
1158 new Thread(new HMMBuild(this, args2)).start();
1164 new Thread(new HMMBuild(this, args)).start();
1169 public void hmmAlign_actionPerformed(boolean withDefaults)
1171 if (!(checkForHMM() && alignmentIsSufficient(2)))
1177 * get default parameters, and optionally show a dialog
1178 * to allow them to be modified
1180 ParamDatastoreI store = HMMERParamStore.forAlign(viewport);
1181 List<ArgumentI> args = store.getServiceParameters();
1185 WsParamSetI set = new HMMERPreset();
1186 WsJobParameters params = new WsJobParameters(store, set, args);
1187 params.showRunDialog().thenAccept((startJob) -> {
1190 var args2 = params.getJobParams();
1191 new Thread(new HMMAlign(this, args2)).start();
1197 new Thread(new HMMAlign(this, args)).start();
1202 public void hmmSearch_actionPerformed(boolean withDefaults)
1210 * get default parameters, and (if requested) show
1211 * dialog to allow modification
1213 ParamDatastoreI store = HMMERParamStore.forSearch(viewport);
1214 List<ArgumentI> args = store.getServiceParameters();
1218 WsParamSetI set = new HMMERPreset();
1219 WsJobParameters params = new WsJobParameters(store, set, args);
1220 params.showRunDialog().thenAccept((startJob) -> {
1223 var args2 = params.getJobParams();
1224 new Thread(new HMMSearch(this, args2)).start();
1225 alignPanel.repaint();
1231 new Thread(new HMMSearch(this, args)).start();
1232 alignPanel.repaint();
1237 public void jackhmmer_actionPerformed(boolean withDefaults)
1241 * get default parameters, and (if requested) show
1242 * dialog to allow modification
1245 ParamDatastoreI store = HMMERParamStore.forJackhmmer(viewport);
1246 List<ArgumentI> args = store.getServiceParameters();
1250 WsParamSetI set = new HMMERPreset();
1251 WsJobParameters params = new WsJobParameters(store, set, args);
1252 params.showRunDialog().thenAccept((startJob) -> {
1255 var args2 = params.getJobParams();
1256 new Thread(new JackHMMER(this, args2)).start();
1257 alignPanel.repaint();
1263 new Thread(new JackHMMER(this, args)).start();
1264 alignPanel.repaint();
1269 * Checks if the alignment has at least one hidden Markov model, if not shows
1270 * a dialog advising to run hmmbuild or load an HMM profile
1274 private boolean checkForHMM()
1276 if (viewport.getAlignment().getHmmSequences().isEmpty())
1278 JOptionPane.showMessageDialog(this,
1279 MessageManager.getString("warn.no_hmm"));
1286 protected void filterByEValue_actionPerformed()
1288 viewport.filterByEvalue(inputDouble("Enter E-Value Cutoff"));
1292 protected void filterByScore_actionPerformed()
1294 viewport.filterByScore(inputDouble("Enter Bit Score Threshold"));
1297 private double inputDouble(String message)
1301 while (d == null || d <= 0)
1303 str = JOptionPane.showInputDialog(this.alignPanel, message);
1306 d = Double.valueOf(str);
1307 } catch (NumberFormatException e)
1315 * Checks if the alignment contains the required number of sequences.
1320 public boolean alignmentIsSufficient(int required)
1322 if (getViewport().getSequenceSelection().length < required)
1324 JOptionPane.showMessageDialog(this,
1325 MessageManager.getString("label.not_enough_sequences"));
1332 * Opens a file browser and adds the selected file, if in Fasta, Stockholm or
1333 * Pfam format, to the list held under preference key "HMMSEARCH_DBS" (as a
1334 * comma-separated list)
1337 public void addDatabase_actionPerformed() throws IOException
1339 if (Cache.getProperty(Preferences.HMMSEARCH_DBS) == null)
1341 Cache.setProperty(Preferences.HMMSEARCH_DBS, "");
1344 String path = openFileChooser(false);
1345 if (path != null && new File(path).exists())
1347 IdentifyFile identifier = new IdentifyFile();
1348 FileFormatI format = identifier.identify(path, DataSourceType.FILE);
1349 if (format == FileFormat.Fasta || format == FileFormat.Stockholm
1350 || format == FileFormat.Pfam)
1352 String currentDbPaths = Cache
1353 .getProperty(Preferences.HMMSEARCH_DBS);
1354 currentDbPaths += Preferences.COMMA + path;
1355 Cache.setProperty(Preferences.HMMSEARCH_DBS, currentDbPaths);
1359 JOptionPane.showMessageDialog(this,
1360 MessageManager.getString("warn.invalid_format"));
1366 * Opens a file chooser, optionally restricted to selecting folders
1367 * (directories) only. Answers the path to the selected file or folder, or
1368 * null if none is chosen.
1373 protected String openFileChooser(boolean forFolder)
1375 // TODO duplicates GPreferences method - relocate to JalviewFileChooser?
1376 String choice = null;
1377 JFileChooser chooser = new JFileChooser();
1380 chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1382 chooser.setDialogTitle(
1383 MessageManager.getString("label.open_local_file"));
1384 chooser.setToolTipText(MessageManager.getString("action.open"));
1386 int value = chooser.showOpenDialog(this);
1388 if (value == JFileChooser.APPROVE_OPTION)
1390 choice = chooser.getSelectedFile().getPath();
1396 public void reload_actionPerformed(ActionEvent e)
1398 if (fileName == null && fileObject == null)
1402 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1403 // originating file's format
1404 // TODO: work out how to recover feature settings for correct view(s) when
1405 // file is reloaded.
1406 if (FileFormat.Jalview.equals(currentFileFormat))
1408 JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
1409 for (int i = 0; i < frames.length; i++)
1411 if (frames[i] instanceof AlignFrame && frames[i] != this
1412 && ((AlignFrame) frames[i]).fileName != null
1413 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1417 frames[i].setSelected(true);
1418 Desktop.getInstance().closeAssociatedWindows();
1419 } catch (java.beans.PropertyVetoException ex)
1425 Desktop.getInstance().closeAssociatedWindows();
1427 FileLoader loader = new FileLoader();
1428 // DataSourceType protocol = fileName.startsWith("http:")
1429 // ? DataSourceType.URL
1430 // : DataSourceType.FILE;
1431 loader.LoadFile(viewport, (fileObject == null ? fileName : fileObject), protocol, currentFileFormat);
1435 Rectangle bounds = this.getBounds();
1437 FileLoader loader = new FileLoader();
1439 AlignFrame newframe = null;
1441 if (fileObject == null)
1443 newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1448 newframe = loader.LoadFileWaitTillLoaded(fileObject,
1449 DataSourceType.FILE, currentFileFormat);
1452 newframe.setBounds(bounds);
1453 if (featureSettings != null && featureSettings.isShowing())
1455 final Rectangle fspos = featureSettings.frame.getBounds();
1456 // TODO: need a 'show feature settings' function that takes bounds -
1457 // need to refactor Desktop.addFrame
1458 newframe.featureSettings_actionPerformed(null);
1459 final FeatureSettings nfs = newframe.featureSettings;
1460 SwingUtilities.invokeLater(new Runnable()
1466 nfs.frame.setBounds(fspos);
1469 this.featureSettings.close();
1470 this.featureSettings = null;
1472 this.closeMenuItem_actionPerformed(true);
1478 public void addFromText_actionPerformed(ActionEvent e)
1480 Desktop.getInstance()
1481 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1485 public void addFromURL_actionPerformed(ActionEvent e)
1487 Desktop.getInstance().inputURLMenuItem_actionPerformed(viewport);
1491 public void save_actionPerformed(ActionEvent e)
1493 if (fileName == null || (currentFileFormat == null)
1494 || fileName.startsWith("http"))
1496 saveAs_actionPerformed();
1500 saveAlignment(fileName, currentFileFormat);
1505 * Saves the alignment to a file with a name chosen by the user, if necessary
1506 * warning if a file would be overwritten
1510 public void saveAs_actionPerformed()
1512 String format = currentFileFormat == null ? null
1513 : currentFileFormat.getName();
1514 JalviewFileChooser chooser = JalviewFileChooser
1515 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1517 chooser.setFileView(new JalviewFileView());
1518 chooser.setDialogTitle(
1519 MessageManager.getString("label.save_alignment_to_file"));
1520 chooser.setToolTipText(MessageManager.getString("action.save"));
1522 int value = chooser.showSaveDialog(this);
1524 if (value != JalviewFileChooser.APPROVE_OPTION)
1528 currentFileFormat = chooser.getSelectedFormat();
1529 // todo is this (2005) test now obsolete - value is never null?
1530 while (currentFileFormat == null)
1532 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
1534 .getString("label.select_file_format_before_saving"),
1535 MessageManager.getString("label.file_format_not_specified"),
1536 JvOptionPane.WARNING_MESSAGE);
1537 currentFileFormat = chooser.getSelectedFormat();
1538 value = chooser.showSaveDialog(this);
1539 if (value != JalviewFileChooser.APPROVE_OPTION)
1545 fileName = chooser.getSelectedFile().getPath();
1547 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1548 Cache.setProperty("LAST_DIRECTORY", fileName);
1549 saveAlignment(fileName, currentFileFormat);
1552 boolean lastSaveSuccessful = false;
1554 FileFormatI lastFormatSaved;
1556 String lastFilenameSaved;
1559 * Raise a dialog or status message for the last call to saveAlignment.
1561 * @return true if last call to saveAlignment(file, format) was successful.
1564 public boolean isSaveAlignmentSuccessful()
1567 if (!lastSaveSuccessful)
1569 JvOptionPane.showInternalMessageDialog(this, MessageManager
1570 .formatMessage("label.couldnt_save_file", new Object[]
1571 { lastFilenameSaved }),
1572 MessageManager.getString("label.error_saving_file"),
1573 JvOptionPane.WARNING_MESSAGE);
1578 setStatus(MessageManager.formatMessage(
1579 "label.successfully_saved_to_file_in_format", new Object[]
1580 { lastFilenameSaved, lastFormatSaved }));
1583 return lastSaveSuccessful;
1587 * Saves the alignment to the specified file path, in the specified format,
1588 * which may be an alignment format, or Jalview project format. If the
1589 * alignment has hidden regions, or the format is one capable of including
1590 * non-sequence data (features, annotations, groups), then the user may be
1591 * prompted to specify what to include in the output.
1597 public void saveAlignment(String file, FileFormatI format)
1599 lastSaveSuccessful = true;
1600 lastFilenameSaved = file;
1601 lastFormatSaved = format;
1603 if (FileFormat.Jalview.equals(format))
1605 String shortName = title;
1606 if (shortName.indexOf(File.separatorChar) > -1)
1608 shortName = shortName
1609 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
1611 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file,
1614 statusBar.setText(MessageManager.formatMessage(
1615 "label.successfully_saved_to_file_in_format", new Object[]
1616 { fileName, format }));
1621 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1622 Runnable cancelAction = new Runnable()
1628 lastSaveSuccessful = false;
1631 Runnable outputAction = new Runnable()
1637 // todo defer this to inside formatSequences (or later)
1638 AlignmentExportData exportData = viewport
1639 .getAlignExportData(options);
1640 String output = new FormatAdapter(alignPanel, options)
1641 .formatSequences(format, exportData.getAlignment(),
1642 exportData.getOmitHidden(),
1643 exportData.getStartEndPostions(),
1644 viewport.getAlignment().getHiddenColumns());
1647 lastSaveSuccessful = false;
1651 // create backupfiles object and get new temp filename destination
1652 boolean doBackup = BackupFiles.getEnabled();
1653 BackupFiles backupfiles = doBackup ? new BackupFiles(file) : null;
1656 String tempFilePath = doBackup ? backupfiles.getTempFilePath()
1658 PrintWriter out = new PrintWriter(new FileWriter(tempFilePath));
1662 AlignFrame.this.setTitle(file);
1663 statusBar.setText(MessageManager.formatMessage(
1664 "label.successfully_saved_to_file_in_format",
1666 { fileName, format.getName() }));
1667 lastSaveSuccessful = true;
1668 } catch (Exception ex)
1670 lastSaveSuccessful = false;
1671 ex.printStackTrace();
1676 backupfiles.setWriteSuccess(lastSaveSuccessful);
1677 // do the backup file roll and rename the temp file to actual file
1678 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1685 * show dialog with export options if applicable; else just do it
1687 if (AlignExportOptions.isNeeded(viewport, format))
1689 AlignExportOptions choices = new AlignExportOptions(
1690 alignPanel.getAlignViewport(), format, options);
1691 choices.setResponseAction(0, outputAction);
1692 choices.setResponseAction(1, cancelAction);
1693 choices.showDialog();
1702 * Outputs the alignment to textbox in the requested format, if necessary
1703 * first prompting the user for whether to include hidden regions or
1706 * @param fileFormatName
1710 protected void outputText_actionPerformed(String fileFormatName)
1712 FileFormatI fileFormat = FileFormats.getInstance()
1713 .forName(fileFormatName);
1714 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1715 Runnable outputAction = new Runnable()
1721 // todo defer this to inside formatSequences (or later)
1722 AlignmentExportData exportData = viewport
1723 .getAlignExportData(options);
1724 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1725 cap.setForInput(null);
1728 FileFormatI format = fileFormat;
1729 cap.setText(new FormatAdapter(alignPanel, options)
1730 .formatSequences(format, exportData.getAlignment(),
1731 exportData.getOmitHidden(),
1732 exportData.getStartEndPostions(),
1733 viewport.getAlignment().getHiddenColumns()));
1734 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1735 "label.alignment_output_command", new Object[]
1736 { fileFormat.getName() }), 600, 500);
1737 } catch (OutOfMemoryError oom)
1739 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1747 * show dialog with export options if applicable; else just do it
1749 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1751 AlignExportOptions choices = new AlignExportOptions(
1752 alignPanel.getAlignViewport(), fileFormat, options);
1753 choices.setResponseAction(0, outputAction);
1754 choices.showDialog();
1770 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1772 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1773 htmlSVG.exportHTML(null);
1777 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1779 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1780 bjs.exportHTML(null);
1785 public void createImageMap(File file, String image)
1787 alignPanel.makePNGImageMap(file, image);
1791 * Creates a PNG image of the alignment and writes it to the given file. If
1792 * the file is null, the user is prompted to choose a file.
1798 public void createPNG(File f)
1800 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1804 * Creates an EPS image of the alignment and writes it to the given file. If
1805 * the file is null, the user is prompted to choose a file.
1811 public void createEPS(File f)
1813 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1817 * Creates an SVG image of the alignment and writes it to the given file. If
1818 * the file is null, the user is prompted to choose a file.
1824 public void createSVG(File f)
1826 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1830 public void pageSetup_actionPerformed(ActionEvent e)
1832 PrinterJob printJob = PrinterJob.getPrinterJob();
1833 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1844 public void printMenuItem_actionPerformed(ActionEvent e)
1846 // Putting in a thread avoids Swing painting problems
1847 PrintThread thread = new PrintThread(alignPanel);
1852 public void exportFeatures_actionPerformed(ActionEvent e)
1854 new AnnotationExporter(alignPanel).exportFeatures();
1858 public void exportAnnotations_actionPerformed(ActionEvent e)
1860 new AnnotationExporter(alignPanel).exportAnnotations();
1864 public void associatedData_actionPerformed(ActionEvent e)
1865 throws IOException, InterruptedException
1867 final JalviewFileChooser chooser = new JalviewFileChooser(
1868 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1869 chooser.setFileView(new JalviewFileView());
1870 String tooltip = MessageManager
1871 .getString("label.load_jalview_annotations");
1872 chooser.setDialogTitle(tooltip);
1873 chooser.setToolTipText(tooltip);
1874 chooser.setResponseHandler(0, new Runnable()
1880 String choice = chooser.getSelectedFile().getPath();
1881 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1882 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1886 chooser.showOpenDialog(this);
1890 * Close the current view or all views in the alignment frame. If the frame
1891 * only contains one view then the alignment will be removed from memory.
1893 * @param closeAllTabs
1897 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1899 if (alignPanels != null && alignPanels.size() < 2)
1901 closeAllTabs = true;
1906 if (alignPanels != null)
1910 if (this.isClosed())
1912 // really close all the windows - otherwise wait till
1913 // setClosed(true) is called
1914 for (int i = 0; i < alignPanels.size(); i++)
1916 AlignmentPanel ap = alignPanels.get(i);
1923 closeView(alignPanel);
1928 if (featureSettings != null && featureSettings.isOpen())
1930 featureSettings.close();
1931 featureSettings = null;
1934 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1935 * be called recursively, with the frame now in 'closed' state
1937 this.setClosed(true);
1939 } catch (Exception ex)
1941 ex.printStackTrace();
1946 * Close the specified panel and close up tabs appropriately.
1948 * @param panelToClose
1951 public void closeView(AlignmentPanel panelToClose)
1953 int index = tabbedPane.getSelectedIndex();
1954 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1955 alignPanels.remove(panelToClose);
1956 panelToClose.closePanel();
1957 panelToClose = null;
1959 tabbedPane.removeTabAt(closedindex);
1960 tabbedPane.validate();
1962 if (index > closedindex || index == tabbedPane.getTabCount())
1964 // modify currently selected tab index if necessary.
1968 this.tabSelectionChanged(index);
1975 void updateEditMenuBar()
1978 if (viewport.getHistoryList().size() > 0)
1980 undoMenuItem.setEnabled(true);
1981 CommandI command = viewport.getHistoryList().peek();
1982 undoMenuItem.setText(MessageManager
1983 .formatMessage("label.undo_command", new Object[]
1984 { command.getDescription() }));
1988 undoMenuItem.setEnabled(false);
1989 undoMenuItem.setText(MessageManager.getString("action.undo"));
1992 if (viewport.getRedoList().size() > 0)
1994 redoMenuItem.setEnabled(true);
1996 CommandI command = viewport.getRedoList().peek();
1997 redoMenuItem.setText(MessageManager
1998 .formatMessage("label.redo_command", new Object[]
1999 { command.getDescription() }));
2003 redoMenuItem.setEnabled(false);
2004 redoMenuItem.setText(MessageManager.getString("action.redo"));
2009 public void addHistoryItem(CommandI command)
2011 if (command.getSize() > 0)
2013 viewport.addToHistoryList(command);
2014 viewport.clearRedoList();
2015 updateEditMenuBar();
2016 viewport.updateHiddenColumns();
2017 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
2018 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2019 // viewport.getColumnSelection()
2020 // .getHiddenColumns().size() > 0);
2026 * @return alignment objects for all views
2029 AlignmentI[] getViewAlignments()
2031 if (alignPanels != null)
2033 AlignmentI[] als = new AlignmentI[alignPanels.size()];
2035 for (AlignmentPanel ap : alignPanels)
2037 als[i++] = ap.av.getAlignment();
2041 if (viewport != null)
2043 return new AlignmentI[] { viewport.getAlignment() };
2056 protected void undoMenuItem_actionPerformed(ActionEvent e)
2058 if (viewport.getHistoryList().isEmpty())
2062 CommandI command = viewport.getHistoryList().pop();
2063 viewport.addToRedoList(command);
2064 command.undoCommand(getViewAlignments());
2066 AlignmentViewport originalSource = getOriginatingSource(command);
2067 updateEditMenuBar();
2069 if (originalSource != null)
2071 if (originalSource != viewport)
2074 "Implementation worry: mismatch of viewport origin for undo");
2076 originalSource.updateHiddenColumns();
2077 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
2079 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2080 // viewport.getColumnSelection()
2081 // .getHiddenColumns().size() > 0);
2082 originalSource.notifyAlignment();
2095 protected void redoMenuItem_actionPerformed(ActionEvent e)
2097 if (viewport.getRedoList().size() < 1)
2102 CommandI command = viewport.getRedoList().pop();
2103 viewport.addToHistoryList(command);
2104 command.doCommand(getViewAlignments());
2106 AlignmentViewport originalSource = getOriginatingSource(command);
2107 updateEditMenuBar();
2109 if (originalSource != null)
2112 if (originalSource != viewport)
2115 "Implementation worry: mismatch of viewport origin for redo");
2117 originalSource.updateHiddenColumns();
2118 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
2120 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2121 // viewport.getColumnSelection()
2122 // .getHiddenColumns().size() > 0);
2123 originalSource.notifyAlignment();
2128 AlignmentViewport getOriginatingSource(CommandI command)
2130 AlignmentViewport originalSource = null;
2131 // For sequence removal and addition, we need to fire
2132 // the property change event FROM the viewport where the
2133 // original alignment was altered
2134 AlignmentI al = null;
2135 if (command instanceof EditCommand)
2137 EditCommand editCommand = (EditCommand) command;
2138 al = editCommand.getAlignment();
2139 List<Component> comps = PaintRefresher.components
2140 .get(viewport.getSequenceSetId());
2142 for (Component comp : comps)
2144 if (comp instanceof AlignmentPanel)
2146 if (al == ((AlignmentPanel) comp).av.getAlignment())
2148 originalSource = ((AlignmentPanel) comp).av;
2155 if (originalSource == null)
2157 // The original view is closed, we must validate
2158 // the current view against the closed view first
2161 PaintRefresher.validateSequences(al, viewport.getAlignment());
2164 originalSource = viewport;
2167 return originalSource;
2177 public void moveSelectedSequences(boolean up)
2179 SequenceGroup sg = viewport.getSelectionGroup();
2185 viewport.getAlignment().moveSelectedSequencesByOne(sg,
2186 viewport.getHiddenRepSequences(), up);
2187 alignPanel.paintAlignment(true, false);
2190 synchronized void slideSequences(boolean right, int size)
2192 List<SequenceI> sg = new ArrayList<>();
2193 if (viewport.cursorMode)
2195 sg.add(viewport.getAlignment()
2196 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
2198 else if (viewport.getSelectionGroup() != null
2199 && viewport.getSelectionGroup().getSize() != viewport
2200 .getAlignment().getHeight())
2202 sg = viewport.getSelectionGroup()
2203 .getSequences(viewport.getHiddenRepSequences());
2211 List<SequenceI> invertGroup = new ArrayList<>();
2213 for (SequenceI seq : viewport.getAlignment().getSequences())
2215 if (!sg.contains(seq))
2217 invertGroup.add(seq);
2221 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
2223 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
2224 for (int i = 0; i < invertGroup.size(); i++)
2226 seqs2[i] = invertGroup.get(i);
2229 SlideSequencesCommand ssc;
2232 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
2233 viewport.getGapCharacter());
2237 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
2238 viewport.getGapCharacter());
2241 int groupAdjustment = 0;
2242 if (ssc.getGapsInsertedBegin() && right)
2244 if (viewport.cursorMode)
2246 alignPanel.getSeqPanel().moveCursor(size, 0);
2250 groupAdjustment = size;
2253 else if (!ssc.getGapsInsertedBegin() && !right)
2255 if (viewport.cursorMode)
2257 alignPanel.getSeqPanel().moveCursor(-size, 0);
2261 groupAdjustment = -size;
2265 if (groupAdjustment != 0)
2267 viewport.getSelectionGroup().setStartRes(
2268 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
2269 viewport.getSelectionGroup().setEndRes(
2270 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
2274 * just extend the last slide command if compatible; but not if in
2275 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
2277 boolean appendHistoryItem = false;
2278 Deque<CommandI> historyList = viewport.getHistoryList();
2279 boolean inSplitFrame = getSplitViewContainer() != null;
2280 if (!inSplitFrame && historyList != null && historyList.size() > 0
2281 && historyList.peek() instanceof SlideSequencesCommand)
2283 appendHistoryItem = ssc.appendSlideCommand(
2284 (SlideSequencesCommand) historyList.peek());
2287 if (!appendHistoryItem)
2289 addHistoryItem(ssc);
2303 protected void copy_actionPerformed()
2305 if (viewport.getSelectionGroup() == null)
2309 // TODO: preserve the ordering of displayed alignment annotation in any
2310 // internal paste (particularly sequence associated annotation)
2311 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2312 String[] omitHidden = null;
2314 if (viewport.hasHiddenColumns())
2316 omitHidden = viewport.getViewAsString(true);
2319 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2320 seqs, omitHidden, null);
2322 StringSelection ss = new StringSelection(output);
2324 Desktop d = Desktop.getInstance();
2327 d.internalCopy = true;
2328 // Its really worth setting the clipboard contents
2329 // to empty before setting the large StringSelection!!
2330 Toolkit.getDefaultToolkit().getSystemClipboard()
2331 .setContents(new StringSelection(""), null);
2333 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2334 Desktop.getInstance());
2335 } catch (OutOfMemoryError er)
2337 new OOMWarning("copying region", er);
2341 HiddenColumns hiddenColumns = null;
2342 if (viewport.hasHiddenColumns())
2344 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2345 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2347 // create new HiddenColumns object with copy of hidden regions
2348 // between startRes and endRes, offset by startRes
2349 hiddenColumns = new HiddenColumns(
2350 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2351 hiddenCutoff, hiddenOffset);
2354 d.jalviewClipboard = new Object[] { seqs,
2355 viewport.getAlignment().getDataset(), hiddenColumns };
2356 setStatus(MessageManager.formatMessage(
2357 "label.copied_sequences_to_clipboard", new Object[]
2358 { Integer.valueOf(seqs.length).toString() }));
2366 * @throws InterruptedException
2367 * @throws IOException
2371 protected void pasteNew_actionPerformed(ActionEvent e)
2372 throws IOException, InterruptedException
2382 * @throws InterruptedException
2383 * @throws IOException
2387 protected void pasteThis_actionPerformed(ActionEvent e)
2388 throws IOException, InterruptedException
2394 * Paste contents of Jalview clipboard
2396 * @param newAlignment
2397 * true to paste to a new alignment, otherwise add to this.
2398 * @throws InterruptedException
2399 * @throws IOException
2401 void paste(boolean newAlignment) throws IOException, InterruptedException
2403 boolean externalPaste = true;
2406 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2407 Transferable contents = c.getContents(this);
2409 if (contents == null)
2418 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2419 if (str.length() < 1)
2424 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2426 } catch (OutOfMemoryError er)
2428 new OOMWarning("Out of memory pasting sequences!!", er);
2432 SequenceI[] sequences;
2433 boolean annotationAdded = false;
2434 AlignmentI alignment = null;
2436 Desktop d = Desktop.getInstance();
2438 if (d.jalviewClipboard != null)
2440 // The clipboard was filled from within Jalview, we must use the
2442 // And dataset from the copied alignment
2443 SequenceI[] newseq = (SequenceI[]) d.jalviewClipboard[0];
2444 // be doubly sure that we create *new* sequence objects.
2445 sequences = new SequenceI[newseq.length];
2446 for (int i = 0; i < newseq.length; i++)
2448 sequences[i] = new Sequence(newseq[i]);
2450 alignment = new Alignment(sequences);
2451 externalPaste = false;
2455 // parse the clipboard as an alignment.
2456 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2458 sequences = alignment.getSequencesArray();
2462 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2468 if (d.jalviewClipboard != null)
2470 // dataset is inherited
2471 alignment.setDataset((Alignment) d.jalviewClipboard[1]);
2475 // new dataset is constructed
2476 alignment.setDataset(null);
2478 alwidth = alignment.getWidth() + 1;
2482 AlignmentI pastedal = alignment; // preserve pasted alignment object
2483 // Add pasted sequences and dataset into existing alignment.
2484 alignment = viewport.getAlignment();
2485 alwidth = alignment.getWidth() + 1;
2486 // decide if we need to import sequences from an existing dataset
2487 boolean importDs = d.jalviewClipboard != null
2488 && d.jalviewClipboard[1] != alignment.getDataset();
2489 // importDs==true instructs us to copy over new dataset sequences from
2490 // an existing alignment
2491 Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2493 // minimum dataset set
2495 for (int i = 0; i < sequences.length; i++)
2499 newDs.addElement(null);
2501 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2503 if (importDs && ds != null)
2505 if (!newDs.contains(ds))
2507 newDs.setElementAt(ds, i);
2508 ds = new Sequence(ds);
2509 // update with new dataset sequence
2510 sequences[i].setDatasetSequence(ds);
2514 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2519 // copy and derive new dataset sequence
2520 sequences[i] = sequences[i].deriveSequence();
2521 alignment.getDataset()
2522 .addSequence(sequences[i].getDatasetSequence());
2523 // TODO: avoid creation of duplicate dataset sequences with a
2524 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2526 alignment.addSequence(sequences[i]); // merges dataset
2530 newDs.clear(); // tidy up
2532 if (alignment.getAlignmentAnnotation() != null)
2534 for (AlignmentAnnotation alan : alignment
2535 .getAlignmentAnnotation())
2537 if (alan.graphGroup > fgroup)
2539 fgroup = alan.graphGroup;
2543 if (pastedal.getAlignmentAnnotation() != null)
2545 // Add any annotation attached to alignment.
2546 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2547 for (int i = 0; i < alann.length; i++)
2549 annotationAdded = true;
2550 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2552 AlignmentAnnotation newann = new AlignmentAnnotation(
2554 if (newann.graphGroup > -1)
2556 if (newGraphGroups.size() <= newann.graphGroup
2557 || newGraphGroups.get(newann.graphGroup) == null)
2559 for (int q = newGraphGroups
2560 .size(); q <= newann.graphGroup; q++)
2562 newGraphGroups.add(q, null);
2564 newGraphGroups.set(newann.graphGroup,
2565 Integer.valueOf(++fgroup));
2567 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2571 newann.padAnnotation(alwidth);
2572 alignment.addAnnotation(newann);
2582 addHistoryItem(new EditCommand(
2583 MessageManager.getString("label.add_sequences"),
2584 Action.PASTE, sequences, 0, alignment.getWidth(),
2587 // Add any annotations attached to sequences
2588 for (int i = 0; i < sequences.length; i++)
2590 if (sequences[i].getAnnotation() != null)
2592 AlignmentAnnotation newann;
2593 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2595 annotationAdded = true;
2596 newann = sequences[i].getAnnotation()[a];
2597 newann.adjustForAlignment();
2598 newann.padAnnotation(alwidth);
2599 if (newann.graphGroup > -1)
2601 if (newann.graphGroup > -1)
2603 if (newGraphGroups.size() <= newann.graphGroup
2604 || newGraphGroups.get(newann.graphGroup) == null)
2606 for (int q = newGraphGroups
2607 .size(); q <= newann.graphGroup; q++)
2609 newGraphGroups.add(q, null);
2611 newGraphGroups.set(newann.graphGroup,
2612 Integer.valueOf(++fgroup));
2614 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2618 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2622 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2630 // propagate alignment changed.
2631 viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2632 if (annotationAdded)
2634 // Duplicate sequence annotation in all views.
2635 AlignmentI[] alview = this.getViewAlignments();
2636 for (int i = 0; i < sequences.length; i++)
2638 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2643 for (int avnum = 0; avnum < alview.length; avnum++)
2645 if (alview[avnum] != alignment)
2647 // duplicate in a view other than the one with input focus
2648 int avwidth = alview[avnum].getWidth() + 1;
2649 // this relies on sann being preserved after we
2650 // modify the sequence's annotation array for each duplication
2651 for (int a = 0; a < sann.length; a++)
2653 AlignmentAnnotation newann = new AlignmentAnnotation(
2655 sequences[i].addAlignmentAnnotation(newann);
2656 newann.padAnnotation(avwidth);
2657 alview[avnum].addAnnotation(newann); // annotation was
2658 // duplicated earlier
2659 // TODO JAL-1145 graphGroups are not updated for sequence
2660 // annotation added to several views. This may cause
2662 alview[avnum].setAnnotationIndex(newann, a);
2667 buildSortByAnnotationScoresMenu();
2669 viewport.notifyAlignment();
2670 if (alignPanels != null)
2672 for (AlignmentPanel ap : alignPanels)
2674 ap.validateAnnotationDimensions(false);
2679 alignPanel.validateAnnotationDimensions(false);
2685 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2687 String newtitle = new String("Copied sequences");
2689 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2691 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2692 af.viewport.setHiddenColumns(hc);
2695 // >>>This is a fix for the moment, until a better solution is
2697 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2698 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2699 .getFeatureRenderer());
2701 // TODO: maintain provenance of an alignment, rather than just make the
2702 // title a concatenation of operations.
2705 if (title.startsWith("Copied sequences"))
2711 newtitle = newtitle.concat("- from " + title);
2716 newtitle = new String("Pasted sequences");
2719 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2724 } catch (Exception ex)
2726 ex.printStackTrace();
2727 System.out.println("Exception whilst pasting: " + ex);
2728 // could be anything being pasted in here
2733 protected void expand_newalign(ActionEvent e)
2737 AlignmentI alignment = AlignmentUtils
2738 .expandContext(getViewport().getAlignment(), -1);
2739 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2741 String newtitle = new String("Flanking alignment");
2742 Desktop d = Desktop.getInstance();
2743 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2745 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2746 af.viewport.setHiddenColumns(hc);
2749 // >>>This is a fix for the moment, until a better solution is
2751 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2752 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2753 .getFeatureRenderer());
2755 // TODO: maintain provenance of an alignment, rather than just make the
2756 // title a concatenation of operations.
2758 if (title.startsWith("Copied sequences"))
2764 newtitle = newtitle.concat("- from " + title);
2768 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2770 } catch (Exception ex)
2772 ex.printStackTrace();
2773 System.out.println("Exception whilst pasting: " + ex);
2774 // could be anything being pasted in here
2775 } catch (OutOfMemoryError oom)
2777 new OOMWarning("Viewing flanking region of alignment", oom);
2782 * Action Cut (delete and copy) the selected region
2786 protected void cut_actionPerformed()
2788 copy_actionPerformed();
2789 delete_actionPerformed();
2793 * Performs menu option to Delete the currently selected region
2797 protected void delete_actionPerformed()
2800 SequenceGroup sg = viewport.getSelectionGroup();
2806 Runnable okAction = new Runnable()
2812 SequenceI[] cut = sg.getSequences()
2813 .toArray(new SequenceI[sg.getSize()]);
2815 addHistoryItem(new EditCommand(
2816 MessageManager.getString("label.cut_sequences"), Action.CUT,
2817 cut, sg.getStartRes(),
2818 sg.getEndRes() - sg.getStartRes() + 1,
2819 viewport.getAlignment()));
2821 viewport.setSelectionGroup(null);
2822 viewport.sendSelection();
2823 viewport.getAlignment().deleteGroup(sg);
2825 viewport.notifyAlignment();
2827 if (viewport.getAlignment().getHeight() < 1)
2831 AlignFrame.this.setClosed(true);
2832 } catch (Exception ex)
2842 * If the cut affects all sequences, prompt for confirmation
2844 boolean wholeHeight = sg.getSize() == viewport.getAlignment()
2846 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2847 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2848 if (wholeHeight && wholeWidth)
2850 JvOptionPane dialog = JvOptionPane
2851 .newOptionDialog(Desktop.getDesktopPane());
2852 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2853 Object[] options = new Object[] {
2854 MessageManager.getString("action.ok"),
2855 MessageManager.getString("action.cancel") };
2856 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2857 MessageManager.getString("label.delete_all"),
2858 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2859 options, options[0]);
2875 protected void deleteGroups_actionPerformed(ActionEvent e)
2877 if (avc.deleteGroups())
2879 updateAll(viewport.getSequenceSetId());
2883 private void updateAll(String id)
2887 // this will force a non-fast repaint of both the IdPanel and SeqPanel
2888 alignPanel.getIdPanel().getIdCanvas().setNoFastPaint();
2889 alignPanel.getSeqPanel().seqCanvas.setNoFastPaint();
2890 alignPanel.repaint();
2895 PaintRefresher.Refresh(this, id);
2896 alignPanel.paintAlignment(true, true);
2898 alignPanel.updateAnnotation();
2909 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2911 alignPanel.selectAllSequences();
2922 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2924 alignPanel.deselectAllSequences();
2935 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2937 SequenceGroup sg = viewport.getSelectionGroup();
2941 alignPanel.selectAllSequences();
2946 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2948 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2950 // JAL-2034 - should delegate to
2951 // alignPanel to decide if overview needs
2954 alignPanel.paintAlignment(true, false);
2955 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2956 viewport.sendSelection();
2960 public void invertColSel_actionPerformed(ActionEvent e)
2962 viewport.invertColumnSelection();
2963 alignPanel.paintAlignment(true, false);
2964 viewport.sendSelection();
2975 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2977 trimAlignment(true);
2988 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2990 trimAlignment(false);
2993 void trimAlignment(boolean trimLeft)
2995 ColumnSelection colSel = viewport.getColumnSelection();
2998 if (!colSel.isEmpty())
3002 column = colSel.getMin();
3006 column = colSel.getMax();
3010 if (viewport.getSelectionGroup() != null)
3012 seqs = viewport.getSelectionGroup()
3013 .getSequencesAsArray(viewport.getHiddenRepSequences());
3017 seqs = viewport.getAlignment().getSequencesArray();
3020 TrimRegionCommand trimRegion;
3023 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
3024 column, viewport.getAlignment());
3025 viewport.getRanges().setStartRes(0);
3029 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
3030 column, viewport.getAlignment());
3033 setStatus(MessageManager.formatMessage("label.removed_columns",
3035 { Integer.valueOf(trimRegion.getSize()).toString() }));
3037 addHistoryItem(trimRegion);
3039 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3041 if ((trimLeft && !sg.adjustForRemoveLeft(column))
3042 || (!trimLeft && !sg.adjustForRemoveRight(column)))
3044 viewport.getAlignment().deleteGroup(sg);
3048 viewport.notifyAlignment();
3061 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
3063 int start = 0, end = viewport.getAlignment().getWidth() - 1;
3066 if (viewport.getSelectionGroup() != null)
3068 seqs = viewport.getSelectionGroup()
3069 .getSequencesAsArray(viewport.getHiddenRepSequences());
3070 start = viewport.getSelectionGroup().getStartRes();
3071 end = viewport.getSelectionGroup().getEndRes();
3075 seqs = viewport.getAlignment().getSequencesArray();
3078 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
3079 "Remove Gapped Columns", seqs, start, end,
3080 viewport.getAlignment());
3082 addHistoryItem(removeGapCols);
3084 setStatus(MessageManager.formatMessage("label.removed_empty_columns",
3086 { Integer.valueOf(removeGapCols.getSize()).toString() }));
3088 // This is to maintain viewport position on first residue
3089 // of first sequence
3090 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3091 ViewportRanges ranges = viewport.getRanges();
3092 int startRes = seq.findPosition(ranges.getStartRes());
3093 // ShiftList shifts;
3094 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
3095 // edit.alColumnChanges=shifts.getInverse();
3096 // if (viewport.hasHiddenColumns)
3097 // viewport.getColumnSelection().compensateForEdits(shifts);
3098 ranges.setStartRes(seq.findIndex(startRes) - 1);
3099 viewport.notifyAlignment();
3112 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
3114 int start = 0, end = viewport.getAlignment().getWidth() - 1;
3117 if (viewport.getSelectionGroup() != null)
3119 seqs = viewport.getSelectionGroup()
3120 .getSequencesAsArray(viewport.getHiddenRepSequences());
3121 start = viewport.getSelectionGroup().getStartRes();
3122 end = viewport.getSelectionGroup().getEndRes();
3126 seqs = viewport.getAlignment().getSequencesArray();
3129 // This is to maintain viewport position on first residue
3130 // of first sequence
3131 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3132 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
3134 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
3135 viewport.getAlignment()));
3137 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
3138 viewport.notifyAlignment();
3150 public void padGapsMenuitem_actionPerformed(ActionEvent e)
3152 viewport.setPadGaps(padGapsMenuitem.isSelected());
3153 viewport.notifyAlignment();
3165 public void findMenuItem_actionPerformed(ActionEvent e)
3171 * Create a new view of the current alignment.
3175 public void newView_actionPerformed(ActionEvent e)
3177 newView(null, true);
3181 * Creates and shows a new view of the current alignment.
3184 * title of newly created view; if null, one will be generated
3185 * @param copyAnnotation
3186 * if true then duplicate all annnotation, groups and settings
3187 * @return new alignment panel, already displayed.
3190 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
3193 * Create a new AlignmentPanel (with its own, new Viewport)
3195 AlignmentPanel newap = new jalview.project.Jalview2XML()
3196 .copyAlignPanel(alignPanel);
3197 if (!copyAnnotation)
3200 * remove all groups and annotation except for the automatic stuff
3202 newap.av.getAlignment().deleteAllGroups();
3203 newap.av.getAlignment().deleteAllAnnotations(false);
3206 newap.av.setGatherViewsHere(false);
3208 if (viewport.getViewName() == null)
3210 viewport.setViewName(
3211 MessageManager.getString("label.view_name_original"));
3215 * Views share the same edits undo and redo stacks
3217 newap.av.setHistoryList(viewport.getHistoryList());
3218 newap.av.setRedoList(viewport.getRedoList());
3221 * copy any visualisation settings that are not saved in the project
3223 newap.av.setColourAppliesToAllGroups(
3224 viewport.getColourAppliesToAllGroups());
3227 * Views share the same mappings; need to deregister any new mappings
3228 * created by copyAlignPanel, and register the new reference to the shared
3231 newap.av.replaceMappings(viewport.getAlignment());
3234 * start up cDNA consensus (if applicable) now mappings are in place
3236 if (newap.av.initComplementConsensus())
3238 newap.refresh(true); // adjust layout of annotations
3241 newap.av.setViewName(getNewViewName(viewTitle));
3243 addAlignmentPanel(newap, true);
3244 newap.alignmentChanged();
3246 if (alignPanels.size() == 2)
3248 viewport.setGatherViewsHere(true);
3250 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
3255 * Make a new name for the view, ensuring it is unique within the current
3256 * sequenceSetId. (This used to be essential for Jalview Project archives, but
3257 * these now use viewId. Unique view names are still desirable for usability.)
3263 protected String getNewViewName(String viewTitle)
3265 int index = Desktop.getViewCount(viewport.getSequenceSetId());
3266 boolean addFirstIndex = false;
3267 if (viewTitle == null || viewTitle.trim().length() == 0)
3269 viewTitle = MessageManager.getString("action.view");
3270 addFirstIndex = true;
3274 index = 1;// we count from 1 if given a specific name
3276 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
3278 List<Component> comps = PaintRefresher.components
3279 .get(viewport.getSequenceSetId());
3281 List<String> existingNames = getExistingViewNames(comps);
3283 while (existingNames.contains(newViewName))
3285 newViewName = viewTitle + " " + (++index);
3291 * Returns a list of distinct view names found in the given list of
3292 * components. View names are held on the viewport of an AlignmentPanel.
3298 protected List<String> getExistingViewNames(List<Component> comps)
3300 List<String> existingNames = new ArrayList<>();
3301 for (Component comp : comps)
3303 if (comp instanceof AlignmentPanel)
3305 AlignmentPanel ap = (AlignmentPanel) comp;
3306 if (!existingNames.contains(ap.av.getViewName()))
3308 existingNames.add(ap.av.getViewName());
3312 return existingNames;
3316 * Explode tabbed views into separate windows.
3320 public void expandViews_actionPerformed(ActionEvent e)
3322 Desktop.explodeViews(this);
3326 * Gather views in separate windows back into a tabbed presentation.
3330 public void gatherViews_actionPerformed(ActionEvent e)
3332 Desktop.getInstance().gatherViews(this);
3343 public void font_actionPerformed(ActionEvent e)
3345 new FontChooser(alignPanel);
3356 protected void seqLimit_actionPerformed(ActionEvent e)
3358 viewport.setShowJVSuffix(seqLimits.isSelected());
3360 alignPanel.getIdPanel().getIdCanvas()
3361 .setPreferredSize(alignPanel.calculateIdWidth());
3362 alignPanel.paintAlignment(true, false);
3366 public void idRightAlign_actionPerformed(ActionEvent e)
3368 viewport.setRightAlignIds(idRightAlign.isSelected());
3369 alignPanel.paintAlignment(false, false);
3373 public void centreColumnLabels_actionPerformed(ActionEvent e)
3375 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3376 alignPanel.paintAlignment(false, false);
3382 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3386 protected void followHighlight_actionPerformed()
3389 * Set the 'follow' flag on the Viewport (and scroll to position if now
3392 final boolean state = this.followHighlightMenuItem.getState();
3393 viewport.setFollowHighlight(state);
3396 alignPanel.scrollToPosition(viewport.getSearchResults());
3408 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3410 viewport.setColourText(colourTextMenuItem.isSelected());
3411 alignPanel.paintAlignment(false, false);
3422 public void wrapMenuItem_actionPerformed(ActionEvent e)
3424 scaleAbove.setVisible(wrapMenuItem.isSelected());
3425 scaleLeft.setVisible(wrapMenuItem.isSelected());
3426 scaleRight.setVisible(wrapMenuItem.isSelected());
3427 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3428 alignPanel.updateLayout();
3432 public void showAllSeqs_actionPerformed(ActionEvent e)
3434 viewport.showAllHiddenSeqs();
3438 public void showAllColumns_actionPerformed(ActionEvent e)
3440 viewport.showAllHiddenColumns();
3441 alignPanel.paintAlignment(true, true);
3442 viewport.sendSelection();
3446 public void hideSelSequences_actionPerformed(ActionEvent e)
3448 viewport.hideAllSelectedSeqs();
3452 * called by key handler and the hide all/show all menu items
3458 protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3461 boolean hide = false;
3462 SequenceGroup sg = viewport.getSelectionGroup();
3463 if (!toggleSeqs && !toggleCols)
3465 // Hide everything by the current selection - this is a hack - we do the
3466 // invert and then hide
3467 // first check that there will be visible columns after the invert.
3468 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3469 && sg.getStartRes() <= sg.getEndRes()))
3471 // now invert the sequence set, if required - empty selection implies
3472 // that no hiding is required.
3475 invertSequenceMenuItem_actionPerformed(null);
3476 sg = viewport.getSelectionGroup();
3480 viewport.expandColSelection(sg, true);
3481 // finally invert the column selection and get the new sequence
3483 invertColSel_actionPerformed(null);
3490 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3492 hideSelSequences_actionPerformed(null);
3495 else if (!(toggleCols && viewport.hasSelectedColumns()))
3497 showAllSeqs_actionPerformed(null);
3503 if (viewport.hasSelectedColumns())
3505 hideSelColumns_actionPerformed(null);
3508 viewport.setSelectionGroup(sg);
3513 showAllColumns_actionPerformed(null);
3522 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3523 * event.ActionEvent)
3527 public void hideAllButSelection_actionPerformed(ActionEvent e)
3529 toggleHiddenRegions(false, false);
3530 viewport.sendSelection();
3537 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3542 public void hideAllSelection_actionPerformed(ActionEvent e)
3544 SequenceGroup sg = viewport.getSelectionGroup();
3545 viewport.expandColSelection(sg, false);
3546 viewport.hideAllSelectedSeqs();
3547 viewport.hideSelectedColumns();
3548 alignPanel.updateLayout();
3549 alignPanel.paintAlignment(true, true);
3550 viewport.sendSelection();
3557 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3562 public void showAllhidden_actionPerformed(ActionEvent e)
3564 viewport.showAllHiddenColumns();
3565 viewport.showAllHiddenSeqs();
3566 alignPanel.paintAlignment(true, true);
3567 viewport.sendSelection();
3571 public void hideSelColumns_actionPerformed(ActionEvent e)
3573 viewport.hideSelectedColumns();
3574 alignPanel.updateLayout();
3575 alignPanel.paintAlignment(true, true);
3576 viewport.sendSelection();
3580 public void hiddenMarkers_actionPerformed(ActionEvent e)
3582 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3594 protected void scaleAbove_actionPerformed(ActionEvent e)
3596 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3597 alignPanel.updateLayout();
3598 alignPanel.paintAlignment(true, false);
3609 protected void scaleLeft_actionPerformed(ActionEvent e)
3611 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3612 alignPanel.updateLayout();
3613 alignPanel.paintAlignment(true, false);
3624 protected void scaleRight_actionPerformed(ActionEvent e)
3626 viewport.setScaleRightWrapped(scaleRight.isSelected());
3627 alignPanel.updateLayout();
3628 alignPanel.paintAlignment(true, false);
3639 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3641 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3642 alignPanel.paintAlignment(false, false);
3653 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3655 viewport.setShowText(viewTextMenuItem.isSelected());
3656 alignPanel.paintAlignment(false, false);
3667 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3669 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3670 alignPanel.paintAlignment(false, false);
3673 public FeatureSettings featureSettings;
3676 public FeatureSettingsControllerI getFeatureSettingsUI()
3678 return featureSettings;
3682 public void featureSettings_actionPerformed(ActionEvent e)
3684 showFeatureSettingsUI();
3688 public FeatureSettingsControllerI showFeatureSettingsUI()
3690 if (featureSettings != null)
3692 featureSettings.closeOldSettings();
3693 featureSettings = null;
3695 if (!showSeqFeatures.isSelected())
3697 // make sure features are actually displayed
3698 showSeqFeatures.setSelected(true);
3699 showSeqFeatures_actionPerformed(null);
3701 featureSettings = new FeatureSettings(this);
3702 return featureSettings;
3706 * Set or clear 'Show Sequence Features'
3713 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3715 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3716 alignPanel.paintAlignment(true, true);
3720 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3721 * the annotations panel as a whole.
3723 * The options to show/hide all annotations should be enabled when the panel
3724 * is shown, and disabled when the panel is hidden.
3730 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3732 final boolean setVisible = annotationPanelMenuItem.isSelected();
3733 viewport.setShowAnnotation(setVisible);
3734 syncAnnotationMenuItems(setVisible);
3735 alignPanel.updateLayout();
3737 SwingUtilities.invokeLater(new Runnable() {
3742 alignPanel.updateScrollBarsFromRanges();
3748 private void syncAnnotationMenuItems(boolean setVisible)
3750 showAllSeqAnnotations.setEnabled(setVisible);
3751 hideAllSeqAnnotations.setEnabled(setVisible);
3752 showAllAlAnnotations.setEnabled(setVisible);
3753 hideAllAlAnnotations.setEnabled(setVisible);
3757 public void alignmentProperties()
3760 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3763 String content = MessageManager.formatMessage("label.html_content",
3765 { contents.toString() });
3768 if (Platform.isJS())
3770 JLabel textLabel = new JLabel();
3771 textLabel.setText(content);
3772 textLabel.setBackground(Color.WHITE);
3774 pane = new JPanel(new BorderLayout());
3775 ((JPanel) pane).setOpaque(true);
3776 pane.setBackground(Color.WHITE);
3777 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3786 JEditorPane editPane = new JEditorPane("text/html", "");
3787 editPane.setEditable(false);
3788 editPane.setText(content);
3792 JInternalFrame frame = new JInternalFrame();
3794 frame.getContentPane().add(new JScrollPane(pane));
3796 Desktop.addInternalFrame(frame, MessageManager
3797 .formatMessage("label.alignment_properties", new Object[]
3798 { getTitle() }), 500, 400);
3809 public void overviewMenuItem_actionPerformed(ActionEvent e)
3811 if (alignPanel.overviewPanel != null)
3816 JInternalFrame frame = new JInternalFrame();
3818 // BH 2019.07.26 we allow for an embedded
3819 // undecorated overview with defined size
3820 frame.setName(Platform.getAppID("overview"));
3822 Dimension dim = Platform.getDimIfEmbedded(frame, -1, -1);
3823 if (dim != null && dim.width == 0)
3825 dim = null; // hidden, not embedded
3827 OverviewPanel overview = new OverviewPanel(alignPanel, dim);
3829 frame.setContentPane(overview);
3832 dim = new Dimension();
3833 // was frame.getSize(), but that is 0,0 at this point;
3837 // we are imbedding, and so we have an undecorated frame
3838 // and we can set the the frame dimensions accordingly.
3840 // allowing for unresizable option using, style="resize:none"
3841 boolean resizable = (Platform.getEmbeddedAttribute(frame,
3842 "resize") != "none");
3843 Desktop.addInternalFrame(frame, MessageManager
3844 .formatMessage("label.overview_params", new Object[]
3845 { this.getTitle() }), Desktop.FRAME_MAKE_VISIBLE, dim.width,
3846 dim.height, resizable, Desktop.FRAME_ALLOW_ANY_SIZE);
3848 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3849 frame.addInternalFrameListener(
3850 new javax.swing.event.InternalFrameAdapter()
3854 public void internalFrameClosed(
3855 javax.swing.event.InternalFrameEvent evt)
3858 alignPanel.setOverviewPanel(null);
3861 if (getKeyListeners().length > 0)
3863 frame.addKeyListener(getKeyListeners()[0]);
3866 alignPanel.setOverviewPanel(overview);
3870 public void textColour_actionPerformed()
3872 new TextColourChooser().chooseColour(alignPanel, null);
3876 * public void covariationColour_actionPerformed() {
3878 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3883 public void annotationColour_actionPerformed()
3885 new AnnotationColourChooser(viewport, alignPanel);
3889 public void annotationColumn_actionPerformed(ActionEvent e)
3891 new AnnotationColumnChooser(viewport, alignPanel);
3895 * Action on the user checking or unchecking the option to apply the selected
3896 * colour scheme to all groups. If unchecked, groups may have their own
3897 * independent colour schemes.
3903 public void applyToAllGroups_actionPerformed(boolean selected)
3905 viewport.setColourAppliesToAllGroups(selected);
3909 * Action on user selecting a colour from the colour menu
3912 * the name (not the menu item label!) of the colour scheme
3916 public void changeColour_actionPerformed(String name)
3919 * 'User Defined' opens a panel to configure or load a
3920 * user-defined colour scheme
3922 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3924 new UserDefinedColours(alignPanel);
3929 * otherwise set the chosen colour scheme (or null for 'None')
3931 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3932 viewport, viewport.getAlignment(),
3933 viewport.getHiddenRepSequences());
3938 * Actions on setting or changing the alignment colour scheme
3944 public void changeColour(ColourSchemeI cs)
3946 // TODO: pull up to controller method
3947 ColourMenuHelper.setColourSelected(colourMenu, cs);
3949 viewport.setGlobalColourScheme(cs);
3951 alignPanel.paintAlignment(true, true);
3955 * Show the PID threshold slider panel
3959 protected void modifyPID_actionPerformed()
3961 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3962 alignPanel.getViewName());
3963 SliderPanel.showPIDSlider();
3967 * Show the Conservation slider panel
3971 protected void modifyConservation_actionPerformed()
3973 SliderPanel.setConservationSlider(alignPanel,
3974 viewport.getResidueShading(), alignPanel.getViewName());
3975 SliderPanel.showConservationSlider();
3979 * Action on selecting or deselecting (Colour) By Conservation
3983 public void conservationMenuItem_actionPerformed(boolean selected)
3985 modifyConservation.setEnabled(selected);
3986 viewport.setConservationSelected(selected);
3987 viewport.getResidueShading().setConservationApplied(selected);
3989 changeColour(viewport.getGlobalColourScheme());
3992 modifyConservation_actionPerformed();
3996 SliderPanel.hideConservationSlider();
4001 * Action on selecting or deselecting (Colour) Above PID Threshold
4005 public void abovePIDThreshold_actionPerformed(boolean selected)
4007 modifyPID.setEnabled(selected);
4008 viewport.setAbovePIDThreshold(selected);
4011 viewport.getResidueShading().setThreshold(0,
4012 viewport.isIgnoreGapsConsensus());
4015 changeColour(viewport.getGlobalColourScheme());
4018 modifyPID_actionPerformed();
4022 SliderPanel.hidePIDSlider();
4034 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
4036 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4037 AlignmentSorter.sortByPID(viewport.getAlignment(),
4038 viewport.getAlignment().getSequenceAt(0));
4039 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
4040 viewport.getAlignment()));
4041 alignPanel.paintAlignment(true, false);
4052 public void sortIDMenuItem_actionPerformed(ActionEvent e)
4054 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4055 AlignmentSorter.sortByID(viewport.getAlignment());
4057 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
4058 alignPanel.paintAlignment(true, false);
4069 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
4071 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4072 AlignmentSorter.sortByLength(viewport.getAlignment());
4073 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
4074 viewport.getAlignment()));
4075 alignPanel.paintAlignment(true, false);
4086 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
4088 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4089 AlignmentSorter.sortByGroup(viewport.getAlignment());
4090 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4091 viewport.getAlignment()));
4093 alignPanel.paintAlignment(true, false);
4097 public void sortEValueMenuItem_actionPerformed(ActionEvent e)
4099 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4100 AlignmentSorter.sortByEValue(viewport.getAlignment());
4101 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4102 viewport.getAlignment()));
4103 alignPanel.paintAlignment(true, false);
4108 public void sortBitScoreMenuItem_actionPerformed(ActionEvent e)
4110 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4111 AlignmentSorter.sortByBitScore(viewport.getAlignment());
4112 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4113 viewport.getAlignment()));
4114 alignPanel.paintAlignment(true, false);
4126 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
4128 new RedundancyPanel(alignPanel, this);
4139 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
4141 if ((viewport.getSelectionGroup() == null)
4142 || (viewport.getSelectionGroup().getSize() < 2))
4144 JvOptionPane.showInternalMessageDialog(this,
4145 MessageManager.getString(
4146 "label.you_must_select_least_two_sequences"),
4147 MessageManager.getString("label.invalid_selection"),
4148 JvOptionPane.WARNING_MESSAGE);
4152 JInternalFrame frame = new JInternalFrame();
4153 frame.setContentPane(new PairwiseAlignPanel(viewport));
4154 Desktop.addInternalFrame(frame,
4155 MessageManager.getString("action.pairwise_alignment"), 600,
4161 public void autoCalculate_actionPerformed(ActionEvent e)
4163 viewport.setAutoCalculateConsensusAndConservation(
4164 autoCalculate.isSelected());
4165 if (viewport.getAutoCalculateConsensusAndConservation())
4167 // viewport.autoCalculateConsensus = autoCalculate.isSelected();
4168 // if (viewport.autoCalculateConsensus)
4170 viewport.notifyAlignment();
4175 public void sortByTreeOption_actionPerformed(ActionEvent e)
4177 viewport.sortByTree = sortByTree.isSelected();
4181 protected void listenToViewSelections_actionPerformed(ActionEvent e)
4183 viewport.followSelection = listenToViewSelections.isSelected();
4187 * Constructs a tree panel and adds it to the desktop
4190 * tree type (NJ or AV)
4192 * name of score model used to compute the tree
4194 * parameters for the distance or similarity calculation
4197 void newTreePanel(String type, String modelName,
4198 SimilarityParamsI options)
4200 String frameTitle = "";
4203 boolean onSelection = false;
4204 if (viewport.getSelectionGroup() != null
4205 && viewport.getSelectionGroup().getSize() > 0)
4207 SequenceGroup sg = viewport.getSelectionGroup();
4209 /* Decide if the selection is a column region */
4210 for (SequenceI _s : sg.getSequences())
4212 if (_s.getLength() < sg.getEndRes())
4214 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4215 MessageManager.getString(
4216 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
4217 MessageManager.getString(
4218 "label.sequences_selection_not_aligned"),
4219 JvOptionPane.WARNING_MESSAGE);
4228 if (viewport.getAlignment().getHeight() < 2)
4234 tp = new TreePanel(alignPanel, type, modelName, options);
4235 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
4237 frameTitle += " from ";
4239 if (viewport.getViewName() != null)
4241 frameTitle += viewport.getViewName() + " of ";
4244 frameTitle += this.title;
4246 Dimension dim = Platform.getDimIfEmbedded(tp, 600, 500);
4247 Desktop.addInternalFrame(tp, frameTitle, dim.width, dim.height);
4259 public void addSortByOrderMenuItem(String title,
4260 final AlignmentOrder order)
4262 final JMenuItem item = new JMenuItem(MessageManager
4263 .formatMessage("action.by_title_param", new Object[]
4266 item.addActionListener(new java.awt.event.ActionListener()
4270 public void actionPerformed(ActionEvent e)
4272 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4274 // TODO: JBPNote - have to map order entries to curent SequenceI
4276 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4278 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
4279 viewport.getAlignment()));
4281 alignPanel.paintAlignment(true, false);
4287 * Add a new sort by annotation score menu item
4290 * the menu to add the option to
4292 * the label used to retrieve scores for each sequence on the
4296 public void addSortByAnnotScoreMenuItem(JMenu sort,
4297 final String scoreLabel)
4299 final JMenuItem item = new JMenuItem(scoreLabel);
4301 item.addActionListener(new java.awt.event.ActionListener()
4305 public void actionPerformed(ActionEvent e)
4307 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4308 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4309 viewport.getAlignment());// ,viewport.getSelectionGroup());
4310 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4311 viewport.getAlignment()));
4312 alignPanel.paintAlignment(true, false);
4318 * last hash for alignment's annotation array - used to minimise cost of
4321 protected int _annotationScoreVectorHash;
4324 * search the alignment and rebuild the sort by annotation score submenu the
4325 * last alignment annotation vector hash is stored to minimize cost of
4326 * rebuilding in subsequence calls.
4331 public void buildSortByAnnotationScoresMenu()
4333 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4338 if (viewport.getAlignment().getAlignmentAnnotation()
4339 .hashCode() == _annotationScoreVectorHash)
4344 sortByAnnotScore.removeAll();
4345 Set<String> scoreSorts = new HashSet<>();
4346 for (SequenceI sqa : viewport.getAlignment().getSequences())
4348 AlignmentAnnotation[] anns = sqa.getAnnotation();
4349 for (int i = 0; anns != null && i < anns.length; i++)
4351 AlignmentAnnotation aa = anns[i];
4352 if (aa != null && aa.hasScore() && aa.sequenceRef != null)
4354 scoreSorts.add(aa.label);
4358 for (String label : scoreSorts)
4360 addSortByAnnotScoreMenuItem(sortByAnnotScore, label);
4362 sortByAnnotScore.setVisible(!scoreSorts.isEmpty());
4364 _annotationScoreVectorHash = viewport.getAlignment()
4365 .getAlignmentAnnotation().hashCode();
4369 * Enable (or, if desired, make visible) the By Tree
4370 * submenu only if it has at least one element (or will have).
4374 protected void enableSortMenuOptions()
4376 List<TreePanel> treePanels = getTreePanels();
4377 sortByTreeMenu.setEnabled(!treePanels.isEmpty());
4381 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4382 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4383 * call. Listeners are added to remove the menu item when the treePanel is
4384 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4389 public void buildTreeSortMenu()
4391 sortByTreeMenu.removeAll();
4393 List<TreePanel> treePanels = getTreePanels();
4395 for (final TreePanel tp : treePanels)
4397 final JMenuItem item = new JMenuItem(tp.getTitle());
4398 item.addActionListener(new java.awt.event.ActionListener()
4402 public void actionPerformed(ActionEvent e)
4404 tp.sortByTree_actionPerformed();
4405 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4410 sortByTreeMenu.add(item);
4414 private List<TreePanel> getTreePanels()
4416 List<Component> comps = PaintRefresher.components
4417 .get(viewport.getSequenceSetId());
4418 List<TreePanel> treePanels = new ArrayList<>();
4419 for (Component comp : comps)
4421 if (comp instanceof TreePanel)
4423 treePanels.add((TreePanel) comp);
4429 public boolean sortBy(AlignmentOrder alorder, String undoname)
4431 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4432 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4433 if (undoname != null)
4435 addHistoryItem(new OrderCommand(undoname, oldOrder,
4436 viewport.getAlignment()));
4438 alignPanel.paintAlignment(true, false);
4443 * Work out whether the whole set of sequences or just the selected set will
4444 * be submitted for multiple alignment.
4448 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4450 // Now, check we have enough sequences
4451 AlignmentView msa = null;
4453 if ((viewport.getSelectionGroup() != null)
4454 && (viewport.getSelectionGroup().getSize() > 1))
4456 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4457 // some common interface!
4459 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4460 * SequenceI[sz = seqs.getSize(false)];
4462 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4463 * seqs.getSequenceAt(i); }
4465 msa = viewport.getAlignmentView(true);
4467 else if (viewport.getSelectionGroup() != null
4468 && viewport.getSelectionGroup().getSize() == 1)
4470 int option = JvOptionPane.showConfirmDialog(this,
4471 MessageManager.getString("warn.oneseq_msainput_selection"),
4472 MessageManager.getString("label.invalid_selection"),
4473 JvOptionPane.OK_CANCEL_OPTION);
4474 if (option == JvOptionPane.OK_OPTION)
4476 msa = viewport.getAlignmentView(false);
4481 msa = viewport.getAlignmentView(false);
4487 * Decides what is submitted to a secondary structure prediction service: the
4488 * first sequence in the alignment, or in the current selection, or, if the
4489 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4490 * region or the whole alignment. (where the first sequence in the set is the
4491 * one that the prediction will be for).
4494 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4496 AlignmentView seqs = null;
4498 if ((viewport.getSelectionGroup() != null)
4499 && (viewport.getSelectionGroup().getSize() > 0))
4501 seqs = viewport.getAlignmentView(true);
4505 seqs = viewport.getAlignmentView(false);
4507 // limit sequences - JBPNote in future - could spawn multiple prediction
4509 // TODO: viewport.getAlignment().isAligned is a global state - the local
4510 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4511 if (!viewport.getAlignment().isAligned(false))
4513 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4514 // TODO: if seqs.getSequences().length>1 then should really have warned
4529 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4531 // Pick the tree file
4532 JalviewFileChooser chooser = new JalviewFileChooser(
4533 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4534 chooser.setFileView(new JalviewFileView());
4535 chooser.setDialogTitle(
4536 MessageManager.getString("label.select_newick_like_tree_file"));
4537 chooser.setToolTipText(
4538 MessageManager.getString("label.load_tree_file"));
4540 chooser.setResponseHandler(0, new Runnable()
4546 String filePath = chooser.getSelectedFile().getPath();
4547 Cache.setProperty("LAST_DIRECTORY", filePath);
4548 NewickFile fin = null;
4551 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4552 DataSourceType.FILE));
4553 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4554 } catch (Exception ex)
4556 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4559 .getString("label.problem_reading_tree_file"),
4560 JvOptionPane.WARNING_MESSAGE);
4561 ex.printStackTrace();
4563 if (fin != null && fin.hasWarningMessage())
4565 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4566 fin.getWarningMessage(),
4567 MessageManager.getString(
4568 "label.possible_problem_with_tree_file"),
4569 JvOptionPane.WARNING_MESSAGE);
4573 chooser.showOpenDialog(this);
4576 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4578 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4581 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4582 int h, int x, int y)
4584 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4588 * Add a treeviewer for the tree extracted from a Newick file object to the
4589 * current alignment view
4596 * Associated alignment input data (or null)
4605 * @return TreePanel handle
4608 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4609 AlignmentView input, int w, int h, int x, int y)
4611 TreePanel tp = null;
4617 if (nf.getTree() != null)
4619 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4620 Dimension dim = Platform.getDimIfEmbedded(tp, -1, -1);
4623 dim = new Dimension(w, h);
4627 // no offset, either
4630 tp.setSize(dim.width, dim.height);
4634 tp.setLocation(x, y);
4637 Desktop.addInternalFrame(tp, treeTitle, dim.width, dim.height);
4639 } catch (Exception ex)
4641 ex.printStackTrace();
4648 * Schedule the web services menu rebuild to the event dispatch thread.
4650 public void buildWebServicesMenu()
4652 SwingUtilities.invokeLater(() -> {
4653 Cache.log.info("Rebuiling WS menu");
4654 webService.removeAll();
4655 if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
4657 Cache.log.info("Building web service menu for slivka");
4658 SlivkaWSDiscoverer discoverer = SlivkaWSDiscoverer.getInstance();
4659 JMenu submenu = new JMenu("Slivka");
4660 buildWebServicesMenu(discoverer, submenu);
4661 webService.add(submenu);
4663 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4665 WSDiscovererI jws2servs = Jws2Discoverer.getInstance();
4666 JMenu submenu = new JMenu("JABAWS");
4667 buildLegacyWebServicesMenu(submenu);
4668 buildWebServicesMenu(jws2servs, submenu);
4669 webService.add(submenu);
4671 build_fetchdbmenu(webService);
4675 private void buildLegacyWebServicesMenu(JMenu menu)
4677 JMenu secstrmenu = new JMenu("Secondary Structure Prediction");
4678 if (Discoverer.getServices() != null && Discoverer.getServices().size() > 0)
4680 var secstrpred = Discoverer.getServices().get("SecStrPred");
4681 if (secstrpred != null)
4683 for (ext.vamsas.ServiceHandle sh : secstrpred)
4685 var menuProvider = Discoverer.getServiceClient(sh);
4686 menuProvider.attachWSMenuEntry(secstrmenu, this);
4690 menu.add(secstrmenu);
4694 * Constructs the web services menu for the given discoverer under the
4695 * specified menu. This method must be called on the EDT
4698 * the discoverer used to build the menu
4700 * parent component which the elements will be attached to
4702 private void buildWebServicesMenu(WSDiscovererI discoverer, JMenu menu)
4704 if (discoverer.hasServices())
4706 PreferredServiceRegistry.getRegistry().populateWSMenuEntry(
4707 discoverer.getServices(), sv -> buildWebServicesMenu(), menu,
4710 if (discoverer.isRunning())
4712 JMenuItem item = new JMenuItem("Service discovery in progress.");
4713 item.setEnabled(false);
4716 else if (!discoverer.hasServices())
4718 JMenuItem item = new JMenuItem("No services available.");
4719 item.setEnabled(false);
4724 private void buildWebServicesMenu(WebServiceDiscovererI discoverer, JMenu menu)
4726 if (discoverer.hasServices())
4728 var builder = new WebServicesMenuBuilder();
4729 builder.addSelectedHostChangeListener((name, op) -> {
4730 Cache.log.info("Rebuilding menu on host change");
4732 builder.buildMenu(menu, this);
4734 builder.addAllOperations(discoverer.getOperations());
4736 builder.buildMenu(menu, this);
4738 if (discoverer.isRunning())
4740 JMenuItem item = new JMenuItem("Service discovery in progress.");
4741 item.setEnabled(false);
4744 else if (!discoverer.hasServices())
4746 JMenuItem item = new JMenuItem("No services available.");
4747 item.setEnabled(false);
4753 * construct any groupURL type service menu entries.
4758 protected void build_urlServiceMenu(JMenu webService)
4760 // TODO: remove this code when 2.7 is released
4761 // DEBUG - alignmentView
4763 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4764 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4766 * public void actionPerformed(ActionEvent e) {
4767 * jalview.datamodel.AlignmentView
4768 * .testSelectionViews(af.viewport.getAlignment(),
4769 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4771 * }); webService.add(testAlView);
4773 // TODO: refactor to RestClient discoverer and merge menu entries for
4774 // rest-style services with other types of analysis/calculation service
4775 // SHmmr test client - still being implemented.
4776 // DEBUG - alignmentView
4778 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4781 client.attachWSMenuEntry(
4782 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4788 * Searches the alignment sequences for xRefs and builds the Show
4789 * Cross-References menu (formerly called Show Products), with database
4790 * sources for which cross-references are found (protein sources for a
4791 * nucleotide alignment and vice versa)
4793 * @return true if Show Cross-references menu should be enabled
4796 public boolean canShowProducts()
4798 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4799 AlignmentI dataset = viewport.getAlignment().getDataset();
4801 showProducts.removeAll();
4802 final boolean dna = viewport.getAlignment().isNucleotide();
4804 if (seqs == null || seqs.length == 0)
4806 // nothing to see here.
4810 boolean showp = false;
4813 List<String> ptypes = new CrossRef(seqs, dataset)
4814 .findXrefSourcesForSequences(dna);
4816 for (final String source : ptypes)
4819 final AlignFrame af = this;
4820 JMenuItem xtype = new JMenuItem(source);
4821 xtype.addActionListener(new ActionListener()
4825 public void actionPerformed(ActionEvent e)
4827 showProductsFor(af.viewport.getSequenceSelection(), dna,
4831 showProducts.add(xtype);
4833 showProducts.setVisible(showp);
4834 showProducts.setEnabled(showp);
4835 } catch (Exception e)
4838 "canShowProducts threw an exception - please report to help@jalview.org",
4846 * Finds and displays cross-references for the selected sequences (protein
4847 * products for nucleotide sequences, dna coding sequences for peptides).
4850 * the sequences to show cross-references for
4852 * true if from a nucleotide alignment (so showing proteins)
4854 * the database to show cross-references for
4857 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4858 final String source)
4860 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4865 * Construct and display a new frame containing the translation of this
4866 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4870 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4872 AlignmentI al = null;
4875 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4877 al = dna.translateCdna(codeTable);
4878 } catch (Exception ex)
4880 jalview.bin.Cache.log.error(
4881 "Exception during translation. Please report this !", ex);
4882 final String msg = MessageManager.getString(
4883 "label.error_when_translating_sequences_submit_bug_report");
4884 final String errorTitle = MessageManager
4885 .getString("label.implementation_error")
4886 + MessageManager.getString("label.translation_failed");
4887 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4888 errorTitle, JvOptionPane.ERROR_MESSAGE);
4891 if (al == null || al.getHeight() == 0)
4893 final String msg = MessageManager.getString(
4894 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4895 final String errorTitle = MessageManager
4896 .getString("label.translation_failed");
4897 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4898 errorTitle, JvOptionPane.WARNING_MESSAGE);
4902 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4903 af.setFileFormat(this.currentFileFormat);
4904 final String newTitle = MessageManager
4905 .formatMessage("label.translation_of_params", new Object[]
4906 { this.getTitle(), codeTable.getId() });
4907 af.setTitle(newTitle);
4908 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4910 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4911 AlignViewport.openSplitFrame(this, af, new Alignment(seqs));
4915 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4922 * Set the file format
4927 public void setFileFormat(FileFormatI format)
4929 this.currentFileFormat = format;
4933 * Try to load a features file onto the alignment.
4936 * contents or path to retrieve file or a File object
4938 * access mode of file (see jalview.io.AlignFile)
4939 * @return true if features file was parsed correctly.
4942 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4945 return avc.parseFeaturesFile(file, sourceType,
4946 Cache.getDefault(Preferences.RELAXEDSEQIDMATCHING, false));
4951 public void refreshFeatureUI(boolean enableIfNecessary)
4953 // note - currently this is only still here rather than in the controller
4954 // because of the featureSettings hard reference that is yet to be
4956 if (enableIfNecessary)
4958 viewport.setShowSequenceFeatures(true);
4959 showSeqFeatures.setSelected(true);
4965 public void dragEnter(DropTargetDragEvent evt)
4970 public void dragExit(DropTargetEvent evt)
4975 public void dragOver(DropTargetDragEvent evt)
4980 public void dropActionChanged(DropTargetDragEvent evt)
4985 public void drop(DropTargetDropEvent evt)
4987 // JAL-1552 - acceptDrop required before getTransferable call for
4988 // Java's Transferable for native dnd
4989 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4990 Transferable t = evt.getTransferable();
4992 final List<Object> files = new ArrayList<>();
4993 List<DataSourceType> protocols = new ArrayList<>();
4997 Desktop.transferFromDropTarget(files, protocols, evt, t);
4998 if (files.size() > 0)
5000 new Thread(new Runnable()
5006 loadDroppedFiles(files, protocols, evt, t);
5010 } catch (Exception e)
5012 e.printStackTrace();
5016 protected void loadDroppedFiles(List<Object> files,
5017 List<DataSourceType> protocols, DropTargetDropEvent evt,
5022 // check to see if any of these files have names matching sequences
5025 SequenceIdMatcher idm = new SequenceIdMatcher(
5026 viewport.getAlignment().getSequencesArray());
5028 * Object[] { String,SequenceI}
5030 ArrayList<Object[]> filesmatched = new ArrayList<>();
5031 ArrayList<Object> filesnotmatched = new ArrayList<>();
5032 for (int i = 0; i < files.size(); i++)
5035 Object fileObj = files.get(i);
5036 String fileName = fileObj.toString();
5038 DataSourceType protocol = (fileObj instanceof File
5039 ? DataSourceType.FILE
5040 : FormatAdapter.checkProtocol(fileName));
5041 if (protocol == DataSourceType.FILE)
5044 if (fileObj instanceof File)
5046 file = (File) fileObj;
5047 Platform.cacheFileData(file);
5051 file = new File(fileName);
5053 pdbfn = file.getName();
5055 else if (protocol == DataSourceType.URL)
5057 URL url = new URL(fileName);
5058 pdbfn = url.getFile();
5060 if (pdbfn.length() > 0)
5062 // attempt to find a match in the alignment
5063 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5064 int l = 0, c = pdbfn.indexOf(".");
5065 while (mtch == null && c != -1)
5070 } while ((c = pdbfn.indexOf(".", l)) > l);
5073 pdbfn = pdbfn.substring(0, l);
5075 mtch = idm.findAllIdMatches(pdbfn);
5082 type = new IdentifyFile().identify(fileObj, protocol);
5083 } catch (Exception ex)
5087 if (type != null && type.isStructureFile())
5089 filesmatched.add(new Object[] { fileObj, protocol, mtch });
5093 // File wasn't named like one of the sequences or wasn't a PDB
5095 filesnotmatched.add(fileObj);
5099 if (filesmatched.size() > 0)
5101 boolean autoAssociate = Cache
5102 .getDefault(Preferences.AUTOASSOCIATE_PDBANDSEQS, false);
5105 String msg = MessageManager.formatMessage(
5106 "label.automatically_associate_structure_files_with_sequences_same_name",
5108 { Integer.valueOf(filesmatched.size()).toString() });
5109 String ttl = MessageManager.getString(
5110 "label.automatically_associate_structure_files_by_name");
5111 int choice = JvOptionPane.showConfirmDialog(this, msg, ttl,
5112 JvOptionPane.YES_NO_OPTION);
5113 autoAssociate = choice == JvOptionPane.YES_OPTION;
5117 for (Object[] fm : filesmatched)
5119 // try and associate
5120 // TODO: may want to set a standard ID naming formalism for
5121 // associating PDB files which have no IDs.
5122 for (SequenceI toassoc : (SequenceI[]) fm[2])
5124 PDBEntry pe = AssociatePdbFileWithSeq.associatePdbWithSeq(
5125 fm[0].toString(), (DataSourceType) fm[1], toassoc,
5129 System.err.println("Associated file : " + (fm[0].toString())
5130 + " with " + toassoc.getDisplayId(true));
5134 // TODO: do we need to update overview ? only if features are
5136 alignPanel.paintAlignment(true, false);
5142 * add declined structures as sequences
5144 for (Object[] o : filesmatched)
5146 filesnotmatched.add(o[0]);
5150 if (filesnotmatched.size() > 0)
5152 if (assocfiles > 0 && (Cache
5153 .getDefault("AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
5154 || JvOptionPane.showConfirmDialog(this,
5155 "<html>" + MessageManager.formatMessage(
5156 "label.ignore_unmatched_dropped_files_info",
5158 { Integer.valueOf(filesnotmatched.size())
5161 MessageManager.getString(
5162 "label.ignore_unmatched_dropped_files"),
5163 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
5167 for (Object fn : filesnotmatched)
5169 loadJalviewDataFile(fn, null, null, null);
5173 } catch (Exception ex)
5175 ex.printStackTrace();
5180 * Attempt to load a "dropped" file or URL string, by testing in turn for
5182 * <li>an Annotation file</li>
5183 * <li>a JNet file</li>
5184 * <li>a features file</li>
5185 * <li>else try to interpret as an alignment file</li>
5189 * either a filename or a URL string.
5190 * @throws InterruptedException
5191 * @throws IOException
5194 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
5195 FileFormatI format, SequenceI assocSeq)
5197 // BH 2018 was String file
5200 if (sourceType == null)
5202 sourceType = FormatAdapter.checkProtocol(file);
5204 // if the file isn't identified, or not positively identified as some
5205 // other filetype (PFAM is default unidentified alignment file type) then
5206 // try to parse as annotation.
5207 boolean isAnnotation = (format == null
5208 || FileFormat.Pfam.equals(format))
5209 ? new AnnotationFile().annotateAlignmentView(viewport,
5215 // first see if its a T-COFFEE score file
5216 TCoffeeScoreFile tcf = null;
5219 tcf = new TCoffeeScoreFile(file, sourceType);
5222 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5226 new TCoffeeColourScheme(viewport.getAlignment()));
5227 isAnnotation = true;
5228 setStatus(MessageManager.getString(
5229 "label.successfully_pasted_tcoffee_scores_to_alignment"));
5233 // some problem - if no warning its probable that the ID matching
5234 // process didn't work
5235 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
5236 tcf.getWarningMessage() == null
5237 ? MessageManager.getString(
5238 "label.check_file_matches_sequence_ids_alignment")
5239 : tcf.getWarningMessage(),
5240 MessageManager.getString(
5241 "label.problem_reading_tcoffee_score_file"),
5242 JvOptionPane.WARNING_MESSAGE);
5249 } catch (Exception x)
5252 "Exception when processing data source as T-COFFEE score file",
5258 // try to see if its a JNet 'concise' style annotation file *before*
5260 // try to parse it as a features file
5263 format = new IdentifyFile().identify(file, sourceType);
5265 if (FileFormat.ScoreMatrix == format)
5267 ScoreMatrixFile sm = new ScoreMatrixFile(
5268 new FileParse(file, sourceType));
5270 // todo: i18n this message
5271 setStatus(MessageManager.formatMessage(
5272 "label.successfully_loaded_matrix",
5273 sm.getMatrixName()));
5275 else if (FileFormat.Jnet.equals(format))
5277 JPredFile predictions = new JPredFile(file, sourceType);
5278 new JnetAnnotationMaker();
5279 JnetAnnotationMaker.add_annotation(predictions,
5280 viewport.getAlignment(), 0, false);
5281 viewport.getAlignment().setupJPredAlignment();
5282 isAnnotation = true;
5284 // else if (IdentifyFile.FeaturesFile.equals(format))
5285 else if (FileFormat.Features.equals(format))
5287 if (parseFeaturesFile(file, sourceType))
5289 SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
5290 if (splitFrame != null)
5292 splitFrame.repaint();
5296 alignPanel.paintAlignment(true, true);
5302 new FileLoader().LoadFile(viewport, file, sourceType, format);
5308 updateForAnnotations();
5310 } catch (Exception ex)
5312 ex.printStackTrace();
5313 } catch (OutOfMemoryError oom)
5318 } catch (Exception x)
5323 + (sourceType != null
5324 ? (sourceType == DataSourceType.PASTE
5326 : "using " + sourceType + " from "
5330 ? "(parsing as '" + format + "' file)"
5332 oom, Desktop.getDesktopPane());
5337 * Do all updates necessary after an annotation file such as jnet. Also called
5338 * from Jalview.loadAppletParams for "annotations", "jnetFile"
5341 public void updateForAnnotations()
5343 alignPanel.adjustAnnotationHeight();
5344 viewport.updateSequenceIdColours();
5345 buildSortByAnnotationScoresMenu();
5346 alignPanel.paintAlignment(true, true);
5350 * Change the display state for the given feature groups -- Added by BH from
5354 * list of group strings
5356 * visible or invisible
5359 public void setFeatureGroupState(String[] groups, boolean state)
5361 jalview.api.FeatureRenderer fr = null;
5362 viewport.setShowSequenceFeatures(true);
5363 if (alignPanel != null
5364 && (fr = alignPanel.getFeatureRenderer()) != null)
5367 fr.setGroupVisibility(Arrays.asList(groups), state);
5368 alignPanel.getSeqPanel().seqCanvas.repaint();
5369 if (alignPanel.overviewPanel != null)
5371 alignPanel.overviewPanel.updateOverviewImage();
5377 * Method invoked by the ChangeListener on the tabbed pane, in other words
5378 * when a different tabbed pane is selected by the user or programmatically.
5382 public void tabSelectionChanged(int index)
5386 alignPanel = alignPanels.get(index);
5387 viewport = alignPanel.av;
5388 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5389 setMenusFromViewport(viewport);
5390 if (featureSettings != null && featureSettings.isOpen()
5391 && featureSettings.fr.getViewport() != viewport)
5393 if (viewport.isShowSequenceFeatures())
5395 // refresh the featureSettings to reflect UI change
5396 showFeatureSettingsUI();
5400 // close feature settings for this view.
5401 featureSettings.close();
5408 * 'focus' any colour slider that is open to the selected viewport
5410 if (viewport.getConservationSelected())
5412 SliderPanel.setConservationSlider(alignPanel,
5413 viewport.getResidueShading(), alignPanel.getViewName());
5417 SliderPanel.hideConservationSlider();
5419 if (viewport.getAbovePIDThreshold())
5421 SliderPanel.setPIDSliderSource(alignPanel,
5422 viewport.getResidueShading(), alignPanel.getViewName());
5426 SliderPanel.hidePIDSlider();
5430 * If there is a frame linked to this one in a SplitPane, switch it to the
5431 * same view tab index. No infinite recursion of calls should happen, since
5432 * tabSelectionChanged() should not get invoked on setting the selected
5433 * index to an unchanged value. Guard against setting an invalid index
5434 * before the new view peer tab has been created.
5436 final AlignViewportI peer = viewport.getCodingComplement();
5439 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
5440 .getAlignPanel().alignFrame;
5441 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5443 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5449 * On right mouse click on view tab, prompt for and set new view name.
5453 public void tabbedPane_mousePressed(MouseEvent e)
5455 if (e.isPopupTrigger())
5457 String msg = MessageManager.getString("label.enter_view_name");
5458 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
5459 String reply = JvOptionPane.showInputDialog(msg, ttl);
5463 viewport.setViewName(reply);
5464 // TODO warn if reply is in getExistingViewNames()?
5465 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5470 public AlignViewport getCurrentView()
5476 * Open the dialog for regex description parsing.
5480 protected void extractScores_actionPerformed(ActionEvent e)
5482 ParseProperties pp = new jalview.analysis.ParseProperties(
5483 viewport.getAlignment());
5484 // TODO: verify regex and introduce GUI dialog for version 2.5
5485 // if (pp.getScoresFromDescription("col", "score column ",
5486 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5488 if (pp.getScoresFromDescription("description column",
5489 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5491 buildSortByAnnotationScoresMenu();
5499 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5504 protected void showDbRefs_actionPerformed(ActionEvent e)
5506 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5512 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5517 protected void showNpFeats_actionPerformed(ActionEvent e)
5519 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5523 * find the viewport amongst the tabs in this alignment frame and close that
5529 public boolean closeView(AlignViewportI av)
5533 this.closeMenuItem_actionPerformed(false);
5536 Component[] comp = tabbedPane.getComponents();
5537 for (int i = 0; comp != null && i < comp.length; i++)
5539 if (comp[i] instanceof AlignmentPanel)
5541 if (((AlignmentPanel) comp[i]).av == av)
5544 closeView((AlignmentPanel) comp[i]);
5552 protected void build_fetchdbmenu(JMenu webService)
5554 // Temporary hack - DBRef Fetcher always top level ws entry.
5555 // TODO We probably want to store a sequence database checklist in
5556 // preferences and have checkboxes.. rather than individual sources selected
5558 final JMenu rfetch = new JMenu(
5559 MessageManager.getString("action.fetch_db_references"));
5560 rfetch.setToolTipText(MessageManager.getString(
5561 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5562 webService.add(rfetch);
5564 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5565 MessageManager.getString("option.trim_retrieved_seqs"));
5566 trimrs.setToolTipText(
5567 MessageManager.getString("label.trim_retrieved_sequences"));
5569 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5570 trimrs.addActionListener(new ActionListener()
5574 public void actionPerformed(ActionEvent e)
5576 trimrs.setSelected(trimrs.isSelected());
5577 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5578 Boolean.valueOf(trimrs.isSelected()).toString());
5582 JMenuItem fetchr = new JMenuItem(
5583 MessageManager.getString("label.standard_databases"));
5584 fetchr.setToolTipText(
5585 MessageManager.getString("label.fetch_embl_uniprot"));
5586 fetchr.addActionListener(new ActionListener()
5590 public void actionPerformed(ActionEvent e)
5592 new Thread(new Runnable()
5598 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5599 .getAlignment().isNucleotide();
5600 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5601 alignPanel.av.getSequenceSelection(),
5602 alignPanel.alignFrame, null,
5603 alignPanel.alignFrame.featureSettings, isNucleotide);
5604 dbRefFetcher.addListener(new FetchFinishedListenerI()
5608 public void finished()
5611 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5612 .getFeatureSettingsModels())
5615 alignPanel.av.mergeFeaturesStyle(srcSettings);
5617 AlignFrame.this.setMenusForViewport();
5620 dbRefFetcher.fetchDBRefs(false);
5628 new Thread(new Runnable()
5635 // final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5636 // .getSequenceFetcherSingleton();
5637 javax.swing.SwingUtilities.invokeLater(new Runnable()
5643 jalview.ws.SequenceFetcher sf = jalview.ws.SequenceFetcher
5645 String[] dbclasses = sf.getNonAlignmentSources();
5646 List<DbSourceProxy> otherdb;
5647 JMenu dfetch = new JMenu();
5648 JMenu ifetch = new JMenu();
5649 JMenuItem fetchr = null;
5650 int comp = 0, icomp = 0, mcomp = 15;
5651 String mname = null;
5653 for (String dbclass : dbclasses)
5655 otherdb = sf.getSourceProxy(dbclass);
5656 // add a single entry for this class, or submenu allowing 'fetch
5658 if (otherdb == null || otherdb.size() < 1)
5664 mname = "From " + dbclass;
5666 if (otherdb.size() == 1)
5668 DbSourceProxy src = otherdb.get(0);
5669 DbSourceProxy[] dassource = new DbSourceProxy[] { src };
5670 fetchr = new JMenuItem(src.getDbSource());
5671 fetchr.addActionListener(new ActionListener()
5675 public void actionPerformed(ActionEvent e)
5677 new Thread(new Runnable()
5683 boolean isNucleotide = alignPanel.alignFrame
5684 .getViewport().getAlignment()
5686 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5687 alignPanel.av.getSequenceSelection(),
5688 alignPanel.alignFrame, dassource,
5689 alignPanel.alignFrame.featureSettings,
5692 .addListener(new FetchFinishedListenerI()
5696 public void finished()
5698 FeatureSettingsModelI srcSettings = dassource[0]
5699 .getFeatureColourScheme();
5700 alignPanel.av.mergeFeaturesStyle(
5702 AlignFrame.this.setMenusForViewport();
5705 dbRefFetcher.fetchDBRefs(false);
5711 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5712 MessageManager.formatMessage(
5713 "label.fetch_retrieve_from", new Object[]
5714 { src.getDbName() })));
5720 final DbSourceProxy[] dassource = otherdb
5721 .toArray(new DbSourceProxy[0]);
5723 DbSourceProxy src = otherdb.get(0);
5724 fetchr = new JMenuItem(MessageManager
5725 .formatMessage("label.fetch_all_param", new Object[]
5726 { src.getDbSource() }));
5727 fetchr.addActionListener(new ActionListener()
5731 public void actionPerformed(ActionEvent e)
5733 new Thread(new Runnable()
5739 boolean isNucleotide = alignPanel.alignFrame
5740 .getViewport().getAlignment()
5742 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5743 alignPanel.av.getSequenceSelection(),
5744 alignPanel.alignFrame, dassource,
5745 alignPanel.alignFrame.featureSettings,
5748 .addListener(new FetchFinishedListenerI()
5752 public void finished()
5754 AlignFrame.this.setMenusForViewport();
5757 dbRefFetcher.fetchDBRefs(false);
5763 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5764 MessageManager.formatMessage(
5765 "label.fetch_retrieve_from_all_sources",
5767 { Integer.valueOf(otherdb.size())
5769 src.getDbSource(), src.getDbName() })));
5772 // and then build the rest of the individual menus
5773 ifetch = new JMenu(MessageManager.formatMessage(
5774 "label.source_from_db_source", new Object[]
5775 { src.getDbSource() }));
5777 String imname = null;
5779 for (DbSourceProxy sproxy : otherdb)
5781 String dbname = sproxy.getDbName();
5782 String sname = dbname.length() > 5
5783 ? dbname.substring(0, 5) + "..."
5785 String msname = dbname.length() > 10
5786 ? dbname.substring(0, 10) + "..."
5790 imname = MessageManager
5791 .formatMessage("label.from_msname", new Object[]
5794 fetchr = new JMenuItem(msname);
5795 final DbSourceProxy[] dassrc = { sproxy };
5796 fetchr.addActionListener(new ActionListener()
5800 public void actionPerformed(ActionEvent e)
5802 new Thread(new Runnable()
5808 boolean isNucleotide = alignPanel.alignFrame
5809 .getViewport().getAlignment()
5811 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5812 alignPanel.av.getSequenceSelection(),
5813 alignPanel.alignFrame, dassrc,
5814 alignPanel.alignFrame.featureSettings,
5817 .addListener(new FetchFinishedListenerI()
5821 public void finished()
5823 AlignFrame.this.setMenusForViewport();
5826 dbRefFetcher.fetchDBRefs(false);
5832 fetchr.setToolTipText(
5833 "<html>" + MessageManager.formatMessage(
5834 "label.fetch_retrieve_from", new Object[]
5838 if (++icomp >= mcomp || i == (otherdb.size()))
5840 ifetch.setText(MessageManager.formatMessage(
5841 "label.source_to_target", imname, sname));
5843 ifetch = new JMenu();
5851 if (comp >= mcomp || dbi >= (dbclasses.length))
5853 dfetch.setText(MessageManager.formatMessage(
5854 "label.source_to_target", mname, dbclass));
5856 dfetch = new JMenu();
5869 * Left justify the whole alignment.
5873 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5875 viewport.getAlignment().justify(false);
5876 viewport.notifyAlignment();
5880 * Right justify the whole alignment.
5884 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5886 viewport.getAlignment().justify(true);
5887 viewport.notifyAlignment();
5891 public void setShowSeqFeatures(boolean b)
5893 showSeqFeatures.setSelected(b);
5894 viewport.setShowSequenceFeatures(b);
5901 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5902 * awt.event.ActionEvent)
5906 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5908 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5909 alignPanel.paintAlignment(false, false);
5916 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5921 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5923 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5924 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5932 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5933 * .event.ActionEvent)
5937 protected void showGroupConservation_actionPerformed(ActionEvent e)
5939 viewport.setShowGroupConservation(showGroupConservation.getState());
5940 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5947 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5948 * .event.ActionEvent)
5952 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5954 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5955 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5962 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5963 * .event.ActionEvent)
5967 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5969 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5970 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5974 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5976 showSequenceLogo.setState(true);
5977 viewport.setShowSequenceLogo(true);
5978 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5979 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5983 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5985 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5992 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5993 * .event.ActionEvent)
5997 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5999 if (avc.makeGroupsFromSelection())
6001 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
6002 alignPanel.updateAnnotation();
6003 alignPanel.paintAlignment(true,
6004 viewport.needToUpdateStructureViews());
6008 public void clearAlignmentSeqRep()
6010 // TODO refactor alignmentseqrep to controller
6011 if (viewport.getAlignment().hasSeqrep())
6013 viewport.getAlignment().setSeqrep(null);
6014 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
6015 alignPanel.updateAnnotation();
6016 alignPanel.paintAlignment(true, true);
6021 protected void createGroup_actionPerformed(ActionEvent e)
6023 if (avc.createGroup())
6025 if (applyAutoAnnotationSettings.isSelected())
6027 alignPanel.updateAnnotation(true, false);
6029 alignPanel.alignmentChanged();
6034 protected void unGroup_actionPerformed(ActionEvent e)
6038 alignPanel.alignmentChanged();
6043 * make the given alignmentPanel the currently selected tab
6045 * @param alignmentPanel
6048 public void setDisplayedView(AlignmentPanel alignmentPanel)
6050 if (!viewport.getSequenceSetId()
6051 .equals(alignmentPanel.av.getSequenceSetId()))
6053 throw new Error(MessageManager.getString(
6054 "error.implementation_error_cannot_show_view_alignment_frame"));
6056 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
6057 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
6059 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
6064 * Action on selection of menu options to Show or Hide annotations.
6067 * @param forSequences
6068 * update sequence-related annotations
6069 * @param forAlignment
6070 * update non-sequence-related annotations
6074 protected void setAnnotationsVisibility(boolean visible,
6075 boolean forSequences, boolean forAlignment)
6077 AlignmentAnnotation[] anns = alignPanel.getAlignment()
6078 .getAlignmentAnnotation();
6083 for (AlignmentAnnotation aa : anns)
6086 * don't display non-positional annotations on an alignment
6088 if (aa.annotations == null)
6092 boolean apply = (aa.sequenceRef == null && forAlignment)
6093 || (aa.sequenceRef != null && forSequences);
6096 aa.visible = visible;
6099 alignPanel.validateAnnotationDimensions(true);
6100 alignPanel.alignmentChanged();
6104 * Store selected annotation sort order for the view and repaint.
6108 protected void sortAnnotations_actionPerformed()
6110 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
6112 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
6113 alignPanel.paintAlignment(false, false);
6118 * @return alignment panels in this alignment frame
6121 public List<? extends AlignmentViewPanel> getAlignPanels()
6123 // alignPanels is never null
6124 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
6129 * Open a new alignment window, with the cDNA associated with this (protein)
6130 * alignment, aligned as is the protein.
6133 protected void viewAsCdna_actionPerformed()
6135 // TODO no longer a menu action - refactor as required
6136 final AlignmentI alignment = getViewport().getAlignment();
6137 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
6138 if (mappings == null)
6142 List<SequenceI> cdnaSeqs = new ArrayList<>();
6143 for (SequenceI aaSeq : alignment.getSequences())
6145 for (AlignedCodonFrame acf : mappings)
6147 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
6151 * There is a cDNA mapping for this protein sequence - add to new
6152 * alignment. It will share the same dataset sequence as other mapped
6153 * cDNA (no new mappings need to be created).
6155 final Sequence newSeq = new Sequence(dnaSeq);
6156 newSeq.setDatasetSequence(dnaSeq);
6157 cdnaSeqs.add(newSeq);
6161 if (cdnaSeqs.size() == 0)
6163 // show a warning dialog no mapped cDNA
6166 AlignmentI cdna = new Alignment(
6167 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
6168 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
6169 AlignFrame.DEFAULT_HEIGHT);
6170 cdna.alignAs(alignment);
6171 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
6173 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
6174 AlignFrame.DEFAULT_HEIGHT);
6178 * Set visibility of dna/protein complement view (available when shown in a
6185 protected void showComplement_actionPerformed(boolean show)
6187 SplitContainerI sf = getSplitViewContainer();
6190 sf.setComplementVisible(this, show);
6195 * Generate the reverse (optionally complemented) of the selected sequences,
6196 * and add them to the alignment
6200 protected void showReverse_actionPerformed(boolean complement)
6202 AlignmentI al = null;
6205 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
6206 al = dna.reverseCdna(complement);
6207 viewport.addAlignment(al, "");
6208 addHistoryItem(new EditCommand(
6209 MessageManager.getString("label.add_sequences"), Action.PASTE,
6210 al.getSequencesArray(), 0, al.getWidth(),
6211 viewport.getAlignment()));
6212 } catch (Exception ex)
6214 System.err.println(ex.getMessage());
6220 * Try to run a script in the Groovy console, having first ensured that this
6221 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
6222 * be targeted at this alignment.
6226 protected void runGroovy_actionPerformed()
6228 Jalview.setCurrentAlignFrame(this);
6229 groovy.ui.Console console = Desktop.getGroovyConsole();
6230 if (console != null)
6234 console.runScript();
6235 } catch (Exception ex)
6237 System.err.println((ex.toString()));
6238 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
6239 MessageManager.getString("label.couldnt_run_groovy_script"),
6240 MessageManager.getString("label.groovy_support_failed"),
6241 JvOptionPane.ERROR_MESSAGE);
6246 System.err.println("Can't run Groovy script as console not found");
6251 * Hides columns containing (or not containing) a specified feature, provided
6252 * that would not leave all columns hidden
6254 * @param featureType
6255 * @param columnsContaining
6259 public boolean hideFeatureColumns(String featureType,
6260 boolean columnsContaining)
6262 boolean notForHiding = avc.markColumnsContainingFeatures(
6263 columnsContaining, false, false, featureType);
6266 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
6267 false, featureType))
6269 getViewport().hideSelectedColumns();
6277 protected void selectHighlightedColumns_actionPerformed(
6278 ActionEvent actionEvent)
6280 // include key modifier check in case user selects from menu
6281 avc.markHighlightedColumns(
6282 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
6283 (actionEvent.getModifiers() & (ActionEvent.META_MASK
6284 | ActionEvent.CTRL_MASK)) != 0);
6288 * Rebuilds the Colour menu, including any user-defined colours which have
6289 * been loaded either on startup or during the session
6292 public void buildColourMenu()
6294 colourMenu.removeAll();
6296 colourMenu.add(applyToAllGroups);
6297 colourMenu.add(textColour);
6298 colourMenu.addSeparator();
6300 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
6301 viewport.getAlignment(), false);
6303 colourMenu.add(annotationColour);
6304 bg.add(annotationColour);
6305 colourMenu.addSeparator();
6306 colourMenu.add(conservationMenuItem);
6307 colourMenu.add(modifyConservation);
6308 colourMenu.add(abovePIDThreshold);
6309 colourMenu.add(modifyPID);
6311 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
6312 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
6316 * Open a dialog (if not already open) that allows the user to select and
6317 * calculate PCA or Tree analysis
6320 protected void openTreePcaDialog()
6322 if (alignPanel.getCalculationDialog() == null)
6324 new CalculationChooser(AlignFrame.this);
6329 * Sets the status of the HMMER menu
6331 public void updateHMMERStatus()
6333 hmmerMenu.setEnabled(HmmerCommand.isHmmerAvailable());
6337 protected void loadVcf_actionPerformed()
6339 JalviewFileChooser chooser = new JalviewFileChooser(
6340 Cache.getProperty("LAST_DIRECTORY"));
6341 chooser.setFileView(new JalviewFileView());
6342 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
6343 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
6344 final AlignFrame us = this;
6345 chooser.setResponseHandler(0, new Runnable()
6351 String choice = chooser.getSelectedFile().getPath();
6352 Cache.setProperty("LAST_DIRECTORY", choice);
6353 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
6354 new VCFLoader(choice).loadVCF(seqs, us);
6357 chooser.showOpenDialog(null);
6361 private Rectangle lastFeatureSettingsBounds = null;
6364 public void setFeatureSettingsGeometry(Rectangle bounds)
6366 lastFeatureSettingsBounds = bounds;
6370 public Rectangle getFeatureSettingsGeometry()
6372 return lastFeatureSettingsBounds;
6375 public void scrollTo(int row, int column)
6377 alignPanel.getSeqPanel().scrollTo(row, column);
6380 public void scrollToRow(int row)
6382 alignPanel.getSeqPanel().scrollToRow(row);
6385 public void scrollToColumn(int column)
6387 alignPanel.getSeqPanel().scrollToColumn(column);
6391 * BH 2019 from JalviewLite
6393 * get sequence feature groups that are hidden or shown
6400 public String[] getFeatureGroupsOfState(boolean visible)
6402 jalview.api.FeatureRenderer fr = null;
6403 if (alignPanel != null
6404 && (fr = alignPanel.getFeatureRenderer()) != null)
6406 List<String> gps = fr.getGroups(visible);
6407 String[] _gps = gps.toArray(new String[gps.size()]);
6415 * @return list of feature groups on the view
6418 public String[] getFeatureGroups()
6420 jalview.api.FeatureRenderer fr = null;
6421 if (alignPanel != null
6422 && (fr = alignPanel.getFeatureRenderer()) != null)
6424 List<String> gps = fr.getFeatureGroups();
6425 String[] _gps = gps.toArray(new String[gps.size()]);
6431 public void select(SequenceGroup sel, ColumnSelection csel,
6432 HiddenColumns hidden)
6434 alignPanel.getSeqPanel().selection(sel, csel, hidden, null);
6442 static class PrintThread extends Thread
6446 public PrintThread(AlignmentPanel ap)
6451 static PageFormat pf;
6456 PrinterJob printJob = PrinterJob.getPrinterJob();
6460 printJob.setPrintable(ap, pf);
6464 printJob.setPrintable(ap);
6467 if (printJob.printDialog())
6472 } catch (Exception PrintException)
6474 PrintException.printStackTrace();