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.ws.slivkaws.SlivkaWSDiscoverer;
119 import java.io.IOException;
120 import java.util.HashSet;
121 import java.util.Set;
123 import javax.swing.JFileChooser;
124 import javax.swing.JOptionPane;
126 import java.awt.BorderLayout;
127 import java.awt.Color;
128 import java.awt.Component;
129 import java.awt.Dimension;
130 import java.awt.Rectangle;
131 import java.awt.Toolkit;
132 import java.awt.datatransfer.Clipboard;
133 import java.awt.datatransfer.DataFlavor;
134 import java.awt.datatransfer.StringSelection;
135 import java.awt.datatransfer.Transferable;
136 import java.awt.dnd.DnDConstants;
137 import java.awt.dnd.DropTargetDragEvent;
138 import java.awt.dnd.DropTargetDropEvent;
139 import java.awt.dnd.DropTargetEvent;
140 import java.awt.dnd.DropTargetListener;
141 import java.awt.event.ActionEvent;
142 import java.awt.event.ActionListener;
143 import java.awt.event.FocusAdapter;
144 import java.awt.event.FocusEvent;
145 import java.awt.event.ItemEvent;
146 import java.awt.event.ItemListener;
147 import java.awt.event.KeyAdapter;
148 import java.awt.event.KeyEvent;
149 import java.awt.event.MouseEvent;
150 import java.awt.print.PageFormat;
151 import java.awt.print.PrinterJob;
152 import java.beans.PropertyChangeEvent;
153 import java.beans.PropertyChangeListener;
155 import java.io.FileWriter;
156 import java.io.PrintWriter;
158 import java.util.ArrayList;
159 import java.util.Arrays;
160 import java.util.Collection;
161 import java.util.Deque;
162 import java.util.Enumeration;
163 import java.util.Hashtable;
164 import java.util.List;
165 import java.util.Vector;
167 import javax.swing.ButtonGroup;
168 import javax.swing.JCheckBoxMenuItem;
169 import javax.swing.JComponent;
170 import javax.swing.JEditorPane;
171 import javax.swing.JInternalFrame;
172 import javax.swing.JLabel;
173 import javax.swing.JLayeredPane;
174 import javax.swing.JMenu;
175 import javax.swing.JMenuItem;
176 import javax.swing.JPanel;
177 import javax.swing.JScrollPane;
178 import javax.swing.SwingUtilities;
179 import javax.swing.event.InternalFrameAdapter;
180 import javax.swing.event.InternalFrameEvent;
182 import ext.vamsas.ServiceHandle;
188 * @version $Revision$
190 @SuppressWarnings("serial")
191 public class AlignFrame extends GAlignFrame
192 implements DropTargetListener, IProgressIndicator,
193 AlignViewControllerGuiI, ColourChangeListener, ServiceChangeListener
196 public static int frameCount;
198 public static final int DEFAULT_WIDTH = 700;
200 public static final int DEFAULT_HEIGHT = 500;
203 * The currently displayed panel (selected tabbed view if more than one)
205 public AlignmentPanel alignPanel;
207 AlignViewport viewport;
209 public AlignViewControllerI avc;
211 List<AlignmentPanel> alignPanels = new ArrayList<>();
214 * Last format used to load or save alignments in this window
216 FileFormatI currentFileFormat = null;
219 * Current filename for this alignment
221 String fileName = null;
224 * TODO: remove reference to 'FileObject' in AlignFrame - not correct mapping
230 private DataSourceType protocol ;
233 * Creates a new AlignFrame object with specific width and height.
239 public AlignFrame(AlignmentI al, int width, int height)
241 this(al, null, width, height);
245 * Creates a new AlignFrame object with specific width, height and
251 * @param sequenceSetId
253 public AlignFrame(AlignmentI al, int width, int height,
254 String sequenceSetId)
256 this(al, null, width, height, sequenceSetId);
260 * Creates a new AlignFrame object with specific width, height and
266 * @param sequenceSetId
269 public AlignFrame(AlignmentI al, int width, int height,
270 String sequenceSetId, String viewId)
272 this(al, null, width, height, sequenceSetId, viewId);
276 * new alignment window with hidden columns
280 * @param hiddenColumns
281 * ColumnSelection or null
283 * Width of alignment frame
287 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
290 this(al, hiddenColumns, width, height, null);
294 * Create alignment frame for al with hiddenColumns, a specific width and
295 * height, and specific sequenceId
298 * @param hiddenColumns
301 * @param sequenceSetId
304 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
305 int height, String sequenceSetId)
307 this(al, hiddenColumns, width, height, sequenceSetId, null);
311 * Create alignment frame for al with hiddenColumns, a specific width and
312 * height, and specific sequenceId
315 * @param hiddenColumns
318 * @param sequenceSetId
323 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
324 int height, String sequenceSetId, String viewId)
329 setSize(width, height);
331 if (al.getDataset() == null)
336 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
338 // JalviewJS needs to distinguish a new panel from an old one in init()
339 // alignPanel = new AlignmentPanel(this, viewport);
340 // addAlignmentPanel(alignPanel, true);
344 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
345 HiddenColumns hiddenColumns, int width, int height)
347 setSize(width, height);
349 if (al.getDataset() == null)
354 viewport = new AlignViewport(al, hiddenColumns);
356 if (hiddenSeqs != null && hiddenSeqs.length > 0)
358 viewport.hideSequence(hiddenSeqs);
360 // alignPanel = new AlignmentPanel(this, viewport);
361 // addAlignmentPanel(alignPanel, true);
366 * Make a new AlignFrame from existing alignmentPanels
373 public AlignFrame(AlignmentPanel ap)
377 // addAlignmentPanel(ap, false);
382 * initalise the alignframe from the underlying viewport data and the
388 boolean newPanel = (alignPanel == null);
389 viewport.setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
394 // need to set this up front if NOANNOTATION is
395 // used in conjunction with SHOWOVERVIEW.
397 // I have not determined if this is appropriate for
398 // Jalview/Java, as it means we are setting this flag
399 // for all subsequent AlignFrames. For now, at least,
400 // I am setting it to be JalviewJS-only.
402 boolean showAnnotation = Jalview.getInstance().getShowAnnotation();
403 viewport.setShowAnnotation(showAnnotation);
405 alignPanel = new AlignmentPanel(this, viewport);
407 addAlignmentPanel(alignPanel, newPanel);
409 // setBackground(Color.white); // BH 2019
411 if (!Jalview.isHeadlessMode())
413 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
415 statusPanel.setVisible(Jalview.getInstance().getShowStatus());
416 alignFrameMenuBar.setVisible(Jalview.getInstance().getAllowMenuBar());
419 avc = new jalview.controller.AlignViewController(this, viewport,
421 if (viewport.getAlignmentConservationAnnotation() == null)
423 // BLOSUM62Colour.setEnabled(false);
424 conservationMenuItem.setEnabled(false);
425 modifyConservation.setEnabled(false);
426 // PIDColour.setEnabled(false);
427 // abovePIDThreshold.setEnabled(false);
428 // modifyPID.setEnabled(false);
431 String sortby = jalview.bin.Cache.getDefault(Preferences.SORT_ALIGNMENT,
434 if (sortby.equals("Id"))
436 sortIDMenuItem_actionPerformed(null);
438 else if (sortby.equals("Pairwise Identity"))
440 sortPairwiseMenuItem_actionPerformed(null);
445 // this.alignPanel.av
446 // .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
448 setMenusFromViewport(viewport);
449 buildSortByAnnotationScoresMenu();
450 calculateTree.addActionListener(new ActionListener()
454 public void actionPerformed(ActionEvent e)
461 if (Desktop.getDesktopPane() != null)
463 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
464 addServiceListeners();
465 if (!Platform.isJS())
471 if (viewport.getWrapAlignment())
473 wrapMenuItem_actionPerformed(null);
476 if (jalview.bin.Cache.getDefault(Preferences.SHOW_OVERVIEW, false))
478 this.overviewMenuItem_actionPerformed(null);
483 final List<AlignmentPanel> selviews = new ArrayList<>();
484 final List<AlignmentPanel> origview = new ArrayList<>();
485 final String menuLabel = MessageManager
486 .getString("label.copy_format_from");
487 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
488 new ViewSetProvider()
492 public AlignmentPanel[] getAllAlignmentPanels()
495 origview.add(alignPanel);
496 // make an array of all alignment panels except for this one
497 List<AlignmentPanel> aps = new ArrayList<>(
498 Arrays.asList(Desktop.getAlignmentPanels(null)));
499 aps.remove(AlignFrame.this.alignPanel);
500 return aps.toArray(new AlignmentPanel[aps.size()]);
502 }, selviews, new ItemListener()
506 public void itemStateChanged(ItemEvent e)
508 if (origview.size() > 0)
510 final AlignmentPanel ap = origview.get(0);
513 * Copy the ViewStyle of the selected panel to 'this one'.
514 * Don't change value of 'scaleProteinAsCdna' unless copying
517 ViewStyleI vs = selviews.get(0).getAlignViewport()
519 boolean fromSplitFrame = selviews.get(0)
520 .getAlignViewport().getCodingComplement() != null;
523 vs.setScaleProteinAsCdna(ap.getAlignViewport()
524 .getViewStyle().isScaleProteinAsCdna());
526 ap.getAlignViewport().setViewStyle(vs);
529 * Also rescale ViewStyle of SplitFrame complement if there is
530 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
531 * the whole ViewStyle (allow cDNA protein to have different
534 AlignViewportI complement = ap.getAlignViewport()
535 .getCodingComplement();
536 if (complement != null && vs.isScaleProteinAsCdna())
538 AlignFrame af = Desktop.getAlignFrameFor(complement);
539 ((SplitFrame) af.getSplitViewContainer())
541 af.setMenusForViewport();
545 ap.setSelected(true);
546 ap.alignFrame.setMenusForViewport();
551 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
552 .indexOf("devel") > -1
553 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
554 .indexOf("test") > -1)
556 formatMenu.add(vsel);
558 addFocusListener(new FocusAdapter()
562 public void focusGained(FocusEvent e)
564 Jalview.setCurrentAlignFrame(AlignFrame.this);
571 * Change the filename and format for the alignment, and enable the 'reload'
572 * button functionality.
581 public void setFileName(String file, FileFormatI format)
584 setFileFormat(format);
585 reload.setEnabled(true);
591 * @param file from SwingJS; may contain bytes -- for reload
592 * @param protocol from SwingJS; may be RELATIVE_URL
595 public void setFile(String fileName, File file, DataSourceType protocol, FileFormatI format)
597 this.fileName = fileName;
598 this.fileObject = file;
599 this.protocol = protocol;
600 setFileFormat(format);
601 reload.setEnabled(true);
605 * JavaScript will have this, maybe others. More dependable than a file name
606 * and maintains a reference to the actual bytes loaded.
611 public void setFileObject(File file)
613 this.fileObject = file;
617 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
621 void addKeyListener()
623 addKeyListener(new KeyAdapter()
627 public void keyPressed(KeyEvent evt)
629 if (viewport.cursorMode
630 && ((evt.getKeyCode() >= KeyEvent.VK_0
631 && evt.getKeyCode() <= KeyEvent.VK_9)
632 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
633 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
634 && Character.isDigit(evt.getKeyChar()))
636 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
639 switch (evt.getKeyCode())
642 case KeyEvent.VK_ESCAPE: // escape key
643 // alignPanel.deselectAllSequences();
644 alignPanel.deselectAllSequences();
648 case KeyEvent.VK_DOWN:
649 if (evt.isAltDown() || !viewport.cursorMode)
651 moveSelectedSequences(false);
653 if (viewport.cursorMode)
655 alignPanel.getSeqPanel().moveCursor(0, 1);
660 if (evt.isAltDown() || !viewport.cursorMode)
662 moveSelectedSequences(true);
664 if (viewport.cursorMode)
666 alignPanel.getSeqPanel().moveCursor(0, -1);
671 case KeyEvent.VK_LEFT:
672 if (evt.isAltDown() || !viewport.cursorMode)
674 slideSequences(false,
675 alignPanel.getSeqPanel().getKeyboardNo1());
679 alignPanel.getSeqPanel().moveCursor(-1, 0);
684 case KeyEvent.VK_RIGHT:
685 if (evt.isAltDown() || !viewport.cursorMode)
687 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
691 alignPanel.getSeqPanel().moveCursor(1, 0);
695 case KeyEvent.VK_SPACE:
696 if (viewport.cursorMode)
698 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
699 || evt.isShiftDown() || evt.isAltDown());
703 // case KeyEvent.VK_A:
704 // if (viewport.cursorMode)
706 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
707 // //System.out.println("A");
711 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
712 * System.out.println("closing bracket"); } break;
714 case KeyEvent.VK_DELETE:
715 case KeyEvent.VK_BACK_SPACE:
716 if (!viewport.cursorMode)
718 cut_actionPerformed();
722 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
723 || evt.isShiftDown() || evt.isAltDown());
729 if (viewport.cursorMode)
731 alignPanel.getSeqPanel().setCursorRow();
735 if (viewport.cursorMode && !evt.isControlDown())
737 alignPanel.getSeqPanel().setCursorColumn();
741 if (viewport.cursorMode)
743 alignPanel.getSeqPanel().setCursorPosition();
747 case KeyEvent.VK_ENTER:
748 case KeyEvent.VK_COMMA:
749 if (viewport.cursorMode)
751 alignPanel.getSeqPanel().setCursorRowAndColumn();
756 if (viewport.cursorMode)
758 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
762 if (viewport.cursorMode)
764 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
769 viewport.cursorMode = !viewport.cursorMode;
770 setStatus(MessageManager
771 .formatMessage("label.keyboard_editing_mode", new String[]
772 { (viewport.cursorMode ? "on" : "off") }));
773 if (viewport.cursorMode)
775 ViewportRanges ranges = viewport.getRanges();
776 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
778 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
781 alignPanel.getSeqPanel().seqCanvas.repaint();
787 Help.showHelpWindow();
788 } catch (Exception ex)
790 ex.printStackTrace();
795 boolean toggleSeqs = !evt.isControlDown();
796 boolean toggleCols = !evt.isShiftDown();
797 toggleHiddenRegions(toggleSeqs, toggleCols);
802 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
803 boolean modifyExisting = true; // always modify, don't clear
804 // evt.isShiftDown();
805 boolean invertHighlighted = evt.isAltDown();
806 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
810 case KeyEvent.VK_PAGE_UP:
811 viewport.getRanges().pageUp();
813 case KeyEvent.VK_PAGE_DOWN:
814 viewport.getRanges().pageDown();
820 public void keyReleased(KeyEvent evt)
822 switch (evt.getKeyCode())
824 case KeyEvent.VK_LEFT:
825 if (evt.isAltDown() || !viewport.cursorMode)
827 viewport.notifyAlignment();
831 case KeyEvent.VK_RIGHT:
832 if (evt.isAltDown() || !viewport.cursorMode)
834 viewport.notifyAlignment();
842 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
844 ap.alignFrame = this;
845 avc = new jalview.controller.AlignViewController(this, viewport,
850 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
852 int aSize = alignPanels.size();
854 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
856 if (aSize == 1 && ap.av.getViewName() == null)
858 this.getContentPane().add(ap, BorderLayout.CENTER);
864 setInitialTabVisible();
867 expandViews.setEnabled(true);
868 gatherViews.setEnabled(true);
869 tabbedPane.addTab(ap.av.getViewName(), ap);
871 ap.setVisible(false);
876 if (ap.av.isPadGaps())
878 ap.av.getAlignment().padGaps();
880 if (Jalview.getInstance().getStartCalculations())
882 ap.av.updateConservation(ap);
883 ap.av.updateConsensus(ap);
884 ap.av.updateStrucConsensus(ap);
885 ap.av.initInformationWorker(ap);
890 public void setInitialTabVisible()
892 expandViews.setEnabled(true);
893 gatherViews.setEnabled(true);
894 tabbedPane.setVisible(true);
895 AlignmentPanel first = alignPanels.get(0);
896 tabbedPane.addTab(first.av.getViewName(), first);
897 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
900 public AlignViewport getViewport()
906 public void servicesChanged(WSDiscovererI discoverer,
907 Collection<? extends ServiceWithParameters> services)
909 buildWebServicesMenu();
912 /* Set up intrinsic listeners for dynamically generated GUI bits. */
913 private void addServiceListeners()
915 if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
917 WSDiscovererI discoverer = SlivkaWSDiscoverer.getInstance();
918 discoverer.addServiceChangeListener(this);
920 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
922 WSDiscovererI discoverer = Jws2Discoverer.getInstance();
923 discoverer.addServiceChangeListener(this);
925 // legacy event listener for compatibility with jws1
926 PropertyChangeListener legacyListener = (changeEvent) -> {
927 buildWebServicesMenu();
929 Desktop.getInstance().addJalviewPropertyChangeListener("services",legacyListener);
931 addInternalFrameListener(new InternalFrameAdapter() {
933 public void internalFrameClosed(InternalFrameEvent e) {
934 System.out.println("deregistering discoverer listener");
935 SlivkaWSDiscoverer.getInstance().removeServiceChangeListener(AlignFrame.this);
936 Jws2Discoverer.getInstance().removeServiceChangeListener(AlignFrame.this);
937 Desktop.getInstance().removeJalviewPropertyChangeListener("services", legacyListener);
938 closeMenuItem_actionPerformed(true);
941 buildWebServicesMenu();
945 * Configure menu items that vary according to whether the alignment is
946 * nucleotide or protein
949 public void setGUINucleotide()
951 AlignmentI al = getViewport().getAlignment();
952 boolean nucleotide = al.isNucleotide();
954 loadVcf.setVisible(nucleotide);
955 showTranslation.setVisible(nucleotide);
956 showReverse.setVisible(nucleotide);
957 showReverseComplement.setVisible(nucleotide);
958 conservationMenuItem.setEnabled(!nucleotide);
960 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
961 showGroupConservation.setEnabled(!nucleotide);
963 showComplementMenuItem
964 .setText(nucleotide ? MessageManager.getString("label.protein")
965 : MessageManager.getString("label.nucleotide"));
969 * set up menus for the current viewport. This may be called after any
970 * operation that affects the data in the current view (selection changed,
971 * etc) to update the menus to reflect the new state.
975 public void setMenusForViewport()
977 setMenusFromViewport(viewport);
981 * Need to call this method when tabs are selected for multiple views, or when
982 * loading from Jalview2XML.java
988 public void setMenusFromViewport(AlignViewport av)
990 padGapsMenuitem.setSelected(av.isPadGaps());
991 colourTextMenuItem.setSelected(av.isShowColourText());
992 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
993 modifyPID.setEnabled(abovePIDThreshold.isSelected());
994 conservationMenuItem.setSelected(av.getConservationSelected());
995 modifyConservation.setEnabled(conservationMenuItem.isSelected());
996 seqLimits.setSelected(av.getShowJVSuffix());
997 idRightAlign.setSelected(av.isRightAlignIds());
998 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
999 renderGapsMenuItem.setSelected(av.isRenderGaps());
1000 wrapMenuItem.setSelected(av.getWrapAlignment());
1001 scaleAbove.setVisible(av.getWrapAlignment());
1002 scaleLeft.setVisible(av.getWrapAlignment());
1003 scaleRight.setVisible(av.getWrapAlignment());
1004 annotationPanelMenuItem.setState(av.isShowAnnotation());
1005 // Show/hide annotations only enabled if annotation panel is shown
1006 syncAnnotationMenuItems(av.isShowAnnotation());
1007 viewBoxesMenuItem.setSelected(av.getShowBoxes());
1008 viewTextMenuItem.setSelected(av.getShowText());
1009 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
1010 showGroupConsensus.setSelected(av.isShowGroupConsensus());
1011 showGroupConservation.setSelected(av.isShowGroupConservation());
1012 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
1013 showSequenceLogo.setSelected(av.isShowSequenceLogo());
1014 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
1015 showInformationHistogram.setSelected(av.isShowInformationHistogram());
1016 showHMMSequenceLogo.setSelected(av.isShowHMMSequenceLogo());
1017 normaliseHMMSequenceLogo.setSelected(av.isNormaliseHMMSequenceLogo());
1019 ColourMenuHelper.setColourSelected(colourMenu,
1020 av.getGlobalColourScheme());
1022 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
1023 hiddenMarkers.setState(av.getShowHiddenMarkers());
1024 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
1025 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
1026 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
1028 .setSelected(av.getAutoCalculateConsensusAndConservation());
1029 sortByTree.setSelected(av.sortByTree);
1030 listenToViewSelections.setSelected(av.followSelection);
1032 showProducts.setEnabled(canShowProducts());
1033 setGroovyEnabled(Desktop.getGroovyConsole() != null);
1035 updateEditMenuBar();
1039 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
1044 public void setGroovyEnabled(boolean b)
1046 runGroovy.setEnabled(b);
1049 private IProgressIndicator progressBar;
1054 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
1058 public void setProgressBar(String message, long id)
1060 progressBar.setProgressBar(message, id);
1064 public void removeProgressBar(long id)
1066 progressBar.removeProgressBar(id);
1070 public void registerHandler(final long id,
1071 final IProgressIndicatorHandler handler)
1073 progressBar.registerHandler(id, handler);
1078 * @return true if any progress bars are still active
1082 public boolean operationInProgress()
1084 return progressBar.operationInProgress();
1088 * Sets the text of the status bar. Note that setting a null or empty value
1089 * will cause the status bar to be hidden, with possibly undesirable flicker
1090 * of the screen layout.
1094 public void setStatus(String text)
1096 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1100 * Added so Castor Mapping file can obtain Jalview Version
1103 public String getVersion()
1105 return jalview.bin.Cache.getProperty("VERSION");
1108 public FeatureRenderer getFeatureRenderer()
1110 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1114 public void fetchSequence_actionPerformed()
1116 new SequenceFetcher(this);
1120 public void addFromFile_actionPerformed(ActionEvent e)
1122 Desktop.getInstance().inputLocalFileMenuItem_actionPerformed(viewport);
1126 public void hmmBuild_actionPerformed(boolean withDefaults)
1128 if (!alignmentIsSufficient(1))
1134 * get default parameters, and optionally show a dialog
1135 * to allow them to be modified
1137 ParamDatastoreI store = HMMERParamStore.forBuild(viewport);
1138 List<ArgumentI> args = store.getServiceParameters();
1142 WsParamSetI set = new HMMERPreset();
1143 WsJobParameters params = new WsJobParameters(store, set, args);
1144 if (params.showRunDialog())
1146 args = params.getJobParams();
1150 return; // user cancelled
1153 new Thread(new HMMBuild(this, args)).start();
1157 public void hmmAlign_actionPerformed(boolean withDefaults)
1159 if (!(checkForHMM() && alignmentIsSufficient(2)))
1165 * get default parameters, and optionally show a dialog
1166 * to allow them to be modified
1168 ParamDatastoreI store = HMMERParamStore.forAlign(viewport);
1169 List<ArgumentI> args = store.getServiceParameters();
1173 WsParamSetI set = new HMMERPreset();
1174 WsJobParameters params = new WsJobParameters(store, set, args);
1175 if (params.showRunDialog())
1177 args = params.getJobParams();
1181 return; // user cancelled
1184 new Thread(new HMMAlign(this, args)).start();
1188 public void hmmSearch_actionPerformed(boolean withDefaults)
1196 * get default parameters, and (if requested) show
1197 * dialog to allow modification
1199 ParamDatastoreI store = HMMERParamStore.forSearch(viewport);
1200 List<ArgumentI> args = store.getServiceParameters();
1204 WsParamSetI set = new HMMERPreset();
1205 WsJobParameters params = new WsJobParameters(store, set, args);
1206 if (params.showRunDialog())
1208 args = params.getJobParams();
1212 return; // user cancelled
1215 new Thread(new HMMSearch(this, args)).start();
1216 alignPanel.repaint();
1220 public void jackhmmer_actionPerformed(boolean withDefaults)
1224 * get default parameters, and (if requested) show
1225 * dialog to allow modification
1228 ParamDatastoreI store = HMMERParamStore.forJackhmmer(viewport);
1229 List<ArgumentI> args = store.getServiceParameters();
1233 WsParamSetI set = new HMMERPreset();
1234 WsJobParameters params = new WsJobParameters(store, set, args);
1235 if (params.showRunDialog())
1237 args = params.getJobParams();
1241 return; // user cancelled
1244 new Thread(new JackHMMER(this, args)).start();
1245 alignPanel.repaint();
1250 * Checks if the alignment has at least one hidden Markov model, if not shows
1251 * a dialog advising to run hmmbuild or load an HMM profile
1255 private boolean checkForHMM()
1257 if (viewport.getAlignment().getHmmSequences().isEmpty())
1259 JOptionPane.showMessageDialog(this,
1260 MessageManager.getString("warn.no_hmm"));
1267 protected void filterByEValue_actionPerformed()
1269 viewport.filterByEvalue(inputDouble("Enter E-Value Cutoff"));
1273 protected void filterByScore_actionPerformed()
1275 viewport.filterByScore(inputDouble("Enter Bit Score Threshold"));
1278 private double inputDouble(String message)
1282 while (d == null || d <= 0)
1284 str = JOptionPane.showInputDialog(this.alignPanel, message);
1287 d = Double.valueOf(str);
1288 } catch (NumberFormatException e)
1296 * Checks if the alignment contains the required number of sequences.
1301 public boolean alignmentIsSufficient(int required)
1303 if (getViewport().getSequenceSelection().length < required)
1305 JOptionPane.showMessageDialog(this,
1306 MessageManager.getString("label.not_enough_sequences"));
1313 * Opens a file browser and adds the selected file, if in Fasta, Stockholm or
1314 * Pfam format, to the list held under preference key "HMMSEARCH_DBS" (as a
1315 * comma-separated list)
1318 public void addDatabase_actionPerformed() throws IOException
1320 if (Cache.getProperty(Preferences.HMMSEARCH_DBS) == null)
1322 Cache.setProperty(Preferences.HMMSEARCH_DBS, "");
1325 String path = openFileChooser(false);
1326 if (path != null && new File(path).exists())
1328 IdentifyFile identifier = new IdentifyFile();
1329 FileFormatI format = identifier.identify(path, DataSourceType.FILE);
1330 if (format == FileFormat.Fasta || format == FileFormat.Stockholm
1331 || format == FileFormat.Pfam)
1333 String currentDbPaths = Cache
1334 .getProperty(Preferences.HMMSEARCH_DBS);
1335 currentDbPaths += Preferences.COMMA + path;
1336 Cache.setProperty(Preferences.HMMSEARCH_DBS, currentDbPaths);
1340 JOptionPane.showMessageDialog(this,
1341 MessageManager.getString("warn.invalid_format"));
1347 * Opens a file chooser, optionally restricted to selecting folders
1348 * (directories) only. Answers the path to the selected file or folder, or
1349 * null if none is chosen.
1354 protected String openFileChooser(boolean forFolder)
1356 // TODO duplicates GPreferences method - relocate to JalviewFileChooser?
1357 String choice = null;
1358 JFileChooser chooser = new JFileChooser();
1361 chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1363 chooser.setDialogTitle(
1364 MessageManager.getString("label.open_local_file"));
1365 chooser.setToolTipText(MessageManager.getString("action.open"));
1367 int value = chooser.showOpenDialog(this);
1369 if (value == JFileChooser.APPROVE_OPTION)
1371 choice = chooser.getSelectedFile().getPath();
1377 public void reload_actionPerformed(ActionEvent e)
1379 if (fileName == null && fileObject == null)
1383 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1384 // originating file's format
1385 // TODO: work out how to recover feature settings for correct view(s) when
1386 // file is reloaded.
1387 if (FileFormat.Jalview.equals(currentFileFormat))
1389 JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
1390 for (int i = 0; i < frames.length; i++)
1392 if (frames[i] instanceof AlignFrame && frames[i] != this
1393 && ((AlignFrame) frames[i]).fileName != null
1394 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1398 frames[i].setSelected(true);
1399 Desktop.getInstance().closeAssociatedWindows();
1400 } catch (java.beans.PropertyVetoException ex)
1406 Desktop.getInstance().closeAssociatedWindows();
1408 FileLoader loader = new FileLoader();
1409 // DataSourceType protocol = fileName.startsWith("http:")
1410 // ? DataSourceType.URL
1411 // : DataSourceType.FILE;
1412 loader.LoadFile(viewport, (fileObject == null ? fileName : fileObject), protocol, currentFileFormat);
1416 Rectangle bounds = this.getBounds();
1418 FileLoader loader = new FileLoader();
1420 AlignFrame newframe = null;
1422 if (fileObject == null)
1424 newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1429 newframe = loader.LoadFileWaitTillLoaded(fileObject,
1430 DataSourceType.FILE, currentFileFormat);
1433 newframe.setBounds(bounds);
1434 if (featureSettings != null && featureSettings.isShowing())
1436 final Rectangle fspos = featureSettings.frame.getBounds();
1437 // TODO: need a 'show feature settings' function that takes bounds -
1438 // need to refactor Desktop.addFrame
1439 newframe.featureSettings_actionPerformed(null);
1440 final FeatureSettings nfs = newframe.featureSettings;
1441 SwingUtilities.invokeLater(new Runnable()
1447 nfs.frame.setBounds(fspos);
1450 this.featureSettings.close();
1451 this.featureSettings = null;
1453 this.closeMenuItem_actionPerformed(true);
1459 public void addFromText_actionPerformed(ActionEvent e)
1461 Desktop.getInstance()
1462 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1466 public void addFromURL_actionPerformed(ActionEvent e)
1468 Desktop.getInstance().inputURLMenuItem_actionPerformed(viewport);
1472 public void save_actionPerformed(ActionEvent e)
1474 if (fileName == null || (currentFileFormat == null)
1475 || fileName.startsWith("http"))
1477 saveAs_actionPerformed();
1481 saveAlignment(fileName, currentFileFormat);
1486 * Saves the alignment to a file with a name chosen by the user, if necessary
1487 * warning if a file would be overwritten
1491 public void saveAs_actionPerformed()
1493 String format = currentFileFormat == null ? null
1494 : currentFileFormat.getName();
1495 JalviewFileChooser chooser = JalviewFileChooser
1496 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1498 chooser.setFileView(new JalviewFileView());
1499 chooser.setDialogTitle(
1500 MessageManager.getString("label.save_alignment_to_file"));
1501 chooser.setToolTipText(MessageManager.getString("action.save"));
1503 int value = chooser.showSaveDialog(this);
1505 if (value != JalviewFileChooser.APPROVE_OPTION)
1509 currentFileFormat = chooser.getSelectedFormat();
1510 // todo is this (2005) test now obsolete - value is never null?
1511 while (currentFileFormat == null)
1513 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
1515 .getString("label.select_file_format_before_saving"),
1516 MessageManager.getString("label.file_format_not_specified"),
1517 JvOptionPane.WARNING_MESSAGE);
1518 currentFileFormat = chooser.getSelectedFormat();
1519 value = chooser.showSaveDialog(this);
1520 if (value != JalviewFileChooser.APPROVE_OPTION)
1526 fileName = chooser.getSelectedFile().getPath();
1528 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1529 Cache.setProperty("LAST_DIRECTORY", fileName);
1530 saveAlignment(fileName, currentFileFormat);
1533 boolean lastSaveSuccessful = false;
1535 FileFormatI lastFormatSaved;
1537 String lastFilenameSaved;
1540 * Raise a dialog or status message for the last call to saveAlignment.
1542 * @return true if last call to saveAlignment(file, format) was successful.
1545 public boolean isSaveAlignmentSuccessful()
1548 if (!lastSaveSuccessful)
1550 JvOptionPane.showInternalMessageDialog(this, MessageManager
1551 .formatMessage("label.couldnt_save_file", new Object[]
1552 { lastFilenameSaved }),
1553 MessageManager.getString("label.error_saving_file"),
1554 JvOptionPane.WARNING_MESSAGE);
1559 setStatus(MessageManager.formatMessage(
1560 "label.successfully_saved_to_file_in_format", new Object[]
1561 { lastFilenameSaved, lastFormatSaved }));
1564 return lastSaveSuccessful;
1568 * Saves the alignment to the specified file path, in the specified format,
1569 * which may be an alignment format, or Jalview project format. If the
1570 * alignment has hidden regions, or the format is one capable of including
1571 * non-sequence data (features, annotations, groups), then the user may be
1572 * prompted to specify what to include in the output.
1578 public void saveAlignment(String file, FileFormatI format)
1580 lastSaveSuccessful = true;
1581 lastFilenameSaved = file;
1582 lastFormatSaved = format;
1584 if (FileFormat.Jalview.equals(format))
1586 String shortName = title;
1587 if (shortName.indexOf(File.separatorChar) > -1)
1589 shortName = shortName
1590 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
1592 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file,
1595 statusBar.setText(MessageManager.formatMessage(
1596 "label.successfully_saved_to_file_in_format", new Object[]
1597 { fileName, format }));
1602 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1603 Runnable cancelAction = new Runnable()
1609 lastSaveSuccessful = false;
1612 Runnable outputAction = new Runnable()
1618 // todo defer this to inside formatSequences (or later)
1619 AlignmentExportData exportData = viewport
1620 .getAlignExportData(options);
1621 String output = new FormatAdapter(alignPanel, options)
1622 .formatSequences(format, exportData.getAlignment(),
1623 exportData.getOmitHidden(),
1624 exportData.getStartEndPostions(),
1625 viewport.getAlignment().getHiddenColumns());
1628 lastSaveSuccessful = false;
1632 // create backupfiles object and get new temp filename destination
1633 boolean doBackup = BackupFiles.getEnabled();
1634 BackupFiles backupfiles = doBackup ? new BackupFiles(file) : null;
1637 String tempFilePath = doBackup ? backupfiles.getTempFilePath()
1639 PrintWriter out = new PrintWriter(new FileWriter(tempFilePath));
1643 AlignFrame.this.setTitle(file);
1644 statusBar.setText(MessageManager.formatMessage(
1645 "label.successfully_saved_to_file_in_format",
1647 { fileName, format.getName() }));
1648 lastSaveSuccessful = true;
1649 } catch (Exception ex)
1651 lastSaveSuccessful = false;
1652 ex.printStackTrace();
1657 backupfiles.setWriteSuccess(lastSaveSuccessful);
1658 // do the backup file roll and rename the temp file to actual file
1659 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1666 * show dialog with export options if applicable; else just do it
1668 if (AlignExportOptions.isNeeded(viewport, format))
1670 AlignExportOptions choices = new AlignExportOptions(
1671 alignPanel.getAlignViewport(), format, options);
1672 choices.setResponseAction(0, outputAction);
1673 choices.setResponseAction(1, cancelAction);
1674 choices.showDialog();
1683 * Outputs the alignment to textbox in the requested format, if necessary
1684 * first prompting the user for whether to include hidden regions or
1687 * @param fileFormatName
1691 protected void outputText_actionPerformed(String fileFormatName)
1693 FileFormatI fileFormat = FileFormats.getInstance()
1694 .forName(fileFormatName);
1695 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1696 Runnable outputAction = new Runnable()
1702 // todo defer this to inside formatSequences (or later)
1703 AlignmentExportData exportData = viewport
1704 .getAlignExportData(options);
1705 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1706 cap.setForInput(null);
1709 FileFormatI format = fileFormat;
1710 cap.setText(new FormatAdapter(alignPanel, options)
1711 .formatSequences(format, exportData.getAlignment(),
1712 exportData.getOmitHidden(),
1713 exportData.getStartEndPostions(),
1714 viewport.getAlignment().getHiddenColumns()));
1715 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1716 "label.alignment_output_command", new Object[]
1717 { fileFormat.getName() }), 600, 500);
1718 } catch (OutOfMemoryError oom)
1720 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1728 * show dialog with export options if applicable; else just do it
1730 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1732 AlignExportOptions choices = new AlignExportOptions(
1733 alignPanel.getAlignViewport(), fileFormat, options);
1734 choices.setResponseAction(0, outputAction);
1735 choices.showDialog();
1751 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1753 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1754 htmlSVG.exportHTML(null);
1758 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1760 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1761 bjs.exportHTML(null);
1766 public void createImageMap(File file, String image)
1768 alignPanel.makePNGImageMap(file, image);
1772 * Creates a PNG image of the alignment and writes it to the given file. If
1773 * the file is null, the user is prompted to choose a file.
1779 public void createPNG(File f)
1781 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1785 * Creates an EPS image of the alignment and writes it to the given file. If
1786 * the file is null, the user is prompted to choose a file.
1792 public void createEPS(File f)
1794 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1798 * Creates an SVG image of the alignment and writes it to the given file. If
1799 * the file is null, the user is prompted to choose a file.
1805 public void createSVG(File f)
1807 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1811 public void pageSetup_actionPerformed(ActionEvent e)
1813 PrinterJob printJob = PrinterJob.getPrinterJob();
1814 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1825 public void printMenuItem_actionPerformed(ActionEvent e)
1827 // Putting in a thread avoids Swing painting problems
1828 PrintThread thread = new PrintThread(alignPanel);
1833 public void exportFeatures_actionPerformed(ActionEvent e)
1835 new AnnotationExporter(alignPanel).exportFeatures();
1839 public void exportAnnotations_actionPerformed(ActionEvent e)
1841 new AnnotationExporter(alignPanel).exportAnnotations();
1845 public void associatedData_actionPerformed(ActionEvent e)
1846 throws IOException, InterruptedException
1848 final JalviewFileChooser chooser = new JalviewFileChooser(
1849 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1850 chooser.setFileView(new JalviewFileView());
1851 String tooltip = MessageManager
1852 .getString("label.load_jalview_annotations");
1853 chooser.setDialogTitle(tooltip);
1854 chooser.setToolTipText(tooltip);
1855 chooser.setResponseHandler(0, new Runnable()
1861 String choice = chooser.getSelectedFile().getPath();
1862 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1863 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1867 chooser.showOpenDialog(this);
1871 * Close the current view or all views in the alignment frame. If the frame
1872 * only contains one view then the alignment will be removed from memory.
1874 * @param closeAllTabs
1878 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1880 if (alignPanels != null && alignPanels.size() < 2)
1882 closeAllTabs = true;
1887 if (alignPanels != null)
1891 if (this.isClosed())
1893 // really close all the windows - otherwise wait till
1894 // setClosed(true) is called
1895 for (int i = 0; i < alignPanels.size(); i++)
1897 AlignmentPanel ap = alignPanels.get(i);
1904 closeView(alignPanel);
1909 if (featureSettings != null && featureSettings.isOpen())
1911 featureSettings.close();
1912 featureSettings = null;
1915 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1916 * be called recursively, with the frame now in 'closed' state
1918 this.setClosed(true);
1920 } catch (Exception ex)
1922 ex.printStackTrace();
1927 * Close the specified panel and close up tabs appropriately.
1929 * @param panelToClose
1932 public void closeView(AlignmentPanel panelToClose)
1934 int index = tabbedPane.getSelectedIndex();
1935 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1936 alignPanels.remove(panelToClose);
1937 panelToClose.closePanel();
1938 panelToClose = null;
1940 tabbedPane.removeTabAt(closedindex);
1941 tabbedPane.validate();
1943 if (index > closedindex || index == tabbedPane.getTabCount())
1945 // modify currently selected tab index if necessary.
1949 this.tabSelectionChanged(index);
1956 void updateEditMenuBar()
1959 if (viewport.getHistoryList().size() > 0)
1961 undoMenuItem.setEnabled(true);
1962 CommandI command = viewport.getHistoryList().peek();
1963 undoMenuItem.setText(MessageManager
1964 .formatMessage("label.undo_command", new Object[]
1965 { command.getDescription() }));
1969 undoMenuItem.setEnabled(false);
1970 undoMenuItem.setText(MessageManager.getString("action.undo"));
1973 if (viewport.getRedoList().size() > 0)
1975 redoMenuItem.setEnabled(true);
1977 CommandI command = viewport.getRedoList().peek();
1978 redoMenuItem.setText(MessageManager
1979 .formatMessage("label.redo_command", new Object[]
1980 { command.getDescription() }));
1984 redoMenuItem.setEnabled(false);
1985 redoMenuItem.setText(MessageManager.getString("action.redo"));
1990 public void addHistoryItem(CommandI command)
1992 if (command.getSize() > 0)
1994 viewport.addToHistoryList(command);
1995 viewport.clearRedoList();
1996 updateEditMenuBar();
1997 viewport.updateHiddenColumns();
1998 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1999 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2000 // viewport.getColumnSelection()
2001 // .getHiddenColumns().size() > 0);
2007 * @return alignment objects for all views
2010 AlignmentI[] getViewAlignments()
2012 if (alignPanels != null)
2014 AlignmentI[] als = new AlignmentI[alignPanels.size()];
2016 for (AlignmentPanel ap : alignPanels)
2018 als[i++] = ap.av.getAlignment();
2022 if (viewport != null)
2024 return new AlignmentI[] { viewport.getAlignment() };
2037 protected void undoMenuItem_actionPerformed(ActionEvent e)
2039 if (viewport.getHistoryList().isEmpty())
2043 CommandI command = viewport.getHistoryList().pop();
2044 viewport.addToRedoList(command);
2045 command.undoCommand(getViewAlignments());
2047 AlignmentViewport originalSource = getOriginatingSource(command);
2048 updateEditMenuBar();
2050 if (originalSource != null)
2052 if (originalSource != viewport)
2055 "Implementation worry: mismatch of viewport origin for undo");
2057 originalSource.updateHiddenColumns();
2058 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
2060 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2061 // viewport.getColumnSelection()
2062 // .getHiddenColumns().size() > 0);
2063 originalSource.notifyAlignment();
2076 protected void redoMenuItem_actionPerformed(ActionEvent e)
2078 if (viewport.getRedoList().size() < 1)
2083 CommandI command = viewport.getRedoList().pop();
2084 viewport.addToHistoryList(command);
2085 command.doCommand(getViewAlignments());
2087 AlignmentViewport originalSource = getOriginatingSource(command);
2088 updateEditMenuBar();
2090 if (originalSource != null)
2093 if (originalSource != viewport)
2096 "Implementation worry: mismatch of viewport origin for redo");
2098 originalSource.updateHiddenColumns();
2099 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
2101 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2102 // viewport.getColumnSelection()
2103 // .getHiddenColumns().size() > 0);
2104 originalSource.notifyAlignment();
2109 AlignmentViewport getOriginatingSource(CommandI command)
2111 AlignmentViewport originalSource = null;
2112 // For sequence removal and addition, we need to fire
2113 // the property change event FROM the viewport where the
2114 // original alignment was altered
2115 AlignmentI al = null;
2116 if (command instanceof EditCommand)
2118 EditCommand editCommand = (EditCommand) command;
2119 al = editCommand.getAlignment();
2120 List<Component> comps = PaintRefresher.components
2121 .get(viewport.getSequenceSetId());
2123 for (Component comp : comps)
2125 if (comp instanceof AlignmentPanel)
2127 if (al == ((AlignmentPanel) comp).av.getAlignment())
2129 originalSource = ((AlignmentPanel) comp).av;
2136 if (originalSource == null)
2138 // The original view is closed, we must validate
2139 // the current view against the closed view first
2142 PaintRefresher.validateSequences(al, viewport.getAlignment());
2145 originalSource = viewport;
2148 return originalSource;
2158 public void moveSelectedSequences(boolean up)
2160 SequenceGroup sg = viewport.getSelectionGroup();
2166 viewport.getAlignment().moveSelectedSequencesByOne(sg,
2167 viewport.getHiddenRepSequences(), up);
2168 alignPanel.paintAlignment(true, false);
2171 synchronized void slideSequences(boolean right, int size)
2173 List<SequenceI> sg = new ArrayList<>();
2174 if (viewport.cursorMode)
2176 sg.add(viewport.getAlignment()
2177 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
2179 else if (viewport.getSelectionGroup() != null
2180 && viewport.getSelectionGroup().getSize() != viewport
2181 .getAlignment().getHeight())
2183 sg = viewport.getSelectionGroup()
2184 .getSequences(viewport.getHiddenRepSequences());
2192 List<SequenceI> invertGroup = new ArrayList<>();
2194 for (SequenceI seq : viewport.getAlignment().getSequences())
2196 if (!sg.contains(seq))
2198 invertGroup.add(seq);
2202 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
2204 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
2205 for (int i = 0; i < invertGroup.size(); i++)
2207 seqs2[i] = invertGroup.get(i);
2210 SlideSequencesCommand ssc;
2213 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
2214 viewport.getGapCharacter());
2218 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
2219 viewport.getGapCharacter());
2222 int groupAdjustment = 0;
2223 if (ssc.getGapsInsertedBegin() && right)
2225 if (viewport.cursorMode)
2227 alignPanel.getSeqPanel().moveCursor(size, 0);
2231 groupAdjustment = size;
2234 else if (!ssc.getGapsInsertedBegin() && !right)
2236 if (viewport.cursorMode)
2238 alignPanel.getSeqPanel().moveCursor(-size, 0);
2242 groupAdjustment = -size;
2246 if (groupAdjustment != 0)
2248 viewport.getSelectionGroup().setStartRes(
2249 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
2250 viewport.getSelectionGroup().setEndRes(
2251 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
2255 * just extend the last slide command if compatible; but not if in
2256 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
2258 boolean appendHistoryItem = false;
2259 Deque<CommandI> historyList = viewport.getHistoryList();
2260 boolean inSplitFrame = getSplitViewContainer() != null;
2261 if (!inSplitFrame && historyList != null && historyList.size() > 0
2262 && historyList.peek() instanceof SlideSequencesCommand)
2264 appendHistoryItem = ssc.appendSlideCommand(
2265 (SlideSequencesCommand) historyList.peek());
2268 if (!appendHistoryItem)
2270 addHistoryItem(ssc);
2284 protected void copy_actionPerformed()
2286 if (viewport.getSelectionGroup() == null)
2290 // TODO: preserve the ordering of displayed alignment annotation in any
2291 // internal paste (particularly sequence associated annotation)
2292 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2293 String[] omitHidden = null;
2295 if (viewport.hasHiddenColumns())
2297 omitHidden = viewport.getViewAsString(true);
2300 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2301 seqs, omitHidden, null);
2303 StringSelection ss = new StringSelection(output);
2305 Desktop d = Desktop.getInstance();
2308 d.internalCopy = true;
2309 // Its really worth setting the clipboard contents
2310 // to empty before setting the large StringSelection!!
2311 Toolkit.getDefaultToolkit().getSystemClipboard()
2312 .setContents(new StringSelection(""), null);
2314 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2315 Desktop.getInstance());
2316 } catch (OutOfMemoryError er)
2318 new OOMWarning("copying region", er);
2322 HiddenColumns hiddenColumns = null;
2323 if (viewport.hasHiddenColumns())
2325 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2326 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2328 // create new HiddenColumns object with copy of hidden regions
2329 // between startRes and endRes, offset by startRes
2330 hiddenColumns = new HiddenColumns(
2331 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2332 hiddenCutoff, hiddenOffset);
2335 d.jalviewClipboard = new Object[] { seqs,
2336 viewport.getAlignment().getDataset(), hiddenColumns };
2337 setStatus(MessageManager.formatMessage(
2338 "label.copied_sequences_to_clipboard", new Object[]
2339 { Integer.valueOf(seqs.length).toString() }));
2347 * @throws InterruptedException
2348 * @throws IOException
2352 protected void pasteNew_actionPerformed(ActionEvent e)
2353 throws IOException, InterruptedException
2363 * @throws InterruptedException
2364 * @throws IOException
2368 protected void pasteThis_actionPerformed(ActionEvent e)
2369 throws IOException, InterruptedException
2375 * Paste contents of Jalview clipboard
2377 * @param newAlignment
2378 * true to paste to a new alignment, otherwise add to this.
2379 * @throws InterruptedException
2380 * @throws IOException
2382 void paste(boolean newAlignment) throws IOException, InterruptedException
2384 boolean externalPaste = true;
2387 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2388 Transferable contents = c.getContents(this);
2390 if (contents == null)
2399 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2400 if (str.length() < 1)
2405 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2407 } catch (OutOfMemoryError er)
2409 new OOMWarning("Out of memory pasting sequences!!", er);
2413 SequenceI[] sequences;
2414 boolean annotationAdded = false;
2415 AlignmentI alignment = null;
2417 Desktop d = Desktop.getInstance();
2419 if (d.jalviewClipboard != null)
2421 // The clipboard was filled from within Jalview, we must use the
2423 // And dataset from the copied alignment
2424 SequenceI[] newseq = (SequenceI[]) d.jalviewClipboard[0];
2425 // be doubly sure that we create *new* sequence objects.
2426 sequences = new SequenceI[newseq.length];
2427 for (int i = 0; i < newseq.length; i++)
2429 sequences[i] = new Sequence(newseq[i]);
2431 alignment = new Alignment(sequences);
2432 externalPaste = false;
2436 // parse the clipboard as an alignment.
2437 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2439 sequences = alignment.getSequencesArray();
2443 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2449 if (d.jalviewClipboard != null)
2451 // dataset is inherited
2452 alignment.setDataset((Alignment) d.jalviewClipboard[1]);
2456 // new dataset is constructed
2457 alignment.setDataset(null);
2459 alwidth = alignment.getWidth() + 1;
2463 AlignmentI pastedal = alignment; // preserve pasted alignment object
2464 // Add pasted sequences and dataset into existing alignment.
2465 alignment = viewport.getAlignment();
2466 alwidth = alignment.getWidth() + 1;
2467 // decide if we need to import sequences from an existing dataset
2468 boolean importDs = d.jalviewClipboard != null
2469 && d.jalviewClipboard[1] != alignment.getDataset();
2470 // importDs==true instructs us to copy over new dataset sequences from
2471 // an existing alignment
2472 Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2474 // minimum dataset set
2476 for (int i = 0; i < sequences.length; i++)
2480 newDs.addElement(null);
2482 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2484 if (importDs && ds != null)
2486 if (!newDs.contains(ds))
2488 newDs.setElementAt(ds, i);
2489 ds = new Sequence(ds);
2490 // update with new dataset sequence
2491 sequences[i].setDatasetSequence(ds);
2495 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2500 // copy and derive new dataset sequence
2501 sequences[i] = sequences[i].deriveSequence();
2502 alignment.getDataset()
2503 .addSequence(sequences[i].getDatasetSequence());
2504 // TODO: avoid creation of duplicate dataset sequences with a
2505 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2507 alignment.addSequence(sequences[i]); // merges dataset
2511 newDs.clear(); // tidy up
2513 if (alignment.getAlignmentAnnotation() != null)
2515 for (AlignmentAnnotation alan : alignment
2516 .getAlignmentAnnotation())
2518 if (alan.graphGroup > fgroup)
2520 fgroup = alan.graphGroup;
2524 if (pastedal.getAlignmentAnnotation() != null)
2526 // Add any annotation attached to alignment.
2527 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2528 for (int i = 0; i < alann.length; i++)
2530 annotationAdded = true;
2531 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2533 AlignmentAnnotation newann = new AlignmentAnnotation(
2535 if (newann.graphGroup > -1)
2537 if (newGraphGroups.size() <= newann.graphGroup
2538 || newGraphGroups.get(newann.graphGroup) == null)
2540 for (int q = newGraphGroups
2541 .size(); q <= newann.graphGroup; q++)
2543 newGraphGroups.add(q, null);
2545 newGraphGroups.set(newann.graphGroup,
2546 Integer.valueOf(++fgroup));
2548 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2552 newann.padAnnotation(alwidth);
2553 alignment.addAnnotation(newann);
2563 addHistoryItem(new EditCommand(
2564 MessageManager.getString("label.add_sequences"),
2565 Action.PASTE, sequences, 0, alignment.getWidth(),
2568 // Add any annotations attached to sequences
2569 for (int i = 0; i < sequences.length; i++)
2571 if (sequences[i].getAnnotation() != null)
2573 AlignmentAnnotation newann;
2574 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2576 annotationAdded = true;
2577 newann = sequences[i].getAnnotation()[a];
2578 newann.adjustForAlignment();
2579 newann.padAnnotation(alwidth);
2580 if (newann.graphGroup > -1)
2582 if (newann.graphGroup > -1)
2584 if (newGraphGroups.size() <= newann.graphGroup
2585 || newGraphGroups.get(newann.graphGroup) == null)
2587 for (int q = newGraphGroups
2588 .size(); q <= newann.graphGroup; q++)
2590 newGraphGroups.add(q, null);
2592 newGraphGroups.set(newann.graphGroup,
2593 Integer.valueOf(++fgroup));
2595 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2599 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2603 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2611 // propagate alignment changed.
2612 viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2613 if (annotationAdded)
2615 // Duplicate sequence annotation in all views.
2616 AlignmentI[] alview = this.getViewAlignments();
2617 for (int i = 0; i < sequences.length; i++)
2619 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2624 for (int avnum = 0; avnum < alview.length; avnum++)
2626 if (alview[avnum] != alignment)
2628 // duplicate in a view other than the one with input focus
2629 int avwidth = alview[avnum].getWidth() + 1;
2630 // this relies on sann being preserved after we
2631 // modify the sequence's annotation array for each duplication
2632 for (int a = 0; a < sann.length; a++)
2634 AlignmentAnnotation newann = new AlignmentAnnotation(
2636 sequences[i].addAlignmentAnnotation(newann);
2637 newann.padAnnotation(avwidth);
2638 alview[avnum].addAnnotation(newann); // annotation was
2639 // duplicated earlier
2640 // TODO JAL-1145 graphGroups are not updated for sequence
2641 // annotation added to several views. This may cause
2643 alview[avnum].setAnnotationIndex(newann, a);
2648 buildSortByAnnotationScoresMenu();
2650 viewport.notifyAlignment();
2651 if (alignPanels != null)
2653 for (AlignmentPanel ap : alignPanels)
2655 ap.validateAnnotationDimensions(false);
2660 alignPanel.validateAnnotationDimensions(false);
2666 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2668 String newtitle = new String("Copied sequences");
2670 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2672 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2673 af.viewport.setHiddenColumns(hc);
2676 // >>>This is a fix for the moment, until a better solution is
2678 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2679 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2680 .getFeatureRenderer());
2682 // TODO: maintain provenance of an alignment, rather than just make the
2683 // title a concatenation of operations.
2686 if (title.startsWith("Copied sequences"))
2692 newtitle = newtitle.concat("- from " + title);
2697 newtitle = new String("Pasted sequences");
2700 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2705 } catch (Exception ex)
2707 ex.printStackTrace();
2708 System.out.println("Exception whilst pasting: " + ex);
2709 // could be anything being pasted in here
2714 protected void expand_newalign(ActionEvent e)
2718 AlignmentI alignment = AlignmentUtils
2719 .expandContext(getViewport().getAlignment(), -1);
2720 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2722 String newtitle = new String("Flanking alignment");
2723 Desktop d = Desktop.getInstance();
2724 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2726 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2727 af.viewport.setHiddenColumns(hc);
2730 // >>>This is a fix for the moment, until a better solution is
2732 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2733 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2734 .getFeatureRenderer());
2736 // TODO: maintain provenance of an alignment, rather than just make the
2737 // title a concatenation of operations.
2739 if (title.startsWith("Copied sequences"))
2745 newtitle = newtitle.concat("- from " + title);
2749 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2751 } catch (Exception ex)
2753 ex.printStackTrace();
2754 System.out.println("Exception whilst pasting: " + ex);
2755 // could be anything being pasted in here
2756 } catch (OutOfMemoryError oom)
2758 new OOMWarning("Viewing flanking region of alignment", oom);
2763 * Action Cut (delete and copy) the selected region
2767 protected void cut_actionPerformed()
2769 copy_actionPerformed();
2770 delete_actionPerformed();
2774 * Performs menu option to Delete the currently selected region
2778 protected void delete_actionPerformed()
2781 SequenceGroup sg = viewport.getSelectionGroup();
2787 Runnable okAction = new Runnable()
2793 SequenceI[] cut = sg.getSequences()
2794 .toArray(new SequenceI[sg.getSize()]);
2796 addHistoryItem(new EditCommand(
2797 MessageManager.getString("label.cut_sequences"), Action.CUT,
2798 cut, sg.getStartRes(),
2799 sg.getEndRes() - sg.getStartRes() + 1,
2800 viewport.getAlignment()));
2802 viewport.setSelectionGroup(null);
2803 viewport.sendSelection();
2804 viewport.getAlignment().deleteGroup(sg);
2806 viewport.notifyAlignment();
2808 if (viewport.getAlignment().getHeight() < 1)
2812 AlignFrame.this.setClosed(true);
2813 } catch (Exception ex)
2823 * If the cut affects all sequences, prompt for confirmation
2825 boolean wholeHeight = sg.getSize() == viewport.getAlignment()
2827 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2828 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2829 if (wholeHeight && wholeWidth)
2831 JvOptionPane dialog = JvOptionPane
2832 .newOptionDialog(Desktop.getDesktopPane());
2833 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2834 Object[] options = new Object[] {
2835 MessageManager.getString("action.ok"),
2836 MessageManager.getString("action.cancel") };
2837 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2838 MessageManager.getString("label.delete_all"),
2839 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2840 options, options[0]);
2856 protected void deleteGroups_actionPerformed(ActionEvent e)
2858 if (avc.deleteGroups())
2860 updateAll(viewport.getSequenceSetId());
2864 private void updateAll(String id)
2868 // this will force a non-fast repaint of both the IdPanel and SeqPanel
2869 alignPanel.getIdPanel().getIdCanvas().setNoFastPaint();
2870 alignPanel.getSeqPanel().seqCanvas.setNoFastPaint();
2871 alignPanel.repaint();
2876 PaintRefresher.Refresh(this, id);
2877 alignPanel.paintAlignment(true, true);
2879 alignPanel.updateAnnotation();
2890 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2892 alignPanel.selectAllSequences();
2903 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2905 alignPanel.deselectAllSequences();
2916 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2918 SequenceGroup sg = viewport.getSelectionGroup();
2922 alignPanel.selectAllSequences();
2927 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2929 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2931 // JAL-2034 - should delegate to
2932 // alignPanel to decide if overview needs
2935 alignPanel.paintAlignment(true, false);
2936 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2937 viewport.sendSelection();
2941 public void invertColSel_actionPerformed(ActionEvent e)
2943 viewport.invertColumnSelection();
2944 alignPanel.paintAlignment(true, false);
2945 viewport.sendSelection();
2956 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2958 trimAlignment(true);
2969 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2971 trimAlignment(false);
2974 void trimAlignment(boolean trimLeft)
2976 ColumnSelection colSel = viewport.getColumnSelection();
2979 if (!colSel.isEmpty())
2983 column = colSel.getMin();
2987 column = colSel.getMax();
2991 if (viewport.getSelectionGroup() != null)
2993 seqs = viewport.getSelectionGroup()
2994 .getSequencesAsArray(viewport.getHiddenRepSequences());
2998 seqs = viewport.getAlignment().getSequencesArray();
3001 TrimRegionCommand trimRegion;
3004 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
3005 column, viewport.getAlignment());
3006 viewport.getRanges().setStartRes(0);
3010 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
3011 column, viewport.getAlignment());
3014 setStatus(MessageManager.formatMessage("label.removed_columns",
3016 { Integer.valueOf(trimRegion.getSize()).toString() }));
3018 addHistoryItem(trimRegion);
3020 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3022 if ((trimLeft && !sg.adjustForRemoveLeft(column))
3023 || (!trimLeft && !sg.adjustForRemoveRight(column)))
3025 viewport.getAlignment().deleteGroup(sg);
3029 viewport.notifyAlignment();
3042 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
3044 int start = 0, end = viewport.getAlignment().getWidth() - 1;
3047 if (viewport.getSelectionGroup() != null)
3049 seqs = viewport.getSelectionGroup()
3050 .getSequencesAsArray(viewport.getHiddenRepSequences());
3051 start = viewport.getSelectionGroup().getStartRes();
3052 end = viewport.getSelectionGroup().getEndRes();
3056 seqs = viewport.getAlignment().getSequencesArray();
3059 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
3060 "Remove Gapped Columns", seqs, start, end,
3061 viewport.getAlignment());
3063 addHistoryItem(removeGapCols);
3065 setStatus(MessageManager.formatMessage("label.removed_empty_columns",
3067 { Integer.valueOf(removeGapCols.getSize()).toString() }));
3069 // This is to maintain viewport position on first residue
3070 // of first sequence
3071 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3072 ViewportRanges ranges = viewport.getRanges();
3073 int startRes = seq.findPosition(ranges.getStartRes());
3074 // ShiftList shifts;
3075 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
3076 // edit.alColumnChanges=shifts.getInverse();
3077 // if (viewport.hasHiddenColumns)
3078 // viewport.getColumnSelection().compensateForEdits(shifts);
3079 ranges.setStartRes(seq.findIndex(startRes) - 1);
3080 viewport.notifyAlignment();
3093 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
3095 int start = 0, end = viewport.getAlignment().getWidth() - 1;
3098 if (viewport.getSelectionGroup() != null)
3100 seqs = viewport.getSelectionGroup()
3101 .getSequencesAsArray(viewport.getHiddenRepSequences());
3102 start = viewport.getSelectionGroup().getStartRes();
3103 end = viewport.getSelectionGroup().getEndRes();
3107 seqs = viewport.getAlignment().getSequencesArray();
3110 // This is to maintain viewport position on first residue
3111 // of first sequence
3112 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3113 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
3115 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
3116 viewport.getAlignment()));
3118 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
3119 viewport.notifyAlignment();
3131 public void padGapsMenuitem_actionPerformed(ActionEvent e)
3133 viewport.setPadGaps(padGapsMenuitem.isSelected());
3134 viewport.notifyAlignment();
3146 public void findMenuItem_actionPerformed(ActionEvent e)
3152 * Create a new view of the current alignment.
3156 public void newView_actionPerformed(ActionEvent e)
3158 newView(null, true);
3162 * Creates and shows a new view of the current alignment.
3165 * title of newly created view; if null, one will be generated
3166 * @param copyAnnotation
3167 * if true then duplicate all annnotation, groups and settings
3168 * @return new alignment panel, already displayed.
3171 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
3174 * Create a new AlignmentPanel (with its own, new Viewport)
3176 AlignmentPanel newap = new jalview.project.Jalview2XML()
3177 .copyAlignPanel(alignPanel);
3178 if (!copyAnnotation)
3181 * remove all groups and annotation except for the automatic stuff
3183 newap.av.getAlignment().deleteAllGroups();
3184 newap.av.getAlignment().deleteAllAnnotations(false);
3187 newap.av.setGatherViewsHere(false);
3189 if (viewport.getViewName() == null)
3191 viewport.setViewName(
3192 MessageManager.getString("label.view_name_original"));
3196 * Views share the same edits undo and redo stacks
3198 newap.av.setHistoryList(viewport.getHistoryList());
3199 newap.av.setRedoList(viewport.getRedoList());
3202 * copy any visualisation settings that are not saved in the project
3204 newap.av.setColourAppliesToAllGroups(
3205 viewport.getColourAppliesToAllGroups());
3208 * Views share the same mappings; need to deregister any new mappings
3209 * created by copyAlignPanel, and register the new reference to the shared
3212 newap.av.replaceMappings(viewport.getAlignment());
3215 * start up cDNA consensus (if applicable) now mappings are in place
3217 if (newap.av.initComplementConsensus())
3219 newap.refresh(true); // adjust layout of annotations
3222 newap.av.setViewName(getNewViewName(viewTitle));
3224 addAlignmentPanel(newap, true);
3225 newap.alignmentChanged();
3227 if (alignPanels.size() == 2)
3229 viewport.setGatherViewsHere(true);
3231 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
3236 * Make a new name for the view, ensuring it is unique within the current
3237 * sequenceSetId. (This used to be essential for Jalview Project archives, but
3238 * these now use viewId. Unique view names are still desirable for usability.)
3244 protected String getNewViewName(String viewTitle)
3246 int index = Desktop.getViewCount(viewport.getSequenceSetId());
3247 boolean addFirstIndex = false;
3248 if (viewTitle == null || viewTitle.trim().length() == 0)
3250 viewTitle = MessageManager.getString("action.view");
3251 addFirstIndex = true;
3255 index = 1;// we count from 1 if given a specific name
3257 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
3259 List<Component> comps = PaintRefresher.components
3260 .get(viewport.getSequenceSetId());
3262 List<String> existingNames = getExistingViewNames(comps);
3264 while (existingNames.contains(newViewName))
3266 newViewName = viewTitle + " " + (++index);
3272 * Returns a list of distinct view names found in the given list of
3273 * components. View names are held on the viewport of an AlignmentPanel.
3279 protected List<String> getExistingViewNames(List<Component> comps)
3281 List<String> existingNames = new ArrayList<>();
3282 for (Component comp : comps)
3284 if (comp instanceof AlignmentPanel)
3286 AlignmentPanel ap = (AlignmentPanel) comp;
3287 if (!existingNames.contains(ap.av.getViewName()))
3289 existingNames.add(ap.av.getViewName());
3293 return existingNames;
3297 * Explode tabbed views into separate windows.
3301 public void expandViews_actionPerformed(ActionEvent e)
3303 Desktop.explodeViews(this);
3307 * Gather views in separate windows back into a tabbed presentation.
3311 public void gatherViews_actionPerformed(ActionEvent e)
3313 Desktop.getInstance().gatherViews(this);
3324 public void font_actionPerformed(ActionEvent e)
3326 new FontChooser(alignPanel);
3337 protected void seqLimit_actionPerformed(ActionEvent e)
3339 viewport.setShowJVSuffix(seqLimits.isSelected());
3341 alignPanel.getIdPanel().getIdCanvas()
3342 .setPreferredSize(alignPanel.calculateIdWidth());
3343 alignPanel.paintAlignment(true, false);
3347 public void idRightAlign_actionPerformed(ActionEvent e)
3349 viewport.setRightAlignIds(idRightAlign.isSelected());
3350 alignPanel.paintAlignment(false, false);
3354 public void centreColumnLabels_actionPerformed(ActionEvent e)
3356 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3357 alignPanel.paintAlignment(false, false);
3363 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3367 protected void followHighlight_actionPerformed()
3370 * Set the 'follow' flag on the Viewport (and scroll to position if now
3373 final boolean state = this.followHighlightMenuItem.getState();
3374 viewport.setFollowHighlight(state);
3377 alignPanel.scrollToPosition(viewport.getSearchResults());
3389 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3391 viewport.setColourText(colourTextMenuItem.isSelected());
3392 alignPanel.paintAlignment(false, false);
3403 public void wrapMenuItem_actionPerformed(ActionEvent e)
3405 scaleAbove.setVisible(wrapMenuItem.isSelected());
3406 scaleLeft.setVisible(wrapMenuItem.isSelected());
3407 scaleRight.setVisible(wrapMenuItem.isSelected());
3408 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3409 alignPanel.updateLayout();
3413 public void showAllSeqs_actionPerformed(ActionEvent e)
3415 viewport.showAllHiddenSeqs();
3419 public void showAllColumns_actionPerformed(ActionEvent e)
3421 viewport.showAllHiddenColumns();
3422 alignPanel.paintAlignment(true, true);
3423 viewport.sendSelection();
3427 public void hideSelSequences_actionPerformed(ActionEvent e)
3429 viewport.hideAllSelectedSeqs();
3433 * called by key handler and the hide all/show all menu items
3439 protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3442 boolean hide = false;
3443 SequenceGroup sg = viewport.getSelectionGroup();
3444 if (!toggleSeqs && !toggleCols)
3446 // Hide everything by the current selection - this is a hack - we do the
3447 // invert and then hide
3448 // first check that there will be visible columns after the invert.
3449 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3450 && sg.getStartRes() <= sg.getEndRes()))
3452 // now invert the sequence set, if required - empty selection implies
3453 // that no hiding is required.
3456 invertSequenceMenuItem_actionPerformed(null);
3457 sg = viewport.getSelectionGroup();
3461 viewport.expandColSelection(sg, true);
3462 // finally invert the column selection and get the new sequence
3464 invertColSel_actionPerformed(null);
3471 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3473 hideSelSequences_actionPerformed(null);
3476 else if (!(toggleCols && viewport.hasSelectedColumns()))
3478 showAllSeqs_actionPerformed(null);
3484 if (viewport.hasSelectedColumns())
3486 hideSelColumns_actionPerformed(null);
3489 viewport.setSelectionGroup(sg);
3494 showAllColumns_actionPerformed(null);
3503 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3504 * event.ActionEvent)
3508 public void hideAllButSelection_actionPerformed(ActionEvent e)
3510 toggleHiddenRegions(false, false);
3511 viewport.sendSelection();
3518 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3523 public void hideAllSelection_actionPerformed(ActionEvent e)
3525 SequenceGroup sg = viewport.getSelectionGroup();
3526 viewport.expandColSelection(sg, false);
3527 viewport.hideAllSelectedSeqs();
3528 viewport.hideSelectedColumns();
3529 alignPanel.updateLayout();
3530 alignPanel.paintAlignment(true, true);
3531 viewport.sendSelection();
3538 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3543 public void showAllhidden_actionPerformed(ActionEvent e)
3545 viewport.showAllHiddenColumns();
3546 viewport.showAllHiddenSeqs();
3547 alignPanel.paintAlignment(true, true);
3548 viewport.sendSelection();
3552 public void hideSelColumns_actionPerformed(ActionEvent e)
3554 viewport.hideSelectedColumns();
3555 alignPanel.updateLayout();
3556 alignPanel.paintAlignment(true, true);
3557 viewport.sendSelection();
3561 public void hiddenMarkers_actionPerformed(ActionEvent e)
3563 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3575 protected void scaleAbove_actionPerformed(ActionEvent e)
3577 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3578 alignPanel.updateLayout();
3579 alignPanel.paintAlignment(true, false);
3590 protected void scaleLeft_actionPerformed(ActionEvent e)
3592 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3593 alignPanel.updateLayout();
3594 alignPanel.paintAlignment(true, false);
3605 protected void scaleRight_actionPerformed(ActionEvent e)
3607 viewport.setScaleRightWrapped(scaleRight.isSelected());
3608 alignPanel.updateLayout();
3609 alignPanel.paintAlignment(true, false);
3620 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3622 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3623 alignPanel.paintAlignment(false, false);
3634 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3636 viewport.setShowText(viewTextMenuItem.isSelected());
3637 alignPanel.paintAlignment(false, false);
3648 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3650 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3651 alignPanel.paintAlignment(false, false);
3654 public FeatureSettings featureSettings;
3657 public FeatureSettingsControllerI getFeatureSettingsUI()
3659 return featureSettings;
3663 public void featureSettings_actionPerformed(ActionEvent e)
3665 showFeatureSettingsUI();
3669 public FeatureSettingsControllerI showFeatureSettingsUI()
3671 if (featureSettings != null)
3673 featureSettings.closeOldSettings();
3674 featureSettings = null;
3676 if (!showSeqFeatures.isSelected())
3678 // make sure features are actually displayed
3679 showSeqFeatures.setSelected(true);
3680 showSeqFeatures_actionPerformed(null);
3682 featureSettings = new FeatureSettings(this);
3683 return featureSettings;
3687 * Set or clear 'Show Sequence Features'
3694 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3696 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3697 alignPanel.paintAlignment(true, true);
3701 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3702 * the annotations panel as a whole.
3704 * The options to show/hide all annotations should be enabled when the panel
3705 * is shown, and disabled when the panel is hidden.
3711 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3713 final boolean setVisible = annotationPanelMenuItem.isSelected();
3714 viewport.setShowAnnotation(setVisible);
3715 syncAnnotationMenuItems(setVisible);
3716 alignPanel.updateLayout();
3718 SwingUtilities.invokeLater(new Runnable() {
3723 alignPanel.updateScrollBarsFromRanges();
3729 private void syncAnnotationMenuItems(boolean setVisible)
3731 showAllSeqAnnotations.setEnabled(setVisible);
3732 hideAllSeqAnnotations.setEnabled(setVisible);
3733 showAllAlAnnotations.setEnabled(setVisible);
3734 hideAllAlAnnotations.setEnabled(setVisible);
3738 public void alignmentProperties()
3741 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3744 String content = MessageManager.formatMessage("label.html_content",
3746 { contents.toString() });
3749 if (Platform.isJS())
3751 JLabel textLabel = new JLabel();
3752 textLabel.setText(content);
3753 textLabel.setBackground(Color.WHITE);
3755 pane = new JPanel(new BorderLayout());
3756 ((JPanel) pane).setOpaque(true);
3757 pane.setBackground(Color.WHITE);
3758 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3767 JEditorPane editPane = new JEditorPane("text/html", "");
3768 editPane.setEditable(false);
3769 editPane.setText(content);
3773 JInternalFrame frame = new JInternalFrame();
3775 frame.getContentPane().add(new JScrollPane(pane));
3777 Desktop.addInternalFrame(frame, MessageManager
3778 .formatMessage("label.alignment_properties", new Object[]
3779 { getTitle() }), 500, 400);
3790 public void overviewMenuItem_actionPerformed(ActionEvent e)
3792 if (alignPanel.overviewPanel != null)
3797 JInternalFrame frame = new JInternalFrame();
3799 // BH 2019.07.26 we allow for an embedded
3800 // undecorated overview with defined size
3801 frame.setName(Platform.getAppID("overview"));
3803 Dimension dim = Platform.getDimIfEmbedded(frame, -1, -1);
3804 if (dim != null && dim.width == 0)
3806 dim = null; // hidden, not embedded
3808 OverviewPanel overview = new OverviewPanel(alignPanel, dim);
3810 frame.setContentPane(overview);
3813 dim = new Dimension();
3814 // was frame.getSize(), but that is 0,0 at this point;
3818 // we are imbedding, and so we have an undecorated frame
3819 // and we can set the the frame dimensions accordingly.
3821 // allowing for unresizable option using, style="resize:none"
3822 boolean resizable = (Platform.getEmbeddedAttribute(frame,
3823 "resize") != "none");
3824 Desktop.addInternalFrame(frame, MessageManager
3825 .formatMessage("label.overview_params", new Object[]
3826 { this.getTitle() }), Desktop.FRAME_MAKE_VISIBLE, dim.width,
3827 dim.height, resizable, Desktop.FRAME_ALLOW_ANY_SIZE);
3829 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3830 frame.addInternalFrameListener(
3831 new javax.swing.event.InternalFrameAdapter()
3835 public void internalFrameClosed(
3836 javax.swing.event.InternalFrameEvent evt)
3839 alignPanel.setOverviewPanel(null);
3842 if (getKeyListeners().length > 0)
3844 frame.addKeyListener(getKeyListeners()[0]);
3847 alignPanel.setOverviewPanel(overview);
3851 public void textColour_actionPerformed()
3853 new TextColourChooser().chooseColour(alignPanel, null);
3857 * public void covariationColour_actionPerformed() {
3859 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3864 public void annotationColour_actionPerformed()
3866 new AnnotationColourChooser(viewport, alignPanel);
3870 public void annotationColumn_actionPerformed(ActionEvent e)
3872 new AnnotationColumnChooser(viewport, alignPanel);
3876 * Action on the user checking or unchecking the option to apply the selected
3877 * colour scheme to all groups. If unchecked, groups may have their own
3878 * independent colour schemes.
3884 public void applyToAllGroups_actionPerformed(boolean selected)
3886 viewport.setColourAppliesToAllGroups(selected);
3890 * Action on user selecting a colour from the colour menu
3893 * the name (not the menu item label!) of the colour scheme
3897 public void changeColour_actionPerformed(String name)
3900 * 'User Defined' opens a panel to configure or load a
3901 * user-defined colour scheme
3903 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3905 new UserDefinedColours(alignPanel);
3910 * otherwise set the chosen colour scheme (or null for 'None')
3912 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3913 viewport, viewport.getAlignment(),
3914 viewport.getHiddenRepSequences());
3919 * Actions on setting or changing the alignment colour scheme
3925 public void changeColour(ColourSchemeI cs)
3927 // TODO: pull up to controller method
3928 ColourMenuHelper.setColourSelected(colourMenu, cs);
3930 viewport.setGlobalColourScheme(cs);
3932 alignPanel.paintAlignment(true, true);
3936 * Show the PID threshold slider panel
3940 protected void modifyPID_actionPerformed()
3942 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3943 alignPanel.getViewName());
3944 SliderPanel.showPIDSlider();
3948 * Show the Conservation slider panel
3952 protected void modifyConservation_actionPerformed()
3954 SliderPanel.setConservationSlider(alignPanel,
3955 viewport.getResidueShading(), alignPanel.getViewName());
3956 SliderPanel.showConservationSlider();
3960 * Action on selecting or deselecting (Colour) By Conservation
3964 public void conservationMenuItem_actionPerformed(boolean selected)
3966 modifyConservation.setEnabled(selected);
3967 viewport.setConservationSelected(selected);
3968 viewport.getResidueShading().setConservationApplied(selected);
3970 changeColour(viewport.getGlobalColourScheme());
3973 modifyConservation_actionPerformed();
3977 SliderPanel.hideConservationSlider();
3982 * Action on selecting or deselecting (Colour) Above PID Threshold
3986 public void abovePIDThreshold_actionPerformed(boolean selected)
3988 modifyPID.setEnabled(selected);
3989 viewport.setAbovePIDThreshold(selected);
3992 viewport.getResidueShading().setThreshold(0,
3993 viewport.isIgnoreGapsConsensus());
3996 changeColour(viewport.getGlobalColourScheme());
3999 modifyPID_actionPerformed();
4003 SliderPanel.hidePIDSlider();
4015 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
4017 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4018 AlignmentSorter.sortByPID(viewport.getAlignment(),
4019 viewport.getAlignment().getSequenceAt(0));
4020 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
4021 viewport.getAlignment()));
4022 alignPanel.paintAlignment(true, false);
4033 public void sortIDMenuItem_actionPerformed(ActionEvent e)
4035 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4036 AlignmentSorter.sortByID(viewport.getAlignment());
4038 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
4039 alignPanel.paintAlignment(true, false);
4050 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
4052 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4053 AlignmentSorter.sortByLength(viewport.getAlignment());
4054 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
4055 viewport.getAlignment()));
4056 alignPanel.paintAlignment(true, false);
4067 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
4069 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4070 AlignmentSorter.sortByGroup(viewport.getAlignment());
4071 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4072 viewport.getAlignment()));
4074 alignPanel.paintAlignment(true, false);
4078 public void sortEValueMenuItem_actionPerformed(ActionEvent e)
4080 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4081 AlignmentSorter.sortByEValue(viewport.getAlignment());
4082 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4083 viewport.getAlignment()));
4084 alignPanel.paintAlignment(true, false);
4089 public void sortBitScoreMenuItem_actionPerformed(ActionEvent e)
4091 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4092 AlignmentSorter.sortByBitScore(viewport.getAlignment());
4093 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4094 viewport.getAlignment()));
4095 alignPanel.paintAlignment(true, false);
4107 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
4109 new RedundancyPanel(alignPanel, this);
4120 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
4122 if ((viewport.getSelectionGroup() == null)
4123 || (viewport.getSelectionGroup().getSize() < 2))
4125 JvOptionPane.showInternalMessageDialog(this,
4126 MessageManager.getString(
4127 "label.you_must_select_least_two_sequences"),
4128 MessageManager.getString("label.invalid_selection"),
4129 JvOptionPane.WARNING_MESSAGE);
4133 JInternalFrame frame = new JInternalFrame();
4134 frame.setContentPane(new PairwiseAlignPanel(viewport));
4135 Desktop.addInternalFrame(frame,
4136 MessageManager.getString("action.pairwise_alignment"), 600,
4142 public void autoCalculate_actionPerformed(ActionEvent e)
4144 viewport.setAutoCalculateConsensusAndConservation(
4145 autoCalculate.isSelected());
4146 if (viewport.getAutoCalculateConsensusAndConservation())
4148 // viewport.autoCalculateConsensus = autoCalculate.isSelected();
4149 // if (viewport.autoCalculateConsensus)
4151 viewport.notifyAlignment();
4156 public void sortByTreeOption_actionPerformed(ActionEvent e)
4158 viewport.sortByTree = sortByTree.isSelected();
4162 protected void listenToViewSelections_actionPerformed(ActionEvent e)
4164 viewport.followSelection = listenToViewSelections.isSelected();
4168 * Constructs a tree panel and adds it to the desktop
4171 * tree type (NJ or AV)
4173 * name of score model used to compute the tree
4175 * parameters for the distance or similarity calculation
4178 void newTreePanel(String type, String modelName,
4179 SimilarityParamsI options)
4181 String frameTitle = "";
4184 boolean onSelection = false;
4185 if (viewport.getSelectionGroup() != null
4186 && viewport.getSelectionGroup().getSize() > 0)
4188 SequenceGroup sg = viewport.getSelectionGroup();
4190 /* Decide if the selection is a column region */
4191 for (SequenceI _s : sg.getSequences())
4193 if (_s.getLength() < sg.getEndRes())
4195 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4196 MessageManager.getString(
4197 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
4198 MessageManager.getString(
4199 "label.sequences_selection_not_aligned"),
4200 JvOptionPane.WARNING_MESSAGE);
4209 if (viewport.getAlignment().getHeight() < 2)
4215 tp = new TreePanel(alignPanel, type, modelName, options);
4216 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
4218 frameTitle += " from ";
4220 if (viewport.getViewName() != null)
4222 frameTitle += viewport.getViewName() + " of ";
4225 frameTitle += this.title;
4227 Dimension dim = Platform.getDimIfEmbedded(tp, 600, 500);
4228 Desktop.addInternalFrame(tp, frameTitle, dim.width, dim.height);
4240 public void addSortByOrderMenuItem(String title,
4241 final AlignmentOrder order)
4243 final JMenuItem item = new JMenuItem(MessageManager
4244 .formatMessage("action.by_title_param", new Object[]
4247 item.addActionListener(new java.awt.event.ActionListener()
4251 public void actionPerformed(ActionEvent e)
4253 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4255 // TODO: JBPNote - have to map order entries to curent SequenceI
4257 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4259 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
4260 viewport.getAlignment()));
4262 alignPanel.paintAlignment(true, false);
4268 * Add a new sort by annotation score menu item
4271 * the menu to add the option to
4273 * the label used to retrieve scores for each sequence on the
4277 public void addSortByAnnotScoreMenuItem(JMenu sort,
4278 final String scoreLabel)
4280 final JMenuItem item = new JMenuItem(scoreLabel);
4282 item.addActionListener(new java.awt.event.ActionListener()
4286 public void actionPerformed(ActionEvent e)
4288 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4289 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4290 viewport.getAlignment());// ,viewport.getSelectionGroup());
4291 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4292 viewport.getAlignment()));
4293 alignPanel.paintAlignment(true, false);
4299 * last hash for alignment's annotation array - used to minimise cost of
4302 protected int _annotationScoreVectorHash;
4305 * search the alignment and rebuild the sort by annotation score submenu the
4306 * last alignment annotation vector hash is stored to minimize cost of
4307 * rebuilding in subsequence calls.
4312 public void buildSortByAnnotationScoresMenu()
4314 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4319 if (viewport.getAlignment().getAlignmentAnnotation()
4320 .hashCode() == _annotationScoreVectorHash)
4325 sortByAnnotScore.removeAll();
4326 Set<String> scoreSorts = new HashSet<>();
4327 for (SequenceI sqa : viewport.getAlignment().getSequences())
4329 AlignmentAnnotation[] anns = sqa.getAnnotation();
4330 for (int i = 0; anns != null && i < anns.length; i++)
4332 AlignmentAnnotation aa = anns[i];
4333 if (aa != null && aa.hasScore() && aa.sequenceRef != null)
4335 scoreSorts.add(aa.label);
4339 for (String label : scoreSorts)
4341 addSortByAnnotScoreMenuItem(sortByAnnotScore, label);
4343 sortByAnnotScore.setVisible(!scoreSorts.isEmpty());
4345 _annotationScoreVectorHash = viewport.getAlignment()
4346 .getAlignmentAnnotation().hashCode();
4350 * Enable (or, if desired, make visible) the By Tree
4351 * submenu only if it has at least one element (or will have).
4355 protected void enableSortMenuOptions()
4357 List<TreePanel> treePanels = getTreePanels();
4358 sortByTreeMenu.setEnabled(!treePanels.isEmpty());
4362 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4363 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4364 * call. Listeners are added to remove the menu item when the treePanel is
4365 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4370 public void buildTreeSortMenu()
4372 sortByTreeMenu.removeAll();
4374 List<TreePanel> treePanels = getTreePanels();
4376 for (final TreePanel tp : treePanels)
4378 final JMenuItem item = new JMenuItem(tp.getTitle());
4379 item.addActionListener(new java.awt.event.ActionListener()
4383 public void actionPerformed(ActionEvent e)
4385 tp.sortByTree_actionPerformed();
4386 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4391 sortByTreeMenu.add(item);
4395 private List<TreePanel> getTreePanels()
4397 List<Component> comps = PaintRefresher.components
4398 .get(viewport.getSequenceSetId());
4399 List<TreePanel> treePanels = new ArrayList<>();
4400 for (Component comp : comps)
4402 if (comp instanceof TreePanel)
4404 treePanels.add((TreePanel) comp);
4410 public boolean sortBy(AlignmentOrder alorder, String undoname)
4412 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4413 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4414 if (undoname != null)
4416 addHistoryItem(new OrderCommand(undoname, oldOrder,
4417 viewport.getAlignment()));
4419 alignPanel.paintAlignment(true, false);
4424 * Work out whether the whole set of sequences or just the selected set will
4425 * be submitted for multiple alignment.
4429 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4431 // Now, check we have enough sequences
4432 AlignmentView msa = null;
4434 if ((viewport.getSelectionGroup() != null)
4435 && (viewport.getSelectionGroup().getSize() > 1))
4437 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4438 // some common interface!
4440 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4441 * SequenceI[sz = seqs.getSize(false)];
4443 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4444 * seqs.getSequenceAt(i); }
4446 msa = viewport.getAlignmentView(true);
4448 else if (viewport.getSelectionGroup() != null
4449 && viewport.getSelectionGroup().getSize() == 1)
4451 int option = JvOptionPane.showConfirmDialog(this,
4452 MessageManager.getString("warn.oneseq_msainput_selection"),
4453 MessageManager.getString("label.invalid_selection"),
4454 JvOptionPane.OK_CANCEL_OPTION);
4455 if (option == JvOptionPane.OK_OPTION)
4457 msa = viewport.getAlignmentView(false);
4462 msa = viewport.getAlignmentView(false);
4468 * Decides what is submitted to a secondary structure prediction service: the
4469 * first sequence in the alignment, or in the current selection, or, if the
4470 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4471 * region or the whole alignment. (where the first sequence in the set is the
4472 * one that the prediction will be for).
4475 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4477 AlignmentView seqs = null;
4479 if ((viewport.getSelectionGroup() != null)
4480 && (viewport.getSelectionGroup().getSize() > 0))
4482 seqs = viewport.getAlignmentView(true);
4486 seqs = viewport.getAlignmentView(false);
4488 // limit sequences - JBPNote in future - could spawn multiple prediction
4490 // TODO: viewport.getAlignment().isAligned is a global state - the local
4491 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4492 if (!viewport.getAlignment().isAligned(false))
4494 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4495 // TODO: if seqs.getSequences().length>1 then should really have warned
4510 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4512 // Pick the tree file
4513 JalviewFileChooser chooser = new JalviewFileChooser(
4514 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4515 chooser.setFileView(new JalviewFileView());
4516 chooser.setDialogTitle(
4517 MessageManager.getString("label.select_newick_like_tree_file"));
4518 chooser.setToolTipText(
4519 MessageManager.getString("label.load_tree_file"));
4521 chooser.setResponseHandler(0, new Runnable()
4527 String filePath = chooser.getSelectedFile().getPath();
4528 Cache.setProperty("LAST_DIRECTORY", filePath);
4529 NewickFile fin = null;
4532 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4533 DataSourceType.FILE));
4534 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4535 } catch (Exception ex)
4537 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4540 .getString("label.problem_reading_tree_file"),
4541 JvOptionPane.WARNING_MESSAGE);
4542 ex.printStackTrace();
4544 if (fin != null && fin.hasWarningMessage())
4546 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4547 fin.getWarningMessage(),
4548 MessageManager.getString(
4549 "label.possible_problem_with_tree_file"),
4550 JvOptionPane.WARNING_MESSAGE);
4554 chooser.showOpenDialog(this);
4557 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4559 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4562 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4563 int h, int x, int y)
4565 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4569 * Add a treeviewer for the tree extracted from a Newick file object to the
4570 * current alignment view
4577 * Associated alignment input data (or null)
4586 * @return TreePanel handle
4589 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4590 AlignmentView input, int w, int h, int x, int y)
4592 TreePanel tp = null;
4598 if (nf.getTree() != null)
4600 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4601 Dimension dim = Platform.getDimIfEmbedded(tp, -1, -1);
4604 dim = new Dimension(w, h);
4608 // no offset, either
4611 tp.setSize(dim.width, dim.height);
4615 tp.setLocation(x, y);
4618 Desktop.addInternalFrame(tp, treeTitle, dim.width, dim.height);
4620 } catch (Exception ex)
4622 ex.printStackTrace();
4629 * Schedule the web services menu rebuild to the event dispatch thread.
4631 public void buildWebServicesMenu()
4633 SwingUtilities.invokeLater(() -> {
4634 Cache.log.info("Rebuiling WS menu");
4635 webService.removeAll();
4636 if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
4638 Cache.log.info("Building web service menu for slivka");
4639 SlivkaWSDiscoverer discoverer = SlivkaWSDiscoverer.getInstance();
4640 JMenu submenu = new JMenu("Slivka");
4641 buildWebServicesMenu(discoverer, submenu);
4642 webService.add(submenu);
4644 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4646 WSDiscovererI jws2servs = Jws2Discoverer.getInstance();
4647 JMenu submenu = new JMenu("JABAWS");
4648 buildLegacyWebServicesMenu(submenu);
4649 buildWebServicesMenu(jws2servs, submenu);
4650 webService.add(submenu);
4655 private void buildLegacyWebServicesMenu(JMenu menu)
4657 JMenu secstrmenu = new JMenu("Secondary Structure Prediction");
4658 if (Discoverer.getServices() != null && Discoverer.getServices().size() > 0)
4660 var secstrpred = Discoverer.getServices().get("SecStrPred");
4661 if (secstrpred != null)
4663 for (ext.vamsas.ServiceHandle sh : secstrpred)
4665 var menuProvider = Discoverer.getServiceClient(sh);
4666 menuProvider.attachWSMenuEntry(secstrmenu, this);
4670 menu.add(secstrmenu);
4674 * Constructs the web services menu for the given discoverer under the
4675 * specified menu. This method must be called on the EDT
4678 * the discoverer used to build the menu
4680 * parent component which the elements will be attached to
4682 private void buildWebServicesMenu(WSDiscovererI discoverer, JMenu menu)
4684 if (discoverer.hasServices())
4686 PreferredServiceRegistry.getRegistry().populateWSMenuEntry(
4687 discoverer.getServices(), sv -> buildWebServicesMenu(), menu,
4690 if (discoverer.isRunning())
4692 JMenuItem item = new JMenuItem("Service discovery in progress.");
4693 item.setEnabled(false);
4696 else if (!discoverer.hasServices())
4698 JMenuItem item = new JMenuItem("No services available.");
4699 item.setEnabled(false);
4705 * construct any groupURL type service menu entries.
4710 protected void build_urlServiceMenu(JMenu webService)
4712 // TODO: remove this code when 2.7 is released
4713 // DEBUG - alignmentView
4715 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4716 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4718 * public void actionPerformed(ActionEvent e) {
4719 * jalview.datamodel.AlignmentView
4720 * .testSelectionViews(af.viewport.getAlignment(),
4721 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4723 * }); webService.add(testAlView);
4725 // TODO: refactor to RestClient discoverer and merge menu entries for
4726 // rest-style services with other types of analysis/calculation service
4727 // SHmmr test client - still being implemented.
4728 // DEBUG - alignmentView
4730 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4733 client.attachWSMenuEntry(
4734 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4740 * Searches the alignment sequences for xRefs and builds the Show
4741 * Cross-References menu (formerly called Show Products), with database
4742 * sources for which cross-references are found (protein sources for a
4743 * nucleotide alignment and vice versa)
4745 * @return true if Show Cross-references menu should be enabled
4748 public boolean canShowProducts()
4750 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4751 AlignmentI dataset = viewport.getAlignment().getDataset();
4753 showProducts.removeAll();
4754 final boolean dna = viewport.getAlignment().isNucleotide();
4756 if (seqs == null || seqs.length == 0)
4758 // nothing to see here.
4762 boolean showp = false;
4765 List<String> ptypes = new CrossRef(seqs, dataset)
4766 .findXrefSourcesForSequences(dna);
4768 for (final String source : ptypes)
4771 final AlignFrame af = this;
4772 JMenuItem xtype = new JMenuItem(source);
4773 xtype.addActionListener(new ActionListener()
4777 public void actionPerformed(ActionEvent e)
4779 showProductsFor(af.viewport.getSequenceSelection(), dna,
4783 showProducts.add(xtype);
4785 showProducts.setVisible(showp);
4786 showProducts.setEnabled(showp);
4787 } catch (Exception e)
4790 "canShowProducts threw an exception - please report to help@jalview.org",
4798 * Finds and displays cross-references for the selected sequences (protein
4799 * products for nucleotide sequences, dna coding sequences for peptides).
4802 * the sequences to show cross-references for
4804 * true if from a nucleotide alignment (so showing proteins)
4806 * the database to show cross-references for
4809 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4810 final String source)
4812 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4817 * Construct and display a new frame containing the translation of this
4818 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4822 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4824 AlignmentI al = null;
4827 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4829 al = dna.translateCdna(codeTable);
4830 } catch (Exception ex)
4832 jalview.bin.Cache.log.error(
4833 "Exception during translation. Please report this !", ex);
4834 final String msg = MessageManager.getString(
4835 "label.error_when_translating_sequences_submit_bug_report");
4836 final String errorTitle = MessageManager
4837 .getString("label.implementation_error")
4838 + MessageManager.getString("label.translation_failed");
4839 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4840 errorTitle, JvOptionPane.ERROR_MESSAGE);
4843 if (al == null || al.getHeight() == 0)
4845 final String msg = MessageManager.getString(
4846 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4847 final String errorTitle = MessageManager
4848 .getString("label.translation_failed");
4849 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4850 errorTitle, JvOptionPane.WARNING_MESSAGE);
4854 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4855 af.setFileFormat(this.currentFileFormat);
4856 final String newTitle = MessageManager
4857 .formatMessage("label.translation_of_params", new Object[]
4858 { this.getTitle(), codeTable.getId() });
4859 af.setTitle(newTitle);
4860 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4862 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4863 AlignViewport.openSplitFrame(this, af, new Alignment(seqs));
4867 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4874 * Set the file format
4879 public void setFileFormat(FileFormatI format)
4881 this.currentFileFormat = format;
4885 * Try to load a features file onto the alignment.
4888 * contents or path to retrieve file or a File object
4890 * access mode of file (see jalview.io.AlignFile)
4891 * @return true if features file was parsed correctly.
4894 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4897 return avc.parseFeaturesFile(file, sourceType,
4898 Cache.getDefault(Preferences.RELAXEDSEQIDMATCHING, false));
4903 public void refreshFeatureUI(boolean enableIfNecessary)
4905 // note - currently this is only still here rather than in the controller
4906 // because of the featureSettings hard reference that is yet to be
4908 if (enableIfNecessary)
4910 viewport.setShowSequenceFeatures(true);
4911 showSeqFeatures.setSelected(true);
4917 public void dragEnter(DropTargetDragEvent evt)
4922 public void dragExit(DropTargetEvent evt)
4927 public void dragOver(DropTargetDragEvent evt)
4932 public void dropActionChanged(DropTargetDragEvent evt)
4937 public void drop(DropTargetDropEvent evt)
4939 // JAL-1552 - acceptDrop required before getTransferable call for
4940 // Java's Transferable for native dnd
4941 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4942 Transferable t = evt.getTransferable();
4944 final List<Object> files = new ArrayList<>();
4945 List<DataSourceType> protocols = new ArrayList<>();
4949 Desktop.transferFromDropTarget(files, protocols, evt, t);
4950 if (files.size() > 0)
4952 new Thread(new Runnable()
4958 loadDroppedFiles(files, protocols, evt, t);
4962 } catch (Exception e)
4964 e.printStackTrace();
4968 protected void loadDroppedFiles(List<Object> files,
4969 List<DataSourceType> protocols, DropTargetDropEvent evt,
4974 // check to see if any of these files have names matching sequences
4977 SequenceIdMatcher idm = new SequenceIdMatcher(
4978 viewport.getAlignment().getSequencesArray());
4980 * Object[] { String,SequenceI}
4982 ArrayList<Object[]> filesmatched = new ArrayList<>();
4983 ArrayList<Object> filesnotmatched = new ArrayList<>();
4984 for (int i = 0; i < files.size(); i++)
4987 Object fileObj = files.get(i);
4988 String fileName = fileObj.toString();
4990 DataSourceType protocol = (fileObj instanceof File
4991 ? DataSourceType.FILE
4992 : FormatAdapter.checkProtocol(fileName));
4993 if (protocol == DataSourceType.FILE)
4996 if (fileObj instanceof File)
4998 file = (File) fileObj;
4999 Platform.cacheFileData(file);
5003 file = new File(fileName);
5005 pdbfn = file.getName();
5007 else if (protocol == DataSourceType.URL)
5009 URL url = new URL(fileName);
5010 pdbfn = url.getFile();
5012 if (pdbfn.length() > 0)
5014 // attempt to find a match in the alignment
5015 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5016 int l = 0, c = pdbfn.indexOf(".");
5017 while (mtch == null && c != -1)
5022 } while ((c = pdbfn.indexOf(".", l)) > l);
5025 pdbfn = pdbfn.substring(0, l);
5027 mtch = idm.findAllIdMatches(pdbfn);
5034 type = new IdentifyFile().identify(fileObj, protocol);
5035 } catch (Exception ex)
5039 if (type != null && type.isStructureFile())
5041 filesmatched.add(new Object[] { fileObj, protocol, mtch });
5045 // File wasn't named like one of the sequences or wasn't a PDB
5047 filesnotmatched.add(fileObj);
5051 if (filesmatched.size() > 0)
5053 boolean autoAssociate = Cache
5054 .getDefault(Preferences.AUTOASSOCIATE_PDBANDSEQS, false);
5057 String msg = MessageManager.formatMessage(
5058 "label.automatically_associate_structure_files_with_sequences_same_name",
5060 { Integer.valueOf(filesmatched.size()).toString() });
5061 String ttl = MessageManager.getString(
5062 "label.automatically_associate_structure_files_by_name");
5063 int choice = JvOptionPane.showConfirmDialog(this, msg, ttl,
5064 JvOptionPane.YES_NO_OPTION);
5065 autoAssociate = choice == JvOptionPane.YES_OPTION;
5069 for (Object[] fm : filesmatched)
5071 // try and associate
5072 // TODO: may want to set a standard ID naming formalism for
5073 // associating PDB files which have no IDs.
5074 for (SequenceI toassoc : (SequenceI[]) fm[2])
5076 PDBEntry pe = AssociatePdbFileWithSeq.associatePdbWithSeq(
5077 fm[0].toString(), (DataSourceType) fm[1], toassoc,
5081 System.err.println("Associated file : " + (fm[0].toString())
5082 + " with " + toassoc.getDisplayId(true));
5086 // TODO: do we need to update overview ? only if features are
5088 alignPanel.paintAlignment(true, false);
5094 * add declined structures as sequences
5096 for (Object[] o : filesmatched)
5098 filesnotmatched.add(o[0]);
5102 if (filesnotmatched.size() > 0)
5104 if (assocfiles > 0 && (Cache
5105 .getDefault("AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
5106 || JvOptionPane.showConfirmDialog(this,
5107 "<html>" + MessageManager.formatMessage(
5108 "label.ignore_unmatched_dropped_files_info",
5110 { Integer.valueOf(filesnotmatched.size())
5113 MessageManager.getString(
5114 "label.ignore_unmatched_dropped_files"),
5115 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
5119 for (Object fn : filesnotmatched)
5121 loadJalviewDataFile(fn, null, null, null);
5125 } catch (Exception ex)
5127 ex.printStackTrace();
5132 * Attempt to load a "dropped" file or URL string, by testing in turn for
5134 * <li>an Annotation file</li>
5135 * <li>a JNet file</li>
5136 * <li>a features file</li>
5137 * <li>else try to interpret as an alignment file</li>
5141 * either a filename or a URL string.
5142 * @throws InterruptedException
5143 * @throws IOException
5146 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
5147 FileFormatI format, SequenceI assocSeq)
5149 // BH 2018 was String file
5152 if (sourceType == null)
5154 sourceType = FormatAdapter.checkProtocol(file);
5156 // if the file isn't identified, or not positively identified as some
5157 // other filetype (PFAM is default unidentified alignment file type) then
5158 // try to parse as annotation.
5159 boolean isAnnotation = (format == null
5160 || FileFormat.Pfam.equals(format))
5161 ? new AnnotationFile().annotateAlignmentView(viewport,
5167 // first see if its a T-COFFEE score file
5168 TCoffeeScoreFile tcf = null;
5171 tcf = new TCoffeeScoreFile(file, sourceType);
5174 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5178 new TCoffeeColourScheme(viewport.getAlignment()));
5179 isAnnotation = true;
5180 setStatus(MessageManager.getString(
5181 "label.successfully_pasted_tcoffee_scores_to_alignment"));
5185 // some problem - if no warning its probable that the ID matching
5186 // process didn't work
5187 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
5188 tcf.getWarningMessage() == null
5189 ? MessageManager.getString(
5190 "label.check_file_matches_sequence_ids_alignment")
5191 : tcf.getWarningMessage(),
5192 MessageManager.getString(
5193 "label.problem_reading_tcoffee_score_file"),
5194 JvOptionPane.WARNING_MESSAGE);
5201 } catch (Exception x)
5204 "Exception when processing data source as T-COFFEE score file",
5210 // try to see if its a JNet 'concise' style annotation file *before*
5212 // try to parse it as a features file
5215 format = new IdentifyFile().identify(file, sourceType);
5217 if (FileFormat.ScoreMatrix == format)
5219 ScoreMatrixFile sm = new ScoreMatrixFile(
5220 new FileParse(file, sourceType));
5222 // todo: i18n this message
5223 setStatus(MessageManager.formatMessage(
5224 "label.successfully_loaded_matrix",
5225 sm.getMatrixName()));
5227 else if (FileFormat.Jnet.equals(format))
5229 JPredFile predictions = new JPredFile(file, sourceType);
5230 new JnetAnnotationMaker();
5231 JnetAnnotationMaker.add_annotation(predictions,
5232 viewport.getAlignment(), 0, false);
5233 viewport.getAlignment().setupJPredAlignment();
5234 isAnnotation = true;
5236 // else if (IdentifyFile.FeaturesFile.equals(format))
5237 else if (FileFormat.Features.equals(format))
5239 if (parseFeaturesFile(file, sourceType))
5241 SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
5242 if (splitFrame != null)
5244 splitFrame.repaint();
5248 alignPanel.paintAlignment(true, true);
5254 new FileLoader().LoadFile(viewport, file, sourceType, format);
5260 updateForAnnotations();
5262 } catch (Exception ex)
5264 ex.printStackTrace();
5265 } catch (OutOfMemoryError oom)
5270 } catch (Exception x)
5275 + (sourceType != null
5276 ? (sourceType == DataSourceType.PASTE
5278 : "using " + sourceType + " from "
5282 ? "(parsing as '" + format + "' file)"
5284 oom, Desktop.getDesktopPane());
5289 * Do all updates necessary after an annotation file such as jnet. Also called
5290 * from Jalview.loadAppletParams for "annotations", "jnetFile"
5293 public void updateForAnnotations()
5295 alignPanel.adjustAnnotationHeight();
5296 viewport.updateSequenceIdColours();
5297 buildSortByAnnotationScoresMenu();
5298 alignPanel.paintAlignment(true, true);
5302 * Change the display state for the given feature groups -- Added by BH from
5306 * list of group strings
5308 * visible or invisible
5311 public void setFeatureGroupState(String[] groups, boolean state)
5313 jalview.api.FeatureRenderer fr = null;
5314 viewport.setShowSequenceFeatures(true);
5315 if (alignPanel != null
5316 && (fr = alignPanel.getFeatureRenderer()) != null)
5319 fr.setGroupVisibility(Arrays.asList(groups), state);
5320 alignPanel.getSeqPanel().seqCanvas.repaint();
5321 if (alignPanel.overviewPanel != null)
5323 alignPanel.overviewPanel.updateOverviewImage();
5329 * Method invoked by the ChangeListener on the tabbed pane, in other words
5330 * when a different tabbed pane is selected by the user or programmatically.
5334 public void tabSelectionChanged(int index)
5338 alignPanel = alignPanels.get(index);
5339 viewport = alignPanel.av;
5340 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5341 setMenusFromViewport(viewport);
5342 if (featureSettings != null && featureSettings.isOpen()
5343 && featureSettings.fr.getViewport() != viewport)
5345 if (viewport.isShowSequenceFeatures())
5347 // refresh the featureSettings to reflect UI change
5348 showFeatureSettingsUI();
5352 // close feature settings for this view.
5353 featureSettings.close();
5360 * 'focus' any colour slider that is open to the selected viewport
5362 if (viewport.getConservationSelected())
5364 SliderPanel.setConservationSlider(alignPanel,
5365 viewport.getResidueShading(), alignPanel.getViewName());
5369 SliderPanel.hideConservationSlider();
5371 if (viewport.getAbovePIDThreshold())
5373 SliderPanel.setPIDSliderSource(alignPanel,
5374 viewport.getResidueShading(), alignPanel.getViewName());
5378 SliderPanel.hidePIDSlider();
5382 * If there is a frame linked to this one in a SplitPane, switch it to the
5383 * same view tab index. No infinite recursion of calls should happen, since
5384 * tabSelectionChanged() should not get invoked on setting the selected
5385 * index to an unchanged value. Guard against setting an invalid index
5386 * before the new view peer tab has been created.
5388 final AlignViewportI peer = viewport.getCodingComplement();
5391 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
5392 .getAlignPanel().alignFrame;
5393 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5395 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5401 * On right mouse click on view tab, prompt for and set new view name.
5405 public void tabbedPane_mousePressed(MouseEvent e)
5407 if (e.isPopupTrigger())
5409 String msg = MessageManager.getString("label.enter_view_name");
5410 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
5411 String reply = JvOptionPane.showInputDialog(msg, ttl);
5415 viewport.setViewName(reply);
5416 // TODO warn if reply is in getExistingViewNames()?
5417 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5422 public AlignViewport getCurrentView()
5428 * Open the dialog for regex description parsing.
5432 protected void extractScores_actionPerformed(ActionEvent e)
5434 ParseProperties pp = new jalview.analysis.ParseProperties(
5435 viewport.getAlignment());
5436 // TODO: verify regex and introduce GUI dialog for version 2.5
5437 // if (pp.getScoresFromDescription("col", "score column ",
5438 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5440 if (pp.getScoresFromDescription("description column",
5441 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5443 buildSortByAnnotationScoresMenu();
5451 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5456 protected void showDbRefs_actionPerformed(ActionEvent e)
5458 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5464 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5469 protected void showNpFeats_actionPerformed(ActionEvent e)
5471 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5475 * find the viewport amongst the tabs in this alignment frame and close that
5481 public boolean closeView(AlignViewportI av)
5485 this.closeMenuItem_actionPerformed(false);
5488 Component[] comp = tabbedPane.getComponents();
5489 for (int i = 0; comp != null && i < comp.length; i++)
5491 if (comp[i] instanceof AlignmentPanel)
5493 if (((AlignmentPanel) comp[i]).av == av)
5496 closeView((AlignmentPanel) comp[i]);
5504 protected void build_fetchdbmenu(JMenu webService)
5506 // Temporary hack - DBRef Fetcher always top level ws entry.
5507 // TODO We probably want to store a sequence database checklist in
5508 // preferences and have checkboxes.. rather than individual sources selected
5510 final JMenu rfetch = new JMenu(
5511 MessageManager.getString("action.fetch_db_references"));
5512 rfetch.setToolTipText(MessageManager.getString(
5513 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5514 webService.add(rfetch);
5516 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5517 MessageManager.getString("option.trim_retrieved_seqs"));
5518 trimrs.setToolTipText(
5519 MessageManager.getString("label.trim_retrieved_sequences"));
5521 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5522 trimrs.addActionListener(new ActionListener()
5526 public void actionPerformed(ActionEvent e)
5528 trimrs.setSelected(trimrs.isSelected());
5529 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5530 Boolean.valueOf(trimrs.isSelected()).toString());
5534 JMenuItem fetchr = new JMenuItem(
5535 MessageManager.getString("label.standard_databases"));
5536 fetchr.setToolTipText(
5537 MessageManager.getString("label.fetch_embl_uniprot"));
5538 fetchr.addActionListener(new ActionListener()
5542 public void actionPerformed(ActionEvent e)
5544 new Thread(new Runnable()
5550 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5551 .getAlignment().isNucleotide();
5552 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5553 alignPanel.av.getSequenceSelection(),
5554 alignPanel.alignFrame, null,
5555 alignPanel.alignFrame.featureSettings, isNucleotide);
5556 dbRefFetcher.addListener(new FetchFinishedListenerI()
5560 public void finished()
5563 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5564 .getFeatureSettingsModels())
5567 alignPanel.av.mergeFeaturesStyle(srcSettings);
5569 AlignFrame.this.setMenusForViewport();
5572 dbRefFetcher.fetchDBRefs(false);
5580 new Thread(new Runnable()
5587 // final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5588 // .getSequenceFetcherSingleton();
5589 javax.swing.SwingUtilities.invokeLater(new Runnable()
5595 jalview.ws.SequenceFetcher sf = jalview.ws.SequenceFetcher
5597 String[] dbclasses = sf.getNonAlignmentSources();
5598 List<DbSourceProxy> otherdb;
5599 JMenu dfetch = new JMenu();
5600 JMenu ifetch = new JMenu();
5601 JMenuItem fetchr = null;
5602 int comp = 0, icomp = 0, mcomp = 15;
5603 String mname = null;
5605 for (String dbclass : dbclasses)
5607 otherdb = sf.getSourceProxy(dbclass);
5608 // add a single entry for this class, or submenu allowing 'fetch
5610 if (otherdb == null || otherdb.size() < 1)
5616 mname = "From " + dbclass;
5618 if (otherdb.size() == 1)
5620 DbSourceProxy src = otherdb.get(0);
5621 DbSourceProxy[] dassource = new DbSourceProxy[] { src };
5622 fetchr = new JMenuItem(src.getDbSource());
5623 fetchr.addActionListener(new ActionListener()
5627 public void actionPerformed(ActionEvent e)
5629 new Thread(new Runnable()
5635 boolean isNucleotide = alignPanel.alignFrame
5636 .getViewport().getAlignment()
5638 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5639 alignPanel.av.getSequenceSelection(),
5640 alignPanel.alignFrame, dassource,
5641 alignPanel.alignFrame.featureSettings,
5644 .addListener(new FetchFinishedListenerI()
5648 public void finished()
5650 FeatureSettingsModelI srcSettings = dassource[0]
5651 .getFeatureColourScheme();
5652 alignPanel.av.mergeFeaturesStyle(
5654 AlignFrame.this.setMenusForViewport();
5657 dbRefFetcher.fetchDBRefs(false);
5663 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5664 MessageManager.formatMessage(
5665 "label.fetch_retrieve_from", new Object[]
5666 { src.getDbName() })));
5672 final DbSourceProxy[] dassource = otherdb
5673 .toArray(new DbSourceProxy[0]);
5675 DbSourceProxy src = otherdb.get(0);
5676 fetchr = new JMenuItem(MessageManager
5677 .formatMessage("label.fetch_all_param", new Object[]
5678 { src.getDbSource() }));
5679 fetchr.addActionListener(new ActionListener()
5683 public void actionPerformed(ActionEvent e)
5685 new Thread(new Runnable()
5691 boolean isNucleotide = alignPanel.alignFrame
5692 .getViewport().getAlignment()
5694 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5695 alignPanel.av.getSequenceSelection(),
5696 alignPanel.alignFrame, dassource,
5697 alignPanel.alignFrame.featureSettings,
5700 .addListener(new FetchFinishedListenerI()
5704 public void finished()
5706 AlignFrame.this.setMenusForViewport();
5709 dbRefFetcher.fetchDBRefs(false);
5715 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5716 MessageManager.formatMessage(
5717 "label.fetch_retrieve_from_all_sources",
5719 { Integer.valueOf(otherdb.size())
5721 src.getDbSource(), src.getDbName() })));
5724 // and then build the rest of the individual menus
5725 ifetch = new JMenu(MessageManager.formatMessage(
5726 "label.source_from_db_source", new Object[]
5727 { src.getDbSource() }));
5729 String imname = null;
5731 for (DbSourceProxy sproxy : otherdb)
5733 String dbname = sproxy.getDbName();
5734 String sname = dbname.length() > 5
5735 ? dbname.substring(0, 5) + "..."
5737 String msname = dbname.length() > 10
5738 ? dbname.substring(0, 10) + "..."
5742 imname = MessageManager
5743 .formatMessage("label.from_msname", new Object[]
5746 fetchr = new JMenuItem(msname);
5747 final DbSourceProxy[] dassrc = { sproxy };
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, dassrc,
5766 alignPanel.alignFrame.featureSettings,
5769 .addListener(new FetchFinishedListenerI()
5773 public void finished()
5775 AlignFrame.this.setMenusForViewport();
5778 dbRefFetcher.fetchDBRefs(false);
5784 fetchr.setToolTipText(
5785 "<html>" + MessageManager.formatMessage(
5786 "label.fetch_retrieve_from", new Object[]
5790 if (++icomp >= mcomp || i == (otherdb.size()))
5792 ifetch.setText(MessageManager.formatMessage(
5793 "label.source_to_target", imname, sname));
5795 ifetch = new JMenu();
5803 if (comp >= mcomp || dbi >= (dbclasses.length))
5805 dfetch.setText(MessageManager.formatMessage(
5806 "label.source_to_target", mname, dbclass));
5808 dfetch = new JMenu();
5821 * Left justify the whole alignment.
5825 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5827 viewport.getAlignment().justify(false);
5828 viewport.notifyAlignment();
5832 * Right justify the whole alignment.
5836 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5838 viewport.getAlignment().justify(true);
5839 viewport.notifyAlignment();
5843 public void setShowSeqFeatures(boolean b)
5845 showSeqFeatures.setSelected(b);
5846 viewport.setShowSequenceFeatures(b);
5853 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5854 * awt.event.ActionEvent)
5858 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5860 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5861 alignPanel.paintAlignment(false, false);
5868 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5873 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5875 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5876 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5884 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5885 * .event.ActionEvent)
5889 protected void showGroupConservation_actionPerformed(ActionEvent e)
5891 viewport.setShowGroupConservation(showGroupConservation.getState());
5892 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5899 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5900 * .event.ActionEvent)
5904 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5906 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5907 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5914 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5915 * .event.ActionEvent)
5919 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5921 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5922 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5926 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5928 showSequenceLogo.setState(true);
5929 viewport.setShowSequenceLogo(true);
5930 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5931 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5935 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5937 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5944 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5945 * .event.ActionEvent)
5949 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5951 if (avc.makeGroupsFromSelection())
5953 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5954 alignPanel.updateAnnotation();
5955 alignPanel.paintAlignment(true,
5956 viewport.needToUpdateStructureViews());
5960 public void clearAlignmentSeqRep()
5962 // TODO refactor alignmentseqrep to controller
5963 if (viewport.getAlignment().hasSeqrep())
5965 viewport.getAlignment().setSeqrep(null);
5966 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5967 alignPanel.updateAnnotation();
5968 alignPanel.paintAlignment(true, true);
5973 protected void createGroup_actionPerformed(ActionEvent e)
5975 if (avc.createGroup())
5977 if (applyAutoAnnotationSettings.isSelected())
5979 alignPanel.updateAnnotation(true, false);
5981 alignPanel.alignmentChanged();
5986 protected void unGroup_actionPerformed(ActionEvent e)
5990 alignPanel.alignmentChanged();
5995 * make the given alignmentPanel the currently selected tab
5997 * @param alignmentPanel
6000 public void setDisplayedView(AlignmentPanel alignmentPanel)
6002 if (!viewport.getSequenceSetId()
6003 .equals(alignmentPanel.av.getSequenceSetId()))
6005 throw new Error(MessageManager.getString(
6006 "error.implementation_error_cannot_show_view_alignment_frame"));
6008 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
6009 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
6011 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
6016 * Action on selection of menu options to Show or Hide annotations.
6019 * @param forSequences
6020 * update sequence-related annotations
6021 * @param forAlignment
6022 * update non-sequence-related annotations
6026 protected void setAnnotationsVisibility(boolean visible,
6027 boolean forSequences, boolean forAlignment)
6029 AlignmentAnnotation[] anns = alignPanel.getAlignment()
6030 .getAlignmentAnnotation();
6035 for (AlignmentAnnotation aa : anns)
6038 * don't display non-positional annotations on an alignment
6040 if (aa.annotations == null)
6044 boolean apply = (aa.sequenceRef == null && forAlignment)
6045 || (aa.sequenceRef != null && forSequences);
6048 aa.visible = visible;
6051 alignPanel.validateAnnotationDimensions(true);
6052 alignPanel.alignmentChanged();
6056 * Store selected annotation sort order for the view and repaint.
6060 protected void sortAnnotations_actionPerformed()
6062 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
6064 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
6065 alignPanel.paintAlignment(false, false);
6070 * @return alignment panels in this alignment frame
6073 public List<? extends AlignmentViewPanel> getAlignPanels()
6075 // alignPanels is never null
6076 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
6081 * Open a new alignment window, with the cDNA associated with this (protein)
6082 * alignment, aligned as is the protein.
6085 protected void viewAsCdna_actionPerformed()
6087 // TODO no longer a menu action - refactor as required
6088 final AlignmentI alignment = getViewport().getAlignment();
6089 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
6090 if (mappings == null)
6094 List<SequenceI> cdnaSeqs = new ArrayList<>();
6095 for (SequenceI aaSeq : alignment.getSequences())
6097 for (AlignedCodonFrame acf : mappings)
6099 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
6103 * There is a cDNA mapping for this protein sequence - add to new
6104 * alignment. It will share the same dataset sequence as other mapped
6105 * cDNA (no new mappings need to be created).
6107 final Sequence newSeq = new Sequence(dnaSeq);
6108 newSeq.setDatasetSequence(dnaSeq);
6109 cdnaSeqs.add(newSeq);
6113 if (cdnaSeqs.size() == 0)
6115 // show a warning dialog no mapped cDNA
6118 AlignmentI cdna = new Alignment(
6119 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
6120 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
6121 AlignFrame.DEFAULT_HEIGHT);
6122 cdna.alignAs(alignment);
6123 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
6125 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
6126 AlignFrame.DEFAULT_HEIGHT);
6130 * Set visibility of dna/protein complement view (available when shown in a
6137 protected void showComplement_actionPerformed(boolean show)
6139 SplitContainerI sf = getSplitViewContainer();
6142 sf.setComplementVisible(this, show);
6147 * Generate the reverse (optionally complemented) of the selected sequences,
6148 * and add them to the alignment
6152 protected void showReverse_actionPerformed(boolean complement)
6154 AlignmentI al = null;
6157 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
6158 al = dna.reverseCdna(complement);
6159 viewport.addAlignment(al, "");
6160 addHistoryItem(new EditCommand(
6161 MessageManager.getString("label.add_sequences"), Action.PASTE,
6162 al.getSequencesArray(), 0, al.getWidth(),
6163 viewport.getAlignment()));
6164 } catch (Exception ex)
6166 System.err.println(ex.getMessage());
6172 * Try to run a script in the Groovy console, having first ensured that this
6173 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
6174 * be targeted at this alignment.
6178 protected void runGroovy_actionPerformed()
6180 Jalview.setCurrentAlignFrame(this);
6181 groovy.ui.Console console = Desktop.getGroovyConsole();
6182 if (console != null)
6186 console.runScript();
6187 } catch (Exception ex)
6189 System.err.println((ex.toString()));
6190 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
6191 MessageManager.getString("label.couldnt_run_groovy_script"),
6192 MessageManager.getString("label.groovy_support_failed"),
6193 JvOptionPane.ERROR_MESSAGE);
6198 System.err.println("Can't run Groovy script as console not found");
6203 * Hides columns containing (or not containing) a specified feature, provided
6204 * that would not leave all columns hidden
6206 * @param featureType
6207 * @param columnsContaining
6211 public boolean hideFeatureColumns(String featureType,
6212 boolean columnsContaining)
6214 boolean notForHiding = avc.markColumnsContainingFeatures(
6215 columnsContaining, false, false, featureType);
6218 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
6219 false, featureType))
6221 getViewport().hideSelectedColumns();
6229 protected void selectHighlightedColumns_actionPerformed(
6230 ActionEvent actionEvent)
6232 // include key modifier check in case user selects from menu
6233 avc.markHighlightedColumns(
6234 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
6235 (actionEvent.getModifiers() & (ActionEvent.META_MASK
6236 | ActionEvent.CTRL_MASK)) != 0);
6240 * Rebuilds the Colour menu, including any user-defined colours which have
6241 * been loaded either on startup or during the session
6244 public void buildColourMenu()
6246 colourMenu.removeAll();
6248 colourMenu.add(applyToAllGroups);
6249 colourMenu.add(textColour);
6250 colourMenu.addSeparator();
6252 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
6253 viewport.getAlignment(), false);
6255 colourMenu.add(annotationColour);
6256 bg.add(annotationColour);
6257 colourMenu.addSeparator();
6258 colourMenu.add(conservationMenuItem);
6259 colourMenu.add(modifyConservation);
6260 colourMenu.add(abovePIDThreshold);
6261 colourMenu.add(modifyPID);
6263 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
6264 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
6268 * Open a dialog (if not already open) that allows the user to select and
6269 * calculate PCA or Tree analysis
6272 protected void openTreePcaDialog()
6274 if (alignPanel.getCalculationDialog() == null)
6276 new CalculationChooser(AlignFrame.this);
6281 * Sets the status of the HMMER menu
6283 public void updateHMMERStatus()
6285 hmmerMenu.setEnabled(HmmerCommand.isHmmerAvailable());
6289 protected void loadVcf_actionPerformed()
6291 JalviewFileChooser chooser = new JalviewFileChooser(
6292 Cache.getProperty("LAST_DIRECTORY"));
6293 chooser.setFileView(new JalviewFileView());
6294 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
6295 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
6296 final AlignFrame us = this;
6297 chooser.setResponseHandler(0, new Runnable()
6303 String choice = chooser.getSelectedFile().getPath();
6304 Cache.setProperty("LAST_DIRECTORY", choice);
6305 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
6306 new VCFLoader(choice).loadVCF(seqs, us);
6309 chooser.showOpenDialog(null);
6313 private Rectangle lastFeatureSettingsBounds = null;
6316 public void setFeatureSettingsGeometry(Rectangle bounds)
6318 lastFeatureSettingsBounds = bounds;
6322 public Rectangle getFeatureSettingsGeometry()
6324 return lastFeatureSettingsBounds;
6327 public void scrollTo(int row, int column)
6329 alignPanel.getSeqPanel().scrollTo(row, column);
6332 public void scrollToRow(int row)
6334 alignPanel.getSeqPanel().scrollToRow(row);
6337 public void scrollToColumn(int column)
6339 alignPanel.getSeqPanel().scrollToColumn(column);
6343 * BH 2019 from JalviewLite
6345 * get sequence feature groups that are hidden or shown
6352 public String[] getFeatureGroupsOfState(boolean visible)
6354 jalview.api.FeatureRenderer fr = null;
6355 if (alignPanel != null
6356 && (fr = alignPanel.getFeatureRenderer()) != null)
6358 List<String> gps = fr.getGroups(visible);
6359 String[] _gps = gps.toArray(new String[gps.size()]);
6367 * @return list of feature groups on the view
6370 public String[] getFeatureGroups()
6372 jalview.api.FeatureRenderer fr = null;
6373 if (alignPanel != null
6374 && (fr = alignPanel.getFeatureRenderer()) != null)
6376 List<String> gps = fr.getFeatureGroups();
6377 String[] _gps = gps.toArray(new String[gps.size()]);
6383 public void select(SequenceGroup sel, ColumnSelection csel,
6384 HiddenColumns hidden)
6386 alignPanel.getSeqPanel().selection(sel, csel, hidden, null);
6394 static class PrintThread extends Thread
6398 public PrintThread(AlignmentPanel ap)
6403 static PageFormat pf;
6408 PrinterJob printJob = PrinterJob.getPrinterJob();
6412 printJob.setPrintable(ap, pf);
6416 printJob.setPrintable(ap);
6419 if (printJob.printDialog())
6424 } catch (Exception PrintException)
6426 PrintException.printStackTrace();