2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AlignmentSorter;
24 import jalview.analysis.AlignmentUtils;
25 import jalview.analysis.CrossRef;
26 import jalview.analysis.Dna;
27 import jalview.analysis.GeneticCodeI;
28 import jalview.analysis.ParseProperties;
29 import jalview.analysis.SequenceIdMatcher;
30 import jalview.api.AlignExportSettingsI;
31 import jalview.api.AlignViewControllerGuiI;
32 import jalview.api.AlignViewControllerI;
33 import jalview.api.AlignViewportI;
34 import jalview.api.AlignmentViewPanel;
35 import jalview.api.FeatureSettingsControllerI;
36 import jalview.api.FeatureSettingsModelI;
37 import jalview.api.SplitContainerI;
38 import jalview.api.ViewStyleI;
39 import jalview.api.analysis.SimilarityParamsI;
40 import jalview.bin.Cache;
41 import jalview.bin.Jalview;
42 import jalview.commands.CommandI;
43 import jalview.commands.EditCommand;
44 import jalview.commands.EditCommand.Action;
45 import jalview.commands.OrderCommand;
46 import jalview.commands.RemoveGapColCommand;
47 import jalview.commands.RemoveGapsCommand;
48 import jalview.commands.SlideSequencesCommand;
49 import jalview.commands.TrimRegionCommand;
50 import jalview.datamodel.AlignExportSettingsAdapter;
51 import jalview.datamodel.AlignedCodonFrame;
52 import jalview.datamodel.Alignment;
53 import jalview.datamodel.AlignmentAnnotation;
54 import jalview.datamodel.AlignmentExportData;
55 import jalview.datamodel.AlignmentI;
56 import jalview.datamodel.AlignmentOrder;
57 import jalview.datamodel.AlignmentView;
58 import jalview.datamodel.ColumnSelection;
59 import jalview.datamodel.HiddenColumns;
60 import jalview.datamodel.PDBEntry;
61 import jalview.datamodel.SeqCigar;
62 import jalview.datamodel.Sequence;
63 import jalview.datamodel.SequenceGroup;
64 import jalview.datamodel.SequenceI;
65 import jalview.gui.ColourMenuHelper.ColourChangeListener;
66 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
67 import jalview.hmmer.HMMAlign;
68 import jalview.hmmer.HMMBuild;
69 import jalview.hmmer.HMMERParamStore;
70 import jalview.hmmer.HMMERPreset;
71 import jalview.hmmer.HMMSearch;
72 import jalview.hmmer.HmmerCommand;
73 import jalview.hmmer.JackHMMER;
74 import jalview.io.AlignmentProperties;
75 import jalview.io.AnnotationFile;
76 import jalview.io.BackupFiles;
77 import jalview.io.BioJsHTMLOutput;
78 import jalview.io.DataSourceType;
79 import jalview.io.FileFormat;
80 import jalview.io.FileFormatI;
81 import jalview.io.FileFormats;
82 import jalview.io.FileLoader;
83 import jalview.io.FileParse;
84 import jalview.io.FormatAdapter;
85 import jalview.io.HtmlSvgOutput;
86 import jalview.io.IdentifyFile;
87 import jalview.io.JPredFile;
88 import jalview.io.JalviewFileChooser;
89 import jalview.io.JalviewFileView;
90 import jalview.io.JnetAnnotationMaker;
91 import jalview.io.NewickFile;
92 import jalview.io.ScoreMatrixFile;
93 import jalview.io.TCoffeeScoreFile;
94 import jalview.io.vcf.VCFLoader;
95 import jalview.jbgui.GAlignFrame;
96 import jalview.project.Jalview2XML;
97 import jalview.schemes.ColourSchemeI;
98 import jalview.schemes.ColourSchemes;
99 import jalview.schemes.ResidueColourScheme;
100 import jalview.schemes.TCoffeeColourScheme;
101 import jalview.util.ImageMaker.TYPE;
102 import jalview.util.MessageManager;
103 import jalview.util.Platform;
104 import jalview.viewmodel.AlignmentViewport;
105 import jalview.viewmodel.ViewportRanges;
106 import jalview.ws.DBRefFetcher;
107 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
108 import jalview.ws.ServiceChangeListener;
109 import jalview.ws.WSDiscovererI;
110 import jalview.ws.api.ServiceWithParameters;
111 import jalview.ws.jws1.Discoverer;
112 import jalview.ws.jws2.Jws2Discoverer;
113 import jalview.ws.jws2.PreferredServiceRegistry;
114 import jalview.ws.params.ArgumentI;
115 import jalview.ws.params.ParamDatastoreI;
116 import jalview.ws.params.WsParamSetI;
117 import jalview.ws.seqfetcher.DbSourceProxy;
118 import jalview.ws2.WebServiceDiscoverer;
119 import jalview.ws2.WebServiceI;
120 import jalview.ws2.operations.Operation;
121 import jalview.ws2.slivka.SlivkaWSDiscoverer;
123 import java.io.IOException;
124 import java.util.HashSet;
125 import java.util.Set;
127 import javax.swing.JFileChooser;
128 import javax.swing.JOptionPane;
130 import java.awt.BorderLayout;
131 import java.awt.Color;
132 import java.awt.Component;
133 import java.awt.Dimension;
134 import java.awt.Rectangle;
135 import java.awt.Toolkit;
136 import java.awt.datatransfer.Clipboard;
137 import java.awt.datatransfer.DataFlavor;
138 import java.awt.datatransfer.StringSelection;
139 import java.awt.datatransfer.Transferable;
140 import java.awt.dnd.DnDConstants;
141 import java.awt.dnd.DropTargetDragEvent;
142 import java.awt.dnd.DropTargetDropEvent;
143 import java.awt.dnd.DropTargetEvent;
144 import java.awt.dnd.DropTargetListener;
145 import java.awt.event.ActionEvent;
146 import java.awt.event.ActionListener;
147 import java.awt.event.FocusAdapter;
148 import java.awt.event.FocusEvent;
149 import java.awt.event.ItemEvent;
150 import java.awt.event.ItemListener;
151 import java.awt.event.KeyAdapter;
152 import java.awt.event.KeyEvent;
153 import java.awt.event.MouseEvent;
154 import java.awt.print.PageFormat;
155 import java.awt.print.PrinterJob;
156 import java.beans.PropertyChangeEvent;
157 import java.beans.PropertyChangeListener;
159 import java.io.FileWriter;
160 import java.io.PrintWriter;
162 import java.util.ArrayList;
163 import java.util.Arrays;
164 import java.util.Collection;
165 import java.util.Comparator;
166 import java.util.Deque;
167 import java.util.Enumeration;
168 import java.util.HashMap;
169 import java.util.Hashtable;
170 import java.util.List;
171 import java.util.Map;
172 import java.util.Vector;
174 import javax.swing.ButtonGroup;
175 import javax.swing.JCheckBoxMenuItem;
176 import javax.swing.JComponent;
177 import javax.swing.JEditorPane;
178 import javax.swing.JInternalFrame;
179 import javax.swing.JLabel;
180 import javax.swing.JLayeredPane;
181 import javax.swing.JMenu;
182 import javax.swing.JMenuItem;
183 import javax.swing.JPanel;
184 import javax.swing.JScrollPane;
185 import javax.swing.SwingUtilities;
186 import javax.swing.event.InternalFrameAdapter;
187 import javax.swing.event.InternalFrameEvent;
189 import ext.vamsas.ServiceHandle;
195 * @version $Revision$
197 @SuppressWarnings("serial")
198 public class AlignFrame extends GAlignFrame
199 implements DropTargetListener, IProgressIndicator,
200 AlignViewControllerGuiI, ColourChangeListener, ServiceChangeListener,
201 WebServiceDiscoverer.ServiceChangeListener
204 public static int frameCount;
206 public static final int DEFAULT_WIDTH = 700;
208 public static final int DEFAULT_HEIGHT = 500;
211 * The currently displayed panel (selected tabbed view if more than one)
213 public AlignmentPanel alignPanel;
215 AlignViewport viewport;
217 public AlignViewControllerI avc;
219 List<AlignmentPanel> alignPanels = new ArrayList<>();
222 * Last format used to load or save alignments in this window
224 FileFormatI currentFileFormat = null;
227 * Current filename for this alignment
229 String fileName = null;
232 * TODO: remove reference to 'FileObject' in AlignFrame - not correct mapping
238 private DataSourceType protocol ;
241 * Creates a new AlignFrame object with specific width and height.
247 public AlignFrame(AlignmentI al, int width, int height)
249 this(al, null, width, height);
253 * Creates a new AlignFrame object with specific width, height and
259 * @param sequenceSetId
261 public AlignFrame(AlignmentI al, int width, int height,
262 String sequenceSetId)
264 this(al, null, width, height, sequenceSetId);
268 * Creates a new AlignFrame object with specific width, height and
274 * @param sequenceSetId
277 public AlignFrame(AlignmentI al, int width, int height,
278 String sequenceSetId, String viewId)
280 this(al, null, width, height, sequenceSetId, viewId);
284 * new alignment window with hidden columns
288 * @param hiddenColumns
289 * ColumnSelection or null
291 * Width of alignment frame
295 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
298 this(al, hiddenColumns, width, height, null);
302 * Create alignment frame for al with hiddenColumns, a specific width and
303 * height, and specific sequenceId
306 * @param hiddenColumns
309 * @param sequenceSetId
312 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
313 int height, String sequenceSetId)
315 this(al, hiddenColumns, width, height, sequenceSetId, null);
319 * Create alignment frame for al with hiddenColumns, a specific width and
320 * height, and specific sequenceId
323 * @param hiddenColumns
326 * @param sequenceSetId
331 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
332 int height, String sequenceSetId, String viewId)
337 setSize(width, height);
339 if (al.getDataset() == null)
344 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
346 // JalviewJS needs to distinguish a new panel from an old one in init()
347 // alignPanel = new AlignmentPanel(this, viewport);
348 // addAlignmentPanel(alignPanel, true);
352 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
353 HiddenColumns hiddenColumns, int width, int height)
355 setSize(width, height);
357 if (al.getDataset() == null)
362 viewport = new AlignViewport(al, hiddenColumns);
364 if (hiddenSeqs != null && hiddenSeqs.length > 0)
366 viewport.hideSequence(hiddenSeqs);
368 // alignPanel = new AlignmentPanel(this, viewport);
369 // addAlignmentPanel(alignPanel, true);
374 * Make a new AlignFrame from existing alignmentPanels
381 public AlignFrame(AlignmentPanel ap)
385 // addAlignmentPanel(ap, false);
390 * initalise the alignframe from the underlying viewport data and the
396 boolean newPanel = (alignPanel == null);
397 viewport.setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
402 // need to set this up front if NOANNOTATION is
403 // used in conjunction with SHOWOVERVIEW.
405 // I have not determined if this is appropriate for
406 // Jalview/Java, as it means we are setting this flag
407 // for all subsequent AlignFrames. For now, at least,
408 // I am setting it to be JalviewJS-only.
410 boolean showAnnotation = Jalview.getInstance().getShowAnnotation();
411 viewport.setShowAnnotation(showAnnotation);
413 alignPanel = new AlignmentPanel(this, viewport);
415 addAlignmentPanel(alignPanel, newPanel);
417 // setBackground(Color.white); // BH 2019
419 if (!Jalview.isHeadlessMode())
421 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
423 statusPanel.setVisible(Jalview.getInstance().getShowStatus());
424 alignFrameMenuBar.setVisible(Jalview.getInstance().getAllowMenuBar());
427 avc = new jalview.controller.AlignViewController(this, viewport,
429 if (viewport.getAlignmentConservationAnnotation() == null)
431 // BLOSUM62Colour.setEnabled(false);
432 conservationMenuItem.setEnabled(false);
433 modifyConservation.setEnabled(false);
434 // PIDColour.setEnabled(false);
435 // abovePIDThreshold.setEnabled(false);
436 // modifyPID.setEnabled(false);
439 String sortby = jalview.bin.Cache.getDefault(Preferences.SORT_ALIGNMENT,
442 if (sortby.equals("Id"))
444 sortIDMenuItem_actionPerformed(null);
446 else if (sortby.equals("Pairwise Identity"))
448 sortPairwiseMenuItem_actionPerformed(null);
453 // this.alignPanel.av
454 // .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
456 setMenusFromViewport(viewport);
457 buildSortByAnnotationScoresMenu();
458 calculateTree.addActionListener(new ActionListener()
462 public void actionPerformed(ActionEvent e)
469 if (Desktop.getDesktopPane() != null)
471 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
472 addServiceListeners();
473 if (!Platform.isJS())
479 if (viewport.getWrapAlignment())
481 wrapMenuItem_actionPerformed(null);
484 if (jalview.bin.Cache.getDefault(Preferences.SHOW_OVERVIEW, false))
486 this.overviewMenuItem_actionPerformed(null);
491 final List<AlignmentPanel> selviews = new ArrayList<>();
492 final List<AlignmentPanel> origview = new ArrayList<>();
493 final String menuLabel = MessageManager
494 .getString("label.copy_format_from");
495 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
496 new ViewSetProvider()
500 public AlignmentPanel[] getAllAlignmentPanels()
503 origview.add(alignPanel);
504 // make an array of all alignment panels except for this one
505 List<AlignmentPanel> aps = new ArrayList<>(
506 Arrays.asList(Desktop.getAlignmentPanels(null)));
507 aps.remove(AlignFrame.this.alignPanel);
508 return aps.toArray(new AlignmentPanel[aps.size()]);
510 }, selviews, new ItemListener()
514 public void itemStateChanged(ItemEvent e)
516 if (origview.size() > 0)
518 final AlignmentPanel ap = origview.get(0);
521 * Copy the ViewStyle of the selected panel to 'this one'.
522 * Don't change value of 'scaleProteinAsCdna' unless copying
525 ViewStyleI vs = selviews.get(0).getAlignViewport()
527 boolean fromSplitFrame = selviews.get(0)
528 .getAlignViewport().getCodingComplement() != null;
531 vs.setScaleProteinAsCdna(ap.getAlignViewport()
532 .getViewStyle().isScaleProteinAsCdna());
534 ap.getAlignViewport().setViewStyle(vs);
537 * Also rescale ViewStyle of SplitFrame complement if there is
538 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
539 * the whole ViewStyle (allow cDNA protein to have different
542 AlignViewportI complement = ap.getAlignViewport()
543 .getCodingComplement();
544 if (complement != null && vs.isScaleProteinAsCdna())
546 AlignFrame af = Desktop.getAlignFrameFor(complement);
547 ((SplitFrame) af.getSplitViewContainer())
549 af.setMenusForViewport();
553 ap.setSelected(true);
554 ap.alignFrame.setMenusForViewport();
559 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
560 .indexOf("devel") > -1
561 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
562 .indexOf("test") > -1)
564 formatMenu.add(vsel);
566 addFocusListener(new FocusAdapter()
570 public void focusGained(FocusEvent e)
572 Jalview.setCurrentAlignFrame(AlignFrame.this);
579 * Change the filename and format for the alignment, and enable the 'reload'
580 * button functionality.
589 public void setFileName(String file, FileFormatI format)
592 setFileFormat(format);
593 reload.setEnabled(true);
599 * @param file from SwingJS; may contain bytes -- for reload
600 * @param protocol from SwingJS; may be RELATIVE_URL
603 public void setFile(String fileName, File file, DataSourceType protocol, FileFormatI format)
605 this.fileName = fileName;
606 this.fileObject = file;
607 this.protocol = protocol;
608 setFileFormat(format);
609 reload.setEnabled(true);
613 * JavaScript will have this, maybe others. More dependable than a file name
614 * and maintains a reference to the actual bytes loaded.
619 public void setFileObject(File file)
621 this.fileObject = file;
625 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
629 void addKeyListener()
631 addKeyListener(new KeyAdapter()
635 public void keyPressed(KeyEvent evt)
637 if (viewport.cursorMode
638 && ((evt.getKeyCode() >= KeyEvent.VK_0
639 && evt.getKeyCode() <= KeyEvent.VK_9)
640 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
641 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
642 && Character.isDigit(evt.getKeyChar()))
644 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
647 switch (evt.getKeyCode())
650 case KeyEvent.VK_ESCAPE: // escape key
651 // alignPanel.deselectAllSequences();
652 alignPanel.deselectAllSequences();
656 case KeyEvent.VK_DOWN:
657 if (evt.isAltDown() || !viewport.cursorMode)
659 moveSelectedSequences(false);
661 if (viewport.cursorMode)
663 alignPanel.getSeqPanel().moveCursor(0, 1);
668 if (evt.isAltDown() || !viewport.cursorMode)
670 moveSelectedSequences(true);
672 if (viewport.cursorMode)
674 alignPanel.getSeqPanel().moveCursor(0, -1);
679 case KeyEvent.VK_LEFT:
680 if (evt.isAltDown() || !viewport.cursorMode)
682 slideSequences(false,
683 alignPanel.getSeqPanel().getKeyboardNo1());
687 alignPanel.getSeqPanel().moveCursor(-1, 0);
692 case KeyEvent.VK_RIGHT:
693 if (evt.isAltDown() || !viewport.cursorMode)
695 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
699 alignPanel.getSeqPanel().moveCursor(1, 0);
703 case KeyEvent.VK_SPACE:
704 if (viewport.cursorMode)
706 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
707 || evt.isShiftDown() || evt.isAltDown());
711 // case KeyEvent.VK_A:
712 // if (viewport.cursorMode)
714 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
715 // //System.out.println("A");
719 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
720 * System.out.println("closing bracket"); } break;
722 case KeyEvent.VK_DELETE:
723 case KeyEvent.VK_BACK_SPACE:
724 if (!viewport.cursorMode)
726 cut_actionPerformed();
730 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
731 || evt.isShiftDown() || evt.isAltDown());
737 if (viewport.cursorMode)
739 alignPanel.getSeqPanel().setCursorRow();
743 if (viewport.cursorMode && !evt.isControlDown())
745 alignPanel.getSeqPanel().setCursorColumn();
749 if (viewport.cursorMode)
751 alignPanel.getSeqPanel().setCursorPosition();
755 case KeyEvent.VK_ENTER:
756 case KeyEvent.VK_COMMA:
757 if (viewport.cursorMode)
759 alignPanel.getSeqPanel().setCursorRowAndColumn();
764 if (viewport.cursorMode)
766 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
770 if (viewport.cursorMode)
772 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
777 viewport.cursorMode = !viewport.cursorMode;
778 setStatus(MessageManager
779 .formatMessage("label.keyboard_editing_mode", new String[]
780 { (viewport.cursorMode ? "on" : "off") }));
781 if (viewport.cursorMode)
783 ViewportRanges ranges = viewport.getRanges();
784 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
786 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
789 alignPanel.getSeqPanel().seqCanvas.repaint();
795 Help.showHelpWindow();
796 } catch (Exception ex)
798 ex.printStackTrace();
803 boolean toggleSeqs = !evt.isControlDown();
804 boolean toggleCols = !evt.isShiftDown();
805 toggleHiddenRegions(toggleSeqs, toggleCols);
810 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
811 boolean modifyExisting = true; // always modify, don't clear
812 // evt.isShiftDown();
813 boolean invertHighlighted = evt.isAltDown();
814 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
818 case KeyEvent.VK_PAGE_UP:
819 viewport.getRanges().pageUp();
821 case KeyEvent.VK_PAGE_DOWN:
822 viewport.getRanges().pageDown();
828 public void keyReleased(KeyEvent evt)
830 switch (evt.getKeyCode())
832 case KeyEvent.VK_LEFT:
833 if (evt.isAltDown() || !viewport.cursorMode)
835 viewport.notifyAlignment();
839 case KeyEvent.VK_RIGHT:
840 if (evt.isAltDown() || !viewport.cursorMode)
842 viewport.notifyAlignment();
850 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
852 ap.alignFrame = this;
853 avc = new jalview.controller.AlignViewController(this, viewport,
858 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
860 int aSize = alignPanels.size();
862 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
864 if (aSize == 1 && ap.av.getViewName() == null)
866 this.getContentPane().add(ap, BorderLayout.CENTER);
872 setInitialTabVisible();
875 expandViews.setEnabled(true);
876 gatherViews.setEnabled(true);
877 tabbedPane.addTab(ap.av.getViewName(), ap);
879 ap.setVisible(false);
884 if (ap.av.isPadGaps())
886 ap.av.getAlignment().padGaps();
888 if (Jalview.getInstance().getStartCalculations())
890 ap.av.updateConservation(ap);
891 ap.av.updateConsensus(ap);
892 ap.av.updateStrucConsensus(ap);
893 ap.av.initInformationWorker(ap);
898 public void setInitialTabVisible()
900 expandViews.setEnabled(true);
901 gatherViews.setEnabled(true);
902 tabbedPane.setVisible(true);
903 AlignmentPanel first = alignPanels.get(0);
904 tabbedPane.addTab(first.av.getViewName(), first);
905 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
908 public AlignViewport getViewport()
914 public void servicesChanged(WSDiscovererI discoverer,
915 Collection<? extends ServiceWithParameters> services)
917 buildWebServicesMenu();
921 public void servicesChanged(WebServiceDiscoverer discoverer,
922 Collection<? extends WebServiceI> services)
924 buildWebServicesMenu();
927 /* Set up intrinsic listeners for dynamically generated GUI bits. */
928 private void addServiceListeners()
930 if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
932 WebServiceDiscoverer discoverer = SlivkaWSDiscoverer.getInstance();
933 discoverer.addServiceChangeListener((disc, srvcs) -> buildWebServicesMenu());
935 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
937 WSDiscovererI discoverer = Jws2Discoverer.getInstance();
938 discoverer.addServiceChangeListener(this);
940 // legacy event listener for compatibility with jws1
941 PropertyChangeListener legacyListener = (changeEvent) -> {
942 buildWebServicesMenu();
944 Desktop.getInstance().addJalviewPropertyChangeListener("services",legacyListener);
946 addInternalFrameListener(new InternalFrameAdapter() {
948 public void internalFrameClosed(InternalFrameEvent e) {
949 System.out.println("deregistering discoverer listener");
950 // SlivkaWSDiscoverer.getInstance().removeServiceChangeListener(AlignFrame.this);
951 Jws2Discoverer.getInstance().removeServiceChangeListener(AlignFrame.this);
952 Desktop.getInstance().removeJalviewPropertyChangeListener("services", legacyListener);
953 closeMenuItem_actionPerformed(true);
956 buildWebServicesMenu();
960 * Configure menu items that vary according to whether the alignment is
961 * nucleotide or protein
964 public void setGUINucleotide()
966 AlignmentI al = getViewport().getAlignment();
967 boolean nucleotide = al.isNucleotide();
969 loadVcf.setVisible(nucleotide);
970 showTranslation.setVisible(nucleotide);
971 showReverse.setVisible(nucleotide);
972 showReverseComplement.setVisible(nucleotide);
973 conservationMenuItem.setEnabled(!nucleotide);
975 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
976 showGroupConservation.setEnabled(!nucleotide);
978 showComplementMenuItem
979 .setText(nucleotide ? MessageManager.getString("label.protein")
980 : MessageManager.getString("label.nucleotide"));
984 * set up menus for the current viewport. This may be called after any
985 * operation that affects the data in the current view (selection changed,
986 * etc) to update the menus to reflect the new state.
990 public void setMenusForViewport()
992 setMenusFromViewport(viewport);
996 * Need to call this method when tabs are selected for multiple views, or when
997 * loading from Jalview2XML.java
1003 public void setMenusFromViewport(AlignViewport av)
1005 padGapsMenuitem.setSelected(av.isPadGaps());
1006 colourTextMenuItem.setSelected(av.isShowColourText());
1007 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
1008 modifyPID.setEnabled(abovePIDThreshold.isSelected());
1009 conservationMenuItem.setSelected(av.getConservationSelected());
1010 modifyConservation.setEnabled(conservationMenuItem.isSelected());
1011 seqLimits.setSelected(av.getShowJVSuffix());
1012 idRightAlign.setSelected(av.isRightAlignIds());
1013 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
1014 renderGapsMenuItem.setSelected(av.isRenderGaps());
1015 wrapMenuItem.setSelected(av.getWrapAlignment());
1016 scaleAbove.setVisible(av.getWrapAlignment());
1017 scaleLeft.setVisible(av.getWrapAlignment());
1018 scaleRight.setVisible(av.getWrapAlignment());
1019 annotationPanelMenuItem.setState(av.isShowAnnotation());
1020 // Show/hide annotations only enabled if annotation panel is shown
1021 syncAnnotationMenuItems(av.isShowAnnotation());
1022 viewBoxesMenuItem.setSelected(av.getShowBoxes());
1023 viewTextMenuItem.setSelected(av.getShowText());
1024 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
1025 showGroupConsensus.setSelected(av.isShowGroupConsensus());
1026 showGroupConservation.setSelected(av.isShowGroupConservation());
1027 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
1028 showSequenceLogo.setSelected(av.isShowSequenceLogo());
1029 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
1030 showInformationHistogram.setSelected(av.isShowInformationHistogram());
1031 showHMMSequenceLogo.setSelected(av.isShowHMMSequenceLogo());
1032 normaliseHMMSequenceLogo.setSelected(av.isNormaliseHMMSequenceLogo());
1034 ColourMenuHelper.setColourSelected(colourMenu,
1035 av.getGlobalColourScheme());
1037 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
1038 hiddenMarkers.setState(av.getShowHiddenMarkers());
1039 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
1040 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
1041 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
1043 .setSelected(av.getAutoCalculateConsensusAndConservation());
1044 sortByTree.setSelected(av.sortByTree);
1045 listenToViewSelections.setSelected(av.followSelection);
1047 showProducts.setEnabled(canShowProducts());
1048 setGroovyEnabled(Desktop.getGroovyConsole() != null);
1050 updateEditMenuBar();
1054 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
1059 public void setGroovyEnabled(boolean b)
1061 runGroovy.setEnabled(b);
1064 private IProgressIndicator progressBar;
1069 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
1073 public void setProgressBar(String message, long id)
1075 progressBar.setProgressBar(message, id);
1079 public void removeProgressBar(long id)
1081 progressBar.removeProgressBar(id);
1085 public void registerHandler(final long id,
1086 final IProgressIndicatorHandler handler)
1088 progressBar.registerHandler(id, handler);
1093 * @return true if any progress bars are still active
1097 public boolean operationInProgress()
1099 return progressBar.operationInProgress();
1103 * Sets the text of the status bar. Note that setting a null or empty value
1104 * will cause the status bar to be hidden, with possibly undesirable flicker
1105 * of the screen layout.
1109 public void setStatus(String text)
1111 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1115 * Added so Castor Mapping file can obtain Jalview Version
1118 public String getVersion()
1120 return jalview.bin.Cache.getProperty("VERSION");
1123 public FeatureRenderer getFeatureRenderer()
1125 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1129 public void fetchSequence_actionPerformed()
1131 new SequenceFetcher(this);
1135 public void addFromFile_actionPerformed(ActionEvent e)
1137 Desktop.getInstance().inputLocalFileMenuItem_actionPerformed(viewport);
1141 public void hmmBuild_actionPerformed(boolean withDefaults)
1143 if (!alignmentIsSufficient(1))
1149 * get default parameters, and optionally show a dialog
1150 * to allow them to be modified
1152 ParamDatastoreI store = HMMERParamStore.forBuild(viewport);
1153 List<ArgumentI> args = store.getServiceParameters();
1157 WsParamSetI set = new HMMERPreset();
1158 WsJobParameters params = new WsJobParameters(store, set, args);
1159 params.showRunDialog().thenAccept((startJob) -> {
1162 var args2 = params.getJobParams();
1163 new Thread(new HMMBuild(this, args2)).start();
1169 new Thread(new HMMBuild(this, args)).start();
1174 public void hmmAlign_actionPerformed(boolean withDefaults)
1176 if (!(checkForHMM() && alignmentIsSufficient(2)))
1182 * get default parameters, and optionally show a dialog
1183 * to allow them to be modified
1185 ParamDatastoreI store = HMMERParamStore.forAlign(viewport);
1186 List<ArgumentI> args = store.getServiceParameters();
1190 WsParamSetI set = new HMMERPreset();
1191 WsJobParameters params = new WsJobParameters(store, set, args);
1192 params.showRunDialog().thenAccept((startJob) -> {
1195 var args2 = params.getJobParams();
1196 new Thread(new HMMAlign(this, args2)).start();
1202 new Thread(new HMMAlign(this, args)).start();
1207 public void hmmSearch_actionPerformed(boolean withDefaults)
1215 * get default parameters, and (if requested) show
1216 * dialog to allow modification
1218 ParamDatastoreI store = HMMERParamStore.forSearch(viewport);
1219 List<ArgumentI> args = store.getServiceParameters();
1223 WsParamSetI set = new HMMERPreset();
1224 WsJobParameters params = new WsJobParameters(store, set, args);
1225 params.showRunDialog().thenAccept((startJob) -> {
1228 var args2 = params.getJobParams();
1229 new Thread(new HMMSearch(this, args2)).start();
1230 alignPanel.repaint();
1236 new Thread(new HMMSearch(this, args)).start();
1237 alignPanel.repaint();
1242 public void jackhmmer_actionPerformed(boolean withDefaults)
1246 * get default parameters, and (if requested) show
1247 * dialog to allow modification
1250 ParamDatastoreI store = HMMERParamStore.forJackhmmer(viewport);
1251 List<ArgumentI> args = store.getServiceParameters();
1255 WsParamSetI set = new HMMERPreset();
1256 WsJobParameters params = new WsJobParameters(store, set, args);
1257 params.showRunDialog().thenAccept((startJob) -> {
1260 var args2 = params.getJobParams();
1261 new Thread(new JackHMMER(this, args2)).start();
1262 alignPanel.repaint();
1268 new Thread(new JackHMMER(this, args)).start();
1269 alignPanel.repaint();
1274 * Checks if the alignment has at least one hidden Markov model, if not shows
1275 * a dialog advising to run hmmbuild or load an HMM profile
1279 private boolean checkForHMM()
1281 if (viewport.getAlignment().getHmmSequences().isEmpty())
1283 JOptionPane.showMessageDialog(this,
1284 MessageManager.getString("warn.no_hmm"));
1291 protected void filterByEValue_actionPerformed()
1293 viewport.filterByEvalue(inputDouble("Enter E-Value Cutoff"));
1297 protected void filterByScore_actionPerformed()
1299 viewport.filterByScore(inputDouble("Enter Bit Score Threshold"));
1302 private double inputDouble(String message)
1306 while (d == null || d <= 0)
1308 str = JOptionPane.showInputDialog(this.alignPanel, message);
1311 d = Double.valueOf(str);
1312 } catch (NumberFormatException e)
1320 * Checks if the alignment contains the required number of sequences.
1325 public boolean alignmentIsSufficient(int required)
1327 if (getViewport().getSequenceSelection().length < required)
1329 JOptionPane.showMessageDialog(this,
1330 MessageManager.getString("label.not_enough_sequences"));
1337 * Opens a file browser and adds the selected file, if in Fasta, Stockholm or
1338 * Pfam format, to the list held under preference key "HMMSEARCH_DBS" (as a
1339 * comma-separated list)
1342 public void addDatabase_actionPerformed() throws IOException
1344 if (Cache.getProperty(Preferences.HMMSEARCH_DBS) == null)
1346 Cache.setProperty(Preferences.HMMSEARCH_DBS, "");
1349 String path = openFileChooser(false);
1350 if (path != null && new File(path).exists())
1352 IdentifyFile identifier = new IdentifyFile();
1353 FileFormatI format = identifier.identify(path, DataSourceType.FILE);
1354 if (format == FileFormat.Fasta || format == FileFormat.Stockholm
1355 || format == FileFormat.Pfam)
1357 String currentDbPaths = Cache
1358 .getProperty(Preferences.HMMSEARCH_DBS);
1359 currentDbPaths += Preferences.COMMA + path;
1360 Cache.setProperty(Preferences.HMMSEARCH_DBS, currentDbPaths);
1364 JOptionPane.showMessageDialog(this,
1365 MessageManager.getString("warn.invalid_format"));
1371 * Opens a file chooser, optionally restricted to selecting folders
1372 * (directories) only. Answers the path to the selected file or folder, or
1373 * null if none is chosen.
1378 protected String openFileChooser(boolean forFolder)
1380 // TODO duplicates GPreferences method - relocate to JalviewFileChooser?
1381 String choice = null;
1382 JFileChooser chooser = new JFileChooser();
1385 chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1387 chooser.setDialogTitle(
1388 MessageManager.getString("label.open_local_file"));
1389 chooser.setToolTipText(MessageManager.getString("action.open"));
1391 int value = chooser.showOpenDialog(this);
1393 if (value == JFileChooser.APPROVE_OPTION)
1395 choice = chooser.getSelectedFile().getPath();
1401 public void reload_actionPerformed(ActionEvent e)
1403 if (fileName == null && fileObject == null)
1407 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1408 // originating file's format
1409 // TODO: work out how to recover feature settings for correct view(s) when
1410 // file is reloaded.
1411 if (FileFormat.Jalview.equals(currentFileFormat))
1413 JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
1414 for (int i = 0; i < frames.length; i++)
1416 if (frames[i] instanceof AlignFrame && frames[i] != this
1417 && ((AlignFrame) frames[i]).fileName != null
1418 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1422 frames[i].setSelected(true);
1423 Desktop.getInstance().closeAssociatedWindows();
1424 } catch (java.beans.PropertyVetoException ex)
1430 Desktop.getInstance().closeAssociatedWindows();
1432 FileLoader loader = new FileLoader();
1433 // DataSourceType protocol = fileName.startsWith("http:")
1434 // ? DataSourceType.URL
1435 // : DataSourceType.FILE;
1436 loader.LoadFile(viewport, (fileObject == null ? fileName : fileObject), protocol, currentFileFormat);
1440 Rectangle bounds = this.getBounds();
1442 FileLoader loader = new FileLoader();
1444 AlignFrame newframe = null;
1446 if (fileObject == null)
1448 newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1453 newframe = loader.LoadFileWaitTillLoaded(fileObject,
1454 DataSourceType.FILE, currentFileFormat);
1457 newframe.setBounds(bounds);
1458 if (featureSettings != null && featureSettings.isShowing())
1460 final Rectangle fspos = featureSettings.frame.getBounds();
1461 // TODO: need a 'show feature settings' function that takes bounds -
1462 // need to refactor Desktop.addFrame
1463 newframe.featureSettings_actionPerformed(null);
1464 final FeatureSettings nfs = newframe.featureSettings;
1465 SwingUtilities.invokeLater(new Runnable()
1471 nfs.frame.setBounds(fspos);
1474 this.featureSettings.close();
1475 this.featureSettings = null;
1477 this.closeMenuItem_actionPerformed(true);
1483 public void addFromText_actionPerformed(ActionEvent e)
1485 Desktop.getInstance()
1486 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1490 public void addFromURL_actionPerformed(ActionEvent e)
1492 Desktop.getInstance().inputURLMenuItem_actionPerformed(viewport);
1496 public void save_actionPerformed(ActionEvent e)
1498 if (fileName == null || (currentFileFormat == null)
1499 || fileName.startsWith("http"))
1501 saveAs_actionPerformed();
1505 saveAlignment(fileName, currentFileFormat);
1510 * Saves the alignment to a file with a name chosen by the user, if necessary
1511 * warning if a file would be overwritten
1515 public void saveAs_actionPerformed()
1517 String format = currentFileFormat == null ? null
1518 : currentFileFormat.getName();
1519 JalviewFileChooser chooser = JalviewFileChooser
1520 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1522 chooser.setFileView(new JalviewFileView());
1523 chooser.setDialogTitle(
1524 MessageManager.getString("label.save_alignment_to_file"));
1525 chooser.setToolTipText(MessageManager.getString("action.save"));
1527 int value = chooser.showSaveDialog(this);
1529 if (value != JalviewFileChooser.APPROVE_OPTION)
1533 currentFileFormat = chooser.getSelectedFormat();
1534 // todo is this (2005) test now obsolete - value is never null?
1535 while (currentFileFormat == null)
1537 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
1539 .getString("label.select_file_format_before_saving"),
1540 MessageManager.getString("label.file_format_not_specified"),
1541 JvOptionPane.WARNING_MESSAGE);
1542 currentFileFormat = chooser.getSelectedFormat();
1543 value = chooser.showSaveDialog(this);
1544 if (value != JalviewFileChooser.APPROVE_OPTION)
1550 fileName = chooser.getSelectedFile().getPath();
1552 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1553 Cache.setProperty("LAST_DIRECTORY", fileName);
1554 saveAlignment(fileName, currentFileFormat);
1557 boolean lastSaveSuccessful = false;
1559 FileFormatI lastFormatSaved;
1561 String lastFilenameSaved;
1564 * Raise a dialog or status message for the last call to saveAlignment.
1566 * @return true if last call to saveAlignment(file, format) was successful.
1569 public boolean isSaveAlignmentSuccessful()
1572 if (!lastSaveSuccessful)
1574 JvOptionPane.showInternalMessageDialog(this, MessageManager
1575 .formatMessage("label.couldnt_save_file", new Object[]
1576 { lastFilenameSaved }),
1577 MessageManager.getString("label.error_saving_file"),
1578 JvOptionPane.WARNING_MESSAGE);
1583 setStatus(MessageManager.formatMessage(
1584 "label.successfully_saved_to_file_in_format", new Object[]
1585 { lastFilenameSaved, lastFormatSaved }));
1588 return lastSaveSuccessful;
1592 * Saves the alignment to the specified file path, in the specified format,
1593 * which may be an alignment format, or Jalview project format. If the
1594 * alignment has hidden regions, or the format is one capable of including
1595 * non-sequence data (features, annotations, groups), then the user may be
1596 * prompted to specify what to include in the output.
1602 public void saveAlignment(String file, FileFormatI format)
1604 lastSaveSuccessful = true;
1605 lastFilenameSaved = file;
1606 lastFormatSaved = format;
1608 if (FileFormat.Jalview.equals(format))
1610 String shortName = title;
1611 if (shortName.indexOf(File.separatorChar) > -1)
1613 shortName = shortName
1614 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
1616 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file,
1619 statusBar.setText(MessageManager.formatMessage(
1620 "label.successfully_saved_to_file_in_format", new Object[]
1621 { fileName, format }));
1626 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1627 Runnable cancelAction = new Runnable()
1633 lastSaveSuccessful = false;
1636 Runnable outputAction = new Runnable()
1642 // todo defer this to inside formatSequences (or later)
1643 AlignmentExportData exportData = viewport
1644 .getAlignExportData(options);
1645 String output = new FormatAdapter(alignPanel, options)
1646 .formatSequences(format, exportData.getAlignment(),
1647 exportData.getOmitHidden(),
1648 exportData.getStartEndPostions(),
1649 viewport.getAlignment().getHiddenColumns());
1652 lastSaveSuccessful = false;
1656 // create backupfiles object and get new temp filename destination
1657 boolean doBackup = BackupFiles.getEnabled();
1658 BackupFiles backupfiles = doBackup ? new BackupFiles(file) : null;
1661 String tempFilePath = doBackup ? backupfiles.getTempFilePath()
1663 PrintWriter out = new PrintWriter(new FileWriter(tempFilePath));
1667 AlignFrame.this.setTitle(file);
1668 statusBar.setText(MessageManager.formatMessage(
1669 "label.successfully_saved_to_file_in_format",
1671 { fileName, format.getName() }));
1672 lastSaveSuccessful = true;
1673 } catch (Exception ex)
1675 lastSaveSuccessful = false;
1676 ex.printStackTrace();
1681 backupfiles.setWriteSuccess(lastSaveSuccessful);
1682 // do the backup file roll and rename the temp file to actual file
1683 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1690 * show dialog with export options if applicable; else just do it
1692 if (AlignExportOptions.isNeeded(viewport, format))
1694 AlignExportOptions choices = new AlignExportOptions(
1695 alignPanel.getAlignViewport(), format, options);
1696 choices.setResponseAction(0, outputAction);
1697 choices.setResponseAction(1, cancelAction);
1698 choices.showDialog();
1707 * Outputs the alignment to textbox in the requested format, if necessary
1708 * first prompting the user for whether to include hidden regions or
1711 * @param fileFormatName
1715 protected void outputText_actionPerformed(String fileFormatName)
1717 FileFormatI fileFormat = FileFormats.getInstance()
1718 .forName(fileFormatName);
1719 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1720 Runnable outputAction = new Runnable()
1726 // todo defer this to inside formatSequences (or later)
1727 AlignmentExportData exportData = viewport
1728 .getAlignExportData(options);
1729 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1730 cap.setForInput(null);
1733 FileFormatI format = fileFormat;
1734 cap.setText(new FormatAdapter(alignPanel, options)
1735 .formatSequences(format, exportData.getAlignment(),
1736 exportData.getOmitHidden(),
1737 exportData.getStartEndPostions(),
1738 viewport.getAlignment().getHiddenColumns()));
1739 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1740 "label.alignment_output_command", new Object[]
1741 { fileFormat.getName() }), 600, 500);
1742 } catch (OutOfMemoryError oom)
1744 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1752 * show dialog with export options if applicable; else just do it
1754 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1756 AlignExportOptions choices = new AlignExportOptions(
1757 alignPanel.getAlignViewport(), fileFormat, options);
1758 choices.setResponseAction(0, outputAction);
1759 choices.showDialog();
1775 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1777 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1778 htmlSVG.exportHTML(null);
1782 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1784 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1785 bjs.exportHTML(null);
1790 public void createImageMap(File file, String image)
1792 alignPanel.makePNGImageMap(file, image);
1796 * Creates a PNG image of the alignment and writes it to the given file. If
1797 * the file is null, the user is prompted to choose a file.
1803 public void createPNG(File f)
1805 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1809 * Creates an EPS image of the alignment and writes it to the given file. If
1810 * the file is null, the user is prompted to choose a file.
1816 public void createEPS(File f)
1818 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1822 * Creates an SVG image of the alignment and writes it to the given file. If
1823 * the file is null, the user is prompted to choose a file.
1829 public void createSVG(File f)
1831 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1835 public void pageSetup_actionPerformed(ActionEvent e)
1837 PrinterJob printJob = PrinterJob.getPrinterJob();
1838 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1849 public void printMenuItem_actionPerformed(ActionEvent e)
1851 // Putting in a thread avoids Swing painting problems
1852 PrintThread thread = new PrintThread(alignPanel);
1857 public void exportFeatures_actionPerformed(ActionEvent e)
1859 new AnnotationExporter(alignPanel).exportFeatures();
1863 public void exportAnnotations_actionPerformed(ActionEvent e)
1865 new AnnotationExporter(alignPanel).exportAnnotations();
1869 public void associatedData_actionPerformed(ActionEvent e)
1870 throws IOException, InterruptedException
1872 final JalviewFileChooser chooser = new JalviewFileChooser(
1873 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1874 chooser.setFileView(new JalviewFileView());
1875 String tooltip = MessageManager
1876 .getString("label.load_jalview_annotations");
1877 chooser.setDialogTitle(tooltip);
1878 chooser.setToolTipText(tooltip);
1879 chooser.setResponseHandler(0, new Runnable()
1885 String choice = chooser.getSelectedFile().getPath();
1886 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1887 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1891 chooser.showOpenDialog(this);
1895 * Close the current view or all views in the alignment frame. If the frame
1896 * only contains one view then the alignment will be removed from memory.
1898 * @param closeAllTabs
1902 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1904 if (alignPanels != null && alignPanels.size() < 2)
1906 closeAllTabs = true;
1911 if (alignPanels != null)
1915 if (this.isClosed())
1917 // really close all the windows - otherwise wait till
1918 // setClosed(true) is called
1919 for (int i = 0; i < alignPanels.size(); i++)
1921 AlignmentPanel ap = alignPanels.get(i);
1928 closeView(alignPanel);
1933 if (featureSettings != null && featureSettings.isOpen())
1935 featureSettings.close();
1936 featureSettings = null;
1939 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1940 * be called recursively, with the frame now in 'closed' state
1942 this.setClosed(true);
1944 } catch (Exception ex)
1946 ex.printStackTrace();
1951 * Close the specified panel and close up tabs appropriately.
1953 * @param panelToClose
1956 public void closeView(AlignmentPanel panelToClose)
1958 int index = tabbedPane.getSelectedIndex();
1959 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1960 alignPanels.remove(panelToClose);
1961 panelToClose.closePanel();
1962 panelToClose = null;
1964 tabbedPane.removeTabAt(closedindex);
1965 tabbedPane.validate();
1967 if (index > closedindex || index == tabbedPane.getTabCount())
1969 // modify currently selected tab index if necessary.
1973 this.tabSelectionChanged(index);
1980 void updateEditMenuBar()
1983 if (viewport.getHistoryList().size() > 0)
1985 undoMenuItem.setEnabled(true);
1986 CommandI command = viewport.getHistoryList().peek();
1987 undoMenuItem.setText(MessageManager
1988 .formatMessage("label.undo_command", new Object[]
1989 { command.getDescription() }));
1993 undoMenuItem.setEnabled(false);
1994 undoMenuItem.setText(MessageManager.getString("action.undo"));
1997 if (viewport.getRedoList().size() > 0)
1999 redoMenuItem.setEnabled(true);
2001 CommandI command = viewport.getRedoList().peek();
2002 redoMenuItem.setText(MessageManager
2003 .formatMessage("label.redo_command", new Object[]
2004 { command.getDescription() }));
2008 redoMenuItem.setEnabled(false);
2009 redoMenuItem.setText(MessageManager.getString("action.redo"));
2014 public void addHistoryItem(CommandI command)
2016 if (command.getSize() > 0)
2018 viewport.addToHistoryList(command);
2019 viewport.clearRedoList();
2020 updateEditMenuBar();
2021 viewport.updateHiddenColumns();
2022 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
2023 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2024 // viewport.getColumnSelection()
2025 // .getHiddenColumns().size() > 0);
2031 * @return alignment objects for all views
2034 AlignmentI[] getViewAlignments()
2036 if (alignPanels != null)
2038 AlignmentI[] als = new AlignmentI[alignPanels.size()];
2040 for (AlignmentPanel ap : alignPanels)
2042 als[i++] = ap.av.getAlignment();
2046 if (viewport != null)
2048 return new AlignmentI[] { viewport.getAlignment() };
2061 protected void undoMenuItem_actionPerformed(ActionEvent e)
2063 if (viewport.getHistoryList().isEmpty())
2067 CommandI command = viewport.getHistoryList().pop();
2068 viewport.addToRedoList(command);
2069 command.undoCommand(getViewAlignments());
2071 AlignmentViewport originalSource = getOriginatingSource(command);
2072 updateEditMenuBar();
2074 if (originalSource != null)
2076 if (originalSource != viewport)
2079 "Implementation worry: mismatch of viewport origin for undo");
2081 originalSource.updateHiddenColumns();
2082 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
2084 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2085 // viewport.getColumnSelection()
2086 // .getHiddenColumns().size() > 0);
2087 originalSource.notifyAlignment();
2100 protected void redoMenuItem_actionPerformed(ActionEvent e)
2102 if (viewport.getRedoList().size() < 1)
2107 CommandI command = viewport.getRedoList().pop();
2108 viewport.addToHistoryList(command);
2109 command.doCommand(getViewAlignments());
2111 AlignmentViewport originalSource = getOriginatingSource(command);
2112 updateEditMenuBar();
2114 if (originalSource != null)
2117 if (originalSource != viewport)
2120 "Implementation worry: mismatch of viewport origin for redo");
2122 originalSource.updateHiddenColumns();
2123 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
2125 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2126 // viewport.getColumnSelection()
2127 // .getHiddenColumns().size() > 0);
2128 originalSource.notifyAlignment();
2133 AlignmentViewport getOriginatingSource(CommandI command)
2135 AlignmentViewport originalSource = null;
2136 // For sequence removal and addition, we need to fire
2137 // the property change event FROM the viewport where the
2138 // original alignment was altered
2139 AlignmentI al = null;
2140 if (command instanceof EditCommand)
2142 EditCommand editCommand = (EditCommand) command;
2143 al = editCommand.getAlignment();
2144 List<Component> comps = PaintRefresher.components
2145 .get(viewport.getSequenceSetId());
2147 for (Component comp : comps)
2149 if (comp instanceof AlignmentPanel)
2151 if (al == ((AlignmentPanel) comp).av.getAlignment())
2153 originalSource = ((AlignmentPanel) comp).av;
2160 if (originalSource == null)
2162 // The original view is closed, we must validate
2163 // the current view against the closed view first
2166 PaintRefresher.validateSequences(al, viewport.getAlignment());
2169 originalSource = viewport;
2172 return originalSource;
2182 public void moveSelectedSequences(boolean up)
2184 SequenceGroup sg = viewport.getSelectionGroup();
2190 viewport.getAlignment().moveSelectedSequencesByOne(sg,
2191 viewport.getHiddenRepSequences(), up);
2192 alignPanel.paintAlignment(true, false);
2195 synchronized void slideSequences(boolean right, int size)
2197 List<SequenceI> sg = new ArrayList<>();
2198 if (viewport.cursorMode)
2200 sg.add(viewport.getAlignment()
2201 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
2203 else if (viewport.getSelectionGroup() != null
2204 && viewport.getSelectionGroup().getSize() != viewport
2205 .getAlignment().getHeight())
2207 sg = viewport.getSelectionGroup()
2208 .getSequences(viewport.getHiddenRepSequences());
2216 List<SequenceI> invertGroup = new ArrayList<>();
2218 for (SequenceI seq : viewport.getAlignment().getSequences())
2220 if (!sg.contains(seq))
2222 invertGroup.add(seq);
2226 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
2228 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
2229 for (int i = 0; i < invertGroup.size(); i++)
2231 seqs2[i] = invertGroup.get(i);
2234 SlideSequencesCommand ssc;
2237 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
2238 viewport.getGapCharacter());
2242 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
2243 viewport.getGapCharacter());
2246 int groupAdjustment = 0;
2247 if (ssc.getGapsInsertedBegin() && right)
2249 if (viewport.cursorMode)
2251 alignPanel.getSeqPanel().moveCursor(size, 0);
2255 groupAdjustment = size;
2258 else if (!ssc.getGapsInsertedBegin() && !right)
2260 if (viewport.cursorMode)
2262 alignPanel.getSeqPanel().moveCursor(-size, 0);
2266 groupAdjustment = -size;
2270 if (groupAdjustment != 0)
2272 viewport.getSelectionGroup().setStartRes(
2273 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
2274 viewport.getSelectionGroup().setEndRes(
2275 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
2279 * just extend the last slide command if compatible; but not if in
2280 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
2282 boolean appendHistoryItem = false;
2283 Deque<CommandI> historyList = viewport.getHistoryList();
2284 boolean inSplitFrame = getSplitViewContainer() != null;
2285 if (!inSplitFrame && historyList != null && historyList.size() > 0
2286 && historyList.peek() instanceof SlideSequencesCommand)
2288 appendHistoryItem = ssc.appendSlideCommand(
2289 (SlideSequencesCommand) historyList.peek());
2292 if (!appendHistoryItem)
2294 addHistoryItem(ssc);
2308 protected void copy_actionPerformed()
2310 if (viewport.getSelectionGroup() == null)
2314 // TODO: preserve the ordering of displayed alignment annotation in any
2315 // internal paste (particularly sequence associated annotation)
2316 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2317 String[] omitHidden = null;
2319 if (viewport.hasHiddenColumns())
2321 omitHidden = viewport.getViewAsString(true);
2324 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2325 seqs, omitHidden, null);
2327 StringSelection ss = new StringSelection(output);
2329 Desktop d = Desktop.getInstance();
2332 d.internalCopy = true;
2333 // Its really worth setting the clipboard contents
2334 // to empty before setting the large StringSelection!!
2335 Toolkit.getDefaultToolkit().getSystemClipboard()
2336 .setContents(new StringSelection(""), null);
2338 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2339 Desktop.getInstance());
2340 } catch (OutOfMemoryError er)
2342 new OOMWarning("copying region", er);
2346 HiddenColumns hiddenColumns = null;
2347 if (viewport.hasHiddenColumns())
2349 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2350 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2352 // create new HiddenColumns object with copy of hidden regions
2353 // between startRes and endRes, offset by startRes
2354 hiddenColumns = new HiddenColumns(
2355 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2356 hiddenCutoff, hiddenOffset);
2359 d.jalviewClipboard = new Object[] { seqs,
2360 viewport.getAlignment().getDataset(), hiddenColumns };
2361 setStatus(MessageManager.formatMessage(
2362 "label.copied_sequences_to_clipboard", new Object[]
2363 { Integer.valueOf(seqs.length).toString() }));
2371 * @throws InterruptedException
2372 * @throws IOException
2376 protected void pasteNew_actionPerformed(ActionEvent e)
2377 throws IOException, InterruptedException
2387 * @throws InterruptedException
2388 * @throws IOException
2392 protected void pasteThis_actionPerformed(ActionEvent e)
2393 throws IOException, InterruptedException
2399 * Paste contents of Jalview clipboard
2401 * @param newAlignment
2402 * true to paste to a new alignment, otherwise add to this.
2403 * @throws InterruptedException
2404 * @throws IOException
2406 void paste(boolean newAlignment) throws IOException, InterruptedException
2408 boolean externalPaste = true;
2411 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2412 Transferable contents = c.getContents(this);
2414 if (contents == null)
2423 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2424 if (str.length() < 1)
2429 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2431 } catch (OutOfMemoryError er)
2433 new OOMWarning("Out of memory pasting sequences!!", er);
2437 SequenceI[] sequences;
2438 boolean annotationAdded = false;
2439 AlignmentI alignment = null;
2441 Desktop d = Desktop.getInstance();
2443 if (d.jalviewClipboard != null)
2445 // The clipboard was filled from within Jalview, we must use the
2447 // And dataset from the copied alignment
2448 SequenceI[] newseq = (SequenceI[]) d.jalviewClipboard[0];
2449 // be doubly sure that we create *new* sequence objects.
2450 sequences = new SequenceI[newseq.length];
2451 for (int i = 0; i < newseq.length; i++)
2453 sequences[i] = new Sequence(newseq[i]);
2455 alignment = new Alignment(sequences);
2456 externalPaste = false;
2460 // parse the clipboard as an alignment.
2461 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2463 sequences = alignment.getSequencesArray();
2467 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2473 if (d.jalviewClipboard != null)
2475 // dataset is inherited
2476 alignment.setDataset((Alignment) d.jalviewClipboard[1]);
2480 // new dataset is constructed
2481 alignment.setDataset(null);
2483 alwidth = alignment.getWidth() + 1;
2487 AlignmentI pastedal = alignment; // preserve pasted alignment object
2488 // Add pasted sequences and dataset into existing alignment.
2489 alignment = viewport.getAlignment();
2490 alwidth = alignment.getWidth() + 1;
2491 // decide if we need to import sequences from an existing dataset
2492 boolean importDs = d.jalviewClipboard != null
2493 && d.jalviewClipboard[1] != alignment.getDataset();
2494 // importDs==true instructs us to copy over new dataset sequences from
2495 // an existing alignment
2496 Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2498 // minimum dataset set
2500 for (int i = 0; i < sequences.length; i++)
2504 newDs.addElement(null);
2506 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2508 if (importDs && ds != null)
2510 if (!newDs.contains(ds))
2512 newDs.setElementAt(ds, i);
2513 ds = new Sequence(ds);
2514 // update with new dataset sequence
2515 sequences[i].setDatasetSequence(ds);
2519 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2524 // copy and derive new dataset sequence
2525 sequences[i] = sequences[i].deriveSequence();
2526 alignment.getDataset()
2527 .addSequence(sequences[i].getDatasetSequence());
2528 // TODO: avoid creation of duplicate dataset sequences with a
2529 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2531 alignment.addSequence(sequences[i]); // merges dataset
2535 newDs.clear(); // tidy up
2537 if (alignment.getAlignmentAnnotation() != null)
2539 for (AlignmentAnnotation alan : alignment
2540 .getAlignmentAnnotation())
2542 if (alan.graphGroup > fgroup)
2544 fgroup = alan.graphGroup;
2548 if (pastedal.getAlignmentAnnotation() != null)
2550 // Add any annotation attached to alignment.
2551 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2552 for (int i = 0; i < alann.length; i++)
2554 annotationAdded = true;
2555 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2557 AlignmentAnnotation newann = new AlignmentAnnotation(
2559 if (newann.graphGroup > -1)
2561 if (newGraphGroups.size() <= newann.graphGroup
2562 || newGraphGroups.get(newann.graphGroup) == null)
2564 for (int q = newGraphGroups
2565 .size(); q <= newann.graphGroup; q++)
2567 newGraphGroups.add(q, null);
2569 newGraphGroups.set(newann.graphGroup,
2570 Integer.valueOf(++fgroup));
2572 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2576 newann.padAnnotation(alwidth);
2577 alignment.addAnnotation(newann);
2587 addHistoryItem(new EditCommand(
2588 MessageManager.getString("label.add_sequences"),
2589 Action.PASTE, sequences, 0, alignment.getWidth(),
2592 // Add any annotations attached to sequences
2593 for (int i = 0; i < sequences.length; i++)
2595 if (sequences[i].getAnnotation() != null)
2597 AlignmentAnnotation newann;
2598 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2600 annotationAdded = true;
2601 newann = sequences[i].getAnnotation()[a];
2602 newann.adjustForAlignment();
2603 newann.padAnnotation(alwidth);
2604 if (newann.graphGroup > -1)
2606 if (newann.graphGroup > -1)
2608 if (newGraphGroups.size() <= newann.graphGroup
2609 || newGraphGroups.get(newann.graphGroup) == null)
2611 for (int q = newGraphGroups
2612 .size(); q <= newann.graphGroup; q++)
2614 newGraphGroups.add(q, null);
2616 newGraphGroups.set(newann.graphGroup,
2617 Integer.valueOf(++fgroup));
2619 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2623 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2627 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2635 // propagate alignment changed.
2636 viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2637 if (annotationAdded)
2639 // Duplicate sequence annotation in all views.
2640 AlignmentI[] alview = this.getViewAlignments();
2641 for (int i = 0; i < sequences.length; i++)
2643 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2648 for (int avnum = 0; avnum < alview.length; avnum++)
2650 if (alview[avnum] != alignment)
2652 // duplicate in a view other than the one with input focus
2653 int avwidth = alview[avnum].getWidth() + 1;
2654 // this relies on sann being preserved after we
2655 // modify the sequence's annotation array for each duplication
2656 for (int a = 0; a < sann.length; a++)
2658 AlignmentAnnotation newann = new AlignmentAnnotation(
2660 sequences[i].addAlignmentAnnotation(newann);
2661 newann.padAnnotation(avwidth);
2662 alview[avnum].addAnnotation(newann); // annotation was
2663 // duplicated earlier
2664 // TODO JAL-1145 graphGroups are not updated for sequence
2665 // annotation added to several views. This may cause
2667 alview[avnum].setAnnotationIndex(newann, a);
2672 buildSortByAnnotationScoresMenu();
2674 viewport.notifyAlignment();
2675 if (alignPanels != null)
2677 for (AlignmentPanel ap : alignPanels)
2679 ap.validateAnnotationDimensions(false);
2684 alignPanel.validateAnnotationDimensions(false);
2690 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2692 String newtitle = new String("Copied sequences");
2694 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2696 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2697 af.viewport.setHiddenColumns(hc);
2700 // >>>This is a fix for the moment, until a better solution is
2702 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2703 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2704 .getFeatureRenderer());
2706 // TODO: maintain provenance of an alignment, rather than just make the
2707 // title a concatenation of operations.
2710 if (title.startsWith("Copied sequences"))
2716 newtitle = newtitle.concat("- from " + title);
2721 newtitle = new String("Pasted sequences");
2724 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2729 } catch (Exception ex)
2731 ex.printStackTrace();
2732 System.out.println("Exception whilst pasting: " + ex);
2733 // could be anything being pasted in here
2738 protected void expand_newalign(ActionEvent e)
2742 AlignmentI alignment = AlignmentUtils
2743 .expandContext(getViewport().getAlignment(), -1);
2744 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2746 String newtitle = new String("Flanking alignment");
2747 Desktop d = Desktop.getInstance();
2748 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2750 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2751 af.viewport.setHiddenColumns(hc);
2754 // >>>This is a fix for the moment, until a better solution is
2756 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2757 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2758 .getFeatureRenderer());
2760 // TODO: maintain provenance of an alignment, rather than just make the
2761 // title a concatenation of operations.
2763 if (title.startsWith("Copied sequences"))
2769 newtitle = newtitle.concat("- from " + title);
2773 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2775 } catch (Exception ex)
2777 ex.printStackTrace();
2778 System.out.println("Exception whilst pasting: " + ex);
2779 // could be anything being pasted in here
2780 } catch (OutOfMemoryError oom)
2782 new OOMWarning("Viewing flanking region of alignment", oom);
2787 * Action Cut (delete and copy) the selected region
2791 protected void cut_actionPerformed()
2793 copy_actionPerformed();
2794 delete_actionPerformed();
2798 * Performs menu option to Delete the currently selected region
2802 protected void delete_actionPerformed()
2805 SequenceGroup sg = viewport.getSelectionGroup();
2811 Runnable okAction = new Runnable()
2817 SequenceI[] cut = sg.getSequences()
2818 .toArray(new SequenceI[sg.getSize()]);
2820 addHistoryItem(new EditCommand(
2821 MessageManager.getString("label.cut_sequences"), Action.CUT,
2822 cut, sg.getStartRes(),
2823 sg.getEndRes() - sg.getStartRes() + 1,
2824 viewport.getAlignment()));
2826 viewport.setSelectionGroup(null);
2827 viewport.sendSelection();
2828 viewport.getAlignment().deleteGroup(sg);
2830 viewport.notifyAlignment();
2832 if (viewport.getAlignment().getHeight() < 1)
2836 AlignFrame.this.setClosed(true);
2837 } catch (Exception ex)
2847 * If the cut affects all sequences, prompt for confirmation
2849 boolean wholeHeight = sg.getSize() == viewport.getAlignment()
2851 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2852 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2853 if (wholeHeight && wholeWidth)
2855 JvOptionPane dialog = JvOptionPane
2856 .newOptionDialog(Desktop.getDesktopPane());
2857 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2858 Object[] options = new Object[] {
2859 MessageManager.getString("action.ok"),
2860 MessageManager.getString("action.cancel") };
2861 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2862 MessageManager.getString("label.delete_all"),
2863 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2864 options, options[0]);
2880 protected void deleteGroups_actionPerformed(ActionEvent e)
2882 if (avc.deleteGroups())
2884 updateAll(viewport.getSequenceSetId());
2888 private void updateAll(String id)
2892 // this will force a non-fast repaint of both the IdPanel and SeqPanel
2893 alignPanel.getIdPanel().getIdCanvas().setNoFastPaint();
2894 alignPanel.getSeqPanel().seqCanvas.setNoFastPaint();
2895 alignPanel.repaint();
2900 PaintRefresher.Refresh(this, id);
2901 alignPanel.paintAlignment(true, true);
2903 alignPanel.updateAnnotation();
2914 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2916 alignPanel.selectAllSequences();
2927 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2929 alignPanel.deselectAllSequences();
2940 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2942 SequenceGroup sg = viewport.getSelectionGroup();
2946 alignPanel.selectAllSequences();
2951 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2953 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2955 // JAL-2034 - should delegate to
2956 // alignPanel to decide if overview needs
2959 alignPanel.paintAlignment(true, false);
2960 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2961 viewport.sendSelection();
2965 public void invertColSel_actionPerformed(ActionEvent e)
2967 viewport.invertColumnSelection();
2968 alignPanel.paintAlignment(true, false);
2969 viewport.sendSelection();
2980 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2982 trimAlignment(true);
2993 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2995 trimAlignment(false);
2998 void trimAlignment(boolean trimLeft)
3000 ColumnSelection colSel = viewport.getColumnSelection();
3003 if (!colSel.isEmpty())
3007 column = colSel.getMin();
3011 column = colSel.getMax();
3015 if (viewport.getSelectionGroup() != null)
3017 seqs = viewport.getSelectionGroup()
3018 .getSequencesAsArray(viewport.getHiddenRepSequences());
3022 seqs = viewport.getAlignment().getSequencesArray();
3025 TrimRegionCommand trimRegion;
3028 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
3029 column, viewport.getAlignment());
3030 viewport.getRanges().setStartRes(0);
3034 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
3035 column, viewport.getAlignment());
3038 setStatus(MessageManager.formatMessage("label.removed_columns",
3040 { Integer.valueOf(trimRegion.getSize()).toString() }));
3042 addHistoryItem(trimRegion);
3044 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3046 if ((trimLeft && !sg.adjustForRemoveLeft(column))
3047 || (!trimLeft && !sg.adjustForRemoveRight(column)))
3049 viewport.getAlignment().deleteGroup(sg);
3053 viewport.notifyAlignment();
3066 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
3068 int start = 0, end = viewport.getAlignment().getWidth() - 1;
3071 if (viewport.getSelectionGroup() != null)
3073 seqs = viewport.getSelectionGroup()
3074 .getSequencesAsArray(viewport.getHiddenRepSequences());
3075 start = viewport.getSelectionGroup().getStartRes();
3076 end = viewport.getSelectionGroup().getEndRes();
3080 seqs = viewport.getAlignment().getSequencesArray();
3083 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
3084 "Remove Gapped Columns", seqs, start, end,
3085 viewport.getAlignment());
3087 addHistoryItem(removeGapCols);
3089 setStatus(MessageManager.formatMessage("label.removed_empty_columns",
3091 { Integer.valueOf(removeGapCols.getSize()).toString() }));
3093 // This is to maintain viewport position on first residue
3094 // of first sequence
3095 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3096 ViewportRanges ranges = viewport.getRanges();
3097 int startRes = seq.findPosition(ranges.getStartRes());
3098 // ShiftList shifts;
3099 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
3100 // edit.alColumnChanges=shifts.getInverse();
3101 // if (viewport.hasHiddenColumns)
3102 // viewport.getColumnSelection().compensateForEdits(shifts);
3103 ranges.setStartRes(seq.findIndex(startRes) - 1);
3104 viewport.notifyAlignment();
3117 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
3119 int start = 0, end = viewport.getAlignment().getWidth() - 1;
3122 if (viewport.getSelectionGroup() != null)
3124 seqs = viewport.getSelectionGroup()
3125 .getSequencesAsArray(viewport.getHiddenRepSequences());
3126 start = viewport.getSelectionGroup().getStartRes();
3127 end = viewport.getSelectionGroup().getEndRes();
3131 seqs = viewport.getAlignment().getSequencesArray();
3134 // This is to maintain viewport position on first residue
3135 // of first sequence
3136 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3137 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
3139 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
3140 viewport.getAlignment()));
3142 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
3143 viewport.notifyAlignment();
3155 public void padGapsMenuitem_actionPerformed(ActionEvent e)
3157 viewport.setPadGaps(padGapsMenuitem.isSelected());
3158 viewport.notifyAlignment();
3170 public void findMenuItem_actionPerformed(ActionEvent e)
3176 * Create a new view of the current alignment.
3180 public void newView_actionPerformed(ActionEvent e)
3182 newView(null, true);
3186 * Creates and shows a new view of the current alignment.
3189 * title of newly created view; if null, one will be generated
3190 * @param copyAnnotation
3191 * if true then duplicate all annnotation, groups and settings
3192 * @return new alignment panel, already displayed.
3195 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
3198 * Create a new AlignmentPanel (with its own, new Viewport)
3200 AlignmentPanel newap = new jalview.project.Jalview2XML()
3201 .copyAlignPanel(alignPanel);
3202 if (!copyAnnotation)
3205 * remove all groups and annotation except for the automatic stuff
3207 newap.av.getAlignment().deleteAllGroups();
3208 newap.av.getAlignment().deleteAllAnnotations(false);
3211 newap.av.setGatherViewsHere(false);
3213 if (viewport.getViewName() == null)
3215 viewport.setViewName(
3216 MessageManager.getString("label.view_name_original"));
3220 * Views share the same edits undo and redo stacks
3222 newap.av.setHistoryList(viewport.getHistoryList());
3223 newap.av.setRedoList(viewport.getRedoList());
3226 * copy any visualisation settings that are not saved in the project
3228 newap.av.setColourAppliesToAllGroups(
3229 viewport.getColourAppliesToAllGroups());
3232 * Views share the same mappings; need to deregister any new mappings
3233 * created by copyAlignPanel, and register the new reference to the shared
3236 newap.av.replaceMappings(viewport.getAlignment());
3239 * start up cDNA consensus (if applicable) now mappings are in place
3241 if (newap.av.initComplementConsensus())
3243 newap.refresh(true); // adjust layout of annotations
3246 newap.av.setViewName(getNewViewName(viewTitle));
3248 addAlignmentPanel(newap, true);
3249 newap.alignmentChanged();
3251 if (alignPanels.size() == 2)
3253 viewport.setGatherViewsHere(true);
3255 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
3260 * Make a new name for the view, ensuring it is unique within the current
3261 * sequenceSetId. (This used to be essential for Jalview Project archives, but
3262 * these now use viewId. Unique view names are still desirable for usability.)
3268 protected String getNewViewName(String viewTitle)
3270 int index = Desktop.getViewCount(viewport.getSequenceSetId());
3271 boolean addFirstIndex = false;
3272 if (viewTitle == null || viewTitle.trim().length() == 0)
3274 viewTitle = MessageManager.getString("action.view");
3275 addFirstIndex = true;
3279 index = 1;// we count from 1 if given a specific name
3281 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
3283 List<Component> comps = PaintRefresher.components
3284 .get(viewport.getSequenceSetId());
3286 List<String> existingNames = getExistingViewNames(comps);
3288 while (existingNames.contains(newViewName))
3290 newViewName = viewTitle + " " + (++index);
3296 * Returns a list of distinct view names found in the given list of
3297 * components. View names are held on the viewport of an AlignmentPanel.
3303 protected List<String> getExistingViewNames(List<Component> comps)
3305 List<String> existingNames = new ArrayList<>();
3306 for (Component comp : comps)
3308 if (comp instanceof AlignmentPanel)
3310 AlignmentPanel ap = (AlignmentPanel) comp;
3311 if (!existingNames.contains(ap.av.getViewName()))
3313 existingNames.add(ap.av.getViewName());
3317 return existingNames;
3321 * Explode tabbed views into separate windows.
3325 public void expandViews_actionPerformed(ActionEvent e)
3327 Desktop.explodeViews(this);
3331 * Gather views in separate windows back into a tabbed presentation.
3335 public void gatherViews_actionPerformed(ActionEvent e)
3337 Desktop.getInstance().gatherViews(this);
3348 public void font_actionPerformed(ActionEvent e)
3350 new FontChooser(alignPanel);
3361 protected void seqLimit_actionPerformed(ActionEvent e)
3363 viewport.setShowJVSuffix(seqLimits.isSelected());
3365 alignPanel.getIdPanel().getIdCanvas()
3366 .setPreferredSize(alignPanel.calculateIdWidth());
3367 alignPanel.paintAlignment(true, false);
3371 public void idRightAlign_actionPerformed(ActionEvent e)
3373 viewport.setRightAlignIds(idRightAlign.isSelected());
3374 alignPanel.paintAlignment(false, false);
3378 public void centreColumnLabels_actionPerformed(ActionEvent e)
3380 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3381 alignPanel.paintAlignment(false, false);
3387 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3391 protected void followHighlight_actionPerformed()
3394 * Set the 'follow' flag on the Viewport (and scroll to position if now
3397 final boolean state = this.followHighlightMenuItem.getState();
3398 viewport.setFollowHighlight(state);
3401 alignPanel.scrollToPosition(viewport.getSearchResults());
3413 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3415 viewport.setColourText(colourTextMenuItem.isSelected());
3416 alignPanel.paintAlignment(false, false);
3427 public void wrapMenuItem_actionPerformed(ActionEvent e)
3429 scaleAbove.setVisible(wrapMenuItem.isSelected());
3430 scaleLeft.setVisible(wrapMenuItem.isSelected());
3431 scaleRight.setVisible(wrapMenuItem.isSelected());
3432 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3433 alignPanel.updateLayout();
3437 public void showAllSeqs_actionPerformed(ActionEvent e)
3439 viewport.showAllHiddenSeqs();
3443 public void showAllColumns_actionPerformed(ActionEvent e)
3445 viewport.showAllHiddenColumns();
3446 alignPanel.paintAlignment(true, true);
3447 viewport.sendSelection();
3451 public void hideSelSequences_actionPerformed(ActionEvent e)
3453 viewport.hideAllSelectedSeqs();
3457 * called by key handler and the hide all/show all menu items
3463 protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3466 boolean hide = false;
3467 SequenceGroup sg = viewport.getSelectionGroup();
3468 if (!toggleSeqs && !toggleCols)
3470 // Hide everything by the current selection - this is a hack - we do the
3471 // invert and then hide
3472 // first check that there will be visible columns after the invert.
3473 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3474 && sg.getStartRes() <= sg.getEndRes()))
3476 // now invert the sequence set, if required - empty selection implies
3477 // that no hiding is required.
3480 invertSequenceMenuItem_actionPerformed(null);
3481 sg = viewport.getSelectionGroup();
3485 viewport.expandColSelection(sg, true);
3486 // finally invert the column selection and get the new sequence
3488 invertColSel_actionPerformed(null);
3495 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3497 hideSelSequences_actionPerformed(null);
3500 else if (!(toggleCols && viewport.hasSelectedColumns()))
3502 showAllSeqs_actionPerformed(null);
3508 if (viewport.hasSelectedColumns())
3510 hideSelColumns_actionPerformed(null);
3513 viewport.setSelectionGroup(sg);
3518 showAllColumns_actionPerformed(null);
3527 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3528 * event.ActionEvent)
3532 public void hideAllButSelection_actionPerformed(ActionEvent e)
3534 toggleHiddenRegions(false, false);
3535 viewport.sendSelection();
3542 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3547 public void hideAllSelection_actionPerformed(ActionEvent e)
3549 SequenceGroup sg = viewport.getSelectionGroup();
3550 viewport.expandColSelection(sg, false);
3551 viewport.hideAllSelectedSeqs();
3552 viewport.hideSelectedColumns();
3553 alignPanel.updateLayout();
3554 alignPanel.paintAlignment(true, true);
3555 viewport.sendSelection();
3562 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3567 public void showAllhidden_actionPerformed(ActionEvent e)
3569 viewport.showAllHiddenColumns();
3570 viewport.showAllHiddenSeqs();
3571 alignPanel.paintAlignment(true, true);
3572 viewport.sendSelection();
3576 public void hideSelColumns_actionPerformed(ActionEvent e)
3578 viewport.hideSelectedColumns();
3579 alignPanel.updateLayout();
3580 alignPanel.paintAlignment(true, true);
3581 viewport.sendSelection();
3585 public void hiddenMarkers_actionPerformed(ActionEvent e)
3587 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3599 protected void scaleAbove_actionPerformed(ActionEvent e)
3601 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3602 alignPanel.updateLayout();
3603 alignPanel.paintAlignment(true, false);
3614 protected void scaleLeft_actionPerformed(ActionEvent e)
3616 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3617 alignPanel.updateLayout();
3618 alignPanel.paintAlignment(true, false);
3629 protected void scaleRight_actionPerformed(ActionEvent e)
3631 viewport.setScaleRightWrapped(scaleRight.isSelected());
3632 alignPanel.updateLayout();
3633 alignPanel.paintAlignment(true, false);
3644 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3646 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3647 alignPanel.paintAlignment(false, false);
3658 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3660 viewport.setShowText(viewTextMenuItem.isSelected());
3661 alignPanel.paintAlignment(false, false);
3672 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3674 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3675 alignPanel.paintAlignment(false, false);
3678 public FeatureSettings featureSettings;
3681 public FeatureSettingsControllerI getFeatureSettingsUI()
3683 return featureSettings;
3687 public void featureSettings_actionPerformed(ActionEvent e)
3689 showFeatureSettingsUI();
3693 public FeatureSettingsControllerI showFeatureSettingsUI()
3695 if (featureSettings != null)
3697 featureSettings.closeOldSettings();
3698 featureSettings = null;
3700 if (!showSeqFeatures.isSelected())
3702 // make sure features are actually displayed
3703 showSeqFeatures.setSelected(true);
3704 showSeqFeatures_actionPerformed(null);
3706 featureSettings = new FeatureSettings(this);
3707 return featureSettings;
3711 * Set or clear 'Show Sequence Features'
3718 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3720 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3721 alignPanel.paintAlignment(true, true);
3725 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3726 * the annotations panel as a whole.
3728 * The options to show/hide all annotations should be enabled when the panel
3729 * is shown, and disabled when the panel is hidden.
3735 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3737 final boolean setVisible = annotationPanelMenuItem.isSelected();
3738 viewport.setShowAnnotation(setVisible);
3739 syncAnnotationMenuItems(setVisible);
3740 alignPanel.updateLayout();
3742 SwingUtilities.invokeLater(new Runnable() {
3747 alignPanel.updateScrollBarsFromRanges();
3753 private void syncAnnotationMenuItems(boolean setVisible)
3755 showAllSeqAnnotations.setEnabled(setVisible);
3756 hideAllSeqAnnotations.setEnabled(setVisible);
3757 showAllAlAnnotations.setEnabled(setVisible);
3758 hideAllAlAnnotations.setEnabled(setVisible);
3762 public void alignmentProperties()
3765 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3768 String content = MessageManager.formatMessage("label.html_content",
3770 { contents.toString() });
3773 if (Platform.isJS())
3775 JLabel textLabel = new JLabel();
3776 textLabel.setText(content);
3777 textLabel.setBackground(Color.WHITE);
3779 pane = new JPanel(new BorderLayout());
3780 ((JPanel) pane).setOpaque(true);
3781 pane.setBackground(Color.WHITE);
3782 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3791 JEditorPane editPane = new JEditorPane("text/html", "");
3792 editPane.setEditable(false);
3793 editPane.setText(content);
3797 JInternalFrame frame = new JInternalFrame();
3799 frame.getContentPane().add(new JScrollPane(pane));
3801 Desktop.addInternalFrame(frame, MessageManager
3802 .formatMessage("label.alignment_properties", new Object[]
3803 { getTitle() }), 500, 400);
3814 public void overviewMenuItem_actionPerformed(ActionEvent e)
3816 if (alignPanel.overviewPanel != null)
3821 JInternalFrame frame = new JInternalFrame();
3823 // BH 2019.07.26 we allow for an embedded
3824 // undecorated overview with defined size
3825 frame.setName(Platform.getAppID("overview"));
3827 Dimension dim = Platform.getDimIfEmbedded(frame, -1, -1);
3828 if (dim != null && dim.width == 0)
3830 dim = null; // hidden, not embedded
3832 OverviewPanel overview = new OverviewPanel(alignPanel, dim);
3834 frame.setContentPane(overview);
3837 dim = new Dimension();
3838 // was frame.getSize(), but that is 0,0 at this point;
3842 // we are imbedding, and so we have an undecorated frame
3843 // and we can set the the frame dimensions accordingly.
3845 // allowing for unresizable option using, style="resize:none"
3846 boolean resizable = (Platform.getEmbeddedAttribute(frame,
3847 "resize") != "none");
3848 Desktop.addInternalFrame(frame, MessageManager
3849 .formatMessage("label.overview_params", new Object[]
3850 { this.getTitle() }), Desktop.FRAME_MAKE_VISIBLE, dim.width,
3851 dim.height, resizable, Desktop.FRAME_ALLOW_ANY_SIZE);
3853 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3854 frame.addInternalFrameListener(
3855 new javax.swing.event.InternalFrameAdapter()
3859 public void internalFrameClosed(
3860 javax.swing.event.InternalFrameEvent evt)
3863 alignPanel.setOverviewPanel(null);
3866 if (getKeyListeners().length > 0)
3868 frame.addKeyListener(getKeyListeners()[0]);
3871 alignPanel.setOverviewPanel(overview);
3875 public void textColour_actionPerformed()
3877 new TextColourChooser().chooseColour(alignPanel, null);
3881 * public void covariationColour_actionPerformed() {
3883 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3888 public void annotationColour_actionPerformed()
3890 new AnnotationColourChooser(viewport, alignPanel);
3894 public void annotationColumn_actionPerformed(ActionEvent e)
3896 new AnnotationColumnChooser(viewport, alignPanel);
3900 * Action on the user checking or unchecking the option to apply the selected
3901 * colour scheme to all groups. If unchecked, groups may have their own
3902 * independent colour schemes.
3908 public void applyToAllGroups_actionPerformed(boolean selected)
3910 viewport.setColourAppliesToAllGroups(selected);
3914 * Action on user selecting a colour from the colour menu
3917 * the name (not the menu item label!) of the colour scheme
3921 public void changeColour_actionPerformed(String name)
3924 * 'User Defined' opens a panel to configure or load a
3925 * user-defined colour scheme
3927 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3929 new UserDefinedColours(alignPanel);
3934 * otherwise set the chosen colour scheme (or null for 'None')
3936 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3937 viewport, viewport.getAlignment(),
3938 viewport.getHiddenRepSequences());
3943 * Actions on setting or changing the alignment colour scheme
3949 public void changeColour(ColourSchemeI cs)
3951 // TODO: pull up to controller method
3952 ColourMenuHelper.setColourSelected(colourMenu, cs);
3954 viewport.setGlobalColourScheme(cs);
3956 alignPanel.paintAlignment(true, true);
3960 * Show the PID threshold slider panel
3964 protected void modifyPID_actionPerformed()
3966 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3967 alignPanel.getViewName());
3968 SliderPanel.showPIDSlider();
3972 * Show the Conservation slider panel
3976 protected void modifyConservation_actionPerformed()
3978 SliderPanel.setConservationSlider(alignPanel,
3979 viewport.getResidueShading(), alignPanel.getViewName());
3980 SliderPanel.showConservationSlider();
3984 * Action on selecting or deselecting (Colour) By Conservation
3988 public void conservationMenuItem_actionPerformed(boolean selected)
3990 modifyConservation.setEnabled(selected);
3991 viewport.setConservationSelected(selected);
3992 viewport.getResidueShading().setConservationApplied(selected);
3994 changeColour(viewport.getGlobalColourScheme());
3997 modifyConservation_actionPerformed();
4001 SliderPanel.hideConservationSlider();
4006 * Action on selecting or deselecting (Colour) Above PID Threshold
4010 public void abovePIDThreshold_actionPerformed(boolean selected)
4012 modifyPID.setEnabled(selected);
4013 viewport.setAbovePIDThreshold(selected);
4016 viewport.getResidueShading().setThreshold(0,
4017 viewport.isIgnoreGapsConsensus());
4020 changeColour(viewport.getGlobalColourScheme());
4023 modifyPID_actionPerformed();
4027 SliderPanel.hidePIDSlider();
4039 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
4041 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4042 AlignmentSorter.sortByPID(viewport.getAlignment(),
4043 viewport.getAlignment().getSequenceAt(0));
4044 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
4045 viewport.getAlignment()));
4046 alignPanel.paintAlignment(true, false);
4057 public void sortIDMenuItem_actionPerformed(ActionEvent e)
4059 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4060 AlignmentSorter.sortByID(viewport.getAlignment());
4062 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
4063 alignPanel.paintAlignment(true, false);
4074 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
4076 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4077 AlignmentSorter.sortByLength(viewport.getAlignment());
4078 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
4079 viewport.getAlignment()));
4080 alignPanel.paintAlignment(true, false);
4091 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
4093 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4094 AlignmentSorter.sortByGroup(viewport.getAlignment());
4095 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4096 viewport.getAlignment()));
4098 alignPanel.paintAlignment(true, false);
4102 public void sortEValueMenuItem_actionPerformed(ActionEvent e)
4104 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4105 AlignmentSorter.sortByEValue(viewport.getAlignment());
4106 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4107 viewport.getAlignment()));
4108 alignPanel.paintAlignment(true, false);
4113 public void sortBitScoreMenuItem_actionPerformed(ActionEvent e)
4115 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4116 AlignmentSorter.sortByBitScore(viewport.getAlignment());
4117 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4118 viewport.getAlignment()));
4119 alignPanel.paintAlignment(true, false);
4131 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
4133 new RedundancyPanel(alignPanel, this);
4144 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
4146 if ((viewport.getSelectionGroup() == null)
4147 || (viewport.getSelectionGroup().getSize() < 2))
4149 JvOptionPane.showInternalMessageDialog(this,
4150 MessageManager.getString(
4151 "label.you_must_select_least_two_sequences"),
4152 MessageManager.getString("label.invalid_selection"),
4153 JvOptionPane.WARNING_MESSAGE);
4157 JInternalFrame frame = new JInternalFrame();
4158 frame.setContentPane(new PairwiseAlignPanel(viewport));
4159 Desktop.addInternalFrame(frame,
4160 MessageManager.getString("action.pairwise_alignment"), 600,
4166 public void autoCalculate_actionPerformed(ActionEvent e)
4168 viewport.setAutoCalculateConsensusAndConservation(
4169 autoCalculate.isSelected());
4170 if (viewport.getAutoCalculateConsensusAndConservation())
4172 // viewport.autoCalculateConsensus = autoCalculate.isSelected();
4173 // if (viewport.autoCalculateConsensus)
4175 viewport.notifyAlignment();
4180 public void sortByTreeOption_actionPerformed(ActionEvent e)
4182 viewport.sortByTree = sortByTree.isSelected();
4186 protected void listenToViewSelections_actionPerformed(ActionEvent e)
4188 viewport.followSelection = listenToViewSelections.isSelected();
4192 * Constructs a tree panel and adds it to the desktop
4195 * tree type (NJ or AV)
4197 * name of score model used to compute the tree
4199 * parameters for the distance or similarity calculation
4202 void newTreePanel(String type, String modelName,
4203 SimilarityParamsI options)
4205 String frameTitle = "";
4208 boolean onSelection = false;
4209 if (viewport.getSelectionGroup() != null
4210 && viewport.getSelectionGroup().getSize() > 0)
4212 SequenceGroup sg = viewport.getSelectionGroup();
4214 /* Decide if the selection is a column region */
4215 for (SequenceI _s : sg.getSequences())
4217 if (_s.getLength() < sg.getEndRes())
4219 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4220 MessageManager.getString(
4221 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
4222 MessageManager.getString(
4223 "label.sequences_selection_not_aligned"),
4224 JvOptionPane.WARNING_MESSAGE);
4233 if (viewport.getAlignment().getHeight() < 2)
4239 tp = new TreePanel(alignPanel, type, modelName, options);
4240 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
4242 frameTitle += " from ";
4244 if (viewport.getViewName() != null)
4246 frameTitle += viewport.getViewName() + " of ";
4249 frameTitle += this.title;
4251 Dimension dim = Platform.getDimIfEmbedded(tp, 600, 500);
4252 Desktop.addInternalFrame(tp, frameTitle, dim.width, dim.height);
4264 public void addSortByOrderMenuItem(String title,
4265 final AlignmentOrder order)
4267 final JMenuItem item = new JMenuItem(MessageManager
4268 .formatMessage("action.by_title_param", new Object[]
4271 item.addActionListener(new java.awt.event.ActionListener()
4275 public void actionPerformed(ActionEvent e)
4277 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4279 // TODO: JBPNote - have to map order entries to curent SequenceI
4281 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4283 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
4284 viewport.getAlignment()));
4286 alignPanel.paintAlignment(true, false);
4292 * Add a new sort by annotation score menu item
4295 * the menu to add the option to
4297 * the label used to retrieve scores for each sequence on the
4301 public void addSortByAnnotScoreMenuItem(JMenu sort,
4302 final String scoreLabel)
4304 final JMenuItem item = new JMenuItem(scoreLabel);
4306 item.addActionListener(new java.awt.event.ActionListener()
4310 public void actionPerformed(ActionEvent e)
4312 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4313 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4314 viewport.getAlignment());// ,viewport.getSelectionGroup());
4315 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4316 viewport.getAlignment()));
4317 alignPanel.paintAlignment(true, false);
4323 * last hash for alignment's annotation array - used to minimise cost of
4326 protected int _annotationScoreVectorHash;
4329 * search the alignment and rebuild the sort by annotation score submenu the
4330 * last alignment annotation vector hash is stored to minimize cost of
4331 * rebuilding in subsequence calls.
4336 public void buildSortByAnnotationScoresMenu()
4338 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4343 if (viewport.getAlignment().getAlignmentAnnotation()
4344 .hashCode() == _annotationScoreVectorHash)
4349 sortByAnnotScore.removeAll();
4350 Set<String> scoreSorts = new HashSet<>();
4351 for (SequenceI sqa : viewport.getAlignment().getSequences())
4353 AlignmentAnnotation[] anns = sqa.getAnnotation();
4354 for (int i = 0; anns != null && i < anns.length; i++)
4356 AlignmentAnnotation aa = anns[i];
4357 if (aa != null && aa.hasScore() && aa.sequenceRef != null)
4359 scoreSorts.add(aa.label);
4363 for (String label : scoreSorts)
4365 addSortByAnnotScoreMenuItem(sortByAnnotScore, label);
4367 sortByAnnotScore.setVisible(!scoreSorts.isEmpty());
4369 _annotationScoreVectorHash = viewport.getAlignment()
4370 .getAlignmentAnnotation().hashCode();
4374 * Enable (or, if desired, make visible) the By Tree
4375 * submenu only if it has at least one element (or will have).
4379 protected void enableSortMenuOptions()
4381 List<TreePanel> treePanels = getTreePanels();
4382 sortByTreeMenu.setEnabled(!treePanels.isEmpty());
4386 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4387 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4388 * call. Listeners are added to remove the menu item when the treePanel is
4389 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4394 public void buildTreeSortMenu()
4396 sortByTreeMenu.removeAll();
4398 List<TreePanel> treePanels = getTreePanels();
4400 for (final TreePanel tp : treePanels)
4402 final JMenuItem item = new JMenuItem(tp.getTitle());
4403 item.addActionListener(new java.awt.event.ActionListener()
4407 public void actionPerformed(ActionEvent e)
4409 tp.sortByTree_actionPerformed();
4410 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4415 sortByTreeMenu.add(item);
4419 private List<TreePanel> getTreePanels()
4421 List<Component> comps = PaintRefresher.components
4422 .get(viewport.getSequenceSetId());
4423 List<TreePanel> treePanels = new ArrayList<>();
4424 for (Component comp : comps)
4426 if (comp instanceof TreePanel)
4428 treePanels.add((TreePanel) comp);
4434 public boolean sortBy(AlignmentOrder alorder, String undoname)
4436 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4437 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4438 if (undoname != null)
4440 addHistoryItem(new OrderCommand(undoname, oldOrder,
4441 viewport.getAlignment()));
4443 alignPanel.paintAlignment(true, false);
4448 * Work out whether the whole set of sequences or just the selected set will
4449 * be submitted for multiple alignment.
4453 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4455 // Now, check we have enough sequences
4456 AlignmentView msa = null;
4458 if ((viewport.getSelectionGroup() != null)
4459 && (viewport.getSelectionGroup().getSize() > 1))
4461 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4462 // some common interface!
4464 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4465 * SequenceI[sz = seqs.getSize(false)];
4467 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4468 * seqs.getSequenceAt(i); }
4470 msa = viewport.getAlignmentView(true);
4472 else if (viewport.getSelectionGroup() != null
4473 && viewport.getSelectionGroup().getSize() == 1)
4475 int option = JvOptionPane.showConfirmDialog(this,
4476 MessageManager.getString("warn.oneseq_msainput_selection"),
4477 MessageManager.getString("label.invalid_selection"),
4478 JvOptionPane.OK_CANCEL_OPTION);
4479 if (option == JvOptionPane.OK_OPTION)
4481 msa = viewport.getAlignmentView(false);
4486 msa = viewport.getAlignmentView(false);
4492 * Decides what is submitted to a secondary structure prediction service: the
4493 * first sequence in the alignment, or in the current selection, or, if the
4494 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4495 * region or the whole alignment. (where the first sequence in the set is the
4496 * one that the prediction will be for).
4499 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4501 AlignmentView seqs = null;
4503 if ((viewport.getSelectionGroup() != null)
4504 && (viewport.getSelectionGroup().getSize() > 0))
4506 seqs = viewport.getAlignmentView(true);
4510 seqs = viewport.getAlignmentView(false);
4512 // limit sequences - JBPNote in future - could spawn multiple prediction
4514 // TODO: viewport.getAlignment().isAligned is a global state - the local
4515 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4516 if (!viewport.getAlignment().isAligned(false))
4518 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4519 // TODO: if seqs.getSequences().length>1 then should really have warned
4534 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4536 // Pick the tree file
4537 JalviewFileChooser chooser = new JalviewFileChooser(
4538 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4539 chooser.setFileView(new JalviewFileView());
4540 chooser.setDialogTitle(
4541 MessageManager.getString("label.select_newick_like_tree_file"));
4542 chooser.setToolTipText(
4543 MessageManager.getString("label.load_tree_file"));
4545 chooser.setResponseHandler(0, new Runnable()
4551 String filePath = chooser.getSelectedFile().getPath();
4552 Cache.setProperty("LAST_DIRECTORY", filePath);
4553 NewickFile fin = null;
4556 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4557 DataSourceType.FILE));
4558 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4559 } catch (Exception ex)
4561 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4564 .getString("label.problem_reading_tree_file"),
4565 JvOptionPane.WARNING_MESSAGE);
4566 ex.printStackTrace();
4568 if (fin != null && fin.hasWarningMessage())
4570 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4571 fin.getWarningMessage(),
4572 MessageManager.getString(
4573 "label.possible_problem_with_tree_file"),
4574 JvOptionPane.WARNING_MESSAGE);
4578 chooser.showOpenDialog(this);
4581 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4583 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4586 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4587 int h, int x, int y)
4589 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4593 * Add a treeviewer for the tree extracted from a Newick file object to the
4594 * current alignment view
4601 * Associated alignment input data (or null)
4610 * @return TreePanel handle
4613 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4614 AlignmentView input, int w, int h, int x, int y)
4616 TreePanel tp = null;
4622 if (nf.getTree() != null)
4624 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4625 Dimension dim = Platform.getDimIfEmbedded(tp, -1, -1);
4628 dim = new Dimension(w, h);
4632 // no offset, either
4635 tp.setSize(dim.width, dim.height);
4639 tp.setLocation(x, y);
4642 Desktop.addInternalFrame(tp, treeTitle, dim.width, dim.height);
4644 } catch (Exception ex)
4646 ex.printStackTrace();
4653 * Schedule the web services menu rebuild to the event dispatch thread.
4655 public void buildWebServicesMenu()
4657 SwingUtilities.invokeLater(() -> {
4658 Cache.log.info("Rebuiling WS menu");
4659 webService.removeAll();
4660 if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
4662 Cache.log.info("Building web service menu for slivka");
4663 SlivkaWSDiscoverer discoverer = SlivkaWSDiscoverer.getInstance();
4664 JMenu submenu = new JMenu("Slivka");
4665 buildWebServicesMenu(discoverer, submenu);
4666 webService.add(submenu);
4668 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4670 WSDiscovererI jws2servs = Jws2Discoverer.getInstance();
4671 JMenu submenu = new JMenu("JABAWS");
4672 buildLegacyWebServicesMenu(submenu);
4673 buildWebServicesMenu(jws2servs, submenu);
4674 webService.add(submenu);
4676 build_fetchdbmenu(webService);
4680 private void buildLegacyWebServicesMenu(JMenu menu)
4682 JMenu secstrmenu = new JMenu("Secondary Structure Prediction");
4683 if (Discoverer.getServices() != null && Discoverer.getServices().size() > 0)
4685 var secstrpred = Discoverer.getServices().get("SecStrPred");
4686 if (secstrpred != null)
4688 for (ext.vamsas.ServiceHandle sh : secstrpred)
4690 var menuProvider = Discoverer.getServiceClient(sh);
4691 menuProvider.attachWSMenuEntry(secstrmenu, this);
4695 menu.add(secstrmenu);
4699 * Constructs the web services menu for the given discoverer under the
4700 * specified menu. This method must be called on the EDT
4703 * the discoverer used to build the menu
4705 * parent component which the elements will be attached to
4707 private void buildWebServicesMenu(WSDiscovererI discoverer, JMenu menu)
4709 if (discoverer.hasServices())
4711 PreferredServiceRegistry.getRegistry().populateWSMenuEntry(
4712 discoverer.getServices(), sv -> buildWebServicesMenu(), menu,
4715 if (discoverer.isRunning())
4717 JMenuItem item = new JMenuItem("Service discovery in progress.");
4718 item.setEnabled(false);
4721 else if (!discoverer.hasServices())
4723 JMenuItem item = new JMenuItem("No services available.");
4724 item.setEnabled(false);
4729 private void buildWebServicesMenu(WebServiceDiscoverer discoverer, JMenu menu)
4731 if (discoverer.hasServices())
4733 var services = new ArrayList<>(discoverer.getServices());
4734 services.sort(Comparator
4735 .<WebServiceI, String>comparing(o -> o.getHostName())
4736 .<String>thenComparing(o -> o.getName()));
4737 Map<String, String> lastHostForOperation = new HashMap<>();
4738 for (final WebServiceI service : services)
4740 var host = service.getHostName();
4741 for (Operation op : service.getOperations())
4743 JMenu atpoint = JvSwingUtils.findOrCreateMenu(menu, op.getTypeName());
4744 String lastHost = lastHostForOperation.get(op.getTypeName());
4745 if (lastHost != host) {
4746 if (lastHost != null)
4747 atpoint.addSeparator();
4748 var menuItem = new JMenuItem(host);
4749 menuItem.setForeground(Color.blue);
4750 menuItem.addActionListener(e -> Desktop.showUrl(host));
4751 atpoint.add(menuItem);
4752 lastHostForOperation.put(op.getTypeName(), host);
4754 atpoint.addSeparator();
4755 op.getMenuBuilder().buildMenu(atpoint, this);
4759 if (discoverer.isRunning())
4761 JMenuItem item = new JMenuItem("Service discovery in progress.");
4762 item.setEnabled(false);
4765 else if (!discoverer.hasServices())
4767 JMenuItem item = new JMenuItem("No services available.");
4768 item.setEnabled(false);
4774 * construct any groupURL type service menu entries.
4779 protected void build_urlServiceMenu(JMenu webService)
4781 // TODO: remove this code when 2.7 is released
4782 // DEBUG - alignmentView
4784 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4785 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4787 * public void actionPerformed(ActionEvent e) {
4788 * jalview.datamodel.AlignmentView
4789 * .testSelectionViews(af.viewport.getAlignment(),
4790 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4792 * }); webService.add(testAlView);
4794 // TODO: refactor to RestClient discoverer and merge menu entries for
4795 // rest-style services with other types of analysis/calculation service
4796 // SHmmr test client - still being implemented.
4797 // DEBUG - alignmentView
4799 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4802 client.attachWSMenuEntry(
4803 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4809 * Searches the alignment sequences for xRefs and builds the Show
4810 * Cross-References menu (formerly called Show Products), with database
4811 * sources for which cross-references are found (protein sources for a
4812 * nucleotide alignment and vice versa)
4814 * @return true if Show Cross-references menu should be enabled
4817 public boolean canShowProducts()
4819 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4820 AlignmentI dataset = viewport.getAlignment().getDataset();
4822 showProducts.removeAll();
4823 final boolean dna = viewport.getAlignment().isNucleotide();
4825 if (seqs == null || seqs.length == 0)
4827 // nothing to see here.
4831 boolean showp = false;
4834 List<String> ptypes = new CrossRef(seqs, dataset)
4835 .findXrefSourcesForSequences(dna);
4837 for (final String source : ptypes)
4840 final AlignFrame af = this;
4841 JMenuItem xtype = new JMenuItem(source);
4842 xtype.addActionListener(new ActionListener()
4846 public void actionPerformed(ActionEvent e)
4848 showProductsFor(af.viewport.getSequenceSelection(), dna,
4852 showProducts.add(xtype);
4854 showProducts.setVisible(showp);
4855 showProducts.setEnabled(showp);
4856 } catch (Exception e)
4859 "canShowProducts threw an exception - please report to help@jalview.org",
4867 * Finds and displays cross-references for the selected sequences (protein
4868 * products for nucleotide sequences, dna coding sequences for peptides).
4871 * the sequences to show cross-references for
4873 * true if from a nucleotide alignment (so showing proteins)
4875 * the database to show cross-references for
4878 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4879 final String source)
4881 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4886 * Construct and display a new frame containing the translation of this
4887 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4891 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4893 AlignmentI al = null;
4896 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4898 al = dna.translateCdna(codeTable);
4899 } catch (Exception ex)
4901 jalview.bin.Cache.log.error(
4902 "Exception during translation. Please report this !", ex);
4903 final String msg = MessageManager.getString(
4904 "label.error_when_translating_sequences_submit_bug_report");
4905 final String errorTitle = MessageManager
4906 .getString("label.implementation_error")
4907 + MessageManager.getString("label.translation_failed");
4908 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4909 errorTitle, JvOptionPane.ERROR_MESSAGE);
4912 if (al == null || al.getHeight() == 0)
4914 final String msg = MessageManager.getString(
4915 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4916 final String errorTitle = MessageManager
4917 .getString("label.translation_failed");
4918 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4919 errorTitle, JvOptionPane.WARNING_MESSAGE);
4923 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4924 af.setFileFormat(this.currentFileFormat);
4925 final String newTitle = MessageManager
4926 .formatMessage("label.translation_of_params", new Object[]
4927 { this.getTitle(), codeTable.getId() });
4928 af.setTitle(newTitle);
4929 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4931 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4932 AlignViewport.openSplitFrame(this, af, new Alignment(seqs));
4936 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4943 * Set the file format
4948 public void setFileFormat(FileFormatI format)
4950 this.currentFileFormat = format;
4954 * Try to load a features file onto the alignment.
4957 * contents or path to retrieve file or a File object
4959 * access mode of file (see jalview.io.AlignFile)
4960 * @return true if features file was parsed correctly.
4963 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4966 return avc.parseFeaturesFile(file, sourceType,
4967 Cache.getDefault(Preferences.RELAXEDSEQIDMATCHING, false));
4972 public void refreshFeatureUI(boolean enableIfNecessary)
4974 // note - currently this is only still here rather than in the controller
4975 // because of the featureSettings hard reference that is yet to be
4977 if (enableIfNecessary)
4979 viewport.setShowSequenceFeatures(true);
4980 showSeqFeatures.setSelected(true);
4986 public void dragEnter(DropTargetDragEvent evt)
4991 public void dragExit(DropTargetEvent evt)
4996 public void dragOver(DropTargetDragEvent evt)
5001 public void dropActionChanged(DropTargetDragEvent evt)
5006 public void drop(DropTargetDropEvent evt)
5008 // JAL-1552 - acceptDrop required before getTransferable call for
5009 // Java's Transferable for native dnd
5010 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
5011 Transferable t = evt.getTransferable();
5013 final List<Object> files = new ArrayList<>();
5014 List<DataSourceType> protocols = new ArrayList<>();
5018 Desktop.transferFromDropTarget(files, protocols, evt, t);
5019 if (files.size() > 0)
5021 new Thread(new Runnable()
5027 loadDroppedFiles(files, protocols, evt, t);
5031 } catch (Exception e)
5033 e.printStackTrace();
5037 protected void loadDroppedFiles(List<Object> files,
5038 List<DataSourceType> protocols, DropTargetDropEvent evt,
5043 // check to see if any of these files have names matching sequences
5046 SequenceIdMatcher idm = new SequenceIdMatcher(
5047 viewport.getAlignment().getSequencesArray());
5049 * Object[] { String,SequenceI}
5051 ArrayList<Object[]> filesmatched = new ArrayList<>();
5052 ArrayList<Object> filesnotmatched = new ArrayList<>();
5053 for (int i = 0; i < files.size(); i++)
5056 Object fileObj = files.get(i);
5057 String fileName = fileObj.toString();
5059 DataSourceType protocol = (fileObj instanceof File
5060 ? DataSourceType.FILE
5061 : FormatAdapter.checkProtocol(fileName));
5062 if (protocol == DataSourceType.FILE)
5065 if (fileObj instanceof File)
5067 file = (File) fileObj;
5068 Platform.cacheFileData(file);
5072 file = new File(fileName);
5074 pdbfn = file.getName();
5076 else if (protocol == DataSourceType.URL)
5078 URL url = new URL(fileName);
5079 pdbfn = url.getFile();
5081 if (pdbfn.length() > 0)
5083 // attempt to find a match in the alignment
5084 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5085 int l = 0, c = pdbfn.indexOf(".");
5086 while (mtch == null && c != -1)
5091 } while ((c = pdbfn.indexOf(".", l)) > l);
5094 pdbfn = pdbfn.substring(0, l);
5096 mtch = idm.findAllIdMatches(pdbfn);
5103 type = new IdentifyFile().identify(fileObj, protocol);
5104 } catch (Exception ex)
5108 if (type != null && type.isStructureFile())
5110 filesmatched.add(new Object[] { fileObj, protocol, mtch });
5114 // File wasn't named like one of the sequences or wasn't a PDB
5116 filesnotmatched.add(fileObj);
5120 if (filesmatched.size() > 0)
5122 boolean autoAssociate = Cache
5123 .getDefault(Preferences.AUTOASSOCIATE_PDBANDSEQS, false);
5126 String msg = MessageManager.formatMessage(
5127 "label.automatically_associate_structure_files_with_sequences_same_name",
5129 { Integer.valueOf(filesmatched.size()).toString() });
5130 String ttl = MessageManager.getString(
5131 "label.automatically_associate_structure_files_by_name");
5132 int choice = JvOptionPane.showConfirmDialog(this, msg, ttl,
5133 JvOptionPane.YES_NO_OPTION);
5134 autoAssociate = choice == JvOptionPane.YES_OPTION;
5138 for (Object[] fm : filesmatched)
5140 // try and associate
5141 // TODO: may want to set a standard ID naming formalism for
5142 // associating PDB files which have no IDs.
5143 for (SequenceI toassoc : (SequenceI[]) fm[2])
5145 PDBEntry pe = AssociatePdbFileWithSeq.associatePdbWithSeq(
5146 fm[0].toString(), (DataSourceType) fm[1], toassoc,
5150 System.err.println("Associated file : " + (fm[0].toString())
5151 + " with " + toassoc.getDisplayId(true));
5155 // TODO: do we need to update overview ? only if features are
5157 alignPanel.paintAlignment(true, false);
5163 * add declined structures as sequences
5165 for (Object[] o : filesmatched)
5167 filesnotmatched.add(o[0]);
5171 if (filesnotmatched.size() > 0)
5173 if (assocfiles > 0 && (Cache
5174 .getDefault("AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
5175 || JvOptionPane.showConfirmDialog(this,
5176 "<html>" + MessageManager.formatMessage(
5177 "label.ignore_unmatched_dropped_files_info",
5179 { Integer.valueOf(filesnotmatched.size())
5182 MessageManager.getString(
5183 "label.ignore_unmatched_dropped_files"),
5184 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
5188 for (Object fn : filesnotmatched)
5190 loadJalviewDataFile(fn, null, null, null);
5194 } catch (Exception ex)
5196 ex.printStackTrace();
5201 * Attempt to load a "dropped" file or URL string, by testing in turn for
5203 * <li>an Annotation file</li>
5204 * <li>a JNet file</li>
5205 * <li>a features file</li>
5206 * <li>else try to interpret as an alignment file</li>
5210 * either a filename or a URL string.
5211 * @throws InterruptedException
5212 * @throws IOException
5215 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
5216 FileFormatI format, SequenceI assocSeq)
5218 // BH 2018 was String file
5221 if (sourceType == null)
5223 sourceType = FormatAdapter.checkProtocol(file);
5225 // if the file isn't identified, or not positively identified as some
5226 // other filetype (PFAM is default unidentified alignment file type) then
5227 // try to parse as annotation.
5228 boolean isAnnotation = (format == null
5229 || FileFormat.Pfam.equals(format))
5230 ? new AnnotationFile().annotateAlignmentView(viewport,
5236 // first see if its a T-COFFEE score file
5237 TCoffeeScoreFile tcf = null;
5240 tcf = new TCoffeeScoreFile(file, sourceType);
5243 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5247 new TCoffeeColourScheme(viewport.getAlignment()));
5248 isAnnotation = true;
5249 setStatus(MessageManager.getString(
5250 "label.successfully_pasted_tcoffee_scores_to_alignment"));
5254 // some problem - if no warning its probable that the ID matching
5255 // process didn't work
5256 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
5257 tcf.getWarningMessage() == null
5258 ? MessageManager.getString(
5259 "label.check_file_matches_sequence_ids_alignment")
5260 : tcf.getWarningMessage(),
5261 MessageManager.getString(
5262 "label.problem_reading_tcoffee_score_file"),
5263 JvOptionPane.WARNING_MESSAGE);
5270 } catch (Exception x)
5273 "Exception when processing data source as T-COFFEE score file",
5279 // try to see if its a JNet 'concise' style annotation file *before*
5281 // try to parse it as a features file
5284 format = new IdentifyFile().identify(file, sourceType);
5286 if (FileFormat.ScoreMatrix == format)
5288 ScoreMatrixFile sm = new ScoreMatrixFile(
5289 new FileParse(file, sourceType));
5291 // todo: i18n this message
5292 setStatus(MessageManager.formatMessage(
5293 "label.successfully_loaded_matrix",
5294 sm.getMatrixName()));
5296 else if (FileFormat.Jnet.equals(format))
5298 JPredFile predictions = new JPredFile(file, sourceType);
5299 new JnetAnnotationMaker();
5300 JnetAnnotationMaker.add_annotation(predictions,
5301 viewport.getAlignment(), 0, false);
5302 viewport.getAlignment().setupJPredAlignment();
5303 isAnnotation = true;
5305 // else if (IdentifyFile.FeaturesFile.equals(format))
5306 else if (FileFormat.Features.equals(format))
5308 if (parseFeaturesFile(file, sourceType))
5310 SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
5311 if (splitFrame != null)
5313 splitFrame.repaint();
5317 alignPanel.paintAlignment(true, true);
5323 new FileLoader().LoadFile(viewport, file, sourceType, format);
5329 updateForAnnotations();
5331 } catch (Exception ex)
5333 ex.printStackTrace();
5334 } catch (OutOfMemoryError oom)
5339 } catch (Exception x)
5344 + (sourceType != null
5345 ? (sourceType == DataSourceType.PASTE
5347 : "using " + sourceType + " from "
5351 ? "(parsing as '" + format + "' file)"
5353 oom, Desktop.getDesktopPane());
5358 * Do all updates necessary after an annotation file such as jnet. Also called
5359 * from Jalview.loadAppletParams for "annotations", "jnetFile"
5362 public void updateForAnnotations()
5364 alignPanel.adjustAnnotationHeight();
5365 viewport.updateSequenceIdColours();
5366 buildSortByAnnotationScoresMenu();
5367 alignPanel.paintAlignment(true, true);
5371 * Change the display state for the given feature groups -- Added by BH from
5375 * list of group strings
5377 * visible or invisible
5380 public void setFeatureGroupState(String[] groups, boolean state)
5382 jalview.api.FeatureRenderer fr = null;
5383 viewport.setShowSequenceFeatures(true);
5384 if (alignPanel != null
5385 && (fr = alignPanel.getFeatureRenderer()) != null)
5388 fr.setGroupVisibility(Arrays.asList(groups), state);
5389 alignPanel.getSeqPanel().seqCanvas.repaint();
5390 if (alignPanel.overviewPanel != null)
5392 alignPanel.overviewPanel.updateOverviewImage();
5398 * Method invoked by the ChangeListener on the tabbed pane, in other words
5399 * when a different tabbed pane is selected by the user or programmatically.
5403 public void tabSelectionChanged(int index)
5407 alignPanel = alignPanels.get(index);
5408 viewport = alignPanel.av;
5409 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5410 setMenusFromViewport(viewport);
5411 if (featureSettings != null && featureSettings.isOpen()
5412 && featureSettings.fr.getViewport() != viewport)
5414 if (viewport.isShowSequenceFeatures())
5416 // refresh the featureSettings to reflect UI change
5417 showFeatureSettingsUI();
5421 // close feature settings for this view.
5422 featureSettings.close();
5429 * 'focus' any colour slider that is open to the selected viewport
5431 if (viewport.getConservationSelected())
5433 SliderPanel.setConservationSlider(alignPanel,
5434 viewport.getResidueShading(), alignPanel.getViewName());
5438 SliderPanel.hideConservationSlider();
5440 if (viewport.getAbovePIDThreshold())
5442 SliderPanel.setPIDSliderSource(alignPanel,
5443 viewport.getResidueShading(), alignPanel.getViewName());
5447 SliderPanel.hidePIDSlider();
5451 * If there is a frame linked to this one in a SplitPane, switch it to the
5452 * same view tab index. No infinite recursion of calls should happen, since
5453 * tabSelectionChanged() should not get invoked on setting the selected
5454 * index to an unchanged value. Guard against setting an invalid index
5455 * before the new view peer tab has been created.
5457 final AlignViewportI peer = viewport.getCodingComplement();
5460 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
5461 .getAlignPanel().alignFrame;
5462 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5464 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5470 * On right mouse click on view tab, prompt for and set new view name.
5474 public void tabbedPane_mousePressed(MouseEvent e)
5476 if (e.isPopupTrigger())
5478 String msg = MessageManager.getString("label.enter_view_name");
5479 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
5480 String reply = JvOptionPane.showInputDialog(msg, ttl);
5484 viewport.setViewName(reply);
5485 // TODO warn if reply is in getExistingViewNames()?
5486 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5491 public AlignViewport getCurrentView()
5497 * Open the dialog for regex description parsing.
5501 protected void extractScores_actionPerformed(ActionEvent e)
5503 ParseProperties pp = new jalview.analysis.ParseProperties(
5504 viewport.getAlignment());
5505 // TODO: verify regex and introduce GUI dialog for version 2.5
5506 // if (pp.getScoresFromDescription("col", "score column ",
5507 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5509 if (pp.getScoresFromDescription("description column",
5510 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5512 buildSortByAnnotationScoresMenu();
5520 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5525 protected void showDbRefs_actionPerformed(ActionEvent e)
5527 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5533 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5538 protected void showNpFeats_actionPerformed(ActionEvent e)
5540 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5544 * find the viewport amongst the tabs in this alignment frame and close that
5550 public boolean closeView(AlignViewportI av)
5554 this.closeMenuItem_actionPerformed(false);
5557 Component[] comp = tabbedPane.getComponents();
5558 for (int i = 0; comp != null && i < comp.length; i++)
5560 if (comp[i] instanceof AlignmentPanel)
5562 if (((AlignmentPanel) comp[i]).av == av)
5565 closeView((AlignmentPanel) comp[i]);
5573 protected void build_fetchdbmenu(JMenu webService)
5575 // Temporary hack - DBRef Fetcher always top level ws entry.
5576 // TODO We probably want to store a sequence database checklist in
5577 // preferences and have checkboxes.. rather than individual sources selected
5579 final JMenu rfetch = new JMenu(
5580 MessageManager.getString("action.fetch_db_references"));
5581 rfetch.setToolTipText(MessageManager.getString(
5582 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5583 webService.add(rfetch);
5585 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5586 MessageManager.getString("option.trim_retrieved_seqs"));
5587 trimrs.setToolTipText(
5588 MessageManager.getString("label.trim_retrieved_sequences"));
5590 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5591 trimrs.addActionListener(new ActionListener()
5595 public void actionPerformed(ActionEvent e)
5597 trimrs.setSelected(trimrs.isSelected());
5598 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5599 Boolean.valueOf(trimrs.isSelected()).toString());
5603 JMenuItem fetchr = new JMenuItem(
5604 MessageManager.getString("label.standard_databases"));
5605 fetchr.setToolTipText(
5606 MessageManager.getString("label.fetch_embl_uniprot"));
5607 fetchr.addActionListener(new ActionListener()
5611 public void actionPerformed(ActionEvent e)
5613 new Thread(new Runnable()
5619 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5620 .getAlignment().isNucleotide();
5621 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5622 alignPanel.av.getSequenceSelection(),
5623 alignPanel.alignFrame, null,
5624 alignPanel.alignFrame.featureSettings, isNucleotide);
5625 dbRefFetcher.addListener(new FetchFinishedListenerI()
5629 public void finished()
5632 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5633 .getFeatureSettingsModels())
5636 alignPanel.av.mergeFeaturesStyle(srcSettings);
5638 AlignFrame.this.setMenusForViewport();
5641 dbRefFetcher.fetchDBRefs(false);
5649 new Thread(new Runnable()
5656 // final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5657 // .getSequenceFetcherSingleton();
5658 javax.swing.SwingUtilities.invokeLater(new Runnable()
5664 jalview.ws.SequenceFetcher sf = jalview.ws.SequenceFetcher
5666 String[] dbclasses = sf.getNonAlignmentSources();
5667 List<DbSourceProxy> otherdb;
5668 JMenu dfetch = new JMenu();
5669 JMenu ifetch = new JMenu();
5670 JMenuItem fetchr = null;
5671 int comp = 0, icomp = 0, mcomp = 15;
5672 String mname = null;
5674 for (String dbclass : dbclasses)
5676 otherdb = sf.getSourceProxy(dbclass);
5677 // add a single entry for this class, or submenu allowing 'fetch
5679 if (otherdb == null || otherdb.size() < 1)
5685 mname = "From " + dbclass;
5687 if (otherdb.size() == 1)
5689 DbSourceProxy src = otherdb.get(0);
5690 DbSourceProxy[] dassource = new DbSourceProxy[] { src };
5691 fetchr = new JMenuItem(src.getDbSource());
5692 fetchr.addActionListener(new ActionListener()
5696 public void actionPerformed(ActionEvent e)
5698 new Thread(new Runnable()
5704 boolean isNucleotide = alignPanel.alignFrame
5705 .getViewport().getAlignment()
5707 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5708 alignPanel.av.getSequenceSelection(),
5709 alignPanel.alignFrame, dassource,
5710 alignPanel.alignFrame.featureSettings,
5713 .addListener(new FetchFinishedListenerI()
5717 public void finished()
5719 FeatureSettingsModelI srcSettings = dassource[0]
5720 .getFeatureColourScheme();
5721 alignPanel.av.mergeFeaturesStyle(
5723 AlignFrame.this.setMenusForViewport();
5726 dbRefFetcher.fetchDBRefs(false);
5732 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5733 MessageManager.formatMessage(
5734 "label.fetch_retrieve_from", new Object[]
5735 { src.getDbName() })));
5741 final DbSourceProxy[] dassource = otherdb
5742 .toArray(new DbSourceProxy[0]);
5744 DbSourceProxy src = otherdb.get(0);
5745 fetchr = new JMenuItem(MessageManager
5746 .formatMessage("label.fetch_all_param", new Object[]
5747 { src.getDbSource() }));
5748 fetchr.addActionListener(new ActionListener()
5752 public void actionPerformed(ActionEvent e)
5754 new Thread(new Runnable()
5760 boolean isNucleotide = alignPanel.alignFrame
5761 .getViewport().getAlignment()
5763 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5764 alignPanel.av.getSequenceSelection(),
5765 alignPanel.alignFrame, dassource,
5766 alignPanel.alignFrame.featureSettings,
5769 .addListener(new FetchFinishedListenerI()
5773 public void finished()
5775 AlignFrame.this.setMenusForViewport();
5778 dbRefFetcher.fetchDBRefs(false);
5784 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5785 MessageManager.formatMessage(
5786 "label.fetch_retrieve_from_all_sources",
5788 { Integer.valueOf(otherdb.size())
5790 src.getDbSource(), src.getDbName() })));
5793 // and then build the rest of the individual menus
5794 ifetch = new JMenu(MessageManager.formatMessage(
5795 "label.source_from_db_source", new Object[]
5796 { src.getDbSource() }));
5798 String imname = null;
5800 for (DbSourceProxy sproxy : otherdb)
5802 String dbname = sproxy.getDbName();
5803 String sname = dbname.length() > 5
5804 ? dbname.substring(0, 5) + "..."
5806 String msname = dbname.length() > 10
5807 ? dbname.substring(0, 10) + "..."
5811 imname = MessageManager
5812 .formatMessage("label.from_msname", new Object[]
5815 fetchr = new JMenuItem(msname);
5816 final DbSourceProxy[] dassrc = { sproxy };
5817 fetchr.addActionListener(new ActionListener()
5821 public void actionPerformed(ActionEvent e)
5823 new Thread(new Runnable()
5829 boolean isNucleotide = alignPanel.alignFrame
5830 .getViewport().getAlignment()
5832 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5833 alignPanel.av.getSequenceSelection(),
5834 alignPanel.alignFrame, dassrc,
5835 alignPanel.alignFrame.featureSettings,
5838 .addListener(new FetchFinishedListenerI()
5842 public void finished()
5844 AlignFrame.this.setMenusForViewport();
5847 dbRefFetcher.fetchDBRefs(false);
5853 fetchr.setToolTipText(
5854 "<html>" + MessageManager.formatMessage(
5855 "label.fetch_retrieve_from", new Object[]
5859 if (++icomp >= mcomp || i == (otherdb.size()))
5861 ifetch.setText(MessageManager.formatMessage(
5862 "label.source_to_target", imname, sname));
5864 ifetch = new JMenu();
5872 if (comp >= mcomp || dbi >= (dbclasses.length))
5874 dfetch.setText(MessageManager.formatMessage(
5875 "label.source_to_target", mname, dbclass));
5877 dfetch = new JMenu();
5890 * Left justify the whole alignment.
5894 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5896 viewport.getAlignment().justify(false);
5897 viewport.notifyAlignment();
5901 * Right justify the whole alignment.
5905 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5907 viewport.getAlignment().justify(true);
5908 viewport.notifyAlignment();
5912 public void setShowSeqFeatures(boolean b)
5914 showSeqFeatures.setSelected(b);
5915 viewport.setShowSequenceFeatures(b);
5922 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5923 * awt.event.ActionEvent)
5927 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5929 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5930 alignPanel.paintAlignment(false, false);
5937 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5942 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5944 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5945 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5953 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5954 * .event.ActionEvent)
5958 protected void showGroupConservation_actionPerformed(ActionEvent e)
5960 viewport.setShowGroupConservation(showGroupConservation.getState());
5961 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5968 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5969 * .event.ActionEvent)
5973 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5975 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5976 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5983 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5984 * .event.ActionEvent)
5988 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5990 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5991 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5995 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5997 showSequenceLogo.setState(true);
5998 viewport.setShowSequenceLogo(true);
5999 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
6000 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
6004 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
6006 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
6013 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
6014 * .event.ActionEvent)
6018 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
6020 if (avc.makeGroupsFromSelection())
6022 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
6023 alignPanel.updateAnnotation();
6024 alignPanel.paintAlignment(true,
6025 viewport.needToUpdateStructureViews());
6029 public void clearAlignmentSeqRep()
6031 // TODO refactor alignmentseqrep to controller
6032 if (viewport.getAlignment().hasSeqrep())
6034 viewport.getAlignment().setSeqrep(null);
6035 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
6036 alignPanel.updateAnnotation();
6037 alignPanel.paintAlignment(true, true);
6042 protected void createGroup_actionPerformed(ActionEvent e)
6044 if (avc.createGroup())
6046 if (applyAutoAnnotationSettings.isSelected())
6048 alignPanel.updateAnnotation(true, false);
6050 alignPanel.alignmentChanged();
6055 protected void unGroup_actionPerformed(ActionEvent e)
6059 alignPanel.alignmentChanged();
6064 * make the given alignmentPanel the currently selected tab
6066 * @param alignmentPanel
6069 public void setDisplayedView(AlignmentPanel alignmentPanel)
6071 if (!viewport.getSequenceSetId()
6072 .equals(alignmentPanel.av.getSequenceSetId()))
6074 throw new Error(MessageManager.getString(
6075 "error.implementation_error_cannot_show_view_alignment_frame"));
6077 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
6078 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
6080 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
6085 * Action on selection of menu options to Show or Hide annotations.
6088 * @param forSequences
6089 * update sequence-related annotations
6090 * @param forAlignment
6091 * update non-sequence-related annotations
6095 protected void setAnnotationsVisibility(boolean visible,
6096 boolean forSequences, boolean forAlignment)
6098 AlignmentAnnotation[] anns = alignPanel.getAlignment()
6099 .getAlignmentAnnotation();
6104 for (AlignmentAnnotation aa : anns)
6107 * don't display non-positional annotations on an alignment
6109 if (aa.annotations == null)
6113 boolean apply = (aa.sequenceRef == null && forAlignment)
6114 || (aa.sequenceRef != null && forSequences);
6117 aa.visible = visible;
6120 alignPanel.validateAnnotationDimensions(true);
6121 alignPanel.alignmentChanged();
6125 * Store selected annotation sort order for the view and repaint.
6129 protected void sortAnnotations_actionPerformed()
6131 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
6133 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
6134 alignPanel.paintAlignment(false, false);
6139 * @return alignment panels in this alignment frame
6142 public List<? extends AlignmentViewPanel> getAlignPanels()
6144 // alignPanels is never null
6145 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
6150 * Open a new alignment window, with the cDNA associated with this (protein)
6151 * alignment, aligned as is the protein.
6154 protected void viewAsCdna_actionPerformed()
6156 // TODO no longer a menu action - refactor as required
6157 final AlignmentI alignment = getViewport().getAlignment();
6158 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
6159 if (mappings == null)
6163 List<SequenceI> cdnaSeqs = new ArrayList<>();
6164 for (SequenceI aaSeq : alignment.getSequences())
6166 for (AlignedCodonFrame acf : mappings)
6168 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
6172 * There is a cDNA mapping for this protein sequence - add to new
6173 * alignment. It will share the same dataset sequence as other mapped
6174 * cDNA (no new mappings need to be created).
6176 final Sequence newSeq = new Sequence(dnaSeq);
6177 newSeq.setDatasetSequence(dnaSeq);
6178 cdnaSeqs.add(newSeq);
6182 if (cdnaSeqs.size() == 0)
6184 // show a warning dialog no mapped cDNA
6187 AlignmentI cdna = new Alignment(
6188 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
6189 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
6190 AlignFrame.DEFAULT_HEIGHT);
6191 cdna.alignAs(alignment);
6192 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
6194 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
6195 AlignFrame.DEFAULT_HEIGHT);
6199 * Set visibility of dna/protein complement view (available when shown in a
6206 protected void showComplement_actionPerformed(boolean show)
6208 SplitContainerI sf = getSplitViewContainer();
6211 sf.setComplementVisible(this, show);
6216 * Generate the reverse (optionally complemented) of the selected sequences,
6217 * and add them to the alignment
6221 protected void showReverse_actionPerformed(boolean complement)
6223 AlignmentI al = null;
6226 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
6227 al = dna.reverseCdna(complement);
6228 viewport.addAlignment(al, "");
6229 addHistoryItem(new EditCommand(
6230 MessageManager.getString("label.add_sequences"), Action.PASTE,
6231 al.getSequencesArray(), 0, al.getWidth(),
6232 viewport.getAlignment()));
6233 } catch (Exception ex)
6235 System.err.println(ex.getMessage());
6241 * Try to run a script in the Groovy console, having first ensured that this
6242 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
6243 * be targeted at this alignment.
6247 protected void runGroovy_actionPerformed()
6249 Jalview.setCurrentAlignFrame(this);
6250 groovy.ui.Console console = Desktop.getGroovyConsole();
6251 if (console != null)
6255 console.runScript();
6256 } catch (Exception ex)
6258 System.err.println((ex.toString()));
6259 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
6260 MessageManager.getString("label.couldnt_run_groovy_script"),
6261 MessageManager.getString("label.groovy_support_failed"),
6262 JvOptionPane.ERROR_MESSAGE);
6267 System.err.println("Can't run Groovy script as console not found");
6272 * Hides columns containing (or not containing) a specified feature, provided
6273 * that would not leave all columns hidden
6275 * @param featureType
6276 * @param columnsContaining
6280 public boolean hideFeatureColumns(String featureType,
6281 boolean columnsContaining)
6283 boolean notForHiding = avc.markColumnsContainingFeatures(
6284 columnsContaining, false, false, featureType);
6287 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
6288 false, featureType))
6290 getViewport().hideSelectedColumns();
6298 protected void selectHighlightedColumns_actionPerformed(
6299 ActionEvent actionEvent)
6301 // include key modifier check in case user selects from menu
6302 avc.markHighlightedColumns(
6303 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
6304 (actionEvent.getModifiers() & (ActionEvent.META_MASK
6305 | ActionEvent.CTRL_MASK)) != 0);
6309 * Rebuilds the Colour menu, including any user-defined colours which have
6310 * been loaded either on startup or during the session
6313 public void buildColourMenu()
6315 colourMenu.removeAll();
6317 colourMenu.add(applyToAllGroups);
6318 colourMenu.add(textColour);
6319 colourMenu.addSeparator();
6321 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
6322 viewport.getAlignment(), false);
6324 colourMenu.add(annotationColour);
6325 bg.add(annotationColour);
6326 colourMenu.addSeparator();
6327 colourMenu.add(conservationMenuItem);
6328 colourMenu.add(modifyConservation);
6329 colourMenu.add(abovePIDThreshold);
6330 colourMenu.add(modifyPID);
6332 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
6333 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
6337 * Open a dialog (if not already open) that allows the user to select and
6338 * calculate PCA or Tree analysis
6341 protected void openTreePcaDialog()
6343 if (alignPanel.getCalculationDialog() == null)
6345 new CalculationChooser(AlignFrame.this);
6350 * Sets the status of the HMMER menu
6352 public void updateHMMERStatus()
6354 hmmerMenu.setEnabled(HmmerCommand.isHmmerAvailable());
6358 protected void loadVcf_actionPerformed()
6360 JalviewFileChooser chooser = new JalviewFileChooser(
6361 Cache.getProperty("LAST_DIRECTORY"));
6362 chooser.setFileView(new JalviewFileView());
6363 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
6364 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
6365 final AlignFrame us = this;
6366 chooser.setResponseHandler(0, new Runnable()
6372 String choice = chooser.getSelectedFile().getPath();
6373 Cache.setProperty("LAST_DIRECTORY", choice);
6374 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
6375 new VCFLoader(choice).loadVCF(seqs, us);
6378 chooser.showOpenDialog(null);
6382 private Rectangle lastFeatureSettingsBounds = null;
6385 public void setFeatureSettingsGeometry(Rectangle bounds)
6387 lastFeatureSettingsBounds = bounds;
6391 public Rectangle getFeatureSettingsGeometry()
6393 return lastFeatureSettingsBounds;
6396 public void scrollTo(int row, int column)
6398 alignPanel.getSeqPanel().scrollTo(row, column);
6401 public void scrollToRow(int row)
6403 alignPanel.getSeqPanel().scrollToRow(row);
6406 public void scrollToColumn(int column)
6408 alignPanel.getSeqPanel().scrollToColumn(column);
6412 * BH 2019 from JalviewLite
6414 * get sequence feature groups that are hidden or shown
6421 public String[] getFeatureGroupsOfState(boolean visible)
6423 jalview.api.FeatureRenderer fr = null;
6424 if (alignPanel != null
6425 && (fr = alignPanel.getFeatureRenderer()) != null)
6427 List<String> gps = fr.getGroups(visible);
6428 String[] _gps = gps.toArray(new String[gps.size()]);
6436 * @return list of feature groups on the view
6439 public String[] getFeatureGroups()
6441 jalview.api.FeatureRenderer fr = null;
6442 if (alignPanel != null
6443 && (fr = alignPanel.getFeatureRenderer()) != null)
6445 List<String> gps = fr.getFeatureGroups();
6446 String[] _gps = gps.toArray(new String[gps.size()]);
6452 public void select(SequenceGroup sel, ColumnSelection csel,
6453 HiddenColumns hidden)
6455 alignPanel.getSeqPanel().selection(sel, csel, hidden, null);
6463 static class PrintThread extends Thread
6467 public PrintThread(AlignmentPanel ap)
6472 static PageFormat pf;
6477 PrinterJob printJob = PrinterJob.getPrinterJob();
6481 printJob.setPrintable(ap, pf);
6485 printJob.setPrintable(ap);
6488 if (printJob.printDialog())
6493 } catch (Exception PrintException)
6495 PrintException.printStackTrace();