2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import java.util.Locale;
25 import java.io.IOException;
26 import java.util.HashSet;
29 import javax.swing.JFileChooser;
30 import javax.swing.JOptionPane;
31 import java.awt.BorderLayout;
32 import java.awt.Color;
33 import java.awt.Component;
34 import java.awt.Dimension;
35 import java.awt.Rectangle;
36 import java.awt.Toolkit;
37 import java.awt.datatransfer.Clipboard;
38 import java.awt.datatransfer.DataFlavor;
39 import java.awt.datatransfer.StringSelection;
40 import java.awt.datatransfer.Transferable;
41 import java.awt.dnd.DnDConstants;
42 import java.awt.dnd.DropTargetDragEvent;
43 import java.awt.dnd.DropTargetDropEvent;
44 import java.awt.dnd.DropTargetEvent;
45 import java.awt.dnd.DropTargetListener;
46 import java.awt.event.ActionEvent;
47 import java.awt.event.ActionListener;
48 import java.awt.event.FocusAdapter;
49 import java.awt.event.FocusEvent;
50 import java.awt.event.ItemEvent;
51 import java.awt.event.ItemListener;
52 import java.awt.event.KeyAdapter;
53 import java.awt.event.KeyEvent;
54 import java.awt.event.MouseEvent;
55 import java.awt.print.PageFormat;
56 import java.awt.print.PrinterJob;
57 import java.beans.PropertyChangeEvent;
58 import java.beans.PropertyChangeListener;
60 import java.io.FileWriter;
61 import java.io.PrintWriter;
63 import java.util.ArrayList;
64 import java.util.Arrays;
65 import java.util.Collection;
66 import java.util.Deque;
67 import java.util.Enumeration;
68 import java.util.Hashtable;
69 import java.util.List;
70 import java.util.Vector;
72 import javax.swing.ButtonGroup;
73 import javax.swing.JCheckBoxMenuItem;
74 import javax.swing.JComponent;
75 import javax.swing.JEditorPane;
76 import javax.swing.JInternalFrame;
77 import javax.swing.JLabel;
78 import javax.swing.JLayeredPane;
79 import javax.swing.JMenu;
80 import javax.swing.JMenuItem;
81 import javax.swing.JPanel;
82 import javax.swing.JScrollPane;
83 import javax.swing.SwingUtilities;
84 import javax.swing.event.InternalFrameAdapter;
85 import javax.swing.event.InternalFrameEvent;
87 import ext.vamsas.ServiceHandle;
88 import jalview.analysis.AlignmentSorter;
89 import jalview.analysis.AlignmentUtils;
90 import jalview.analysis.CrossRef;
91 import jalview.analysis.Dna;
92 import jalview.analysis.GeneticCodeI;
93 import jalview.analysis.ParseProperties;
94 import jalview.analysis.SequenceIdMatcher;
95 import jalview.api.AlignExportSettingsI;
96 import jalview.api.AlignViewControllerGuiI;
97 import jalview.api.AlignViewControllerI;
98 import jalview.api.AlignViewportI;
99 import jalview.api.AlignmentViewPanel;
100 import jalview.api.FeatureSettingsControllerI;
101 import jalview.api.FeatureSettingsModelI;
102 import jalview.api.SplitContainerI;
103 import jalview.api.ViewStyleI;
104 import jalview.api.analysis.SimilarityParamsI;
105 import jalview.bin.Cache;
106 import jalview.bin.Console;
107 import jalview.bin.Jalview;
108 import jalview.commands.CommandI;
109 import jalview.commands.EditCommand;
110 import jalview.commands.EditCommand.Action;
111 import jalview.commands.OrderCommand;
112 import jalview.commands.RemoveGapColCommand;
113 import jalview.commands.RemoveGapsCommand;
114 import jalview.commands.SlideSequencesCommand;
115 import jalview.commands.TrimRegionCommand;
116 import jalview.datamodel.AlignExportSettingsAdapter;
117 import jalview.datamodel.AlignedCodonFrame;
118 import jalview.datamodel.Alignment;
119 import jalview.datamodel.AlignmentAnnotation;
120 import jalview.datamodel.AlignmentExportData;
121 import jalview.datamodel.AlignmentI;
122 import jalview.datamodel.AlignmentOrder;
123 import jalview.datamodel.AlignmentView;
124 import jalview.datamodel.ColumnSelection;
125 import jalview.datamodel.HiddenColumns;
126 import jalview.datamodel.PDBEntry;
127 import jalview.datamodel.SeqCigar;
128 import jalview.datamodel.Sequence;
129 import jalview.datamodel.SequenceGroup;
130 import jalview.datamodel.SequenceI;
131 import jalview.gui.ColourMenuHelper.ColourChangeListener;
132 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
133 import jalview.hmmer.HMMAlign;
134 import jalview.hmmer.HMMBuild;
135 import jalview.hmmer.HMMERParamStore;
136 import jalview.hmmer.HMMERPreset;
137 import jalview.hmmer.HMMSearch;
138 import jalview.hmmer.HmmerCommand;
139 import jalview.hmmer.JackHMMER;
140 import jalview.io.AlignmentProperties;
141 import jalview.io.AnnotationFile;
142 import jalview.io.BackupFiles;
143 import jalview.io.BioJsHTMLOutput;
144 import jalview.io.DataSourceType;
145 import jalview.io.FileFormat;
146 import jalview.io.FileFormatI;
147 import jalview.io.FileFormats;
148 import jalview.io.FileLoader;
149 import jalview.io.FileParse;
150 import jalview.io.FormatAdapter;
151 import jalview.io.HtmlSvgOutput;
152 import jalview.io.IdentifyFile;
153 import jalview.io.JPredFile;
154 import jalview.io.JalviewFileChooser;
155 import jalview.io.JalviewFileView;
156 import jalview.io.JnetAnnotationMaker;
157 import jalview.io.NewickFile;
158 import jalview.io.ScoreMatrixFile;
159 import jalview.io.TCoffeeScoreFile;
160 import jalview.io.vcf.VCFLoader;
161 import jalview.jbgui.GAlignFrame;
162 import jalview.project.Jalview2XML;
163 import jalview.schemes.ColourSchemeI;
164 import jalview.schemes.ColourSchemes;
165 import jalview.schemes.ResidueColourScheme;
166 import jalview.schemes.TCoffeeColourScheme;
167 import jalview.util.HttpUtils;
168 import jalview.util.ImageMaker.TYPE;
169 import jalview.util.MessageManager;
170 import jalview.util.Platform;
171 import jalview.viewmodel.AlignmentViewport;
172 import jalview.viewmodel.ViewportRanges;
173 import jalview.ws.DBRefFetcher;
174 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
175 import jalview.ws.ServiceChangeListener;
176 import jalview.ws.WSDiscovererI;
177 import jalview.ws.api.ServiceWithParameters;
178 import jalview.ws.jws1.Discoverer;
179 import jalview.ws.jws2.Jws2Discoverer;
180 import jalview.ws.jws2.PreferredServiceRegistry;
181 import jalview.ws.params.ArgumentI;
182 import jalview.ws.params.ParamDatastoreI;
183 import jalview.ws.params.WsParamSetI;
184 import jalview.ws.seqfetcher.DbSourceProxy;
185 import jalview.ws2.client.api.WebServiceDiscovererI;
186 import jalview.ws2.client.slivka.SlivkaWSDiscoverer;
187 import jalview.ws2.gui.WebServicesMenuManager;
193 * @version $Revision$
195 @SuppressWarnings("serial")
196 public class AlignFrame extends GAlignFrame
197 implements DropTargetListener, IProgressIndicator,
198 AlignViewControllerGuiI, ColourChangeListener, ServiceChangeListener
201 public static int frameCount;
203 public static final int DEFAULT_WIDTH = 700;
205 public static final int DEFAULT_HEIGHT = 500;
208 * The currently displayed panel (selected tabbed view if more than one)
210 public AlignmentPanel alignPanel;
212 AlignViewport viewport;
214 public AlignViewControllerI avc;
216 List<AlignmentPanel> alignPanels = new ArrayList<>();
219 * Last format used to load or save alignments in this window
221 FileFormatI currentFileFormat = null;
224 * Current filename for this alignment
226 String fileName = null;
229 * TODO: remove reference to 'FileObject' in AlignFrame - not correct mapping
235 private DataSourceType protocol ;
238 * Creates a new AlignFrame object with specific width and height.
244 public AlignFrame(AlignmentI al, int width, int height)
246 this(al, null, width, height);
250 * Creates a new AlignFrame object with specific width, height and
256 * @param sequenceSetId
258 public AlignFrame(AlignmentI al, int width, int height,
259 String sequenceSetId)
261 this(al, null, width, height, sequenceSetId);
265 * Creates a new AlignFrame object with specific width, height and
271 * @param sequenceSetId
274 public AlignFrame(AlignmentI al, int width, int height,
275 String sequenceSetId, String viewId)
277 this(al, null, width, height, sequenceSetId, viewId);
281 * new alignment window with hidden columns
285 * @param hiddenColumns
286 * ColumnSelection or null
288 * Width of alignment frame
292 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
295 this(al, hiddenColumns, width, height, null);
299 * Create alignment frame for al with hiddenColumns, a specific width and
300 * height, and specific sequenceId
303 * @param hiddenColumns
306 * @param sequenceSetId
309 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
310 int height, String sequenceSetId)
312 this(al, hiddenColumns, width, height, sequenceSetId, null);
316 * Create alignment frame for al with hiddenColumns, a specific width and
317 * height, and specific sequenceId
320 * @param hiddenColumns
323 * @param sequenceSetId
328 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
329 int height, String sequenceSetId, String viewId)
334 setSize(width, height);
336 if (al.getDataset() == null)
341 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
343 // JalviewJS needs to distinguish a new panel from an old one in init()
344 // alignPanel = new AlignmentPanel(this, viewport);
345 // addAlignmentPanel(alignPanel, true);
349 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
350 HiddenColumns hiddenColumns, int width, int height)
352 setSize(width, height);
354 if (al.getDataset() == null)
359 viewport = new AlignViewport(al, hiddenColumns);
361 if (hiddenSeqs != null && hiddenSeqs.length > 0)
363 viewport.hideSequence(hiddenSeqs);
365 // alignPanel = new AlignmentPanel(this, viewport);
366 // addAlignmentPanel(alignPanel, true);
371 * Make a new AlignFrame from existing alignmentPanels
378 public AlignFrame(AlignmentPanel ap)
382 // addAlignmentPanel(ap, false);
387 * initalise the alignframe from the underlying viewport data and the
393 boolean newPanel = (alignPanel == null);
394 viewport.setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
399 // need to set this up front if NOANNOTATION is
400 // used in conjunction with SHOWOVERVIEW.
402 // I have not determined if this is appropriate for
403 // Jalview/Java, as it means we are setting this flag
404 // for all subsequent AlignFrames. For now, at least,
405 // I am setting it to be JalviewJS-only.
407 boolean showAnnotation = Jalview.getInstance().getShowAnnotation();
408 viewport.setShowAnnotation(showAnnotation);
410 alignPanel = new AlignmentPanel(this, viewport);
412 addAlignmentPanel(alignPanel, newPanel);
414 // setBackground(Color.white); // BH 2019
416 if (!Jalview.isHeadlessMode())
418 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
420 statusPanel.setVisible(Jalview.getInstance().getShowStatus());
421 alignFrameMenuBar.setVisible(Jalview.getInstance().getAllowMenuBar());
424 avc = new jalview.controller.AlignViewController(this, viewport,
426 if (viewport.getAlignmentConservationAnnotation() == null)
428 // BLOSUM62Colour.setEnabled(false);
429 conservationMenuItem.setEnabled(false);
430 modifyConservation.setEnabled(false);
431 // PIDColour.setEnabled(false);
432 // abovePIDThreshold.setEnabled(false);
433 // modifyPID.setEnabled(false);
436 String sortby = Cache.getDefault(Preferences.SORT_ALIGNMENT,
439 if (sortby.equals("Id"))
441 sortIDMenuItem_actionPerformed(null);
443 else if (sortby.equals("Pairwise Identity"))
445 sortPairwiseMenuItem_actionPerformed(null);
450 // this.alignPanel.av
451 // .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
453 setMenusFromViewport(viewport);
454 buildSortByAnnotationScoresMenu();
455 calculateTree.addActionListener(new ActionListener()
459 public void actionPerformed(ActionEvent e)
466 if (Desktop.getDesktopPane() != null)
468 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
469 addServiceListeners();
470 if (!Platform.isJS())
476 if (viewport.getWrapAlignment())
478 wrapMenuItem_actionPerformed(null);
481 if (Cache.getDefault(Preferences.SHOW_OVERVIEW, false))
483 this.overviewMenuItem_actionPerformed(null);
488 final List<AlignmentViewPanel> selviews = new ArrayList<>();
489 final List<AlignmentPanel> origview = new ArrayList<>();
490 final String menuLabel = MessageManager
491 .getString("label.copy_format_from");
492 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
493 new ViewSetProvider()
497 public AlignmentPanel[] getAllAlignmentPanels()
500 origview.add(alignPanel);
501 // make an array of all alignment panels except for this one
502 List<AlignmentPanel> aps = new ArrayList<>(
503 Arrays.asList(Desktop.getAlignmentPanels(null)));
504 aps.remove(AlignFrame.this.alignPanel);
505 return aps.toArray(new AlignmentPanel[aps.size()]);
507 }, selviews, new ItemListener()
511 public void itemStateChanged(ItemEvent e)
513 if (origview.size() > 0)
515 final AlignmentPanel ap = origview.get(0);
518 * Copy the ViewStyle of the selected panel to 'this one'.
519 * Don't change value of 'scaleProteinAsCdna' unless copying
522 ViewStyleI vs = selviews.get(0).getAlignViewport()
524 boolean fromSplitFrame = selviews.get(0)
525 .getAlignViewport().getCodingComplement() != null;
528 vs.setScaleProteinAsCdna(ap.getAlignViewport()
529 .getViewStyle().isScaleProteinAsCdna());
531 ap.getAlignViewport().setViewStyle(vs);
534 * Also rescale ViewStyle of SplitFrame complement if there is
535 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
536 * the whole ViewStyle (allow cDNA protein to have different
539 AlignViewportI complement = ap.getAlignViewport()
540 .getCodingComplement();
541 if (complement != null && vs.isScaleProteinAsCdna())
543 AlignFrame af = Desktop.getAlignFrameFor(complement);
544 ((SplitFrame) af.getSplitViewContainer())
546 af.setMenusForViewport();
550 ap.setSelected(true);
551 ap.alignFrame.setMenusForViewport();
556 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase(Locale.ROOT)
557 .indexOf("devel") > -1
558 || Cache.getDefault("VERSION", "DEVELOPMENT")
559 .toLowerCase(Locale.ROOT).indexOf("test") > -1)
561 formatMenu.add(vsel);
563 addFocusListener(new FocusAdapter()
567 public void focusGained(FocusEvent e)
569 Jalview.setCurrentAlignFrame(AlignFrame.this);
576 * Change the filename and format for the alignment, and enable the 'reload'
577 * button functionality.
586 public void setFileName(String file, FileFormatI format)
589 setFileFormat(format);
590 reload.setEnabled(true);
596 * @param file from SwingJS; may contain bytes -- for reload
597 * @param protocol from SwingJS; may be RELATIVE_URL
600 public void setFile(String fileName, File file, DataSourceType protocol, FileFormatI format)
602 this.fileName = fileName;
603 this.fileObject = file;
604 this.protocol = protocol;
605 setFileFormat(format);
606 reload.setEnabled(true);
610 * JavaScript will have this, maybe others. More dependable than a file name
611 * and maintains a reference to the actual bytes loaded.
616 public void setFileObject(File file)
618 this.fileObject = file;
622 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
626 void addKeyListener()
628 addKeyListener(new KeyAdapter()
632 public void keyPressed(KeyEvent evt)
634 if (viewport.cursorMode
635 && ((evt.getKeyCode() >= KeyEvent.VK_0
636 && evt.getKeyCode() <= KeyEvent.VK_9)
637 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
638 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
639 && Character.isDigit(evt.getKeyChar()))
641 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
644 switch (evt.getKeyCode())
647 case KeyEvent.VK_ESCAPE: // escape key
648 // alignPanel.deselectAllSequences();
649 alignPanel.deselectAllSequences();
653 case KeyEvent.VK_DOWN:
654 if (evt.isAltDown() || !viewport.cursorMode)
656 moveSelectedSequences(false);
658 if (viewport.cursorMode)
660 alignPanel.getSeqPanel().moveCursor(0, 1, evt.isShiftDown());
665 if (evt.isAltDown() || !viewport.cursorMode)
667 moveSelectedSequences(true);
669 if (viewport.cursorMode)
671 alignPanel.getSeqPanel().moveCursor(0, -1, evt.isShiftDown());
676 case KeyEvent.VK_LEFT:
677 if (evt.isAltDown() || !viewport.cursorMode)
679 slideSequences(false,
680 alignPanel.getSeqPanel().getKeyboardNo1());
684 alignPanel.getSeqPanel().moveCursor(-1, 0, evt.isShiftDown());
689 case KeyEvent.VK_RIGHT:
690 if (evt.isAltDown() || !viewport.cursorMode)
692 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
696 alignPanel.getSeqPanel().moveCursor(1, 0, evt.isShiftDown());
700 case KeyEvent.VK_SPACE:
701 if (viewport.cursorMode)
703 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
704 || evt.isShiftDown() || evt.isAltDown());
708 // case KeyEvent.VK_A:
709 // if (viewport.cursorMode)
711 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
712 // //System.out.println("A");
716 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
717 * System.out.println("closing bracket"); } break;
719 case KeyEvent.VK_DELETE:
720 case KeyEvent.VK_BACK_SPACE:
721 if (!viewport.cursorMode)
723 cut_actionPerformed();
727 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
728 || evt.isShiftDown() || evt.isAltDown());
734 if (viewport.cursorMode)
736 alignPanel.getSeqPanel().setCursorRow();
740 if (viewport.cursorMode && !evt.isControlDown())
742 alignPanel.getSeqPanel().setCursorColumn();
746 if (viewport.cursorMode)
748 alignPanel.getSeqPanel().setCursorPosition();
752 case KeyEvent.VK_ENTER:
753 case KeyEvent.VK_COMMA:
754 if (viewport.cursorMode)
756 alignPanel.getSeqPanel().setCursorRowAndColumn();
761 if (viewport.cursorMode)
763 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
767 if (viewport.cursorMode)
769 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
774 viewport.cursorMode = !viewport.cursorMode;
775 setStatus(MessageManager
776 .formatMessage("label.keyboard_editing_mode", new String[]
777 { (viewport.cursorMode ? "on" : "off") }));
778 if (viewport.cursorMode)
780 ViewportRanges ranges = viewport.getRanges();
781 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
783 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
786 alignPanel.getSeqPanel().seqCanvas.repaint();
792 Help.showHelpWindow();
793 } catch (Exception ex)
795 ex.printStackTrace();
800 boolean toggleSeqs = !evt.isControlDown();
801 boolean toggleCols = !evt.isShiftDown();
802 toggleHiddenRegions(toggleSeqs, toggleCols);
807 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
808 boolean modifyExisting = true; // always modify, don't clear
809 // evt.isShiftDown();
810 boolean invertHighlighted = evt.isAltDown();
811 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
815 case KeyEvent.VK_PAGE_UP:
816 viewport.getRanges().pageUp();
818 case KeyEvent.VK_PAGE_DOWN:
819 viewport.getRanges().pageDown();
825 public void keyReleased(KeyEvent evt)
827 switch (evt.getKeyCode())
829 case KeyEvent.VK_LEFT:
830 if (evt.isAltDown() || !viewport.cursorMode)
832 viewport.notifyAlignment();
836 case KeyEvent.VK_RIGHT:
837 if (evt.isAltDown() || !viewport.cursorMode)
839 viewport.notifyAlignment();
847 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
849 ap.alignFrame = this;
850 avc = new jalview.controller.AlignViewController(this, viewport,
855 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
857 int aSize = alignPanels.size();
859 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
861 if (aSize == 1 && ap.av.getViewName() == null)
863 this.getContentPane().add(ap, BorderLayout.CENTER);
869 setInitialTabVisible();
872 expandViews.setEnabled(true);
873 gatherViews.setEnabled(true);
874 tabbedPane.addTab(ap.av.getViewName(), ap);
876 ap.setVisible(false);
881 if (ap.av.isPadGaps())
883 ap.av.getAlignment().padGaps();
885 if (Jalview.getInstance().getStartCalculations())
887 ap.av.updateConservation(ap);
888 ap.av.updateConsensus(ap);
889 ap.av.updateStrucConsensus(ap);
890 ap.av.initInformationWorker(ap);
895 public void setInitialTabVisible()
897 expandViews.setEnabled(true);
898 gatherViews.setEnabled(true);
899 tabbedPane.setVisible(true);
900 AlignmentPanel first = alignPanels.get(0);
901 tabbedPane.addTab(first.av.getViewName(), first);
902 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
905 public AlignViewport getViewport()
911 public void servicesChanged(WSDiscovererI discoverer,
912 Collection<? extends ServiceWithParameters> services)
914 buildWebServicesMenu();
917 private WebServiceDiscovererI.ServicesChangeListener slivkaServiceChangeListener =
918 (discoverer, services) -> {
919 // run when slivka services change
920 var menu = AlignFrame.this.slivkaMenu;
921 menu.setServices(discoverer);
922 menu.setInProgress(discoverer.isRunning());
923 menu.setNoServices(services.isEmpty() && discoverer.isDone());
926 /* Set up intrinsic listeners for dynamically generated GUI bits. */
927 private void addServiceListeners()
929 if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
931 WebServiceDiscovererI discoverer = SlivkaWSDiscoverer.getInstance();
932 discoverer.addServicesChangeListener(slivkaServiceChangeListener);
934 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
936 WSDiscovererI discoverer = Jws2Discoverer.getInstance();
937 discoverer.addServiceChangeListener(this);
939 // legacy event listener for compatibility with jws1
940 PropertyChangeListener legacyListener = (changeEvent) -> {
941 buildWebServicesMenu();
943 Desktop.getInstance().addJalviewPropertyChangeListener("services",legacyListener);
945 addInternalFrameListener(new InternalFrameAdapter() {
947 public void internalFrameClosed(InternalFrameEvent e) {
948 System.out.println("deregistering discoverer listener");
949 SlivkaWSDiscoverer.getInstance().removeServicesChangeListener(slivkaServiceChangeListener);
950 Jws2Discoverer.getInstance().removeServiceChangeListener(AlignFrame.this);
951 Desktop.getInstance().removeJalviewPropertyChangeListener("services", legacyListener);
952 closeMenuItem_actionPerformed(true);
955 buildWebServicesMenu();
959 * Configure menu items that vary according to whether the alignment is
960 * nucleotide or protein
963 public void setGUINucleotide()
965 AlignmentI al = getViewport().getAlignment();
966 boolean nucleotide = al.isNucleotide();
968 loadVcf.setVisible(nucleotide);
969 showTranslation.setVisible(nucleotide);
970 showReverse.setVisible(nucleotide);
971 showReverseComplement.setVisible(nucleotide);
972 conservationMenuItem.setEnabled(!nucleotide);
974 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
975 showGroupConservation.setEnabled(!nucleotide);
977 showComplementMenuItem
978 .setText(nucleotide ? MessageManager.getString("label.protein")
979 : MessageManager.getString("label.nucleotide"));
983 * set up menus for the current viewport. This may be called after any
984 * operation that affects the data in the current view (selection changed,
985 * etc) to update the menus to reflect the new state.
989 public void setMenusForViewport()
991 setMenusFromViewport(viewport);
995 * Need to call this method when tabs are selected for multiple views, or when
996 * loading from Jalview2XML.java
1002 public void setMenusFromViewport(AlignViewport av)
1004 padGapsMenuitem.setSelected(av.isPadGaps());
1005 colourTextMenuItem.setSelected(av.isShowColourText());
1006 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
1007 modifyPID.setEnabled(abovePIDThreshold.isSelected());
1008 conservationMenuItem.setSelected(av.getConservationSelected());
1009 modifyConservation.setEnabled(conservationMenuItem.isSelected());
1010 seqLimits.setSelected(av.getShowJVSuffix());
1011 idRightAlign.setSelected(av.isRightAlignIds());
1012 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
1013 renderGapsMenuItem.setSelected(av.isRenderGaps());
1014 wrapMenuItem.setSelected(av.getWrapAlignment());
1015 scaleAbove.setVisible(av.getWrapAlignment());
1016 scaleLeft.setVisible(av.getWrapAlignment());
1017 scaleRight.setVisible(av.getWrapAlignment());
1018 annotationPanelMenuItem.setState(av.isShowAnnotation());
1019 // Show/hide annotations only enabled if annotation panel is shown
1020 syncAnnotationMenuItems(av.isShowAnnotation());
1021 viewBoxesMenuItem.setSelected(av.getShowBoxes());
1022 viewTextMenuItem.setSelected(av.getShowText());
1023 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
1024 showGroupConsensus.setSelected(av.isShowGroupConsensus());
1025 showGroupConservation.setSelected(av.isShowGroupConservation());
1026 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
1027 showSequenceLogo.setSelected(av.isShowSequenceLogo());
1028 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
1029 showInformationHistogram.setSelected(av.isShowInformationHistogram());
1030 showHMMSequenceLogo.setSelected(av.isShowHMMSequenceLogo());
1031 normaliseHMMSequenceLogo.setSelected(av.isNormaliseHMMSequenceLogo());
1033 ColourMenuHelper.setColourSelected(colourMenu,
1034 av.getGlobalColourScheme());
1036 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
1037 hiddenMarkers.setState(av.getShowHiddenMarkers());
1038 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
1039 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
1040 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
1042 .setSelected(av.getAutoCalculateConsensusAndConservation());
1043 sortByTree.setSelected(av.sortByTree);
1044 listenToViewSelections.setSelected(av.followSelection);
1046 showProducts.setEnabled(canShowProducts());
1047 setGroovyEnabled(Desktop.getGroovyConsole() != null);
1049 updateEditMenuBar();
1053 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
1058 public void setGroovyEnabled(boolean b)
1060 runGroovy.setEnabled(b);
1063 private IProgressIndicator progressBar;
1068 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
1072 public void setProgressBar(String message, long id)
1074 progressBar.setProgressBar(message, id);
1078 public void addProgressBar(long id, String message)
1080 progressBar.addProgressBar(id, message);
1084 public void removeProgressBar(long id)
1086 progressBar.removeProgressBar(id);
1090 public void registerHandler(final long id,
1091 final IProgressIndicatorHandler handler)
1093 progressBar.registerHandler(id, handler);
1098 * @return true if any progress bars are still active
1102 public boolean operationInProgress()
1104 return progressBar.operationInProgress();
1108 * Sets the text of the status bar. Note that setting a null or empty value
1109 * will cause the status bar to be hidden, with possibly undesirable flicker
1110 * of the screen layout.
1114 public void setStatus(String text)
1116 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1120 * Added so Castor Mapping file can obtain Jalview Version
1123 public String getVersion()
1125 return Cache.getProperty("VERSION");
1128 public FeatureRenderer getFeatureRenderer()
1130 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1134 public void fetchSequence_actionPerformed()
1136 new SequenceFetcher(this);
1140 public void addFromFile_actionPerformed(ActionEvent e)
1142 Desktop.getInstance().inputLocalFileMenuItem_actionPerformed(viewport);
1146 public void hmmBuild_actionPerformed(boolean withDefaults)
1148 if (!alignmentIsSufficient(1))
1154 * get default parameters, and optionally show a dialog
1155 * to allow them to be modified
1157 ParamDatastoreI store = HMMERParamStore.forBuild(viewport);
1158 List<ArgumentI> args = store.getServiceParameters();
1162 WsParamSetI set = new HMMERPreset();
1163 WsJobParameters params = new WsJobParameters(store, set, args);
1164 params.showRunDialog().thenAccept((startJob) -> {
1167 var args2 = params.getJobParams();
1168 new Thread(new HMMBuild(this, args2)).start();
1174 new Thread(new HMMBuild(this, args)).start();
1179 public void hmmAlign_actionPerformed(boolean withDefaults)
1181 if (!(checkForHMM() && alignmentIsSufficient(2)))
1187 * get default parameters, and optionally show a dialog
1188 * to allow them to be modified
1190 ParamDatastoreI store = HMMERParamStore.forAlign(viewport);
1191 List<ArgumentI> args = store.getServiceParameters();
1195 WsParamSetI set = new HMMERPreset();
1196 WsJobParameters params = new WsJobParameters(store, set, args);
1197 params.showRunDialog().thenAccept((startJob) -> {
1200 var args2 = params.getJobParams();
1201 new Thread(new HMMAlign(this, args2)).start();
1207 new Thread(new HMMAlign(this, args)).start();
1212 public void hmmSearch_actionPerformed(boolean withDefaults)
1220 * get default parameters, and (if requested) show
1221 * dialog to allow modification
1223 ParamDatastoreI store = HMMERParamStore.forSearch(viewport);
1224 List<ArgumentI> args = store.getServiceParameters();
1228 WsParamSetI set = new HMMERPreset();
1229 WsJobParameters params = new WsJobParameters(store, set, args);
1230 params.showRunDialog().thenAccept((startJob) -> {
1233 var args2 = params.getJobParams();
1234 new Thread(new HMMSearch(this, args2)).start();
1235 alignPanel.repaint();
1241 new Thread(new HMMSearch(this, args)).start();
1242 alignPanel.repaint();
1247 public void jackhmmer_actionPerformed(boolean withDefaults)
1251 * get default parameters, and (if requested) show
1252 * dialog to allow modification
1255 ParamDatastoreI store = HMMERParamStore.forJackhmmer(viewport);
1256 List<ArgumentI> args = store.getServiceParameters();
1260 WsParamSetI set = new HMMERPreset();
1261 WsJobParameters params = new WsJobParameters(store, set, args);
1262 params.showRunDialog().thenAccept((startJob) -> {
1265 var args2 = params.getJobParams();
1266 new Thread(new JackHMMER(this, args2)).start();
1267 alignPanel.repaint();
1273 new Thread(new JackHMMER(this, args)).start();
1274 alignPanel.repaint();
1279 * Checks if the alignment has at least one hidden Markov model, if not shows
1280 * a dialog advising to run hmmbuild or load an HMM profile
1284 private boolean checkForHMM()
1286 if (viewport.getAlignment().getHmmSequences().isEmpty())
1288 JOptionPane.showMessageDialog(this,
1289 MessageManager.getString("warn.no_hmm"));
1296 protected void filterByEValue_actionPerformed()
1298 viewport.filterByEvalue(inputDouble("Enter E-Value Cutoff"));
1302 protected void filterByScore_actionPerformed()
1304 viewport.filterByScore(inputDouble("Enter Bit Score Threshold"));
1307 private double inputDouble(String message)
1311 while (d == null || d <= 0)
1313 str = JOptionPane.showInputDialog(this.alignPanel, message);
1316 d = Double.valueOf(str);
1317 } catch (NumberFormatException e)
1325 * Checks if the alignment contains the required number of sequences.
1330 public boolean alignmentIsSufficient(int required)
1332 if (getViewport().getSequenceSelection().length < required)
1334 JOptionPane.showMessageDialog(this,
1335 MessageManager.getString("label.not_enough_sequences"));
1342 * Opens a file browser and adds the selected file, if in Fasta, Stockholm or
1343 * Pfam format, to the list held under preference key "HMMSEARCH_DBS" (as a
1344 * comma-separated list)
1347 public void addDatabase_actionPerformed() throws IOException
1349 if (Cache.getProperty(Preferences.HMMSEARCH_DBS) == null)
1351 Cache.setProperty(Preferences.HMMSEARCH_DBS, "");
1354 String path = openFileChooser(false);
1355 if (path != null && new File(path).exists())
1357 IdentifyFile identifier = new IdentifyFile();
1358 FileFormatI format = identifier.identify(path, DataSourceType.FILE);
1359 if (format == FileFormat.Fasta || format == FileFormat.Stockholm
1360 || format == FileFormat.Pfam)
1362 String currentDbPaths = Cache
1363 .getProperty(Preferences.HMMSEARCH_DBS);
1364 currentDbPaths += Preferences.COMMA + path;
1365 Cache.setProperty(Preferences.HMMSEARCH_DBS, currentDbPaths);
1369 JOptionPane.showMessageDialog(this,
1370 MessageManager.getString("warn.invalid_format"));
1376 * Opens a file chooser, optionally restricted to selecting folders
1377 * (directories) only. Answers the path to the selected file or folder, or
1378 * null if none is chosen.
1383 protected String openFileChooser(boolean forFolder)
1385 // TODO duplicates GPreferences method - relocate to JalviewFileChooser?
1386 String choice = null;
1387 JFileChooser chooser = new JFileChooser();
1390 chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1392 chooser.setDialogTitle(
1393 MessageManager.getString("label.open_local_file"));
1394 chooser.setToolTipText(MessageManager.getString("action.open"));
1396 int value = chooser.showOpenDialog(this);
1398 if (value == JFileChooser.APPROVE_OPTION)
1400 choice = chooser.getSelectedFile().getPath();
1406 public void reload_actionPerformed(ActionEvent e)
1408 if (fileName == null && fileObject == null)
1412 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1413 // originating file's format
1414 // TODO: work out how to recover feature settings for correct view(s) when
1415 // file is reloaded.
1416 if (FileFormat.Jalview.equals(currentFileFormat))
1418 JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
1419 for (int i = 0; i < frames.length; i++)
1421 if (frames[i] instanceof AlignFrame && frames[i] != this
1422 && ((AlignFrame) frames[i]).fileName != null
1423 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1427 frames[i].setSelected(true);
1428 Desktop.getInstance().closeAssociatedWindows();
1429 } catch (java.beans.PropertyVetoException ex)
1435 Desktop.getInstance().closeAssociatedWindows();
1437 FileLoader loader = new FileLoader();
1438 loader.LoadFile(viewport, (fileObject == null ? fileName : fileObject), protocol, currentFileFormat);
1442 Rectangle bounds = this.getBounds();
1444 FileLoader loader = new FileLoader();
1446 AlignFrame newframe = null;
1448 if (fileObject == null)
1450 newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1455 newframe = loader.LoadFileWaitTillLoaded(fileObject,
1456 DataSourceType.FILE, currentFileFormat);
1459 newframe.setBounds(bounds);
1460 if (featureSettings != null && featureSettings.isShowing())
1462 final Rectangle fspos = featureSettings.frame.getBounds();
1463 // TODO: need a 'show feature settings' function that takes bounds -
1464 // need to refactor Desktop.addFrame
1465 newframe.featureSettings_actionPerformed(null);
1466 final FeatureSettings nfs = newframe.featureSettings;
1467 SwingUtilities.invokeLater(new Runnable()
1473 nfs.frame.setBounds(fspos);
1476 this.featureSettings.close();
1477 this.featureSettings = null;
1479 this.closeMenuItem_actionPerformed(true);
1485 public void addFromText_actionPerformed(ActionEvent e)
1487 Desktop.getInstance()
1488 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1492 public void addFromURL_actionPerformed(ActionEvent e)
1494 Desktop.getInstance().inputURLMenuItem_actionPerformed(viewport);
1498 public void save_actionPerformed(ActionEvent e)
1500 if (fileName == null || (currentFileFormat == null)
1501 || HttpUtils.startsWithHttpOrHttps(fileName))
1503 saveAs_actionPerformed();
1507 saveAlignment(fileName, currentFileFormat);
1512 * Saves the alignment to a file with a name chosen by the user, if necessary
1513 * warning if a file would be overwritten
1517 public void saveAs_actionPerformed()
1519 String format = currentFileFormat == null ? null
1520 : currentFileFormat.getName();
1521 JalviewFileChooser chooser = JalviewFileChooser
1522 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1524 chooser.setFileView(new JalviewFileView());
1525 chooser.setDialogTitle(
1526 MessageManager.getString("label.save_alignment_to_file"));
1527 chooser.setToolTipText(MessageManager.getString("action.save"));
1529 int value = chooser.showSaveDialog(this);
1531 if (value != JalviewFileChooser.APPROVE_OPTION)
1535 currentFileFormat = chooser.getSelectedFormat();
1536 // todo is this (2005) test now obsolete - value is never null?
1537 while (currentFileFormat == null)
1539 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
1541 .getString("label.select_file_format_before_saving"),
1542 MessageManager.getString("label.file_format_not_specified"),
1543 JvOptionPane.WARNING_MESSAGE);
1544 currentFileFormat = chooser.getSelectedFormat();
1545 value = chooser.showSaveDialog(this);
1546 if (value != JalviewFileChooser.APPROVE_OPTION)
1552 fileName = chooser.getSelectedFile().getPath();
1554 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1555 Cache.setProperty("LAST_DIRECTORY", fileName);
1556 saveAlignment(fileName, currentFileFormat);
1559 boolean lastSaveSuccessful = false;
1561 FileFormatI lastFormatSaved;
1563 String lastFilenameSaved;
1566 * Raise a dialog or status message for the last call to saveAlignment.
1568 * @return true if last call to saveAlignment(file, format) was successful.
1571 public boolean isSaveAlignmentSuccessful()
1574 if (!lastSaveSuccessful)
1576 if (!Platform.isHeadless())
1578 JvOptionPane.showInternalMessageDialog(this, MessageManager
1579 .formatMessage("label.couldnt_save_file", new Object[]
1580 { lastFilenameSaved }),
1581 MessageManager.getString("label.error_saving_file"),
1582 JvOptionPane.WARNING_MESSAGE);
1586 Console.error(MessageManager
1587 .formatMessage("label.couldnt_save_file", new Object[]
1588 { lastFilenameSaved }));
1594 setStatus(MessageManager.formatMessage(
1595 "label.successfully_saved_to_file_in_format", new Object[]
1596 { lastFilenameSaved, lastFormatSaved }));
1599 return lastSaveSuccessful;
1603 * Saves the alignment to the specified file path, in the specified format,
1604 * which may be an alignment format, or Jalview project format. If the
1605 * alignment has hidden regions, or the format is one capable of including
1606 * non-sequence data (features, annotations, groups), then the user may be
1607 * prompted to specify what to include in the output.
1613 public void saveAlignment(String file, FileFormatI format)
1615 lastSaveSuccessful = true;
1616 lastFilenameSaved = file;
1617 lastFormatSaved = format;
1619 if (FileFormat.Jalview.equals(format))
1621 String shortName = title;
1622 if (shortName.indexOf(File.separatorChar) > -1)
1624 shortName = shortName
1625 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
1627 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file,
1630 statusBar.setText(MessageManager.formatMessage(
1631 "label.successfully_saved_to_file_in_format", new Object[]
1632 { fileName, format }));
1637 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1638 Runnable cancelAction = new Runnable()
1644 lastSaveSuccessful = false;
1647 Runnable outputAction = new Runnable()
1653 // todo defer this to inside formatSequences (or later)
1654 AlignmentExportData exportData = viewport
1655 .getAlignExportData(options);
1656 String output = new FormatAdapter(alignPanel, options)
1657 .formatSequences(format, exportData.getAlignment(),
1658 exportData.getOmitHidden(),
1659 exportData.getStartEndPostions(),
1660 viewport.getAlignment().getHiddenColumns());
1663 lastSaveSuccessful = false;
1667 // create backupfiles object and get new temp filename destination
1668 boolean doBackup = BackupFiles.getEnabled();
1669 BackupFiles backupfiles = null;
1673 "ALIGNFRAME making backupfiles object for " + file);
1674 backupfiles = new BackupFiles(file);
1678 String tempFilePath = doBackup ? backupfiles.getTempFilePath()
1680 Console.trace("ALIGNFRAME setting PrintWriter");
1681 PrintWriter out = new PrintWriter(new FileWriter(tempFilePath));
1683 if (backupfiles != null)
1685 Console.trace("ALIGNFRAME about to write to temp file "
1686 + backupfiles.getTempFilePath());
1689 Console.trace("ALIGNFRAME about to close file");
1691 Console.trace("ALIGNFRAME closed file");
1692 AlignFrame.this.setTitle(file);
1693 statusBar.setText(MessageManager.formatMessage(
1694 "label.successfully_saved_to_file_in_format",
1696 { fileName, format.getName() }));
1697 lastSaveSuccessful = true;
1698 } catch (IOException e)
1700 lastSaveSuccessful = false;
1702 "ALIGNFRAME Something happened writing the temp file");
1703 Console.error(e.getMessage());
1704 Console.debug(Cache.getStackTraceString(e));
1705 } catch (Exception ex)
1707 lastSaveSuccessful = false;
1709 "ALIGNFRAME Something unexpected happened writing the temp file");
1710 Console.error(ex.getMessage());
1711 Console.debug(Cache.getStackTraceString(ex));
1716 backupfiles.setWriteSuccess(lastSaveSuccessful);
1717 Console.debug("ALIGNFRAME writing temp file was "
1718 + (lastSaveSuccessful ? "" : "NOT ") + "successful");
1719 // do the backup file roll and rename the temp file to actual file
1721 "ALIGNFRAME about to rollBackupsAndRenameTempFile");
1722 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1724 "ALIGNFRAME performed rollBackupsAndRenameTempFile "
1725 + (lastSaveSuccessful ? "" : "un")
1733 * show dialog with export options if applicable; else just do it
1735 if (AlignExportOptions.isNeeded(viewport, format))
1737 AlignExportOptions choices = new AlignExportOptions(
1738 alignPanel.getAlignViewport(), format, options);
1739 choices.setResponseAction(0, outputAction);
1740 choices.setResponseAction(1, cancelAction);
1741 choices.showDialog();
1750 * Outputs the alignment to textbox in the requested format, if necessary
1751 * first prompting the user for whether to include hidden regions or
1754 * @param fileFormatName
1758 protected void outputText_actionPerformed(String fileFormatName)
1760 FileFormatI fileFormat = FileFormats.getInstance()
1761 .forName(fileFormatName);
1762 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1763 Runnable outputAction = new Runnable()
1769 // todo defer this to inside formatSequences (or later)
1770 AlignmentExportData exportData = viewport
1771 .getAlignExportData(options);
1772 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1773 cap.setForInput(null);
1776 FileFormatI format = fileFormat;
1777 cap.setText(new FormatAdapter(alignPanel, options)
1778 .formatSequences(format, exportData.getAlignment(),
1779 exportData.getOmitHidden(),
1780 exportData.getStartEndPostions(),
1781 viewport.getAlignment().getHiddenColumns()));
1782 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1783 "label.alignment_output_command", new Object[]
1784 { fileFormat.getName() }), 600, 500);
1785 } catch (OutOfMemoryError oom)
1787 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1795 * show dialog with export options if applicable; else just do it
1797 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1799 AlignExportOptions choices = new AlignExportOptions(
1800 alignPanel.getAlignViewport(), fileFormat, options);
1801 choices.setResponseAction(0, outputAction);
1802 choices.showDialog();
1818 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1820 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1821 htmlSVG.exportHTML(null);
1825 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1827 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1828 bjs.exportHTML(null);
1833 public void createImageMap(File file, String image)
1835 alignPanel.makePNGImageMap(file, image);
1839 * Creates a PNG image of the alignment and writes it to the given file. If
1840 * the file is null, the user is prompted to choose a file.
1846 public void createPNG(File f)
1848 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1852 * Creates an EPS image of the alignment and writes it to the given file. If
1853 * the file is null, the user is prompted to choose a file.
1859 public void createEPS(File f)
1861 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1865 * Creates an SVG image of the alignment and writes it to the given file. If
1866 * the file is null, the user is prompted to choose a file.
1872 public void createSVG(File f)
1874 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1878 public void pageSetup_actionPerformed(ActionEvent e)
1880 PrinterJob printJob = PrinterJob.getPrinterJob();
1881 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1892 public void printMenuItem_actionPerformed(ActionEvent e)
1894 // Putting in a thread avoids Swing painting problems
1895 PrintThread thread = new PrintThread(alignPanel);
1900 public void exportFeatures_actionPerformed(ActionEvent e)
1902 new AnnotationExporter(alignPanel).exportFeatures();
1906 public void exportAnnotations_actionPerformed(ActionEvent e)
1908 new AnnotationExporter(alignPanel).exportAnnotations();
1912 public void associatedData_actionPerformed(ActionEvent e)
1913 throws IOException, InterruptedException
1915 final JalviewFileChooser chooser = new JalviewFileChooser(
1916 Cache.getProperty("LAST_DIRECTORY"));
1917 chooser.setFileView(new JalviewFileView());
1918 String tooltip = MessageManager
1919 .getString("label.load_jalview_annotations");
1920 chooser.setDialogTitle(tooltip);
1921 chooser.setToolTipText(tooltip);
1922 chooser.setResponseHandler(0, new Runnable()
1928 String choice = chooser.getSelectedFile().getPath();
1929 Cache.setProperty("LAST_DIRECTORY", choice);
1930 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1934 chooser.showOpenDialog(this);
1938 * Close the current view or all views in the alignment frame. If the frame
1939 * only contains one view then the alignment will be removed from memory.
1941 * @param closeAllTabs
1945 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1947 if (alignPanels != null && alignPanels.size() < 2)
1949 closeAllTabs = true;
1954 if (alignPanels != null)
1958 if (this.isClosed())
1960 // really close all the windows - otherwise wait till
1961 // setClosed(true) is called
1962 for (int i = 0; i < alignPanels.size(); i++)
1964 AlignmentPanel ap = alignPanels.get(i);
1971 closeView(alignPanel);
1976 if (featureSettings != null && featureSettings.isOpen())
1978 featureSettings.close();
1979 featureSettings = null;
1982 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1983 * be called recursively, with the frame now in 'closed' state
1985 this.setClosed(true);
1987 } catch (Exception ex)
1989 ex.printStackTrace();
1994 * Close the specified panel and close up tabs appropriately.
1996 * @param panelToClose
1999 public void closeView(AlignmentPanel panelToClose)
2001 int index = tabbedPane.getSelectedIndex();
2002 int closedindex = tabbedPane.indexOfComponent(panelToClose);
2003 alignPanels.remove(panelToClose);
2004 panelToClose.closePanel();
2005 panelToClose = null;
2007 tabbedPane.removeTabAt(closedindex);
2008 tabbedPane.validate();
2010 if (index > closedindex || index == tabbedPane.getTabCount())
2012 // modify currently selected tab index if necessary.
2016 this.tabSelectionChanged(index);
2023 void updateEditMenuBar()
2026 if (viewport.getHistoryList().size() > 0)
2028 undoMenuItem.setEnabled(true);
2029 CommandI command = viewport.getHistoryList().peek();
2030 undoMenuItem.setText(MessageManager
2031 .formatMessage("label.undo_command", new Object[]
2032 { command.getDescription() }));
2036 undoMenuItem.setEnabled(false);
2037 undoMenuItem.setText(MessageManager.getString("action.undo"));
2040 if (viewport.getRedoList().size() > 0)
2042 redoMenuItem.setEnabled(true);
2044 CommandI command = viewport.getRedoList().peek();
2045 redoMenuItem.setText(MessageManager
2046 .formatMessage("label.redo_command", new Object[]
2047 { command.getDescription() }));
2051 redoMenuItem.setEnabled(false);
2052 redoMenuItem.setText(MessageManager.getString("action.redo"));
2057 public void addHistoryItem(CommandI command)
2059 if (command.getSize() > 0)
2061 viewport.addToHistoryList(command);
2062 viewport.clearRedoList();
2063 updateEditMenuBar();
2064 viewport.updateHiddenColumns();
2065 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
2066 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2067 // viewport.getColumnSelection()
2068 // .getHiddenColumns().size() > 0);
2074 * @return alignment objects for all views
2077 AlignmentI[] getViewAlignments()
2079 if (alignPanels != null)
2081 AlignmentI[] als = new AlignmentI[alignPanels.size()];
2083 for (AlignmentPanel ap : alignPanels)
2085 als[i++] = ap.av.getAlignment();
2089 if (viewport != null)
2091 return new AlignmentI[] { viewport.getAlignment() };
2104 protected void undoMenuItem_actionPerformed(ActionEvent e)
2106 if (viewport.getHistoryList().isEmpty())
2110 CommandI command = viewport.getHistoryList().pop();
2111 viewport.addToRedoList(command);
2112 command.undoCommand(getViewAlignments());
2114 AlignmentViewport originalSource = getOriginatingSource(command);
2115 updateEditMenuBar();
2117 if (originalSource != null)
2119 if (originalSource != viewport)
2122 "Implementation worry: mismatch of viewport origin for undo");
2124 originalSource.updateHiddenColumns();
2125 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
2127 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2128 // viewport.getColumnSelection()
2129 // .getHiddenColumns().size() > 0);
2130 originalSource.notifyAlignment();
2143 protected void redoMenuItem_actionPerformed(ActionEvent e)
2145 if (viewport.getRedoList().size() < 1)
2150 CommandI command = viewport.getRedoList().pop();
2151 viewport.addToHistoryList(command);
2152 command.doCommand(getViewAlignments());
2154 AlignmentViewport originalSource = getOriginatingSource(command);
2155 updateEditMenuBar();
2157 if (originalSource != null)
2160 if (originalSource != viewport)
2163 "Implementation worry: mismatch of viewport origin for redo");
2165 originalSource.updateHiddenColumns();
2166 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
2168 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2169 // viewport.getColumnSelection()
2170 // .getHiddenColumns().size() > 0);
2171 originalSource.notifyAlignment();
2176 AlignmentViewport getOriginatingSource(CommandI command)
2178 AlignmentViewport originalSource = null;
2179 // For sequence removal and addition, we need to fire
2180 // the property change event FROM the viewport where the
2181 // original alignment was altered
2182 AlignmentI al = null;
2183 if (command instanceof EditCommand)
2185 EditCommand editCommand = (EditCommand) command;
2186 al = editCommand.getAlignment();
2187 List<Component> comps = PaintRefresher.components
2188 .get(viewport.getSequenceSetId());
2190 for (Component comp : comps)
2192 if (comp instanceof AlignmentPanel)
2194 if (al == ((AlignmentPanel) comp).av.getAlignment())
2196 originalSource = ((AlignmentPanel) comp).av;
2203 if (originalSource == null)
2205 // The original view is closed, we must validate
2206 // the current view against the closed view first
2209 PaintRefresher.validateSequences(al, viewport.getAlignment());
2212 originalSource = viewport;
2215 return originalSource;
2219 * Calls AlignmentI.moveSelectedSequencesByOne with current sequence selection
2220 * or the sequence under cursor in keyboard mode
2226 public void moveSelectedSequences(boolean up)
2228 SequenceGroup sg = viewport.getSelectionGroup();
2232 if (viewport.cursorMode)
2234 sg = new SequenceGroup();
2235 sg.addSequence(viewport.getAlignment().getSequenceAt(
2236 alignPanel.getSeqPanel().seqCanvas.cursorY), false);
2244 if (sg.getSize() < 1)
2248 // TODO: JAL-3733 - add an event to the undo buffer for this !
2249 viewport.getAlignment().moveSelectedSequencesByOne(sg,
2250 viewport.getHiddenRepSequences(), up);
2251 alignPanel.paintAlignment(true, false);
2254 synchronized void slideSequences(boolean right, int size)
2256 List<SequenceI> sg = new ArrayList<>();
2257 if (viewport.cursorMode)
2259 sg.add(viewport.getAlignment()
2260 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
2262 else if (viewport.getSelectionGroup() != null
2263 && viewport.getSelectionGroup().getSize() != viewport
2264 .getAlignment().getHeight())
2266 sg = viewport.getSelectionGroup()
2267 .getSequences(viewport.getHiddenRepSequences());
2275 List<SequenceI> invertGroup = new ArrayList<>();
2277 for (SequenceI seq : viewport.getAlignment().getSequences())
2279 if (!sg.contains(seq))
2281 invertGroup.add(seq);
2285 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
2287 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
2288 for (int i = 0; i < invertGroup.size(); i++)
2290 seqs2[i] = invertGroup.get(i);
2293 SlideSequencesCommand ssc;
2296 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
2297 viewport.getGapCharacter());
2301 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
2302 viewport.getGapCharacter());
2305 int groupAdjustment = 0;
2306 if (ssc.getGapsInsertedBegin() && right)
2308 if (viewport.cursorMode)
2310 alignPanel.getSeqPanel().moveCursor(size, 0);
2314 groupAdjustment = size;
2317 else if (!ssc.getGapsInsertedBegin() && !right)
2319 if (viewport.cursorMode)
2321 alignPanel.getSeqPanel().moveCursor(-size, 0);
2325 groupAdjustment = -size;
2329 if (groupAdjustment != 0)
2331 viewport.getSelectionGroup().setStartRes(
2332 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
2333 viewport.getSelectionGroup().setEndRes(
2334 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
2338 * just extend the last slide command if compatible; but not if in
2339 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
2341 boolean appendHistoryItem = false;
2342 Deque<CommandI> historyList = viewport.getHistoryList();
2343 boolean inSplitFrame = getSplitViewContainer() != null;
2344 if (!inSplitFrame && historyList != null && historyList.size() > 0
2345 && historyList.peek() instanceof SlideSequencesCommand)
2347 appendHistoryItem = ssc.appendSlideCommand(
2348 (SlideSequencesCommand) historyList.peek());
2351 if (!appendHistoryItem)
2353 addHistoryItem(ssc);
2367 protected void copy_actionPerformed()
2369 if (viewport.getSelectionGroup() == null)
2373 // TODO: preserve the ordering of displayed alignment annotation in any
2374 // internal paste (particularly sequence associated annotation)
2375 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2376 String[] omitHidden = null;
2378 if (viewport.hasHiddenColumns())
2380 omitHidden = viewport.getViewAsString(true);
2383 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2384 seqs, omitHidden, null);
2386 StringSelection ss = new StringSelection(output);
2388 Desktop d = Desktop.getInstance();
2391 d.internalCopy = true;
2392 // Its really worth setting the clipboard contents
2393 // to empty before setting the large StringSelection!!
2394 Toolkit.getDefaultToolkit().getSystemClipboard()
2395 .setContents(new StringSelection(""), null);
2397 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2399 } catch (OutOfMemoryError er)
2401 new OOMWarning("copying region", er);
2405 HiddenColumns hiddenColumns = null;
2406 if (viewport.hasHiddenColumns())
2408 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2409 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2411 // create new HiddenColumns object with copy of hidden regions
2412 // between startRes and endRes, offset by startRes
2413 hiddenColumns = new HiddenColumns(
2414 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2415 hiddenCutoff, hiddenOffset);
2418 d.jalviewClipboard = new Object[] { seqs,
2419 viewport.getAlignment().getDataset(), hiddenColumns };
2420 setStatus(MessageManager.formatMessage(
2421 "label.copied_sequences_to_clipboard", new Object[]
2422 { Integer.valueOf(seqs.length).toString() }));
2430 * @throws InterruptedException
2431 * @throws IOException
2435 protected void pasteNew_actionPerformed(ActionEvent e)
2436 throws IOException, InterruptedException
2446 * @throws InterruptedException
2447 * @throws IOException
2451 protected void pasteThis_actionPerformed(ActionEvent e)
2452 throws IOException, InterruptedException
2458 * Paste contents of Jalview clipboard
2460 * @param newAlignment
2461 * true to paste to a new alignment, otherwise add to this.
2462 * @throws InterruptedException
2463 * @throws IOException
2465 void paste(boolean newAlignment) throws IOException, InterruptedException
2467 boolean externalPaste = true;
2470 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2471 Transferable contents = c.getContents(this);
2473 if (contents == null)
2482 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2483 if (str.length() < 1)
2488 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2490 } catch (OutOfMemoryError er)
2492 new OOMWarning("Out of memory pasting sequences!!", er);
2496 SequenceI[] sequences;
2497 boolean annotationAdded = false;
2498 AlignmentI alignment = null;
2500 Desktop d = Desktop.getInstance();
2502 if (d.jalviewClipboard != null)
2504 // The clipboard was filled from within Jalview, we must use the
2506 // And dataset from the copied alignment
2507 SequenceI[] newseq = (SequenceI[]) d.jalviewClipboard[0];
2508 // be doubly sure that we create *new* sequence objects.
2509 sequences = new SequenceI[newseq.length];
2510 for (int i = 0; i < newseq.length; i++)
2512 sequences[i] = new Sequence(newseq[i]);
2514 alignment = new Alignment(sequences);
2515 externalPaste = false;
2519 // parse the clipboard as an alignment.
2520 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2522 sequences = alignment.getSequencesArray();
2526 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2532 if (d.jalviewClipboard != null)
2534 // dataset is inherited
2535 alignment.setDataset((Alignment) d.jalviewClipboard[1]);
2539 // new dataset is constructed
2540 alignment.setDataset(null);
2542 alwidth = alignment.getWidth() + 1;
2546 AlignmentI pastedal = alignment; // preserve pasted alignment object
2547 // Add pasted sequences and dataset into existing alignment.
2548 alignment = viewport.getAlignment();
2549 alwidth = alignment.getWidth() + 1;
2550 // decide if we need to import sequences from an existing dataset
2551 boolean importDs = d.jalviewClipboard != null
2552 && d.jalviewClipboard[1] != alignment.getDataset();
2553 // importDs==true instructs us to copy over new dataset sequences from
2554 // an existing alignment
2555 Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2557 // minimum dataset set
2559 for (int i = 0; i < sequences.length; i++)
2563 newDs.addElement(null);
2565 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2567 if (importDs && ds != null)
2569 if (!newDs.contains(ds))
2571 newDs.setElementAt(ds, i);
2572 ds = new Sequence(ds);
2573 // update with new dataset sequence
2574 sequences[i].setDatasetSequence(ds);
2578 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2583 // copy and derive new dataset sequence
2584 sequences[i] = sequences[i].deriveSequence();
2585 alignment.getDataset()
2586 .addSequence(sequences[i].getDatasetSequence());
2587 // TODO: avoid creation of duplicate dataset sequences with a
2588 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2590 alignment.addSequence(sequences[i]); // merges dataset
2594 newDs.clear(); // tidy up
2596 if (alignment.getAlignmentAnnotation() != null)
2598 for (AlignmentAnnotation alan : alignment
2599 .getAlignmentAnnotation())
2601 if (alan.graphGroup > fgroup)
2603 fgroup = alan.graphGroup;
2607 if (pastedal.getAlignmentAnnotation() != null)
2609 // Add any annotation attached to alignment.
2610 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2611 for (int i = 0; i < alann.length; i++)
2613 annotationAdded = true;
2614 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2616 AlignmentAnnotation newann = new AlignmentAnnotation(
2618 if (newann.graphGroup > -1)
2620 if (newGraphGroups.size() <= newann.graphGroup
2621 || newGraphGroups.get(newann.graphGroup) == null)
2623 for (int q = newGraphGroups
2624 .size(); q <= newann.graphGroup; q++)
2626 newGraphGroups.add(q, null);
2628 newGraphGroups.set(newann.graphGroup,
2629 Integer.valueOf(++fgroup));
2631 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2635 newann.padAnnotation(alwidth);
2636 alignment.addAnnotation(newann);
2646 addHistoryItem(new EditCommand(
2647 MessageManager.getString("label.add_sequences"),
2648 Action.PASTE, sequences, 0, alignment.getWidth(),
2651 // Add any annotations attached to sequences
2652 for (int i = 0; i < sequences.length; i++)
2654 if (sequences[i].getAnnotation() != null)
2656 AlignmentAnnotation newann;
2657 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2659 annotationAdded = true;
2660 newann = sequences[i].getAnnotation()[a];
2661 newann.adjustForAlignment();
2662 newann.padAnnotation(alwidth);
2663 if (newann.graphGroup > -1)
2665 if (newann.graphGroup > -1)
2667 if (newGraphGroups.size() <= newann.graphGroup
2668 || newGraphGroups.get(newann.graphGroup) == null)
2670 for (int q = newGraphGroups
2671 .size(); q <= newann.graphGroup; q++)
2673 newGraphGroups.add(q, null);
2675 newGraphGroups.set(newann.graphGroup,
2676 Integer.valueOf(++fgroup));
2678 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2682 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2686 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2694 // propagate alignment changed.
2695 viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2696 if (annotationAdded)
2698 // Duplicate sequence annotation in all views.
2699 AlignmentI[] alview = this.getViewAlignments();
2700 for (int i = 0; i < sequences.length; i++)
2702 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2707 for (int avnum = 0; avnum < alview.length; avnum++)
2709 if (alview[avnum] != alignment)
2711 // duplicate in a view other than the one with input focus
2712 int avwidth = alview[avnum].getWidth() + 1;
2713 // this relies on sann being preserved after we
2714 // modify the sequence's annotation array for each duplication
2715 for (int a = 0; a < sann.length; a++)
2717 AlignmentAnnotation newann = new AlignmentAnnotation(
2719 sequences[i].addAlignmentAnnotation(newann);
2720 newann.padAnnotation(avwidth);
2721 alview[avnum].addAnnotation(newann); // annotation was
2722 // duplicated earlier
2723 // TODO JAL-1145 graphGroups are not updated for sequence
2724 // annotation added to several views. This may cause
2726 alview[avnum].setAnnotationIndex(newann, a);
2731 buildSortByAnnotationScoresMenu();
2733 viewport.notifyAlignment();
2734 if (alignPanels != null)
2736 for (AlignmentPanel ap : alignPanels)
2738 ap.validateAnnotationDimensions(false);
2743 alignPanel.validateAnnotationDimensions(false);
2749 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2751 String newtitle = new String("Copied sequences");
2753 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2755 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2756 af.viewport.setHiddenColumns(hc);
2759 // >>>This is a fix for the moment, until a better solution is
2761 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2762 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2763 .getFeatureRenderer());
2765 // TODO: maintain provenance of an alignment, rather than just make the
2766 // title a concatenation of operations.
2769 if (title.startsWith("Copied sequences"))
2775 newtitle = newtitle.concat("- from " + title);
2780 newtitle = new String("Pasted sequences");
2783 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2788 } catch (Exception ex)
2790 ex.printStackTrace();
2791 System.out.println("Exception whilst pasting: " + ex);
2792 // could be anything being pasted in here
2797 protected void expand_newalign(ActionEvent e)
2801 AlignmentI alignment = AlignmentUtils
2802 .expandContext(getViewport().getAlignment(), -1);
2803 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2805 String newtitle = new String("Flanking alignment");
2806 Desktop d = Desktop.getInstance();
2807 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2809 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2810 af.viewport.setHiddenColumns(hc);
2813 // >>>This is a fix for the moment, until a better solution is
2815 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2816 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2817 .getFeatureRenderer());
2819 // TODO: maintain provenance of an alignment, rather than just make the
2820 // title a concatenation of operations.
2822 if (title.startsWith("Copied sequences"))
2828 newtitle = newtitle.concat("- from " + title);
2832 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2834 } catch (Exception ex)
2836 ex.printStackTrace();
2837 System.out.println("Exception whilst pasting: " + ex);
2838 // could be anything being pasted in here
2839 } catch (OutOfMemoryError oom)
2841 new OOMWarning("Viewing flanking region of alignment", oom);
2846 * Action Cut (delete and copy) the selected region
2850 protected void cut_actionPerformed()
2852 copy_actionPerformed();
2853 delete_actionPerformed();
2857 * Performs menu option to Delete the currently selected region
2861 protected void delete_actionPerformed()
2864 SequenceGroup sg = viewport.getSelectionGroup();
2870 Runnable okAction = new Runnable()
2876 SequenceI[] cut = sg.getSequences()
2877 .toArray(new SequenceI[sg.getSize()]);
2879 addHistoryItem(new EditCommand(
2880 MessageManager.getString("label.cut_sequences"), Action.CUT,
2881 cut, sg.getStartRes(),
2882 sg.getEndRes() - sg.getStartRes() + 1,
2883 viewport.getAlignment()));
2885 viewport.setSelectionGroup(null);
2886 viewport.sendSelection();
2887 viewport.getAlignment().deleteGroup(sg);
2889 viewport.notifyAlignment();
2891 if (viewport.getAlignment().getHeight() < 1)
2895 AlignFrame.this.setClosed(true);
2896 } catch (Exception ex)
2906 * If the cut affects all sequences, prompt for confirmation
2908 boolean wholeHeight = sg.getSize() == viewport.getAlignment()
2910 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2911 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2912 if (wholeHeight && wholeWidth)
2914 JvOptionPane dialog = JvOptionPane
2915 .newOptionDialog(Desktop.getDesktopPane());
2916 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2917 Object[] options = new Object[] {
2918 MessageManager.getString("action.ok"),
2919 MessageManager.getString("action.cancel") };
2920 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2921 MessageManager.getString("label.delete_all"),
2922 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2923 options, options[0]);
2939 protected void deleteGroups_actionPerformed(ActionEvent e)
2941 if (avc.deleteGroups())
2943 updateAll(viewport.getSequenceSetId());
2947 private void updateAll(String id)
2951 // this will force a non-fast repaint of both the IdPanel and SeqPanel
2952 alignPanel.getIdPanel().getIdCanvas().setNoFastPaint();
2953 alignPanel.getSeqPanel().seqCanvas.setNoFastPaint();
2954 alignPanel.repaint();
2959 PaintRefresher.Refresh(this, id);
2960 alignPanel.paintAlignment(true, true);
2962 alignPanel.updateAnnotation();
2973 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2975 alignPanel.selectAllSequences();
2986 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2988 alignPanel.deselectAllSequences();
2999 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
3001 SequenceGroup sg = viewport.getSelectionGroup();
3005 alignPanel.selectAllSequences();
3010 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
3012 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
3014 // JAL-2034 - should delegate to
3015 // alignPanel to decide if overview needs
3018 alignPanel.paintAlignment(true, false);
3019 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
3020 viewport.sendSelection();
3024 public void invertColSel_actionPerformed(ActionEvent e)
3026 viewport.invertColumnSelection();
3027 alignPanel.paintAlignment(true, false);
3028 viewport.sendSelection();
3039 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
3041 trimAlignment(true);
3052 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
3054 trimAlignment(false);
3057 void trimAlignment(boolean trimLeft)
3059 ColumnSelection colSel = viewport.getColumnSelection();
3062 if (!colSel.isEmpty())
3066 column = colSel.getMin();
3070 column = colSel.getMax();
3074 if (viewport.getSelectionGroup() != null)
3076 seqs = viewport.getSelectionGroup()
3077 .getSequencesAsArray(viewport.getHiddenRepSequences());
3081 seqs = viewport.getAlignment().getSequencesArray();
3084 TrimRegionCommand trimRegion;
3087 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
3088 column, viewport.getAlignment());
3089 viewport.getRanges().setStartRes(0);
3093 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
3094 column, viewport.getAlignment());
3097 setStatus(MessageManager.formatMessage("label.removed_columns",
3099 { Integer.valueOf(trimRegion.getSize()).toString() }));
3101 addHistoryItem(trimRegion);
3103 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3105 if ((trimLeft && !sg.adjustForRemoveLeft(column))
3106 || (!trimLeft && !sg.adjustForRemoveRight(column)))
3108 viewport.getAlignment().deleteGroup(sg);
3112 viewport.notifyAlignment();
3125 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
3127 int start = 0, end = viewport.getAlignment().getWidth() - 1;
3130 if (viewport.getSelectionGroup() != null)
3132 seqs = viewport.getSelectionGroup()
3133 .getSequencesAsArray(viewport.getHiddenRepSequences());
3134 start = viewport.getSelectionGroup().getStartRes();
3135 end = viewport.getSelectionGroup().getEndRes();
3139 seqs = viewport.getAlignment().getSequencesArray();
3142 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
3143 "Remove Gapped Columns", seqs, start, end,
3144 viewport.getAlignment());
3146 addHistoryItem(removeGapCols);
3148 setStatus(MessageManager.formatMessage("label.removed_empty_columns",
3150 { Integer.valueOf(removeGapCols.getSize()).toString() }));
3152 // This is to maintain viewport position on first residue
3153 // of first sequence
3154 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3155 ViewportRanges ranges = viewport.getRanges();
3156 int startRes = seq.findPosition(ranges.getStartRes());
3157 // ShiftList shifts;
3158 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
3159 // edit.alColumnChanges=shifts.getInverse();
3160 // if (viewport.hasHiddenColumns)
3161 // viewport.getColumnSelection().compensateForEdits(shifts);
3162 ranges.setStartRes(seq.findIndex(startRes) - 1);
3163 viewport.notifyAlignment();
3176 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
3178 int start = 0, end = viewport.getAlignment().getWidth() - 1;
3181 if (viewport.getSelectionGroup() != null)
3183 seqs = viewport.getSelectionGroup()
3184 .getSequencesAsArray(viewport.getHiddenRepSequences());
3185 start = viewport.getSelectionGroup().getStartRes();
3186 end = viewport.getSelectionGroup().getEndRes();
3190 seqs = viewport.getAlignment().getSequencesArray();
3193 // This is to maintain viewport position on first residue
3194 // of first sequence
3195 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3196 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
3198 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
3199 viewport.getAlignment()));
3201 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
3202 viewport.notifyAlignment();
3214 public void padGapsMenuitem_actionPerformed(ActionEvent e)
3216 viewport.setPadGaps(padGapsMenuitem.isSelected());
3217 viewport.notifyAlignment();
3222 * Opens a Finder dialog
3228 public void findMenuItem_actionPerformed(ActionEvent e)
3230 new Finder(alignPanel, false, null);
3234 * Create a new view of the current alignment.
3238 public void newView_actionPerformed(ActionEvent e)
3240 newView(null, true);
3244 * Creates and shows a new view of the current alignment.
3247 * title of newly created view; if null, one will be generated
3248 * @param copyAnnotation
3249 * if true then duplicate all annnotation, groups and settings
3250 * @return new alignment panel, already displayed.
3253 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
3256 * Create a new AlignmentPanel (with its own, new Viewport)
3258 AlignmentPanel newap = new jalview.project.Jalview2XML()
3259 .copyAlignPanel(alignPanel);
3260 if (!copyAnnotation)
3263 * remove all groups and annotation except for the automatic stuff
3265 newap.av.getAlignment().deleteAllGroups();
3266 newap.av.getAlignment().deleteAllAnnotations(false);
3269 newap.av.setGatherViewsHere(false);
3271 if (viewport.getViewName() == null)
3273 viewport.setViewName(
3274 MessageManager.getString("label.view_name_original"));
3278 * Views share the same edits undo and redo stacks
3280 newap.av.setHistoryList(viewport.getHistoryList());
3281 newap.av.setRedoList(viewport.getRedoList());
3284 * copy any visualisation settings that are not saved in the project
3286 newap.av.setColourAppliesToAllGroups(
3287 viewport.getColourAppliesToAllGroups());
3290 * Views share the same mappings; need to deregister any new mappings
3291 * created by copyAlignPanel, and register the new reference to the shared
3294 newap.av.replaceMappings(viewport.getAlignment());
3297 * start up cDNA consensus (if applicable) now mappings are in place
3299 if (newap.av.initComplementConsensus())
3301 newap.refresh(true); // adjust layout of annotations
3304 newap.av.setViewName(getNewViewName(viewTitle));
3306 addAlignmentPanel(newap, true);
3307 newap.alignmentChanged();
3309 if (alignPanels.size() == 2)
3311 viewport.setGatherViewsHere(true);
3313 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
3318 * Make a new name for the view, ensuring it is unique within the current
3319 * sequenceSetId. (This used to be essential for Jalview Project archives, but
3320 * these now use viewId. Unique view names are still desirable for usability.)
3326 protected String getNewViewName(String viewTitle)
3328 int index = Desktop.getViewCount(viewport.getSequenceSetId());
3329 boolean addFirstIndex = false;
3330 if (viewTitle == null || viewTitle.trim().length() == 0)
3332 viewTitle = MessageManager.getString("action.view");
3333 addFirstIndex = true;
3337 index = 1;// we count from 1 if given a specific name
3339 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
3341 List<Component> comps = PaintRefresher.components
3342 .get(viewport.getSequenceSetId());
3344 List<String> existingNames = getExistingViewNames(comps);
3346 while (existingNames.contains(newViewName))
3348 newViewName = viewTitle + " " + (++index);
3354 * Returns a list of distinct view names found in the given list of
3355 * components. View names are held on the viewport of an AlignmentPanel.
3361 protected List<String> getExistingViewNames(List<Component> comps)
3363 List<String> existingNames = new ArrayList<>();
3364 for (Component comp : comps)
3366 if (comp instanceof AlignmentPanel)
3368 AlignmentPanel ap = (AlignmentPanel) comp;
3369 if (!existingNames.contains(ap.av.getViewName()))
3371 existingNames.add(ap.av.getViewName());
3375 return existingNames;
3379 * Explode tabbed views into separate windows.
3383 public void expandViews_actionPerformed(ActionEvent e)
3385 Desktop.explodeViews(this);
3389 * Gather views in separate windows back into a tabbed presentation.
3393 public void gatherViews_actionPerformed(ActionEvent e)
3395 Desktop.getInstance().gatherViews(this);
3406 public void font_actionPerformed(ActionEvent e)
3408 new FontChooser(alignPanel);
3419 protected void seqLimit_actionPerformed(ActionEvent e)
3421 viewport.setShowJVSuffix(seqLimits.isSelected());
3423 alignPanel.getIdPanel().getIdCanvas()
3424 .setPreferredSize(alignPanel.calculateIdWidth());
3425 alignPanel.paintAlignment(true, false);
3429 public void idRightAlign_actionPerformed(ActionEvent e)
3431 viewport.setRightAlignIds(idRightAlign.isSelected());
3432 alignPanel.paintAlignment(false, false);
3436 public void centreColumnLabels_actionPerformed(ActionEvent e)
3438 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3439 alignPanel.paintAlignment(false, false);
3445 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3449 protected void followHighlight_actionPerformed()
3452 * Set the 'follow' flag on the Viewport (and scroll to position if now
3455 final boolean state = this.followHighlightMenuItem.getState();
3456 viewport.setFollowHighlight(state);
3459 alignPanel.scrollToPosition(viewport.getSearchResults());
3471 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3473 viewport.setColourText(colourTextMenuItem.isSelected());
3474 alignPanel.paintAlignment(false, false);
3485 public void wrapMenuItem_actionPerformed(ActionEvent e)
3487 scaleAbove.setVisible(wrapMenuItem.isSelected());
3488 scaleLeft.setVisible(wrapMenuItem.isSelected());
3489 scaleRight.setVisible(wrapMenuItem.isSelected());
3490 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3491 alignPanel.updateLayout();
3495 public void showAllSeqs_actionPerformed(ActionEvent e)
3497 viewport.showAllHiddenSeqs();
3501 public void showAllColumns_actionPerformed(ActionEvent e)
3503 viewport.showAllHiddenColumns();
3504 alignPanel.paintAlignment(true, true);
3505 viewport.sendSelection();
3509 public void hideSelSequences_actionPerformed(ActionEvent e)
3511 viewport.hideAllSelectedSeqs();
3515 * called by key handler and the hide all/show all menu items
3521 protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3524 boolean hide = false;
3525 SequenceGroup sg = viewport.getSelectionGroup();
3526 if (!toggleSeqs && !toggleCols)
3528 // Hide everything by the current selection - this is a hack - we do the
3529 // invert and then hide
3530 // first check that there will be visible columns after the invert.
3531 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3532 && sg.getStartRes() <= sg.getEndRes()))
3534 // now invert the sequence set, if required - empty selection implies
3535 // that no hiding is required.
3538 invertSequenceMenuItem_actionPerformed(null);
3539 sg = viewport.getSelectionGroup();
3543 viewport.expandColSelection(sg, true);
3544 // finally invert the column selection and get the new sequence
3546 invertColSel_actionPerformed(null);
3553 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3555 hideSelSequences_actionPerformed(null);
3558 else if (!(toggleCols && viewport.hasSelectedColumns()))
3560 showAllSeqs_actionPerformed(null);
3566 if (viewport.hasSelectedColumns())
3568 hideSelColumns_actionPerformed(null);
3571 viewport.setSelectionGroup(sg);
3576 showAllColumns_actionPerformed(null);
3585 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3586 * event.ActionEvent)
3590 public void hideAllButSelection_actionPerformed(ActionEvent e)
3592 toggleHiddenRegions(false, false);
3593 viewport.sendSelection();
3600 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3605 public void hideAllSelection_actionPerformed(ActionEvent e)
3607 SequenceGroup sg = viewport.getSelectionGroup();
3608 viewport.expandColSelection(sg, false);
3609 viewport.hideAllSelectedSeqs();
3610 viewport.hideSelectedColumns();
3611 alignPanel.updateLayout();
3612 alignPanel.paintAlignment(true, true);
3613 viewport.sendSelection();
3620 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3625 public void showAllhidden_actionPerformed(ActionEvent e)
3627 viewport.showAllHiddenColumns();
3628 viewport.showAllHiddenSeqs();
3629 alignPanel.paintAlignment(true, true);
3630 viewport.sendSelection();
3634 public void hideSelColumns_actionPerformed(ActionEvent e)
3636 viewport.hideSelectedColumns();
3637 alignPanel.updateLayout();
3638 alignPanel.paintAlignment(true, true);
3639 viewport.sendSelection();
3643 public void hiddenMarkers_actionPerformed(ActionEvent e)
3645 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3657 protected void scaleAbove_actionPerformed(ActionEvent e)
3659 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3660 alignPanel.updateLayout();
3661 alignPanel.paintAlignment(true, false);
3672 protected void scaleLeft_actionPerformed(ActionEvent e)
3674 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3675 alignPanel.updateLayout();
3676 alignPanel.paintAlignment(true, false);
3687 protected void scaleRight_actionPerformed(ActionEvent e)
3689 viewport.setScaleRightWrapped(scaleRight.isSelected());
3690 alignPanel.updateLayout();
3691 alignPanel.paintAlignment(true, false);
3702 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3704 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3705 alignPanel.paintAlignment(false, false);
3716 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3718 viewport.setShowText(viewTextMenuItem.isSelected());
3719 alignPanel.paintAlignment(false, false);
3730 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3732 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3733 alignPanel.paintAlignment(false, false);
3736 public FeatureSettings featureSettings;
3739 public FeatureSettingsControllerI getFeatureSettingsUI()
3741 return featureSettings;
3745 public void featureSettings_actionPerformed(ActionEvent e)
3747 showFeatureSettingsUI();
3751 public FeatureSettingsControllerI showFeatureSettingsUI()
3753 if (featureSettings != null)
3755 featureSettings.closeOldSettings();
3756 featureSettings = null;
3758 if (!showSeqFeatures.isSelected())
3760 // make sure features are actually displayed
3761 showSeqFeatures.setSelected(true);
3762 showSeqFeatures_actionPerformed(null);
3764 featureSettings = new FeatureSettings(this);
3765 return featureSettings;
3769 * Set or clear 'Show Sequence Features'
3776 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3778 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3779 alignPanel.paintAlignment(true, true);
3783 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3784 * the annotations panel as a whole.
3786 * The options to show/hide all annotations should be enabled when the panel
3787 * is shown, and disabled when the panel is hidden.
3793 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3795 final boolean setVisible = annotationPanelMenuItem.isSelected();
3796 viewport.setShowAnnotation(setVisible);
3797 syncAnnotationMenuItems(setVisible);
3798 alignPanel.updateLayout();
3800 SwingUtilities.invokeLater(new Runnable() {
3805 alignPanel.updateScrollBarsFromRanges();
3811 private void syncAnnotationMenuItems(boolean setVisible)
3813 showAllSeqAnnotations.setEnabled(setVisible);
3814 hideAllSeqAnnotations.setEnabled(setVisible);
3815 showAllAlAnnotations.setEnabled(setVisible);
3816 hideAllAlAnnotations.setEnabled(setVisible);
3820 public void alignmentProperties()
3823 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3826 String content = MessageManager.formatMessage("label.html_content",
3828 { contents.toString() });
3831 if (Platform.isJS())
3833 JLabel textLabel = new JLabel();
3834 textLabel.setText(content);
3835 textLabel.setBackground(Color.WHITE);
3837 pane = new JPanel(new BorderLayout());
3838 ((JPanel) pane).setOpaque(true);
3839 pane.setBackground(Color.WHITE);
3840 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3849 JEditorPane editPane = new JEditorPane("text/html", "");
3850 editPane.setEditable(false);
3851 editPane.setText(content);
3855 JInternalFrame frame = new JInternalFrame();
3857 frame.getContentPane().add(new JScrollPane(pane));
3859 Desktop.addInternalFrame(frame, MessageManager
3860 .formatMessage("label.alignment_properties", new Object[]
3861 { getTitle() }), 500, 400);
3872 public void overviewMenuItem_actionPerformed(ActionEvent e)
3874 if (alignPanel.overviewPanel != null)
3879 JInternalFrame frame = new JInternalFrame();
3881 // BH 2019.07.26 we allow for an embedded
3882 // undecorated overview with defined size
3883 frame.setName(Platform.getAppID("overview"));
3885 Dimension dim = Platform.getDimIfEmbedded(frame, -1, -1);
3886 if (dim != null && dim.width == 0)
3888 dim = null; // hidden, not embedded
3890 OverviewPanel overview = new OverviewPanel(alignPanel, dim);
3892 frame.setContentPane(overview);
3895 dim = new Dimension();
3896 // was frame.getSize(), but that is 0,0 at this point;
3900 // we are imbedding, and so we have an undecorated frame
3901 // and we can set the the frame dimensions accordingly.
3903 // allowing for unresizable option using, style="resize:none"
3904 boolean resizable = (Platform.getEmbeddedAttribute(frame,
3905 "resize") != "none");
3906 Desktop.addInternalFrame(frame, MessageManager
3907 .formatMessage("label.overview_params", new Object[]
3908 { this.getTitle() }), Desktop.FRAME_MAKE_VISIBLE, dim.width,
3909 dim.height, resizable, Desktop.FRAME_ALLOW_ANY_SIZE);
3911 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3912 frame.addInternalFrameListener(
3913 new javax.swing.event.InternalFrameAdapter()
3917 public void internalFrameClosed(
3918 javax.swing.event.InternalFrameEvent evt)
3921 alignPanel.setOverviewPanel(null);
3924 if (getKeyListeners().length > 0)
3926 frame.addKeyListener(getKeyListeners()[0]);
3929 alignPanel.setOverviewPanel(overview);
3933 public void textColour_actionPerformed()
3935 new TextColourChooser().chooseColour(alignPanel, null);
3939 * public void covariationColour_actionPerformed() {
3941 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3946 public void annotationColour_actionPerformed()
3948 new AnnotationColourChooser(viewport, alignPanel);
3952 public void annotationColumn_actionPerformed(ActionEvent e)
3954 new AnnotationColumnChooser(viewport, alignPanel);
3958 * Action on the user checking or unchecking the option to apply the selected
3959 * colour scheme to all groups. If unchecked, groups may have their own
3960 * independent colour schemes.
3966 public void applyToAllGroups_actionPerformed(boolean selected)
3968 viewport.setColourAppliesToAllGroups(selected);
3972 * Action on user selecting a colour from the colour menu
3975 * the name (not the menu item label!) of the colour scheme
3979 public void changeColour_actionPerformed(String name)
3982 * 'User Defined' opens a panel to configure or load a
3983 * user-defined colour scheme
3985 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3987 new UserDefinedColours(alignPanel);
3992 * otherwise set the chosen colour scheme (or null for 'None')
3994 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3995 viewport, viewport.getAlignment(),
3996 viewport.getHiddenRepSequences());
4001 * Actions on setting or changing the alignment colour scheme
4007 public void changeColour(ColourSchemeI cs)
4009 // TODO: pull up to controller method
4010 ColourMenuHelper.setColourSelected(colourMenu, cs);
4012 viewport.setGlobalColourScheme(cs);
4014 alignPanel.paintAlignment(true, true);
4018 * Show the PID threshold slider panel
4022 protected void modifyPID_actionPerformed()
4024 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
4025 alignPanel.getViewName());
4026 SliderPanel.showPIDSlider();
4030 * Show the Conservation slider panel
4034 protected void modifyConservation_actionPerformed()
4036 SliderPanel.setConservationSlider(alignPanel,
4037 viewport.getResidueShading(), alignPanel.getViewName());
4038 SliderPanel.showConservationSlider();
4042 * Action on selecting or deselecting (Colour) By Conservation
4046 public void conservationMenuItem_actionPerformed(boolean selected)
4048 modifyConservation.setEnabled(selected);
4049 viewport.setConservationSelected(selected);
4050 viewport.getResidueShading().setConservationApplied(selected);
4052 changeColour(viewport.getGlobalColourScheme());
4055 modifyConservation_actionPerformed();
4059 SliderPanel.hideConservationSlider();
4064 * Action on selecting or deselecting (Colour) Above PID Threshold
4068 public void abovePIDThreshold_actionPerformed(boolean selected)
4070 modifyPID.setEnabled(selected);
4071 viewport.setAbovePIDThreshold(selected);
4074 viewport.getResidueShading().setThreshold(0,
4075 viewport.isIgnoreGapsConsensus());
4078 changeColour(viewport.getGlobalColourScheme());
4081 modifyPID_actionPerformed();
4085 SliderPanel.hidePIDSlider();
4097 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
4099 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4100 AlignmentSorter.sortByPID(viewport.getAlignment(),
4101 viewport.getAlignment().getSequenceAt(0));
4102 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
4103 viewport.getAlignment()));
4104 alignPanel.paintAlignment(true, false);
4115 public void sortIDMenuItem_actionPerformed(ActionEvent e)
4117 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4118 AlignmentSorter.sortByID(viewport.getAlignment());
4120 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
4121 alignPanel.paintAlignment(true, false);
4132 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
4134 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4135 AlignmentSorter.sortByLength(viewport.getAlignment());
4136 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
4137 viewport.getAlignment()));
4138 alignPanel.paintAlignment(true, false);
4149 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
4151 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4152 AlignmentSorter.sortByGroup(viewport.getAlignment());
4153 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4154 viewport.getAlignment()));
4156 alignPanel.paintAlignment(true, false);
4160 public void sortEValueMenuItem_actionPerformed(ActionEvent e)
4162 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4163 AlignmentSorter.sortByEValue(viewport.getAlignment());
4164 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4165 viewport.getAlignment()));
4166 alignPanel.paintAlignment(true, false);
4171 public void sortBitScoreMenuItem_actionPerformed(ActionEvent e)
4173 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4174 AlignmentSorter.sortByBitScore(viewport.getAlignment());
4175 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4176 viewport.getAlignment()));
4177 alignPanel.paintAlignment(true, false);
4189 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
4191 new RedundancyPanel(alignPanel, this);
4202 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
4204 if ((viewport.getSelectionGroup() == null)
4205 || (viewport.getSelectionGroup().getSize() < 2))
4207 JvOptionPane.showInternalMessageDialog(this,
4208 MessageManager.getString(
4209 "label.you_must_select_least_two_sequences"),
4210 MessageManager.getString("label.invalid_selection"),
4211 JvOptionPane.WARNING_MESSAGE);
4215 JInternalFrame frame = new JInternalFrame();
4216 frame.setContentPane(new PairwiseAlignPanel(viewport));
4217 Desktop.addInternalFrame(frame,
4218 MessageManager.getString("action.pairwise_alignment"), 600,
4224 public void autoCalculate_actionPerformed(ActionEvent e)
4226 viewport.setAutoCalculateConsensusAndConservation(
4227 autoCalculate.isSelected());
4228 if (viewport.getAutoCalculateConsensusAndConservation())
4230 viewport.notifyAlignment();
4235 public void sortByTreeOption_actionPerformed(ActionEvent e)
4237 viewport.sortByTree = sortByTree.isSelected();
4241 protected void listenToViewSelections_actionPerformed(ActionEvent e)
4243 viewport.followSelection = listenToViewSelections.isSelected();
4247 * Constructs a tree panel and adds it to the desktop
4250 * tree type (NJ or AV)
4252 * name of score model used to compute the tree
4254 * parameters for the distance or similarity calculation
4257 void newTreePanel(String type, String modelName,
4258 SimilarityParamsI options)
4260 String frameTitle = "";
4263 boolean onSelection = false;
4264 if (viewport.getSelectionGroup() != null
4265 && viewport.getSelectionGroup().getSize() > 0)
4267 SequenceGroup sg = viewport.getSelectionGroup();
4269 /* Decide if the selection is a column region */
4270 for (SequenceI _s : sg.getSequences())
4272 if (_s.getLength() < sg.getEndRes())
4274 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4275 MessageManager.getString(
4276 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
4277 MessageManager.getString(
4278 "label.sequences_selection_not_aligned"),
4279 JvOptionPane.WARNING_MESSAGE);
4288 if (viewport.getAlignment().getHeight() < 2)
4294 tp = new TreePanel(alignPanel, type, modelName, options);
4295 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
4297 frameTitle += " from ";
4299 if (viewport.getViewName() != null)
4301 frameTitle += viewport.getViewName() + " of ";
4304 frameTitle += this.title;
4306 Dimension dim = Platform.getDimIfEmbedded(tp, 600, 500);
4307 Desktop.addInternalFrame(tp, frameTitle, dim.width, dim.height);
4319 public void addSortByOrderMenuItem(String title,
4320 final AlignmentOrder order)
4322 final JMenuItem item = new JMenuItem(MessageManager
4323 .formatMessage("action.by_title_param", new Object[]
4326 item.addActionListener(new java.awt.event.ActionListener()
4330 public void actionPerformed(ActionEvent e)
4332 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4334 // TODO: JBPNote - have to map order entries to curent SequenceI
4336 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4338 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
4339 viewport.getAlignment()));
4341 alignPanel.paintAlignment(true, false);
4347 * Add a new sort by annotation score menu item
4350 * the menu to add the option to
4352 * the label used to retrieve scores for each sequence on the
4356 public void addSortByAnnotScoreMenuItem(JMenu sort,
4357 final String scoreLabel)
4359 final JMenuItem item = new JMenuItem(scoreLabel);
4361 item.addActionListener(new java.awt.event.ActionListener()
4365 public void actionPerformed(ActionEvent e)
4367 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4368 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4369 viewport.getAlignment());// ,viewport.getSelectionGroup());
4370 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4371 viewport.getAlignment()));
4372 alignPanel.paintAlignment(true, false);
4378 * last hash for alignment's annotation array - used to minimise cost of
4381 protected int _annotationScoreVectorHash;
4384 * search the alignment and rebuild the sort by annotation score submenu the
4385 * last alignment annotation vector hash is stored to minimize cost of
4386 * rebuilding in subsequence calls.
4391 public void buildSortByAnnotationScoresMenu()
4393 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4398 if (viewport.getAlignment().getAlignmentAnnotation()
4399 .hashCode() == _annotationScoreVectorHash)
4404 sortByAnnotScore.removeAll();
4405 Set<String> scoreSorts = new HashSet<>();
4406 for (SequenceI sqa : viewport.getAlignment().getSequences())
4408 AlignmentAnnotation[] anns = sqa.getAnnotation();
4409 for (int i = 0; anns != null && i < anns.length; i++)
4411 AlignmentAnnotation aa = anns[i];
4412 if (aa != null && aa.hasScore() && aa.sequenceRef != null)
4414 scoreSorts.add(aa.label);
4418 for (String label : scoreSorts)
4420 addSortByAnnotScoreMenuItem(sortByAnnotScore, label);
4422 sortByAnnotScore.setVisible(!scoreSorts.isEmpty());
4424 _annotationScoreVectorHash = viewport.getAlignment()
4425 .getAlignmentAnnotation().hashCode();
4429 * Enable (or, if desired, make visible) the By Tree
4430 * submenu only if it has at least one element (or will have).
4434 protected void enableSortMenuOptions()
4436 List<TreePanel> treePanels = getTreePanels();
4437 sortByTreeMenu.setEnabled(!treePanels.isEmpty());
4441 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4442 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4443 * call. Listeners are added to remove the menu item when the treePanel is
4444 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4449 public void buildTreeSortMenu()
4451 sortByTreeMenu.removeAll();
4453 List<TreePanel> treePanels = getTreePanels();
4455 for (final TreePanel tp : treePanels)
4457 final JMenuItem item = new JMenuItem(tp.getTitle());
4458 item.addActionListener(new java.awt.event.ActionListener()
4462 public void actionPerformed(ActionEvent e)
4464 tp.sortByTree_actionPerformed();
4465 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4470 sortByTreeMenu.add(item);
4474 private List<TreePanel> getTreePanels()
4476 List<Component> comps = PaintRefresher.components
4477 .get(viewport.getSequenceSetId());
4478 List<TreePanel> treePanels = new ArrayList<>();
4479 for (Component comp : comps)
4481 if (comp instanceof TreePanel)
4483 treePanels.add((TreePanel) comp);
4489 public boolean sortBy(AlignmentOrder alorder, String undoname)
4491 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4492 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4493 if (undoname != null)
4495 addHistoryItem(new OrderCommand(undoname, oldOrder,
4496 viewport.getAlignment()));
4498 alignPanel.paintAlignment(true, false);
4503 * Work out whether the whole set of sequences or just the selected set will
4504 * be submitted for multiple alignment.
4508 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4510 // Now, check we have enough sequences
4511 AlignmentView msa = null;
4513 if ((viewport.getSelectionGroup() != null)
4514 && (viewport.getSelectionGroup().getSize() > 1))
4516 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4517 // some common interface!
4519 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4520 * SequenceI[sz = seqs.getSize(false)];
4522 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4523 * seqs.getSequenceAt(i); }
4525 msa = viewport.getAlignmentView(true);
4527 else if (viewport.getSelectionGroup() != null
4528 && viewport.getSelectionGroup().getSize() == 1)
4530 int option = JvOptionPane.showConfirmDialog(this,
4531 MessageManager.getString("warn.oneseq_msainput_selection"),
4532 MessageManager.getString("label.invalid_selection"),
4533 JvOptionPane.OK_CANCEL_OPTION);
4534 if (option == JvOptionPane.OK_OPTION)
4536 msa = viewport.getAlignmentView(false);
4541 msa = viewport.getAlignmentView(false);
4547 * Decides what is submitted to a secondary structure prediction service: the
4548 * first sequence in the alignment, or in the current selection, or, if the
4549 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4550 * region or the whole alignment. (where the first sequence in the set is the
4551 * one that the prediction will be for).
4554 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4556 AlignmentView seqs = null;
4558 if ((viewport.getSelectionGroup() != null)
4559 && (viewport.getSelectionGroup().getSize() > 0))
4561 seqs = viewport.getAlignmentView(true);
4565 seqs = viewport.getAlignmentView(false);
4567 // limit sequences - JBPNote in future - could spawn multiple prediction
4569 // TODO: viewport.getAlignment().isAligned is a global state - the local
4570 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4571 if (!viewport.getAlignment().isAligned(false))
4573 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4574 // TODO: if seqs.getSequences().length>1 then should really have warned
4589 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4591 // Pick the tree file
4592 JalviewFileChooser chooser = new JalviewFileChooser(
4593 Cache.getProperty("LAST_DIRECTORY"));
4594 chooser.setFileView(new JalviewFileView());
4595 chooser.setDialogTitle(
4596 MessageManager.getString("label.select_newick_like_tree_file"));
4597 chooser.setToolTipText(
4598 MessageManager.getString("label.load_tree_file"));
4600 chooser.setResponseHandler(0, new Runnable()
4606 String filePath = chooser.getSelectedFile().getPath();
4607 Cache.setProperty("LAST_DIRECTORY", filePath);
4608 NewickFile fin = null;
4611 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4612 DataSourceType.FILE));
4613 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4614 } catch (Exception ex)
4616 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4619 .getString("label.problem_reading_tree_file"),
4620 JvOptionPane.WARNING_MESSAGE);
4621 ex.printStackTrace();
4623 if (fin != null && fin.hasWarningMessage())
4625 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4626 fin.getWarningMessage(),
4627 MessageManager.getString(
4628 "label.possible_problem_with_tree_file"),
4629 JvOptionPane.WARNING_MESSAGE);
4633 chooser.showOpenDialog(this);
4636 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4638 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4641 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4642 int h, int x, int y)
4644 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4648 * Add a treeviewer for the tree extracted from a Newick file object to the
4649 * current alignment view
4656 * Associated alignment input data (or null)
4665 * @return TreePanel handle
4668 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4669 AlignmentView input, int w, int h, int x, int y)
4671 TreePanel tp = null;
4677 if (nf.getTree() != null)
4679 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4680 Dimension dim = Platform.getDimIfEmbedded(tp, -1, -1);
4683 dim = new Dimension(w, h);
4687 // no offset, either
4690 tp.setSize(dim.width, dim.height);
4694 tp.setLocation(x, y);
4697 Desktop.addInternalFrame(tp, treeTitle, dim.width, dim.height);
4699 } catch (Exception ex)
4701 ex.printStackTrace();
4707 private WebServicesMenuManager slivkaMenu = new WebServicesMenuManager("slivka", this);
4709 * Schedule the web services menu rebuild to the event dispatch thread.
4711 public void buildWebServicesMenu()
4713 SwingUtilities.invokeLater(() -> {
4714 Console.info("Rebuiling WS menu");
4715 webService.removeAll();
4716 if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
4718 Console.info("Building web service menu for slivka");
4719 SlivkaWSDiscoverer discoverer = SlivkaWSDiscoverer.getInstance();
4720 slivkaMenu.setServices(discoverer);
4721 slivkaMenu.setInProgress(discoverer.isRunning());
4722 slivkaMenu.setNoServices(discoverer.isDone() && !discoverer.hasServices());
4723 webService.add(slivkaMenu.getMenu());
4725 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4727 WSDiscovererI jws2servs = Jws2Discoverer.getInstance();
4728 JMenu submenu = new JMenu("JABAWS");
4729 buildLegacyWebServicesMenu(submenu);
4730 buildWebServicesMenu(jws2servs, submenu);
4731 webService.add(submenu);
4733 build_urlServiceMenu(webService);
4734 build_fetchdbmenu(webService);
4738 private void buildLegacyWebServicesMenu(JMenu menu)
4740 JMenu secstrmenu = new JMenu("Secondary Structure Prediction");
4741 if (Discoverer.getServices() != null && Discoverer.getServices().size() > 0)
4743 var secstrpred = Discoverer.getServices().get("SecStrPred");
4744 if (secstrpred != null)
4746 for (ext.vamsas.ServiceHandle sh : secstrpred)
4748 var menuProvider = Discoverer.getServiceClient(sh);
4749 menuProvider.attachWSMenuEntry(secstrmenu, this);
4753 menu.add(secstrmenu);
4757 * Constructs the web services menu for the given discoverer under the
4758 * specified menu. This method must be called on the EDT
4761 * the discoverer used to build the menu
4763 * parent component which the elements will be attached to
4765 private void buildWebServicesMenu(WSDiscovererI discoverer, JMenu menu)
4767 if (discoverer.hasServices())
4769 PreferredServiceRegistry.getRegistry().populateWSMenuEntry(
4770 discoverer.getServices(), sv -> buildWebServicesMenu(), menu,
4773 if (discoverer.isRunning())
4775 JMenuItem item = new JMenuItem("Service discovery in progress.");
4776 item.setEnabled(false);
4779 else if (!discoverer.hasServices())
4781 JMenuItem item = new JMenuItem("No services available.");
4782 item.setEnabled(false);
4788 * construct any groupURL type service menu entries.
4793 protected void build_urlServiceMenu(JMenu webService)
4795 // TODO: remove this code when 2.7 is released
4796 // DEBUG - alignmentView
4798 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4799 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4801 * public void actionPerformed(ActionEvent e) {
4802 * jalview.datamodel.AlignmentView
4803 * .testSelectionViews(af.viewport.getAlignment(),
4804 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4806 * }); webService.add(testAlView);
4808 // TODO: refactor to RestClient discoverer and merge menu entries for
4809 // rest-style services with other types of analysis/calculation service
4810 // SHmmr test client - still being implemented.
4811 // DEBUG - alignmentView
4813 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4816 client.attachWSMenuEntry(
4817 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4823 * Searches the alignment sequences for xRefs and builds the Show
4824 * Cross-References menu (formerly called Show Products), with database
4825 * sources for which cross-references are found (protein sources for a
4826 * nucleotide alignment and vice versa)
4828 * @return true if Show Cross-references menu should be enabled
4831 public boolean canShowProducts()
4833 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4834 AlignmentI dataset = viewport.getAlignment().getDataset();
4836 showProducts.removeAll();
4837 final boolean dna = viewport.getAlignment().isNucleotide();
4839 if (seqs == null || seqs.length == 0)
4841 // nothing to see here.
4845 boolean showp = false;
4848 List<String> ptypes = new CrossRef(seqs, dataset)
4849 .findXrefSourcesForSequences(dna);
4851 for (final String source : ptypes)
4854 final AlignFrame af = this;
4855 JMenuItem xtype = new JMenuItem(source);
4856 xtype.addActionListener(new ActionListener()
4860 public void actionPerformed(ActionEvent e)
4862 showProductsFor(af.viewport.getSequenceSelection(), dna,
4866 showProducts.add(xtype);
4868 showProducts.setVisible(showp);
4869 showProducts.setEnabled(showp);
4870 } catch (Exception e)
4873 "canShowProducts threw an exception - please report to help@jalview.org",
4881 * Finds and displays cross-references for the selected sequences (protein
4882 * products for nucleotide sequences, dna coding sequences for peptides).
4885 * the sequences to show cross-references for
4887 * true if from a nucleotide alignment (so showing proteins)
4889 * the database to show cross-references for
4892 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4893 final String source)
4895 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4900 * Construct and display a new frame containing the translation of this
4901 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4905 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4907 AlignmentI al = null;
4910 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4912 al = dna.translateCdna(codeTable);
4913 } catch (Exception ex)
4915 Console.error("Exception during translation. Please report this !",
4917 final String msg = MessageManager.getString(
4918 "label.error_when_translating_sequences_submit_bug_report");
4919 final String errorTitle = MessageManager
4920 .getString("label.implementation_error")
4921 + MessageManager.getString("label.translation_failed");
4922 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4923 errorTitle, JvOptionPane.ERROR_MESSAGE);
4926 if (al == null || al.getHeight() == 0)
4928 final String msg = MessageManager.getString(
4929 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4930 final String errorTitle = MessageManager
4931 .getString("label.translation_failed");
4932 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4933 errorTitle, JvOptionPane.WARNING_MESSAGE);
4937 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4938 af.setFileFormat(this.currentFileFormat);
4939 final String newTitle = MessageManager
4940 .formatMessage("label.translation_of_params", new Object[]
4941 { this.getTitle(), codeTable.getId() });
4942 af.setTitle(newTitle);
4943 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4945 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4946 AlignViewport.openSplitFrame(this, af, new Alignment(seqs));
4950 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4957 * Set the file format
4962 public void setFileFormat(FileFormatI format)
4964 this.currentFileFormat = format;
4968 * Try to load a features file onto the alignment.
4971 * contents or path to retrieve file or a File object
4973 * access mode of file (see jalview.io.AlignFile)
4974 * @return true if features file was parsed correctly.
4977 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4980 return avc.parseFeaturesFile(file, sourceType,
4981 Cache.getDefault(Preferences.RELAXEDSEQIDMATCHING, false));
4986 public void refreshFeatureUI(boolean enableIfNecessary)
4988 // note - currently this is only still here rather than in the controller
4989 // because of the featureSettings hard reference that is yet to be
4991 if (enableIfNecessary)
4993 viewport.setShowSequenceFeatures(true);
4994 showSeqFeatures.setSelected(true);
5000 public void dragEnter(DropTargetDragEvent evt)
5005 public void dragExit(DropTargetEvent evt)
5010 public void dragOver(DropTargetDragEvent evt)
5015 public void dropActionChanged(DropTargetDragEvent evt)
5020 public void drop(DropTargetDropEvent evt)
5022 // JAL-1552 - acceptDrop required before getTransferable call for
5023 // Java's Transferable for native dnd
5024 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
5025 Transferable t = evt.getTransferable();
5027 final List<Object> files = new ArrayList<>();
5028 List<DataSourceType> protocols = new ArrayList<>();
5032 Desktop.transferFromDropTarget(files, protocols, evt, t);
5033 if (files.size() > 0)
5035 new Thread(new Runnable()
5041 loadDroppedFiles(files, protocols, evt, t);
5045 } catch (Exception e)
5047 e.printStackTrace();
5051 protected void loadDroppedFiles(List<Object> files,
5052 List<DataSourceType> protocols, DropTargetDropEvent evt,
5057 // check to see if any of these files have names matching sequences
5060 SequenceIdMatcher idm = new SequenceIdMatcher(
5061 viewport.getAlignment().getSequencesArray());
5063 * Object[] { String,SequenceI}
5065 ArrayList<Object[]> filesmatched = new ArrayList<>();
5066 ArrayList<Object> filesnotmatched = new ArrayList<>();
5067 for (int i = 0; i < files.size(); i++)
5070 Object fileObj = files.get(i);
5071 String fileName = fileObj.toString();
5073 DataSourceType protocol = (fileObj instanceof File
5074 ? DataSourceType.FILE
5075 : FormatAdapter.checkProtocol(fileName));
5076 if (protocol == DataSourceType.FILE)
5079 if (fileObj instanceof File)
5081 file = (File) fileObj;
5082 Platform.cacheFileData(file);
5086 file = new File(fileName);
5088 pdbfn = file.getName();
5090 else if (protocol == DataSourceType.URL)
5092 URL url = new URL(fileName);
5093 pdbfn = url.getFile();
5095 if (pdbfn.length() > 0)
5097 // attempt to find a match in the alignment
5098 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5099 int l = 0, c = pdbfn.indexOf(".");
5100 while (mtch == null && c != -1)
5105 } while ((c = pdbfn.indexOf(".", l)) > l);
5108 pdbfn = pdbfn.substring(0, l);
5110 mtch = idm.findAllIdMatches(pdbfn);
5117 type = new IdentifyFile().identify(fileObj, protocol);
5118 } catch (Exception ex)
5122 if (type != null && type.isStructureFile())
5124 filesmatched.add(new Object[] { fileObj, protocol, mtch });
5128 // File wasn't named like one of the sequences or wasn't a PDB
5130 filesnotmatched.add(fileObj);
5134 if (filesmatched.size() > 0)
5136 boolean autoAssociate = Cache
5137 .getDefault(Preferences.AUTOASSOCIATE_PDBANDSEQS, false);
5140 String msg = MessageManager.formatMessage(
5141 "label.automatically_associate_structure_files_with_sequences_same_name",
5143 { Integer.valueOf(filesmatched.size()).toString() });
5144 String ttl = MessageManager.getString(
5145 "label.automatically_associate_structure_files_by_name");
5146 int choice = JvOptionPane.showConfirmDialog(this, msg, ttl,
5147 JvOptionPane.YES_NO_OPTION);
5148 autoAssociate = choice == JvOptionPane.YES_OPTION;
5152 for (Object[] fm : filesmatched)
5154 // try and associate
5155 // TODO: may want to set a standard ID naming formalism for
5156 // associating PDB files which have no IDs.
5157 for (SequenceI toassoc : (SequenceI[]) fm[2])
5159 PDBEntry pe = AssociatePdbFileWithSeq.associatePdbWithSeq(
5160 fm[0].toString(), (DataSourceType) fm[1], toassoc,
5164 System.err.println("Associated file : " + (fm[0].toString())
5165 + " with " + toassoc.getDisplayId(true));
5169 // TODO: do we need to update overview ? only if features are
5171 alignPanel.paintAlignment(true, false);
5177 * add declined structures as sequences
5179 for (Object[] o : filesmatched)
5181 filesnotmatched.add(o[0]);
5185 if (filesnotmatched.size() > 0)
5187 if (assocfiles > 0 && (Cache
5188 .getDefault("AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
5189 || JvOptionPane.showConfirmDialog(this,
5190 "<html>" + MessageManager.formatMessage(
5191 "label.ignore_unmatched_dropped_files_info",
5193 { Integer.valueOf(filesnotmatched.size())
5196 MessageManager.getString(
5197 "label.ignore_unmatched_dropped_files"),
5198 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
5202 for (Object fn : filesnotmatched)
5204 loadJalviewDataFile(fn, null, null, null);
5208 } catch (Exception ex)
5210 ex.printStackTrace();
5215 * Attempt to load a "dropped" file or URL string, by testing in turn for
5217 * <li>an Annotation file</li>
5218 * <li>a JNet file</li>
5219 * <li>a features file</li>
5220 * <li>else try to interpret as an alignment file</li>
5224 * either a filename or a URL string.
5225 * @throws InterruptedException
5226 * @throws IOException
5229 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
5230 FileFormatI format, SequenceI assocSeq)
5232 // BH 2018 was String file
5235 if (sourceType == null)
5237 sourceType = FormatAdapter.checkProtocol(file);
5239 // if the file isn't identified, or not positively identified as some
5240 // other filetype (PFAM is default unidentified alignment file type) then
5241 // try to parse as annotation.
5242 boolean isAnnotation = (format == null
5243 || FileFormat.Pfam.equals(format))
5244 ? new AnnotationFile().annotateAlignmentView(viewport,
5250 // first see if its a T-COFFEE score file
5251 TCoffeeScoreFile tcf = null;
5254 tcf = new TCoffeeScoreFile(file, sourceType);
5257 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5261 new TCoffeeColourScheme(viewport.getAlignment()));
5262 isAnnotation = true;
5263 setStatus(MessageManager.getString(
5264 "label.successfully_pasted_tcoffee_scores_to_alignment"));
5268 // some problem - if no warning its probable that the ID matching
5269 // process didn't work
5270 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
5271 tcf.getWarningMessage() == null
5272 ? MessageManager.getString(
5273 "label.check_file_matches_sequence_ids_alignment")
5274 : tcf.getWarningMessage(),
5275 MessageManager.getString(
5276 "label.problem_reading_tcoffee_score_file"),
5277 JvOptionPane.WARNING_MESSAGE);
5284 } catch (Exception x)
5287 "Exception when processing data source as T-COFFEE score file",
5293 // try to see if its a JNet 'concise' style annotation file *before*
5295 // try to parse it as a features file
5298 format = new IdentifyFile().identify(file, sourceType);
5300 if (FileFormat.ScoreMatrix == format)
5302 ScoreMatrixFile sm = new ScoreMatrixFile(
5303 new FileParse(file, sourceType));
5305 // todo: i18n this message
5306 setStatus(MessageManager.formatMessage(
5307 "label.successfully_loaded_matrix",
5308 sm.getMatrixName()));
5310 else if (FileFormat.Jnet.equals(format))
5312 JPredFile predictions = new JPredFile(file, sourceType);
5313 new JnetAnnotationMaker();
5314 JnetAnnotationMaker.add_annotation(predictions,
5315 viewport.getAlignment(), 0, false);
5316 viewport.getAlignment().setupJPredAlignment();
5317 isAnnotation = true;
5319 // else if (IdentifyFile.FeaturesFile.equals(format))
5320 else if (FileFormat.Features.equals(format))
5322 if (parseFeaturesFile(file, sourceType))
5324 SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
5325 if (splitFrame != null)
5327 splitFrame.repaint();
5331 alignPanel.paintAlignment(true, true);
5337 new FileLoader().LoadFile(viewport, file, sourceType, format);
5343 updateForAnnotations();
5345 } catch (Exception ex)
5347 ex.printStackTrace();
5348 } catch (OutOfMemoryError oom)
5353 } catch (Exception x)
5358 + (sourceType != null
5359 ? (sourceType == DataSourceType.PASTE
5361 : "using " + sourceType + " from "
5365 ? "(parsing as '" + format + "' file)"
5367 oom, Desktop.getDesktopPane());
5372 * Do all updates necessary after an annotation file such as jnet. Also called
5373 * from Jalview.loadAppletParams for "annotations", "jnetFile"
5376 public void updateForAnnotations()
5378 alignPanel.adjustAnnotationHeight();
5379 viewport.updateSequenceIdColours();
5380 buildSortByAnnotationScoresMenu();
5381 alignPanel.paintAlignment(true, true);
5385 * Change the display state for the given feature groups -- Added by BH from
5389 * list of group strings
5391 * visible or invisible
5394 public void setFeatureGroupState(String[] groups, boolean state)
5396 jalview.api.FeatureRenderer fr = null;
5397 viewport.setShowSequenceFeatures(true);
5398 if (alignPanel != null
5399 && (fr = alignPanel.getFeatureRenderer()) != null)
5402 fr.setGroupVisibility(Arrays.asList(groups), state);
5403 alignPanel.getSeqPanel().seqCanvas.repaint();
5404 if (alignPanel.overviewPanel != null)
5406 alignPanel.overviewPanel.updateOverviewImage();
5412 * Method invoked by the ChangeListener on the tabbed pane, in other words
5413 * when a different tabbed pane is selected by the user or programmatically.
5417 public void tabSelectionChanged(int index)
5421 alignPanel = alignPanels.get(index);
5422 viewport = alignPanel.av;
5423 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5424 setMenusFromViewport(viewport);
5425 if (featureSettings != null && featureSettings.isOpen()
5426 && featureSettings.fr.getViewport() != viewport)
5428 if (viewport.isShowSequenceFeatures())
5430 // refresh the featureSettings to reflect UI change
5431 showFeatureSettingsUI();
5435 // close feature settings for this view.
5436 featureSettings.close();
5443 * 'focus' any colour slider that is open to the selected viewport
5445 if (viewport.getConservationSelected())
5447 SliderPanel.setConservationSlider(alignPanel,
5448 viewport.getResidueShading(), alignPanel.getViewName());
5452 SliderPanel.hideConservationSlider();
5454 if (viewport.getAbovePIDThreshold())
5456 SliderPanel.setPIDSliderSource(alignPanel,
5457 viewport.getResidueShading(), alignPanel.getViewName());
5461 SliderPanel.hidePIDSlider();
5465 * If there is a frame linked to this one in a SplitPane, switch it to the
5466 * same view tab index. No infinite recursion of calls should happen, since
5467 * tabSelectionChanged() should not get invoked on setting the selected
5468 * index to an unchanged value. Guard against setting an invalid index
5469 * before the new view peer tab has been created.
5471 final AlignViewportI peer = viewport.getCodingComplement();
5474 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
5475 .getAlignPanel().alignFrame;
5476 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5478 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5484 * On right mouse click on view tab, prompt for and set new view name.
5488 public void tabbedPane_mousePressed(MouseEvent e)
5490 if (e.isPopupTrigger())
5492 String msg = MessageManager.getString("label.enter_view_name");
5493 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
5494 String reply = JvOptionPane.showInputDialog(msg, ttl);
5498 viewport.setViewName(reply);
5499 // TODO warn if reply is in getExistingViewNames()?
5500 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5505 public AlignViewport getCurrentView()
5511 * Open the dialog for regex description parsing.
5515 protected void extractScores_actionPerformed(ActionEvent e)
5517 ParseProperties pp = new jalview.analysis.ParseProperties(
5518 viewport.getAlignment());
5519 // TODO: verify regex and introduce GUI dialog for version 2.5
5520 // if (pp.getScoresFromDescription("col", "score column ",
5521 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5523 if (pp.getScoresFromDescription("description column",
5524 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5526 buildSortByAnnotationScoresMenu();
5534 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5539 protected void showDbRefs_actionPerformed(ActionEvent e)
5541 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5547 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5552 protected void showNpFeats_actionPerformed(ActionEvent e)
5554 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5558 * find the viewport amongst the tabs in this alignment frame and close that
5564 public boolean closeView(AlignViewportI av)
5568 this.closeMenuItem_actionPerformed(false);
5571 Component[] comp = tabbedPane.getComponents();
5572 for (int i = 0; comp != null && i < comp.length; i++)
5574 if (comp[i] instanceof AlignmentPanel)
5576 if (((AlignmentPanel) comp[i]).av == av)
5579 closeView((AlignmentPanel) comp[i]);
5587 protected void build_fetchdbmenu(JMenu webService)
5589 // Temporary hack - DBRef Fetcher always top level ws entry.
5590 // TODO We probably want to store a sequence database checklist in
5591 // preferences and have checkboxes.. rather than individual sources selected
5593 final JMenu rfetch = new JMenu(
5594 MessageManager.getString("action.fetch_db_references"));
5595 rfetch.setToolTipText(MessageManager.getString(
5596 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5597 webService.add(rfetch);
5599 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5600 MessageManager.getString("option.trim_retrieved_seqs"));
5601 trimrs.setToolTipText(
5602 MessageManager.getString("label.trim_retrieved_sequences"));
5604 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5605 trimrs.addActionListener(new ActionListener()
5609 public void actionPerformed(ActionEvent e)
5611 trimrs.setSelected(trimrs.isSelected());
5612 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5613 Boolean.valueOf(trimrs.isSelected()).toString());
5617 JMenuItem fetchr = new JMenuItem(
5618 MessageManager.getString("label.standard_databases"));
5619 fetchr.setToolTipText(
5620 MessageManager.getString("label.fetch_embl_uniprot"));
5621 fetchr.addActionListener(new ActionListener()
5625 public void actionPerformed(ActionEvent e)
5627 new Thread(new Runnable()
5633 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5634 .getAlignment().isNucleotide();
5635 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5636 alignPanel.av.getSequenceSelection(),
5637 alignPanel.alignFrame, null,
5638 alignPanel.alignFrame.featureSettings, isNucleotide);
5639 dbRefFetcher.addListener(new FetchFinishedListenerI()
5643 public void finished()
5646 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5647 .getFeatureSettingsModels())
5650 alignPanel.av.mergeFeaturesStyle(srcSettings);
5652 AlignFrame.this.setMenusForViewport();
5655 dbRefFetcher.fetchDBRefs(false);
5663 new Thread(new Runnable()
5670 // final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5671 // .getSequenceFetcherSingleton();
5672 javax.swing.SwingUtilities.invokeLater(new Runnable()
5678 jalview.ws.SequenceFetcher sf = jalview.ws.SequenceFetcher
5680 String[] dbclasses = sf.getNonAlignmentSources();
5681 List<DbSourceProxy> otherdb;
5682 JMenu dfetch = new JMenu();
5683 JMenu ifetch = new JMenu();
5684 JMenuItem fetchr = null;
5685 int comp = 0, icomp = 0, mcomp = 15;
5686 String mname = null;
5688 for (String dbclass : dbclasses)
5690 otherdb = sf.getSourceProxy(dbclass);
5691 // add a single entry for this class, or submenu allowing 'fetch
5693 if (otherdb == null || otherdb.size() < 1)
5699 mname = "From " + dbclass;
5701 if (otherdb.size() == 1)
5703 DbSourceProxy src = otherdb.get(0);
5704 DbSourceProxy[] dassource = new DbSourceProxy[] { src };
5705 fetchr = new JMenuItem(src.getDbSource());
5706 fetchr.addActionListener(new ActionListener()
5710 public void actionPerformed(ActionEvent e)
5712 new Thread(new Runnable()
5718 boolean isNucleotide = alignPanel.alignFrame
5719 .getViewport().getAlignment()
5721 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5722 alignPanel.av.getSequenceSelection(),
5723 alignPanel.alignFrame, dassource,
5724 alignPanel.alignFrame.featureSettings,
5727 .addListener(new FetchFinishedListenerI()
5731 public void finished()
5733 FeatureSettingsModelI srcSettings = dassource[0]
5734 .getFeatureColourScheme();
5735 alignPanel.av.mergeFeaturesStyle(
5737 AlignFrame.this.setMenusForViewport();
5740 dbRefFetcher.fetchDBRefs(false);
5746 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5747 MessageManager.formatMessage(
5748 "label.fetch_retrieve_from", new Object[]
5749 { src.getDbName() })));
5755 final DbSourceProxy[] dassource = otherdb
5756 .toArray(new DbSourceProxy[0]);
5758 DbSourceProxy src = otherdb.get(0);
5759 fetchr = new JMenuItem(MessageManager
5760 .formatMessage("label.fetch_all_param", new Object[]
5761 { src.getDbSource() }));
5762 fetchr.addActionListener(new ActionListener()
5766 public void actionPerformed(ActionEvent e)
5768 new Thread(new Runnable()
5774 boolean isNucleotide = alignPanel.alignFrame
5775 .getViewport().getAlignment()
5777 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5778 alignPanel.av.getSequenceSelection(),
5779 alignPanel.alignFrame, dassource,
5780 alignPanel.alignFrame.featureSettings,
5783 .addListener(new FetchFinishedListenerI()
5787 public void finished()
5789 AlignFrame.this.setMenusForViewport();
5792 dbRefFetcher.fetchDBRefs(false);
5798 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5799 MessageManager.formatMessage(
5800 "label.fetch_retrieve_from_all_sources",
5802 { Integer.valueOf(otherdb.size())
5804 src.getDbSource(), src.getDbName() })));
5807 // and then build the rest of the individual menus
5808 ifetch = new JMenu(MessageManager.formatMessage(
5809 "label.source_from_db_source", new Object[]
5810 { src.getDbSource() }));
5812 String imname = null;
5814 for (DbSourceProxy sproxy : otherdb)
5816 String dbname = sproxy.getDbName();
5817 String sname = dbname.length() > 5
5818 ? dbname.substring(0, 5) + "..."
5820 String msname = dbname.length() > 10
5821 ? dbname.substring(0, 10) + "..."
5825 imname = MessageManager
5826 .formatMessage("label.from_msname", new Object[]
5829 fetchr = new JMenuItem(msname);
5830 final DbSourceProxy[] dassrc = { sproxy };
5831 fetchr.addActionListener(new ActionListener()
5835 public void actionPerformed(ActionEvent e)
5837 new Thread(new Runnable()
5843 boolean isNucleotide = alignPanel.alignFrame
5844 .getViewport().getAlignment()
5846 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5847 alignPanel.av.getSequenceSelection(),
5848 alignPanel.alignFrame, dassrc,
5849 alignPanel.alignFrame.featureSettings,
5852 .addListener(new FetchFinishedListenerI()
5856 public void finished()
5858 AlignFrame.this.setMenusForViewport();
5861 dbRefFetcher.fetchDBRefs(false);
5867 fetchr.setToolTipText(
5868 "<html>" + MessageManager.formatMessage(
5869 "label.fetch_retrieve_from", new Object[]
5873 if (++icomp >= mcomp || i == (otherdb.size()))
5875 ifetch.setText(MessageManager.formatMessage(
5876 "label.source_to_target", imname, sname));
5878 ifetch = new JMenu();
5886 if (comp >= mcomp || dbi >= (dbclasses.length))
5888 dfetch.setText(MessageManager.formatMessage(
5889 "label.source_to_target", mname, dbclass));
5891 dfetch = new JMenu();
5904 * Left justify the whole alignment.
5908 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5910 viewport.getAlignment().justify(false);
5911 viewport.notifyAlignment();
5915 * Right justify the whole alignment.
5919 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5921 viewport.getAlignment().justify(true);
5922 viewport.notifyAlignment();
5926 public void setShowSeqFeatures(boolean b)
5928 showSeqFeatures.setSelected(b);
5929 viewport.setShowSequenceFeatures(b);
5936 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5937 * awt.event.ActionEvent)
5941 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5943 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5944 alignPanel.paintAlignment(false, false);
5951 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5956 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5958 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5959 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5967 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5968 * .event.ActionEvent)
5972 protected void showGroupConservation_actionPerformed(ActionEvent e)
5974 viewport.setShowGroupConservation(showGroupConservation.getState());
5975 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5982 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5983 * .event.ActionEvent)
5987 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5989 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5990 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5997 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5998 * .event.ActionEvent)
6002 protected void showSequenceLogo_actionPerformed(ActionEvent e)
6004 viewport.setShowSequenceLogo(showSequenceLogo.getState());
6005 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
6009 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
6011 showSequenceLogo.setState(true);
6012 viewport.setShowSequenceLogo(true);
6013 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
6014 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
6018 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
6020 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
6027 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
6028 * .event.ActionEvent)
6032 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
6034 if (avc.makeGroupsFromSelection())
6036 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
6037 alignPanel.updateAnnotation();
6038 alignPanel.paintAlignment(true,
6039 viewport.needToUpdateStructureViews());
6043 public void clearAlignmentSeqRep()
6045 // TODO refactor alignmentseqrep to controller
6046 if (viewport.getAlignment().hasSeqrep())
6048 viewport.getAlignment().setSeqrep(null);
6049 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
6050 alignPanel.updateAnnotation();
6051 alignPanel.paintAlignment(true, true);
6056 protected void createGroup_actionPerformed(ActionEvent e)
6058 if (avc.createGroup())
6060 if (applyAutoAnnotationSettings.isSelected())
6062 alignPanel.updateAnnotation(true, false);
6064 alignPanel.alignmentChanged();
6069 protected void unGroup_actionPerformed(ActionEvent e)
6073 alignPanel.alignmentChanged();
6078 * make the given alignmentPanel the currently selected tab
6080 * @param alignmentPanel
6083 public void setDisplayedView(AlignmentPanel alignmentPanel)
6085 if (!viewport.getSequenceSetId()
6086 .equals(alignmentPanel.av.getSequenceSetId()))
6088 throw new Error(MessageManager.getString(
6089 "error.implementation_error_cannot_show_view_alignment_frame"));
6091 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
6092 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
6094 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
6099 * Action on selection of menu options to Show or Hide annotations.
6102 * @param forSequences
6103 * update sequence-related annotations
6104 * @param forAlignment
6105 * update non-sequence-related annotations
6109 protected void setAnnotationsVisibility(boolean visible,
6110 boolean forSequences, boolean forAlignment)
6112 AlignmentAnnotation[] anns = alignPanel.getAlignment()
6113 .getAlignmentAnnotation();
6118 for (AlignmentAnnotation aa : anns)
6121 * don't display non-positional annotations on an alignment
6123 if (aa.annotations == null)
6127 boolean apply = (aa.sequenceRef == null && forAlignment)
6128 || (aa.sequenceRef != null && forSequences);
6131 aa.visible = visible;
6134 alignPanel.validateAnnotationDimensions(true);
6135 alignPanel.alignmentChanged();
6139 * Store selected annotation sort order for the view and repaint.
6143 protected void sortAnnotations_actionPerformed()
6145 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
6147 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
6148 alignPanel.paintAlignment(false, false);
6153 * @return alignment panels in this alignment frame
6156 public List<? extends AlignmentViewPanel> getAlignPanels()
6158 // alignPanels is never null
6159 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
6164 * Open a new alignment window, with the cDNA associated with this (protein)
6165 * alignment, aligned as is the protein.
6168 protected void viewAsCdna_actionPerformed()
6170 // TODO no longer a menu action - refactor as required
6171 final AlignmentI alignment = getViewport().getAlignment();
6172 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
6173 if (mappings == null)
6177 List<SequenceI> cdnaSeqs = new ArrayList<>();
6178 for (SequenceI aaSeq : alignment.getSequences())
6180 for (AlignedCodonFrame acf : mappings)
6182 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
6186 * There is a cDNA mapping for this protein sequence - add to new
6187 * alignment. It will share the same dataset sequence as other mapped
6188 * cDNA (no new mappings need to be created).
6190 final Sequence newSeq = new Sequence(dnaSeq);
6191 newSeq.setDatasetSequence(dnaSeq);
6192 cdnaSeqs.add(newSeq);
6196 if (cdnaSeqs.size() == 0)
6198 // show a warning dialog no mapped cDNA
6201 AlignmentI cdna = new Alignment(
6202 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
6203 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
6204 AlignFrame.DEFAULT_HEIGHT);
6205 cdna.alignAs(alignment);
6206 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
6208 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
6209 AlignFrame.DEFAULT_HEIGHT);
6213 * Set visibility of dna/protein complement view (available when shown in a
6220 protected void showComplement_actionPerformed(boolean show)
6222 SplitContainerI sf = getSplitViewContainer();
6225 sf.setComplementVisible(this, show);
6230 * Generate the reverse (optionally complemented) of the selected sequences,
6231 * and add them to the alignment
6235 protected void showReverse_actionPerformed(boolean complement)
6237 AlignmentI al = null;
6240 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
6241 al = dna.reverseCdna(complement);
6242 viewport.addAlignment(al, "");
6243 addHistoryItem(new EditCommand(
6244 MessageManager.getString("label.add_sequences"), Action.PASTE,
6245 al.getSequencesArray(), 0, al.getWidth(),
6246 viewport.getAlignment()));
6247 } catch (Exception ex)
6249 System.err.println(ex.getMessage());
6255 * Try to run a script in the Groovy console, having first ensured that this
6256 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
6257 * be targeted at this alignment.
6261 protected void runGroovy_actionPerformed()
6263 Jalview.setCurrentAlignFrame(this);
6264 groovy.ui.Console console = Desktop.getGroovyConsole();
6265 if (console != null)
6269 console.runScript();
6270 } catch (Exception ex)
6272 System.err.println((ex.toString()));
6273 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
6274 MessageManager.getString("label.couldnt_run_groovy_script"),
6275 MessageManager.getString("label.groovy_support_failed"),
6276 JvOptionPane.ERROR_MESSAGE);
6281 System.err.println("Can't run Groovy script as console not found");
6286 * Hides columns containing (or not containing) a specified feature, provided
6287 * that would not leave all columns hidden
6289 * @param featureType
6290 * @param columnsContaining
6294 public boolean hideFeatureColumns(String featureType,
6295 boolean columnsContaining)
6297 boolean notForHiding = avc.markColumnsContainingFeatures(
6298 columnsContaining, false, false, featureType);
6301 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
6302 false, featureType))
6304 getViewport().hideSelectedColumns();
6312 protected void selectHighlightedColumns_actionPerformed(
6313 ActionEvent actionEvent)
6315 // include key modifier check in case user selects from menu
6316 avc.markHighlightedColumns(
6317 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
6318 (actionEvent.getModifiers() & (ActionEvent.META_MASK
6319 | ActionEvent.CTRL_MASK)) != 0);
6323 * Rebuilds the Colour menu, including any user-defined colours which have
6324 * been loaded either on startup or during the session
6327 public void buildColourMenu()
6329 colourMenu.removeAll();
6331 colourMenu.add(applyToAllGroups);
6332 colourMenu.add(textColour);
6333 colourMenu.addSeparator();
6335 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
6336 viewport.getAlignment(), false);
6338 colourMenu.add(annotationColour);
6339 bg.add(annotationColour);
6340 colourMenu.addSeparator();
6341 colourMenu.add(conservationMenuItem);
6342 colourMenu.add(modifyConservation);
6343 colourMenu.add(abovePIDThreshold);
6344 colourMenu.add(modifyPID);
6346 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
6347 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
6351 * Open a dialog (if not already open) that allows the user to select and
6352 * calculate PCA or Tree analysis
6355 protected void openTreePcaDialog()
6357 if (alignPanel.getCalculationDialog() == null)
6359 new CalculationChooser(AlignFrame.this);
6364 * Sets the status of the HMMER menu
6366 public void updateHMMERStatus()
6368 hmmerMenu.setEnabled(HmmerCommand.isHmmerAvailable());
6372 protected void loadVcf_actionPerformed()
6374 JalviewFileChooser chooser = new JalviewFileChooser(
6375 Cache.getProperty("LAST_DIRECTORY"));
6376 chooser.setFileView(new JalviewFileView());
6377 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
6378 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
6379 final AlignFrame us = this;
6380 chooser.setResponseHandler(0, new Runnable()
6386 String choice = chooser.getSelectedFile().getPath();
6387 Cache.setProperty("LAST_DIRECTORY", choice);
6388 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
6389 new VCFLoader(choice).loadVCF(seqs, us);
6392 chooser.showOpenDialog(null);
6396 private Rectangle lastFeatureSettingsBounds = null;
6399 public void setFeatureSettingsGeometry(Rectangle bounds)
6401 lastFeatureSettingsBounds = bounds;
6405 public Rectangle getFeatureSettingsGeometry()
6407 return lastFeatureSettingsBounds;
6410 public void scrollTo(int row, int column)
6412 alignPanel.getSeqPanel().scrollTo(row, column);
6415 public void scrollToRow(int row)
6417 alignPanel.getSeqPanel().scrollToRow(row);
6420 public void scrollToColumn(int column)
6422 alignPanel.getSeqPanel().scrollToColumn(column);
6426 * BH 2019 from JalviewLite
6428 * get sequence feature groups that are hidden or shown
6435 public String[] getFeatureGroupsOfState(boolean visible)
6437 jalview.api.FeatureRenderer fr = null;
6438 if (alignPanel != null
6439 && (fr = alignPanel.getFeatureRenderer()) != null)
6441 List<String> gps = fr.getGroups(visible);
6442 String[] _gps = gps.toArray(new String[gps.size()]);
6450 * @return list of feature groups on the view
6453 public String[] getFeatureGroups()
6455 jalview.api.FeatureRenderer fr = null;
6456 if (alignPanel != null
6457 && (fr = alignPanel.getFeatureRenderer()) != null)
6459 List<String> gps = fr.getFeatureGroups();
6460 String[] _gps = gps.toArray(new String[gps.size()]);
6466 public void select(SequenceGroup sel, ColumnSelection csel,
6467 HiddenColumns hidden)
6469 alignPanel.getSeqPanel().selection(sel, csel, hidden, null);
6477 static class PrintThread extends Thread
6481 public PrintThread(AlignmentPanel ap)
6486 static PageFormat pf;
6491 PrinterJob printJob = PrinterJob.getPrinterJob();
6495 printJob.setPrintable(ap, pf);
6499 printJob.setPrintable(ap);
6502 if (printJob.printDialog())
6507 } catch (Exception PrintException)
6509 PrintException.printStackTrace();