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 params.showRunDialog().thenAccept((startJob) -> {
1147 var args2 = params.getJobParams();
1148 new Thread(new HMMBuild(this, args2)).start();
1154 new Thread(new HMMBuild(this, args)).start();
1159 public void hmmAlign_actionPerformed(boolean withDefaults)
1161 if (!(checkForHMM() && alignmentIsSufficient(2)))
1167 * get default parameters, and optionally show a dialog
1168 * to allow them to be modified
1170 ParamDatastoreI store = HMMERParamStore.forAlign(viewport);
1171 List<ArgumentI> args = store.getServiceParameters();
1175 WsParamSetI set = new HMMERPreset();
1176 WsJobParameters params = new WsJobParameters(store, set, args);
1177 params.showRunDialog().thenAccept((startJob) -> {
1180 var args2 = params.getJobParams();
1181 new Thread(new HMMAlign(this, args2)).start();
1187 new Thread(new HMMAlign(this, args)).start();
1192 public void hmmSearch_actionPerformed(boolean withDefaults)
1200 * get default parameters, and (if requested) show
1201 * dialog to allow modification
1203 ParamDatastoreI store = HMMERParamStore.forSearch(viewport);
1204 List<ArgumentI> args = store.getServiceParameters();
1208 WsParamSetI set = new HMMERPreset();
1209 WsJobParameters params = new WsJobParameters(store, set, args);
1210 params.showRunDialog().thenAccept((startJob) -> {
1213 var args2 = params.getJobParams();
1214 new Thread(new HMMSearch(this, args2)).start();
1215 alignPanel.repaint();
1221 new Thread(new HMMSearch(this, args)).start();
1222 alignPanel.repaint();
1227 public void jackhmmer_actionPerformed(boolean withDefaults)
1231 * get default parameters, and (if requested) show
1232 * dialog to allow modification
1235 ParamDatastoreI store = HMMERParamStore.forJackhmmer(viewport);
1236 List<ArgumentI> args = store.getServiceParameters();
1240 WsParamSetI set = new HMMERPreset();
1241 WsJobParameters params = new WsJobParameters(store, set, args);
1242 params.showRunDialog().thenAccept((startJob) -> {
1245 var args2 = params.getJobParams();
1246 new Thread(new JackHMMER(this, args2)).start();
1247 alignPanel.repaint();
1253 new Thread(new JackHMMER(this, args)).start();
1254 alignPanel.repaint();
1259 * Checks if the alignment has at least one hidden Markov model, if not shows
1260 * a dialog advising to run hmmbuild or load an HMM profile
1264 private boolean checkForHMM()
1266 if (viewport.getAlignment().getHmmSequences().isEmpty())
1268 JOptionPane.showMessageDialog(this,
1269 MessageManager.getString("warn.no_hmm"));
1276 protected void filterByEValue_actionPerformed()
1278 viewport.filterByEvalue(inputDouble("Enter E-Value Cutoff"));
1282 protected void filterByScore_actionPerformed()
1284 viewport.filterByScore(inputDouble("Enter Bit Score Threshold"));
1287 private double inputDouble(String message)
1291 while (d == null || d <= 0)
1293 str = JOptionPane.showInputDialog(this.alignPanel, message);
1296 d = Double.valueOf(str);
1297 } catch (NumberFormatException e)
1305 * Checks if the alignment contains the required number of sequences.
1310 public boolean alignmentIsSufficient(int required)
1312 if (getViewport().getSequenceSelection().length < required)
1314 JOptionPane.showMessageDialog(this,
1315 MessageManager.getString("label.not_enough_sequences"));
1322 * Opens a file browser and adds the selected file, if in Fasta, Stockholm or
1323 * Pfam format, to the list held under preference key "HMMSEARCH_DBS" (as a
1324 * comma-separated list)
1327 public void addDatabase_actionPerformed() throws IOException
1329 if (Cache.getProperty(Preferences.HMMSEARCH_DBS) == null)
1331 Cache.setProperty(Preferences.HMMSEARCH_DBS, "");
1334 String path = openFileChooser(false);
1335 if (path != null && new File(path).exists())
1337 IdentifyFile identifier = new IdentifyFile();
1338 FileFormatI format = identifier.identify(path, DataSourceType.FILE);
1339 if (format == FileFormat.Fasta || format == FileFormat.Stockholm
1340 || format == FileFormat.Pfam)
1342 String currentDbPaths = Cache
1343 .getProperty(Preferences.HMMSEARCH_DBS);
1344 currentDbPaths += Preferences.COMMA + path;
1345 Cache.setProperty(Preferences.HMMSEARCH_DBS, currentDbPaths);
1349 JOptionPane.showMessageDialog(this,
1350 MessageManager.getString("warn.invalid_format"));
1356 * Opens a file chooser, optionally restricted to selecting folders
1357 * (directories) only. Answers the path to the selected file or folder, or
1358 * null if none is chosen.
1363 protected String openFileChooser(boolean forFolder)
1365 // TODO duplicates GPreferences method - relocate to JalviewFileChooser?
1366 String choice = null;
1367 JFileChooser chooser = new JFileChooser();
1370 chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1372 chooser.setDialogTitle(
1373 MessageManager.getString("label.open_local_file"));
1374 chooser.setToolTipText(MessageManager.getString("action.open"));
1376 int value = chooser.showOpenDialog(this);
1378 if (value == JFileChooser.APPROVE_OPTION)
1380 choice = chooser.getSelectedFile().getPath();
1386 public void reload_actionPerformed(ActionEvent e)
1388 if (fileName == null && fileObject == null)
1392 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1393 // originating file's format
1394 // TODO: work out how to recover feature settings for correct view(s) when
1395 // file is reloaded.
1396 if (FileFormat.Jalview.equals(currentFileFormat))
1398 JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
1399 for (int i = 0; i < frames.length; i++)
1401 if (frames[i] instanceof AlignFrame && frames[i] != this
1402 && ((AlignFrame) frames[i]).fileName != null
1403 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1407 frames[i].setSelected(true);
1408 Desktop.getInstance().closeAssociatedWindows();
1409 } catch (java.beans.PropertyVetoException ex)
1415 Desktop.getInstance().closeAssociatedWindows();
1417 FileLoader loader = new FileLoader();
1418 // DataSourceType protocol = fileName.startsWith("http:")
1419 // ? DataSourceType.URL
1420 // : DataSourceType.FILE;
1421 loader.LoadFile(viewport, (fileObject == null ? fileName : fileObject), protocol, currentFileFormat);
1425 Rectangle bounds = this.getBounds();
1427 FileLoader loader = new FileLoader();
1429 AlignFrame newframe = null;
1431 if (fileObject == null)
1433 newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1438 newframe = loader.LoadFileWaitTillLoaded(fileObject,
1439 DataSourceType.FILE, currentFileFormat);
1442 newframe.setBounds(bounds);
1443 if (featureSettings != null && featureSettings.isShowing())
1445 final Rectangle fspos = featureSettings.frame.getBounds();
1446 // TODO: need a 'show feature settings' function that takes bounds -
1447 // need to refactor Desktop.addFrame
1448 newframe.featureSettings_actionPerformed(null);
1449 final FeatureSettings nfs = newframe.featureSettings;
1450 SwingUtilities.invokeLater(new Runnable()
1456 nfs.frame.setBounds(fspos);
1459 this.featureSettings.close();
1460 this.featureSettings = null;
1462 this.closeMenuItem_actionPerformed(true);
1468 public void addFromText_actionPerformed(ActionEvent e)
1470 Desktop.getInstance()
1471 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1475 public void addFromURL_actionPerformed(ActionEvent e)
1477 Desktop.getInstance().inputURLMenuItem_actionPerformed(viewport);
1481 public void save_actionPerformed(ActionEvent e)
1483 if (fileName == null || (currentFileFormat == null)
1484 || fileName.startsWith("http"))
1486 saveAs_actionPerformed();
1490 saveAlignment(fileName, currentFileFormat);
1495 * Saves the alignment to a file with a name chosen by the user, if necessary
1496 * warning if a file would be overwritten
1500 public void saveAs_actionPerformed()
1502 String format = currentFileFormat == null ? null
1503 : currentFileFormat.getName();
1504 JalviewFileChooser chooser = JalviewFileChooser
1505 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1507 chooser.setFileView(new JalviewFileView());
1508 chooser.setDialogTitle(
1509 MessageManager.getString("label.save_alignment_to_file"));
1510 chooser.setToolTipText(MessageManager.getString("action.save"));
1512 int value = chooser.showSaveDialog(this);
1514 if (value != JalviewFileChooser.APPROVE_OPTION)
1518 currentFileFormat = chooser.getSelectedFormat();
1519 // todo is this (2005) test now obsolete - value is never null?
1520 while (currentFileFormat == null)
1522 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
1524 .getString("label.select_file_format_before_saving"),
1525 MessageManager.getString("label.file_format_not_specified"),
1526 JvOptionPane.WARNING_MESSAGE);
1527 currentFileFormat = chooser.getSelectedFormat();
1528 value = chooser.showSaveDialog(this);
1529 if (value != JalviewFileChooser.APPROVE_OPTION)
1535 fileName = chooser.getSelectedFile().getPath();
1537 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1538 Cache.setProperty("LAST_DIRECTORY", fileName);
1539 saveAlignment(fileName, currentFileFormat);
1542 boolean lastSaveSuccessful = false;
1544 FileFormatI lastFormatSaved;
1546 String lastFilenameSaved;
1549 * Raise a dialog or status message for the last call to saveAlignment.
1551 * @return true if last call to saveAlignment(file, format) was successful.
1554 public boolean isSaveAlignmentSuccessful()
1557 if (!lastSaveSuccessful)
1559 JvOptionPane.showInternalMessageDialog(this, MessageManager
1560 .formatMessage("label.couldnt_save_file", new Object[]
1561 { lastFilenameSaved }),
1562 MessageManager.getString("label.error_saving_file"),
1563 JvOptionPane.WARNING_MESSAGE);
1568 setStatus(MessageManager.formatMessage(
1569 "label.successfully_saved_to_file_in_format", new Object[]
1570 { lastFilenameSaved, lastFormatSaved }));
1573 return lastSaveSuccessful;
1577 * Saves the alignment to the specified file path, in the specified format,
1578 * which may be an alignment format, or Jalview project format. If the
1579 * alignment has hidden regions, or the format is one capable of including
1580 * non-sequence data (features, annotations, groups), then the user may be
1581 * prompted to specify what to include in the output.
1587 public void saveAlignment(String file, FileFormatI format)
1589 lastSaveSuccessful = true;
1590 lastFilenameSaved = file;
1591 lastFormatSaved = format;
1593 if (FileFormat.Jalview.equals(format))
1595 String shortName = title;
1596 if (shortName.indexOf(File.separatorChar) > -1)
1598 shortName = shortName
1599 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
1601 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file,
1604 statusBar.setText(MessageManager.formatMessage(
1605 "label.successfully_saved_to_file_in_format", new Object[]
1606 { fileName, format }));
1611 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1612 Runnable cancelAction = new Runnable()
1618 lastSaveSuccessful = false;
1621 Runnable outputAction = new Runnable()
1627 // todo defer this to inside formatSequences (or later)
1628 AlignmentExportData exportData = viewport
1629 .getAlignExportData(options);
1630 String output = new FormatAdapter(alignPanel, options)
1631 .formatSequences(format, exportData.getAlignment(),
1632 exportData.getOmitHidden(),
1633 exportData.getStartEndPostions(),
1634 viewport.getAlignment().getHiddenColumns());
1637 lastSaveSuccessful = false;
1641 // create backupfiles object and get new temp filename destination
1642 boolean doBackup = BackupFiles.getEnabled();
1643 BackupFiles backupfiles = doBackup ? new BackupFiles(file) : null;
1646 String tempFilePath = doBackup ? backupfiles.getTempFilePath()
1648 PrintWriter out = new PrintWriter(new FileWriter(tempFilePath));
1652 AlignFrame.this.setTitle(file);
1653 statusBar.setText(MessageManager.formatMessage(
1654 "label.successfully_saved_to_file_in_format",
1656 { fileName, format.getName() }));
1657 lastSaveSuccessful = true;
1658 } catch (Exception ex)
1660 lastSaveSuccessful = false;
1661 ex.printStackTrace();
1666 backupfiles.setWriteSuccess(lastSaveSuccessful);
1667 // do the backup file roll and rename the temp file to actual file
1668 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1675 * show dialog with export options if applicable; else just do it
1677 if (AlignExportOptions.isNeeded(viewport, format))
1679 AlignExportOptions choices = new AlignExportOptions(
1680 alignPanel.getAlignViewport(), format, options);
1681 choices.setResponseAction(0, outputAction);
1682 choices.setResponseAction(1, cancelAction);
1683 choices.showDialog();
1692 * Outputs the alignment to textbox in the requested format, if necessary
1693 * first prompting the user for whether to include hidden regions or
1696 * @param fileFormatName
1700 protected void outputText_actionPerformed(String fileFormatName)
1702 FileFormatI fileFormat = FileFormats.getInstance()
1703 .forName(fileFormatName);
1704 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1705 Runnable outputAction = new Runnable()
1711 // todo defer this to inside formatSequences (or later)
1712 AlignmentExportData exportData = viewport
1713 .getAlignExportData(options);
1714 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1715 cap.setForInput(null);
1718 FileFormatI format = fileFormat;
1719 cap.setText(new FormatAdapter(alignPanel, options)
1720 .formatSequences(format, exportData.getAlignment(),
1721 exportData.getOmitHidden(),
1722 exportData.getStartEndPostions(),
1723 viewport.getAlignment().getHiddenColumns()));
1724 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1725 "label.alignment_output_command", new Object[]
1726 { fileFormat.getName() }), 600, 500);
1727 } catch (OutOfMemoryError oom)
1729 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1737 * show dialog with export options if applicable; else just do it
1739 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1741 AlignExportOptions choices = new AlignExportOptions(
1742 alignPanel.getAlignViewport(), fileFormat, options);
1743 choices.setResponseAction(0, outputAction);
1744 choices.showDialog();
1760 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1762 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1763 htmlSVG.exportHTML(null);
1767 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1769 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1770 bjs.exportHTML(null);
1775 public void createImageMap(File file, String image)
1777 alignPanel.makePNGImageMap(file, image);
1781 * Creates a PNG image of the alignment and writes it to the given file. If
1782 * the file is null, the user is prompted to choose a file.
1788 public void createPNG(File f)
1790 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1794 * Creates an EPS image of the alignment and writes it to the given file. If
1795 * the file is null, the user is prompted to choose a file.
1801 public void createEPS(File f)
1803 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1807 * Creates an SVG image of the alignment and writes it to the given file. If
1808 * the file is null, the user is prompted to choose a file.
1814 public void createSVG(File f)
1816 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1820 public void pageSetup_actionPerformed(ActionEvent e)
1822 PrinterJob printJob = PrinterJob.getPrinterJob();
1823 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1834 public void printMenuItem_actionPerformed(ActionEvent e)
1836 // Putting in a thread avoids Swing painting problems
1837 PrintThread thread = new PrintThread(alignPanel);
1842 public void exportFeatures_actionPerformed(ActionEvent e)
1844 new AnnotationExporter(alignPanel).exportFeatures();
1848 public void exportAnnotations_actionPerformed(ActionEvent e)
1850 new AnnotationExporter(alignPanel).exportAnnotations();
1854 public void associatedData_actionPerformed(ActionEvent e)
1855 throws IOException, InterruptedException
1857 final JalviewFileChooser chooser = new JalviewFileChooser(
1858 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1859 chooser.setFileView(new JalviewFileView());
1860 String tooltip = MessageManager
1861 .getString("label.load_jalview_annotations");
1862 chooser.setDialogTitle(tooltip);
1863 chooser.setToolTipText(tooltip);
1864 chooser.setResponseHandler(0, new Runnable()
1870 String choice = chooser.getSelectedFile().getPath();
1871 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1872 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1876 chooser.showOpenDialog(this);
1880 * Close the current view or all views in the alignment frame. If the frame
1881 * only contains one view then the alignment will be removed from memory.
1883 * @param closeAllTabs
1887 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1889 if (alignPanels != null && alignPanels.size() < 2)
1891 closeAllTabs = true;
1896 if (alignPanels != null)
1900 if (this.isClosed())
1902 // really close all the windows - otherwise wait till
1903 // setClosed(true) is called
1904 for (int i = 0; i < alignPanels.size(); i++)
1906 AlignmentPanel ap = alignPanels.get(i);
1913 closeView(alignPanel);
1918 if (featureSettings != null && featureSettings.isOpen())
1920 featureSettings.close();
1921 featureSettings = null;
1924 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1925 * be called recursively, with the frame now in 'closed' state
1927 this.setClosed(true);
1929 } catch (Exception ex)
1931 ex.printStackTrace();
1936 * Close the specified panel and close up tabs appropriately.
1938 * @param panelToClose
1941 public void closeView(AlignmentPanel panelToClose)
1943 int index = tabbedPane.getSelectedIndex();
1944 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1945 alignPanels.remove(panelToClose);
1946 panelToClose.closePanel();
1947 panelToClose = null;
1949 tabbedPane.removeTabAt(closedindex);
1950 tabbedPane.validate();
1952 if (index > closedindex || index == tabbedPane.getTabCount())
1954 // modify currently selected tab index if necessary.
1958 this.tabSelectionChanged(index);
1965 void updateEditMenuBar()
1968 if (viewport.getHistoryList().size() > 0)
1970 undoMenuItem.setEnabled(true);
1971 CommandI command = viewport.getHistoryList().peek();
1972 undoMenuItem.setText(MessageManager
1973 .formatMessage("label.undo_command", new Object[]
1974 { command.getDescription() }));
1978 undoMenuItem.setEnabled(false);
1979 undoMenuItem.setText(MessageManager.getString("action.undo"));
1982 if (viewport.getRedoList().size() > 0)
1984 redoMenuItem.setEnabled(true);
1986 CommandI command = viewport.getRedoList().peek();
1987 redoMenuItem.setText(MessageManager
1988 .formatMessage("label.redo_command", new Object[]
1989 { command.getDescription() }));
1993 redoMenuItem.setEnabled(false);
1994 redoMenuItem.setText(MessageManager.getString("action.redo"));
1999 public void addHistoryItem(CommandI command)
2001 if (command.getSize() > 0)
2003 viewport.addToHistoryList(command);
2004 viewport.clearRedoList();
2005 updateEditMenuBar();
2006 viewport.updateHiddenColumns();
2007 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
2008 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2009 // viewport.getColumnSelection()
2010 // .getHiddenColumns().size() > 0);
2016 * @return alignment objects for all views
2019 AlignmentI[] getViewAlignments()
2021 if (alignPanels != null)
2023 AlignmentI[] als = new AlignmentI[alignPanels.size()];
2025 for (AlignmentPanel ap : alignPanels)
2027 als[i++] = ap.av.getAlignment();
2031 if (viewport != null)
2033 return new AlignmentI[] { viewport.getAlignment() };
2046 protected void undoMenuItem_actionPerformed(ActionEvent e)
2048 if (viewport.getHistoryList().isEmpty())
2052 CommandI command = viewport.getHistoryList().pop();
2053 viewport.addToRedoList(command);
2054 command.undoCommand(getViewAlignments());
2056 AlignmentViewport originalSource = getOriginatingSource(command);
2057 updateEditMenuBar();
2059 if (originalSource != null)
2061 if (originalSource != viewport)
2064 "Implementation worry: mismatch of viewport origin for undo");
2066 originalSource.updateHiddenColumns();
2067 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
2069 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2070 // viewport.getColumnSelection()
2071 // .getHiddenColumns().size() > 0);
2072 originalSource.notifyAlignment();
2085 protected void redoMenuItem_actionPerformed(ActionEvent e)
2087 if (viewport.getRedoList().size() < 1)
2092 CommandI command = viewport.getRedoList().pop();
2093 viewport.addToHistoryList(command);
2094 command.doCommand(getViewAlignments());
2096 AlignmentViewport originalSource = getOriginatingSource(command);
2097 updateEditMenuBar();
2099 if (originalSource != null)
2102 if (originalSource != viewport)
2105 "Implementation worry: mismatch of viewport origin for redo");
2107 originalSource.updateHiddenColumns();
2108 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
2110 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2111 // viewport.getColumnSelection()
2112 // .getHiddenColumns().size() > 0);
2113 originalSource.notifyAlignment();
2118 AlignmentViewport getOriginatingSource(CommandI command)
2120 AlignmentViewport originalSource = null;
2121 // For sequence removal and addition, we need to fire
2122 // the property change event FROM the viewport where the
2123 // original alignment was altered
2124 AlignmentI al = null;
2125 if (command instanceof EditCommand)
2127 EditCommand editCommand = (EditCommand) command;
2128 al = editCommand.getAlignment();
2129 List<Component> comps = PaintRefresher.components
2130 .get(viewport.getSequenceSetId());
2132 for (Component comp : comps)
2134 if (comp instanceof AlignmentPanel)
2136 if (al == ((AlignmentPanel) comp).av.getAlignment())
2138 originalSource = ((AlignmentPanel) comp).av;
2145 if (originalSource == null)
2147 // The original view is closed, we must validate
2148 // the current view against the closed view first
2151 PaintRefresher.validateSequences(al, viewport.getAlignment());
2154 originalSource = viewport;
2157 return originalSource;
2167 public void moveSelectedSequences(boolean up)
2169 SequenceGroup sg = viewport.getSelectionGroup();
2175 viewport.getAlignment().moveSelectedSequencesByOne(sg,
2176 viewport.getHiddenRepSequences(), up);
2177 alignPanel.paintAlignment(true, false);
2180 synchronized void slideSequences(boolean right, int size)
2182 List<SequenceI> sg = new ArrayList<>();
2183 if (viewport.cursorMode)
2185 sg.add(viewport.getAlignment()
2186 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
2188 else if (viewport.getSelectionGroup() != null
2189 && viewport.getSelectionGroup().getSize() != viewport
2190 .getAlignment().getHeight())
2192 sg = viewport.getSelectionGroup()
2193 .getSequences(viewport.getHiddenRepSequences());
2201 List<SequenceI> invertGroup = new ArrayList<>();
2203 for (SequenceI seq : viewport.getAlignment().getSequences())
2205 if (!sg.contains(seq))
2207 invertGroup.add(seq);
2211 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
2213 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
2214 for (int i = 0; i < invertGroup.size(); i++)
2216 seqs2[i] = invertGroup.get(i);
2219 SlideSequencesCommand ssc;
2222 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
2223 viewport.getGapCharacter());
2227 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
2228 viewport.getGapCharacter());
2231 int groupAdjustment = 0;
2232 if (ssc.getGapsInsertedBegin() && right)
2234 if (viewport.cursorMode)
2236 alignPanel.getSeqPanel().moveCursor(size, 0);
2240 groupAdjustment = size;
2243 else if (!ssc.getGapsInsertedBegin() && !right)
2245 if (viewport.cursorMode)
2247 alignPanel.getSeqPanel().moveCursor(-size, 0);
2251 groupAdjustment = -size;
2255 if (groupAdjustment != 0)
2257 viewport.getSelectionGroup().setStartRes(
2258 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
2259 viewport.getSelectionGroup().setEndRes(
2260 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
2264 * just extend the last slide command if compatible; but not if in
2265 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
2267 boolean appendHistoryItem = false;
2268 Deque<CommandI> historyList = viewport.getHistoryList();
2269 boolean inSplitFrame = getSplitViewContainer() != null;
2270 if (!inSplitFrame && historyList != null && historyList.size() > 0
2271 && historyList.peek() instanceof SlideSequencesCommand)
2273 appendHistoryItem = ssc.appendSlideCommand(
2274 (SlideSequencesCommand) historyList.peek());
2277 if (!appendHistoryItem)
2279 addHistoryItem(ssc);
2293 protected void copy_actionPerformed()
2295 if (viewport.getSelectionGroup() == null)
2299 // TODO: preserve the ordering of displayed alignment annotation in any
2300 // internal paste (particularly sequence associated annotation)
2301 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2302 String[] omitHidden = null;
2304 if (viewport.hasHiddenColumns())
2306 omitHidden = viewport.getViewAsString(true);
2309 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2310 seqs, omitHidden, null);
2312 StringSelection ss = new StringSelection(output);
2314 Desktop d = Desktop.getInstance();
2317 d.internalCopy = true;
2318 // Its really worth setting the clipboard contents
2319 // to empty before setting the large StringSelection!!
2320 Toolkit.getDefaultToolkit().getSystemClipboard()
2321 .setContents(new StringSelection(""), null);
2323 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2324 Desktop.getInstance());
2325 } catch (OutOfMemoryError er)
2327 new OOMWarning("copying region", er);
2331 HiddenColumns hiddenColumns = null;
2332 if (viewport.hasHiddenColumns())
2334 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2335 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2337 // create new HiddenColumns object with copy of hidden regions
2338 // between startRes and endRes, offset by startRes
2339 hiddenColumns = new HiddenColumns(
2340 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2341 hiddenCutoff, hiddenOffset);
2344 d.jalviewClipboard = new Object[] { seqs,
2345 viewport.getAlignment().getDataset(), hiddenColumns };
2346 setStatus(MessageManager.formatMessage(
2347 "label.copied_sequences_to_clipboard", new Object[]
2348 { Integer.valueOf(seqs.length).toString() }));
2356 * @throws InterruptedException
2357 * @throws IOException
2361 protected void pasteNew_actionPerformed(ActionEvent e)
2362 throws IOException, InterruptedException
2372 * @throws InterruptedException
2373 * @throws IOException
2377 protected void pasteThis_actionPerformed(ActionEvent e)
2378 throws IOException, InterruptedException
2384 * Paste contents of Jalview clipboard
2386 * @param newAlignment
2387 * true to paste to a new alignment, otherwise add to this.
2388 * @throws InterruptedException
2389 * @throws IOException
2391 void paste(boolean newAlignment) throws IOException, InterruptedException
2393 boolean externalPaste = true;
2396 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2397 Transferable contents = c.getContents(this);
2399 if (contents == null)
2408 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2409 if (str.length() < 1)
2414 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2416 } catch (OutOfMemoryError er)
2418 new OOMWarning("Out of memory pasting sequences!!", er);
2422 SequenceI[] sequences;
2423 boolean annotationAdded = false;
2424 AlignmentI alignment = null;
2426 Desktop d = Desktop.getInstance();
2428 if (d.jalviewClipboard != null)
2430 // The clipboard was filled from within Jalview, we must use the
2432 // And dataset from the copied alignment
2433 SequenceI[] newseq = (SequenceI[]) d.jalviewClipboard[0];
2434 // be doubly sure that we create *new* sequence objects.
2435 sequences = new SequenceI[newseq.length];
2436 for (int i = 0; i < newseq.length; i++)
2438 sequences[i] = new Sequence(newseq[i]);
2440 alignment = new Alignment(sequences);
2441 externalPaste = false;
2445 // parse the clipboard as an alignment.
2446 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2448 sequences = alignment.getSequencesArray();
2452 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2458 if (d.jalviewClipboard != null)
2460 // dataset is inherited
2461 alignment.setDataset((Alignment) d.jalviewClipboard[1]);
2465 // new dataset is constructed
2466 alignment.setDataset(null);
2468 alwidth = alignment.getWidth() + 1;
2472 AlignmentI pastedal = alignment; // preserve pasted alignment object
2473 // Add pasted sequences and dataset into existing alignment.
2474 alignment = viewport.getAlignment();
2475 alwidth = alignment.getWidth() + 1;
2476 // decide if we need to import sequences from an existing dataset
2477 boolean importDs = d.jalviewClipboard != null
2478 && d.jalviewClipboard[1] != alignment.getDataset();
2479 // importDs==true instructs us to copy over new dataset sequences from
2480 // an existing alignment
2481 Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2483 // minimum dataset set
2485 for (int i = 0; i < sequences.length; i++)
2489 newDs.addElement(null);
2491 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2493 if (importDs && ds != null)
2495 if (!newDs.contains(ds))
2497 newDs.setElementAt(ds, i);
2498 ds = new Sequence(ds);
2499 // update with new dataset sequence
2500 sequences[i].setDatasetSequence(ds);
2504 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2509 // copy and derive new dataset sequence
2510 sequences[i] = sequences[i].deriveSequence();
2511 alignment.getDataset()
2512 .addSequence(sequences[i].getDatasetSequence());
2513 // TODO: avoid creation of duplicate dataset sequences with a
2514 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2516 alignment.addSequence(sequences[i]); // merges dataset
2520 newDs.clear(); // tidy up
2522 if (alignment.getAlignmentAnnotation() != null)
2524 for (AlignmentAnnotation alan : alignment
2525 .getAlignmentAnnotation())
2527 if (alan.graphGroup > fgroup)
2529 fgroup = alan.graphGroup;
2533 if (pastedal.getAlignmentAnnotation() != null)
2535 // Add any annotation attached to alignment.
2536 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2537 for (int i = 0; i < alann.length; i++)
2539 annotationAdded = true;
2540 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2542 AlignmentAnnotation newann = new AlignmentAnnotation(
2544 if (newann.graphGroup > -1)
2546 if (newGraphGroups.size() <= newann.graphGroup
2547 || newGraphGroups.get(newann.graphGroup) == null)
2549 for (int q = newGraphGroups
2550 .size(); q <= newann.graphGroup; q++)
2552 newGraphGroups.add(q, null);
2554 newGraphGroups.set(newann.graphGroup,
2555 Integer.valueOf(++fgroup));
2557 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2561 newann.padAnnotation(alwidth);
2562 alignment.addAnnotation(newann);
2572 addHistoryItem(new EditCommand(
2573 MessageManager.getString("label.add_sequences"),
2574 Action.PASTE, sequences, 0, alignment.getWidth(),
2577 // Add any annotations attached to sequences
2578 for (int i = 0; i < sequences.length; i++)
2580 if (sequences[i].getAnnotation() != null)
2582 AlignmentAnnotation newann;
2583 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2585 annotationAdded = true;
2586 newann = sequences[i].getAnnotation()[a];
2587 newann.adjustForAlignment();
2588 newann.padAnnotation(alwidth);
2589 if (newann.graphGroup > -1)
2591 if (newann.graphGroup > -1)
2593 if (newGraphGroups.size() <= newann.graphGroup
2594 || newGraphGroups.get(newann.graphGroup) == null)
2596 for (int q = newGraphGroups
2597 .size(); q <= newann.graphGroup; q++)
2599 newGraphGroups.add(q, null);
2601 newGraphGroups.set(newann.graphGroup,
2602 Integer.valueOf(++fgroup));
2604 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2608 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2612 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2620 // propagate alignment changed.
2621 viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2622 if (annotationAdded)
2624 // Duplicate sequence annotation in all views.
2625 AlignmentI[] alview = this.getViewAlignments();
2626 for (int i = 0; i < sequences.length; i++)
2628 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2633 for (int avnum = 0; avnum < alview.length; avnum++)
2635 if (alview[avnum] != alignment)
2637 // duplicate in a view other than the one with input focus
2638 int avwidth = alview[avnum].getWidth() + 1;
2639 // this relies on sann being preserved after we
2640 // modify the sequence's annotation array for each duplication
2641 for (int a = 0; a < sann.length; a++)
2643 AlignmentAnnotation newann = new AlignmentAnnotation(
2645 sequences[i].addAlignmentAnnotation(newann);
2646 newann.padAnnotation(avwidth);
2647 alview[avnum].addAnnotation(newann); // annotation was
2648 // duplicated earlier
2649 // TODO JAL-1145 graphGroups are not updated for sequence
2650 // annotation added to several views. This may cause
2652 alview[avnum].setAnnotationIndex(newann, a);
2657 buildSortByAnnotationScoresMenu();
2659 viewport.notifyAlignment();
2660 if (alignPanels != null)
2662 for (AlignmentPanel ap : alignPanels)
2664 ap.validateAnnotationDimensions(false);
2669 alignPanel.validateAnnotationDimensions(false);
2675 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2677 String newtitle = new String("Copied sequences");
2679 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2681 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2682 af.viewport.setHiddenColumns(hc);
2685 // >>>This is a fix for the moment, until a better solution is
2687 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2688 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2689 .getFeatureRenderer());
2691 // TODO: maintain provenance of an alignment, rather than just make the
2692 // title a concatenation of operations.
2695 if (title.startsWith("Copied sequences"))
2701 newtitle = newtitle.concat("- from " + title);
2706 newtitle = new String("Pasted sequences");
2709 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2714 } catch (Exception ex)
2716 ex.printStackTrace();
2717 System.out.println("Exception whilst pasting: " + ex);
2718 // could be anything being pasted in here
2723 protected void expand_newalign(ActionEvent e)
2727 AlignmentI alignment = AlignmentUtils
2728 .expandContext(getViewport().getAlignment(), -1);
2729 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2731 String newtitle = new String("Flanking alignment");
2732 Desktop d = Desktop.getInstance();
2733 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2735 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2736 af.viewport.setHiddenColumns(hc);
2739 // >>>This is a fix for the moment, until a better solution is
2741 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2742 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2743 .getFeatureRenderer());
2745 // TODO: maintain provenance of an alignment, rather than just make the
2746 // title a concatenation of operations.
2748 if (title.startsWith("Copied sequences"))
2754 newtitle = newtitle.concat("- from " + title);
2758 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2760 } catch (Exception ex)
2762 ex.printStackTrace();
2763 System.out.println("Exception whilst pasting: " + ex);
2764 // could be anything being pasted in here
2765 } catch (OutOfMemoryError oom)
2767 new OOMWarning("Viewing flanking region of alignment", oom);
2772 * Action Cut (delete and copy) the selected region
2776 protected void cut_actionPerformed()
2778 copy_actionPerformed();
2779 delete_actionPerformed();
2783 * Performs menu option to Delete the currently selected region
2787 protected void delete_actionPerformed()
2790 SequenceGroup sg = viewport.getSelectionGroup();
2796 Runnable okAction = new Runnable()
2802 SequenceI[] cut = sg.getSequences()
2803 .toArray(new SequenceI[sg.getSize()]);
2805 addHistoryItem(new EditCommand(
2806 MessageManager.getString("label.cut_sequences"), Action.CUT,
2807 cut, sg.getStartRes(),
2808 sg.getEndRes() - sg.getStartRes() + 1,
2809 viewport.getAlignment()));
2811 viewport.setSelectionGroup(null);
2812 viewport.sendSelection();
2813 viewport.getAlignment().deleteGroup(sg);
2815 viewport.notifyAlignment();
2817 if (viewport.getAlignment().getHeight() < 1)
2821 AlignFrame.this.setClosed(true);
2822 } catch (Exception ex)
2832 * If the cut affects all sequences, prompt for confirmation
2834 boolean wholeHeight = sg.getSize() == viewport.getAlignment()
2836 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2837 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2838 if (wholeHeight && wholeWidth)
2840 JvOptionPane dialog = JvOptionPane
2841 .newOptionDialog(Desktop.getDesktopPane());
2842 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2843 Object[] options = new Object[] {
2844 MessageManager.getString("action.ok"),
2845 MessageManager.getString("action.cancel") };
2846 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2847 MessageManager.getString("label.delete_all"),
2848 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2849 options, options[0]);
2865 protected void deleteGroups_actionPerformed(ActionEvent e)
2867 if (avc.deleteGroups())
2869 updateAll(viewport.getSequenceSetId());
2873 private void updateAll(String id)
2877 // this will force a non-fast repaint of both the IdPanel and SeqPanel
2878 alignPanel.getIdPanel().getIdCanvas().setNoFastPaint();
2879 alignPanel.getSeqPanel().seqCanvas.setNoFastPaint();
2880 alignPanel.repaint();
2885 PaintRefresher.Refresh(this, id);
2886 alignPanel.paintAlignment(true, true);
2888 alignPanel.updateAnnotation();
2899 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2901 alignPanel.selectAllSequences();
2912 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2914 alignPanel.deselectAllSequences();
2925 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2927 SequenceGroup sg = viewport.getSelectionGroup();
2931 alignPanel.selectAllSequences();
2936 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2938 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2940 // JAL-2034 - should delegate to
2941 // alignPanel to decide if overview needs
2944 alignPanel.paintAlignment(true, false);
2945 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2946 viewport.sendSelection();
2950 public void invertColSel_actionPerformed(ActionEvent e)
2952 viewport.invertColumnSelection();
2953 alignPanel.paintAlignment(true, false);
2954 viewport.sendSelection();
2965 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2967 trimAlignment(true);
2978 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2980 trimAlignment(false);
2983 void trimAlignment(boolean trimLeft)
2985 ColumnSelection colSel = viewport.getColumnSelection();
2988 if (!colSel.isEmpty())
2992 column = colSel.getMin();
2996 column = colSel.getMax();
3000 if (viewport.getSelectionGroup() != null)
3002 seqs = viewport.getSelectionGroup()
3003 .getSequencesAsArray(viewport.getHiddenRepSequences());
3007 seqs = viewport.getAlignment().getSequencesArray();
3010 TrimRegionCommand trimRegion;
3013 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
3014 column, viewport.getAlignment());
3015 viewport.getRanges().setStartRes(0);
3019 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
3020 column, viewport.getAlignment());
3023 setStatus(MessageManager.formatMessage("label.removed_columns",
3025 { Integer.valueOf(trimRegion.getSize()).toString() }));
3027 addHistoryItem(trimRegion);
3029 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3031 if ((trimLeft && !sg.adjustForRemoveLeft(column))
3032 || (!trimLeft && !sg.adjustForRemoveRight(column)))
3034 viewport.getAlignment().deleteGroup(sg);
3038 viewport.notifyAlignment();
3051 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
3053 int start = 0, end = viewport.getAlignment().getWidth() - 1;
3056 if (viewport.getSelectionGroup() != null)
3058 seqs = viewport.getSelectionGroup()
3059 .getSequencesAsArray(viewport.getHiddenRepSequences());
3060 start = viewport.getSelectionGroup().getStartRes();
3061 end = viewport.getSelectionGroup().getEndRes();
3065 seqs = viewport.getAlignment().getSequencesArray();
3068 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
3069 "Remove Gapped Columns", seqs, start, end,
3070 viewport.getAlignment());
3072 addHistoryItem(removeGapCols);
3074 setStatus(MessageManager.formatMessage("label.removed_empty_columns",
3076 { Integer.valueOf(removeGapCols.getSize()).toString() }));
3078 // This is to maintain viewport position on first residue
3079 // of first sequence
3080 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3081 ViewportRanges ranges = viewport.getRanges();
3082 int startRes = seq.findPosition(ranges.getStartRes());
3083 // ShiftList shifts;
3084 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
3085 // edit.alColumnChanges=shifts.getInverse();
3086 // if (viewport.hasHiddenColumns)
3087 // viewport.getColumnSelection().compensateForEdits(shifts);
3088 ranges.setStartRes(seq.findIndex(startRes) - 1);
3089 viewport.notifyAlignment();
3102 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
3104 int start = 0, end = viewport.getAlignment().getWidth() - 1;
3107 if (viewport.getSelectionGroup() != null)
3109 seqs = viewport.getSelectionGroup()
3110 .getSequencesAsArray(viewport.getHiddenRepSequences());
3111 start = viewport.getSelectionGroup().getStartRes();
3112 end = viewport.getSelectionGroup().getEndRes();
3116 seqs = viewport.getAlignment().getSequencesArray();
3119 // This is to maintain viewport position on first residue
3120 // of first sequence
3121 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3122 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
3124 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
3125 viewport.getAlignment()));
3127 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
3128 viewport.notifyAlignment();
3140 public void padGapsMenuitem_actionPerformed(ActionEvent e)
3142 viewport.setPadGaps(padGapsMenuitem.isSelected());
3143 viewport.notifyAlignment();
3155 public void findMenuItem_actionPerformed(ActionEvent e)
3161 * Create a new view of the current alignment.
3165 public void newView_actionPerformed(ActionEvent e)
3167 newView(null, true);
3171 * Creates and shows a new view of the current alignment.
3174 * title of newly created view; if null, one will be generated
3175 * @param copyAnnotation
3176 * if true then duplicate all annnotation, groups and settings
3177 * @return new alignment panel, already displayed.
3180 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
3183 * Create a new AlignmentPanel (with its own, new Viewport)
3185 AlignmentPanel newap = new jalview.project.Jalview2XML()
3186 .copyAlignPanel(alignPanel);
3187 if (!copyAnnotation)
3190 * remove all groups and annotation except for the automatic stuff
3192 newap.av.getAlignment().deleteAllGroups();
3193 newap.av.getAlignment().deleteAllAnnotations(false);
3196 newap.av.setGatherViewsHere(false);
3198 if (viewport.getViewName() == null)
3200 viewport.setViewName(
3201 MessageManager.getString("label.view_name_original"));
3205 * Views share the same edits undo and redo stacks
3207 newap.av.setHistoryList(viewport.getHistoryList());
3208 newap.av.setRedoList(viewport.getRedoList());
3211 * copy any visualisation settings that are not saved in the project
3213 newap.av.setColourAppliesToAllGroups(
3214 viewport.getColourAppliesToAllGroups());
3217 * Views share the same mappings; need to deregister any new mappings
3218 * created by copyAlignPanel, and register the new reference to the shared
3221 newap.av.replaceMappings(viewport.getAlignment());
3224 * start up cDNA consensus (if applicable) now mappings are in place
3226 if (newap.av.initComplementConsensus())
3228 newap.refresh(true); // adjust layout of annotations
3231 newap.av.setViewName(getNewViewName(viewTitle));
3233 addAlignmentPanel(newap, true);
3234 newap.alignmentChanged();
3236 if (alignPanels.size() == 2)
3238 viewport.setGatherViewsHere(true);
3240 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
3245 * Make a new name for the view, ensuring it is unique within the current
3246 * sequenceSetId. (This used to be essential for Jalview Project archives, but
3247 * these now use viewId. Unique view names are still desirable for usability.)
3253 protected String getNewViewName(String viewTitle)
3255 int index = Desktop.getViewCount(viewport.getSequenceSetId());
3256 boolean addFirstIndex = false;
3257 if (viewTitle == null || viewTitle.trim().length() == 0)
3259 viewTitle = MessageManager.getString("action.view");
3260 addFirstIndex = true;
3264 index = 1;// we count from 1 if given a specific name
3266 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
3268 List<Component> comps = PaintRefresher.components
3269 .get(viewport.getSequenceSetId());
3271 List<String> existingNames = getExistingViewNames(comps);
3273 while (existingNames.contains(newViewName))
3275 newViewName = viewTitle + " " + (++index);
3281 * Returns a list of distinct view names found in the given list of
3282 * components. View names are held on the viewport of an AlignmentPanel.
3288 protected List<String> getExistingViewNames(List<Component> comps)
3290 List<String> existingNames = new ArrayList<>();
3291 for (Component comp : comps)
3293 if (comp instanceof AlignmentPanel)
3295 AlignmentPanel ap = (AlignmentPanel) comp;
3296 if (!existingNames.contains(ap.av.getViewName()))
3298 existingNames.add(ap.av.getViewName());
3302 return existingNames;
3306 * Explode tabbed views into separate windows.
3310 public void expandViews_actionPerformed(ActionEvent e)
3312 Desktop.explodeViews(this);
3316 * Gather views in separate windows back into a tabbed presentation.
3320 public void gatherViews_actionPerformed(ActionEvent e)
3322 Desktop.getInstance().gatherViews(this);
3333 public void font_actionPerformed(ActionEvent e)
3335 new FontChooser(alignPanel);
3346 protected void seqLimit_actionPerformed(ActionEvent e)
3348 viewport.setShowJVSuffix(seqLimits.isSelected());
3350 alignPanel.getIdPanel().getIdCanvas()
3351 .setPreferredSize(alignPanel.calculateIdWidth());
3352 alignPanel.paintAlignment(true, false);
3356 public void idRightAlign_actionPerformed(ActionEvent e)
3358 viewport.setRightAlignIds(idRightAlign.isSelected());
3359 alignPanel.paintAlignment(false, false);
3363 public void centreColumnLabels_actionPerformed(ActionEvent e)
3365 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3366 alignPanel.paintAlignment(false, false);
3372 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3376 protected void followHighlight_actionPerformed()
3379 * Set the 'follow' flag on the Viewport (and scroll to position if now
3382 final boolean state = this.followHighlightMenuItem.getState();
3383 viewport.setFollowHighlight(state);
3386 alignPanel.scrollToPosition(viewport.getSearchResults());
3398 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3400 viewport.setColourText(colourTextMenuItem.isSelected());
3401 alignPanel.paintAlignment(false, false);
3412 public void wrapMenuItem_actionPerformed(ActionEvent e)
3414 scaleAbove.setVisible(wrapMenuItem.isSelected());
3415 scaleLeft.setVisible(wrapMenuItem.isSelected());
3416 scaleRight.setVisible(wrapMenuItem.isSelected());
3417 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3418 alignPanel.updateLayout();
3422 public void showAllSeqs_actionPerformed(ActionEvent e)
3424 viewport.showAllHiddenSeqs();
3428 public void showAllColumns_actionPerformed(ActionEvent e)
3430 viewport.showAllHiddenColumns();
3431 alignPanel.paintAlignment(true, true);
3432 viewport.sendSelection();
3436 public void hideSelSequences_actionPerformed(ActionEvent e)
3438 viewport.hideAllSelectedSeqs();
3442 * called by key handler and the hide all/show all menu items
3448 protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3451 boolean hide = false;
3452 SequenceGroup sg = viewport.getSelectionGroup();
3453 if (!toggleSeqs && !toggleCols)
3455 // Hide everything by the current selection - this is a hack - we do the
3456 // invert and then hide
3457 // first check that there will be visible columns after the invert.
3458 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3459 && sg.getStartRes() <= sg.getEndRes()))
3461 // now invert the sequence set, if required - empty selection implies
3462 // that no hiding is required.
3465 invertSequenceMenuItem_actionPerformed(null);
3466 sg = viewport.getSelectionGroup();
3470 viewport.expandColSelection(sg, true);
3471 // finally invert the column selection and get the new sequence
3473 invertColSel_actionPerformed(null);
3480 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3482 hideSelSequences_actionPerformed(null);
3485 else if (!(toggleCols && viewport.hasSelectedColumns()))
3487 showAllSeqs_actionPerformed(null);
3493 if (viewport.hasSelectedColumns())
3495 hideSelColumns_actionPerformed(null);
3498 viewport.setSelectionGroup(sg);
3503 showAllColumns_actionPerformed(null);
3512 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3513 * event.ActionEvent)
3517 public void hideAllButSelection_actionPerformed(ActionEvent e)
3519 toggleHiddenRegions(false, false);
3520 viewport.sendSelection();
3527 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3532 public void hideAllSelection_actionPerformed(ActionEvent e)
3534 SequenceGroup sg = viewport.getSelectionGroup();
3535 viewport.expandColSelection(sg, false);
3536 viewport.hideAllSelectedSeqs();
3537 viewport.hideSelectedColumns();
3538 alignPanel.updateLayout();
3539 alignPanel.paintAlignment(true, true);
3540 viewport.sendSelection();
3547 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3552 public void showAllhidden_actionPerformed(ActionEvent e)
3554 viewport.showAllHiddenColumns();
3555 viewport.showAllHiddenSeqs();
3556 alignPanel.paintAlignment(true, true);
3557 viewport.sendSelection();
3561 public void hideSelColumns_actionPerformed(ActionEvent e)
3563 viewport.hideSelectedColumns();
3564 alignPanel.updateLayout();
3565 alignPanel.paintAlignment(true, true);
3566 viewport.sendSelection();
3570 public void hiddenMarkers_actionPerformed(ActionEvent e)
3572 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3584 protected void scaleAbove_actionPerformed(ActionEvent e)
3586 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3587 alignPanel.updateLayout();
3588 alignPanel.paintAlignment(true, false);
3599 protected void scaleLeft_actionPerformed(ActionEvent e)
3601 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3602 alignPanel.updateLayout();
3603 alignPanel.paintAlignment(true, false);
3614 protected void scaleRight_actionPerformed(ActionEvent e)
3616 viewport.setScaleRightWrapped(scaleRight.isSelected());
3617 alignPanel.updateLayout();
3618 alignPanel.paintAlignment(true, false);
3629 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3631 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3632 alignPanel.paintAlignment(false, false);
3643 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3645 viewport.setShowText(viewTextMenuItem.isSelected());
3646 alignPanel.paintAlignment(false, false);
3657 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3659 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3660 alignPanel.paintAlignment(false, false);
3663 public FeatureSettings featureSettings;
3666 public FeatureSettingsControllerI getFeatureSettingsUI()
3668 return featureSettings;
3672 public void featureSettings_actionPerformed(ActionEvent e)
3674 showFeatureSettingsUI();
3678 public FeatureSettingsControllerI showFeatureSettingsUI()
3680 if (featureSettings != null)
3682 featureSettings.closeOldSettings();
3683 featureSettings = null;
3685 if (!showSeqFeatures.isSelected())
3687 // make sure features are actually displayed
3688 showSeqFeatures.setSelected(true);
3689 showSeqFeatures_actionPerformed(null);
3691 featureSettings = new FeatureSettings(this);
3692 return featureSettings;
3696 * Set or clear 'Show Sequence Features'
3703 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3705 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3706 alignPanel.paintAlignment(true, true);
3710 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3711 * the annotations panel as a whole.
3713 * The options to show/hide all annotations should be enabled when the panel
3714 * is shown, and disabled when the panel is hidden.
3720 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3722 final boolean setVisible = annotationPanelMenuItem.isSelected();
3723 viewport.setShowAnnotation(setVisible);
3724 syncAnnotationMenuItems(setVisible);
3725 alignPanel.updateLayout();
3727 SwingUtilities.invokeLater(new Runnable() {
3732 alignPanel.updateScrollBarsFromRanges();
3738 private void syncAnnotationMenuItems(boolean setVisible)
3740 showAllSeqAnnotations.setEnabled(setVisible);
3741 hideAllSeqAnnotations.setEnabled(setVisible);
3742 showAllAlAnnotations.setEnabled(setVisible);
3743 hideAllAlAnnotations.setEnabled(setVisible);
3747 public void alignmentProperties()
3750 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3753 String content = MessageManager.formatMessage("label.html_content",
3755 { contents.toString() });
3758 if (Platform.isJS())
3760 JLabel textLabel = new JLabel();
3761 textLabel.setText(content);
3762 textLabel.setBackground(Color.WHITE);
3764 pane = new JPanel(new BorderLayout());
3765 ((JPanel) pane).setOpaque(true);
3766 pane.setBackground(Color.WHITE);
3767 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3776 JEditorPane editPane = new JEditorPane("text/html", "");
3777 editPane.setEditable(false);
3778 editPane.setText(content);
3782 JInternalFrame frame = new JInternalFrame();
3784 frame.getContentPane().add(new JScrollPane(pane));
3786 Desktop.addInternalFrame(frame, MessageManager
3787 .formatMessage("label.alignment_properties", new Object[]
3788 { getTitle() }), 500, 400);
3799 public void overviewMenuItem_actionPerformed(ActionEvent e)
3801 if (alignPanel.overviewPanel != null)
3806 JInternalFrame frame = new JInternalFrame();
3808 // BH 2019.07.26 we allow for an embedded
3809 // undecorated overview with defined size
3810 frame.setName(Platform.getAppID("overview"));
3812 Dimension dim = Platform.getDimIfEmbedded(frame, -1, -1);
3813 if (dim != null && dim.width == 0)
3815 dim = null; // hidden, not embedded
3817 OverviewPanel overview = new OverviewPanel(alignPanel, dim);
3819 frame.setContentPane(overview);
3822 dim = new Dimension();
3823 // was frame.getSize(), but that is 0,0 at this point;
3827 // we are imbedding, and so we have an undecorated frame
3828 // and we can set the the frame dimensions accordingly.
3830 // allowing for unresizable option using, style="resize:none"
3831 boolean resizable = (Platform.getEmbeddedAttribute(frame,
3832 "resize") != "none");
3833 Desktop.addInternalFrame(frame, MessageManager
3834 .formatMessage("label.overview_params", new Object[]
3835 { this.getTitle() }), Desktop.FRAME_MAKE_VISIBLE, dim.width,
3836 dim.height, resizable, Desktop.FRAME_ALLOW_ANY_SIZE);
3838 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3839 frame.addInternalFrameListener(
3840 new javax.swing.event.InternalFrameAdapter()
3844 public void internalFrameClosed(
3845 javax.swing.event.InternalFrameEvent evt)
3848 alignPanel.setOverviewPanel(null);
3851 if (getKeyListeners().length > 0)
3853 frame.addKeyListener(getKeyListeners()[0]);
3856 alignPanel.setOverviewPanel(overview);
3860 public void textColour_actionPerformed()
3862 new TextColourChooser().chooseColour(alignPanel, null);
3866 * public void covariationColour_actionPerformed() {
3868 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3873 public void annotationColour_actionPerformed()
3875 new AnnotationColourChooser(viewport, alignPanel);
3879 public void annotationColumn_actionPerformed(ActionEvent e)
3881 new AnnotationColumnChooser(viewport, alignPanel);
3885 * Action on the user checking or unchecking the option to apply the selected
3886 * colour scheme to all groups. If unchecked, groups may have their own
3887 * independent colour schemes.
3893 public void applyToAllGroups_actionPerformed(boolean selected)
3895 viewport.setColourAppliesToAllGroups(selected);
3899 * Action on user selecting a colour from the colour menu
3902 * the name (not the menu item label!) of the colour scheme
3906 public void changeColour_actionPerformed(String name)
3909 * 'User Defined' opens a panel to configure or load a
3910 * user-defined colour scheme
3912 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3914 new UserDefinedColours(alignPanel);
3919 * otherwise set the chosen colour scheme (or null for 'None')
3921 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3922 viewport, viewport.getAlignment(),
3923 viewport.getHiddenRepSequences());
3928 * Actions on setting or changing the alignment colour scheme
3934 public void changeColour(ColourSchemeI cs)
3936 // TODO: pull up to controller method
3937 ColourMenuHelper.setColourSelected(colourMenu, cs);
3939 viewport.setGlobalColourScheme(cs);
3941 alignPanel.paintAlignment(true, true);
3945 * Show the PID threshold slider panel
3949 protected void modifyPID_actionPerformed()
3951 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3952 alignPanel.getViewName());
3953 SliderPanel.showPIDSlider();
3957 * Show the Conservation slider panel
3961 protected void modifyConservation_actionPerformed()
3963 SliderPanel.setConservationSlider(alignPanel,
3964 viewport.getResidueShading(), alignPanel.getViewName());
3965 SliderPanel.showConservationSlider();
3969 * Action on selecting or deselecting (Colour) By Conservation
3973 public void conservationMenuItem_actionPerformed(boolean selected)
3975 modifyConservation.setEnabled(selected);
3976 viewport.setConservationSelected(selected);
3977 viewport.getResidueShading().setConservationApplied(selected);
3979 changeColour(viewport.getGlobalColourScheme());
3982 modifyConservation_actionPerformed();
3986 SliderPanel.hideConservationSlider();
3991 * Action on selecting or deselecting (Colour) Above PID Threshold
3995 public void abovePIDThreshold_actionPerformed(boolean selected)
3997 modifyPID.setEnabled(selected);
3998 viewport.setAbovePIDThreshold(selected);
4001 viewport.getResidueShading().setThreshold(0,
4002 viewport.isIgnoreGapsConsensus());
4005 changeColour(viewport.getGlobalColourScheme());
4008 modifyPID_actionPerformed();
4012 SliderPanel.hidePIDSlider();
4024 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
4026 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4027 AlignmentSorter.sortByPID(viewport.getAlignment(),
4028 viewport.getAlignment().getSequenceAt(0));
4029 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
4030 viewport.getAlignment()));
4031 alignPanel.paintAlignment(true, false);
4042 public void sortIDMenuItem_actionPerformed(ActionEvent e)
4044 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4045 AlignmentSorter.sortByID(viewport.getAlignment());
4047 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
4048 alignPanel.paintAlignment(true, false);
4059 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
4061 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4062 AlignmentSorter.sortByLength(viewport.getAlignment());
4063 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
4064 viewport.getAlignment()));
4065 alignPanel.paintAlignment(true, false);
4076 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
4078 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4079 AlignmentSorter.sortByGroup(viewport.getAlignment());
4080 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4081 viewport.getAlignment()));
4083 alignPanel.paintAlignment(true, false);
4087 public void sortEValueMenuItem_actionPerformed(ActionEvent e)
4089 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4090 AlignmentSorter.sortByEValue(viewport.getAlignment());
4091 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4092 viewport.getAlignment()));
4093 alignPanel.paintAlignment(true, false);
4098 public void sortBitScoreMenuItem_actionPerformed(ActionEvent e)
4100 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4101 AlignmentSorter.sortByBitScore(viewport.getAlignment());
4102 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4103 viewport.getAlignment()));
4104 alignPanel.paintAlignment(true, false);
4116 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
4118 new RedundancyPanel(alignPanel, this);
4129 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
4131 if ((viewport.getSelectionGroup() == null)
4132 || (viewport.getSelectionGroup().getSize() < 2))
4134 JvOptionPane.showInternalMessageDialog(this,
4135 MessageManager.getString(
4136 "label.you_must_select_least_two_sequences"),
4137 MessageManager.getString("label.invalid_selection"),
4138 JvOptionPane.WARNING_MESSAGE);
4142 JInternalFrame frame = new JInternalFrame();
4143 frame.setContentPane(new PairwiseAlignPanel(viewport));
4144 Desktop.addInternalFrame(frame,
4145 MessageManager.getString("action.pairwise_alignment"), 600,
4151 public void autoCalculate_actionPerformed(ActionEvent e)
4153 viewport.setAutoCalculateConsensusAndConservation(
4154 autoCalculate.isSelected());
4155 if (viewport.getAutoCalculateConsensusAndConservation())
4157 // viewport.autoCalculateConsensus = autoCalculate.isSelected();
4158 // if (viewport.autoCalculateConsensus)
4160 viewport.notifyAlignment();
4165 public void sortByTreeOption_actionPerformed(ActionEvent e)
4167 viewport.sortByTree = sortByTree.isSelected();
4171 protected void listenToViewSelections_actionPerformed(ActionEvent e)
4173 viewport.followSelection = listenToViewSelections.isSelected();
4177 * Constructs a tree panel and adds it to the desktop
4180 * tree type (NJ or AV)
4182 * name of score model used to compute the tree
4184 * parameters for the distance or similarity calculation
4187 void newTreePanel(String type, String modelName,
4188 SimilarityParamsI options)
4190 String frameTitle = "";
4193 boolean onSelection = false;
4194 if (viewport.getSelectionGroup() != null
4195 && viewport.getSelectionGroup().getSize() > 0)
4197 SequenceGroup sg = viewport.getSelectionGroup();
4199 /* Decide if the selection is a column region */
4200 for (SequenceI _s : sg.getSequences())
4202 if (_s.getLength() < sg.getEndRes())
4204 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4205 MessageManager.getString(
4206 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
4207 MessageManager.getString(
4208 "label.sequences_selection_not_aligned"),
4209 JvOptionPane.WARNING_MESSAGE);
4218 if (viewport.getAlignment().getHeight() < 2)
4224 tp = new TreePanel(alignPanel, type, modelName, options);
4225 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
4227 frameTitle += " from ";
4229 if (viewport.getViewName() != null)
4231 frameTitle += viewport.getViewName() + " of ";
4234 frameTitle += this.title;
4236 Dimension dim = Platform.getDimIfEmbedded(tp, 600, 500);
4237 Desktop.addInternalFrame(tp, frameTitle, dim.width, dim.height);
4249 public void addSortByOrderMenuItem(String title,
4250 final AlignmentOrder order)
4252 final JMenuItem item = new JMenuItem(MessageManager
4253 .formatMessage("action.by_title_param", new Object[]
4256 item.addActionListener(new java.awt.event.ActionListener()
4260 public void actionPerformed(ActionEvent e)
4262 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4264 // TODO: JBPNote - have to map order entries to curent SequenceI
4266 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4268 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
4269 viewport.getAlignment()));
4271 alignPanel.paintAlignment(true, false);
4277 * Add a new sort by annotation score menu item
4280 * the menu to add the option to
4282 * the label used to retrieve scores for each sequence on the
4286 public void addSortByAnnotScoreMenuItem(JMenu sort,
4287 final String scoreLabel)
4289 final JMenuItem item = new JMenuItem(scoreLabel);
4291 item.addActionListener(new java.awt.event.ActionListener()
4295 public void actionPerformed(ActionEvent e)
4297 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4298 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4299 viewport.getAlignment());// ,viewport.getSelectionGroup());
4300 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4301 viewport.getAlignment()));
4302 alignPanel.paintAlignment(true, false);
4308 * last hash for alignment's annotation array - used to minimise cost of
4311 protected int _annotationScoreVectorHash;
4314 * search the alignment and rebuild the sort by annotation score submenu the
4315 * last alignment annotation vector hash is stored to minimize cost of
4316 * rebuilding in subsequence calls.
4321 public void buildSortByAnnotationScoresMenu()
4323 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4328 if (viewport.getAlignment().getAlignmentAnnotation()
4329 .hashCode() == _annotationScoreVectorHash)
4334 sortByAnnotScore.removeAll();
4335 Set<String> scoreSorts = new HashSet<>();
4336 for (SequenceI sqa : viewport.getAlignment().getSequences())
4338 AlignmentAnnotation[] anns = sqa.getAnnotation();
4339 for (int i = 0; anns != null && i < anns.length; i++)
4341 AlignmentAnnotation aa = anns[i];
4342 if (aa != null && aa.hasScore() && aa.sequenceRef != null)
4344 scoreSorts.add(aa.label);
4348 for (String label : scoreSorts)
4350 addSortByAnnotScoreMenuItem(sortByAnnotScore, label);
4352 sortByAnnotScore.setVisible(!scoreSorts.isEmpty());
4354 _annotationScoreVectorHash = viewport.getAlignment()
4355 .getAlignmentAnnotation().hashCode();
4359 * Enable (or, if desired, make visible) the By Tree
4360 * submenu only if it has at least one element (or will have).
4364 protected void enableSortMenuOptions()
4366 List<TreePanel> treePanels = getTreePanels();
4367 sortByTreeMenu.setEnabled(!treePanels.isEmpty());
4371 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4372 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4373 * call. Listeners are added to remove the menu item when the treePanel is
4374 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4379 public void buildTreeSortMenu()
4381 sortByTreeMenu.removeAll();
4383 List<TreePanel> treePanels = getTreePanels();
4385 for (final TreePanel tp : treePanels)
4387 final JMenuItem item = new JMenuItem(tp.getTitle());
4388 item.addActionListener(new java.awt.event.ActionListener()
4392 public void actionPerformed(ActionEvent e)
4394 tp.sortByTree_actionPerformed();
4395 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4400 sortByTreeMenu.add(item);
4404 private List<TreePanel> getTreePanels()
4406 List<Component> comps = PaintRefresher.components
4407 .get(viewport.getSequenceSetId());
4408 List<TreePanel> treePanels = new ArrayList<>();
4409 for (Component comp : comps)
4411 if (comp instanceof TreePanel)
4413 treePanels.add((TreePanel) comp);
4419 public boolean sortBy(AlignmentOrder alorder, String undoname)
4421 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4422 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4423 if (undoname != null)
4425 addHistoryItem(new OrderCommand(undoname, oldOrder,
4426 viewport.getAlignment()));
4428 alignPanel.paintAlignment(true, false);
4433 * Work out whether the whole set of sequences or just the selected set will
4434 * be submitted for multiple alignment.
4438 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4440 // Now, check we have enough sequences
4441 AlignmentView msa = null;
4443 if ((viewport.getSelectionGroup() != null)
4444 && (viewport.getSelectionGroup().getSize() > 1))
4446 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4447 // some common interface!
4449 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4450 * SequenceI[sz = seqs.getSize(false)];
4452 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4453 * seqs.getSequenceAt(i); }
4455 msa = viewport.getAlignmentView(true);
4457 else if (viewport.getSelectionGroup() != null
4458 && viewport.getSelectionGroup().getSize() == 1)
4460 int option = JvOptionPane.showConfirmDialog(this,
4461 MessageManager.getString("warn.oneseq_msainput_selection"),
4462 MessageManager.getString("label.invalid_selection"),
4463 JvOptionPane.OK_CANCEL_OPTION);
4464 if (option == JvOptionPane.OK_OPTION)
4466 msa = viewport.getAlignmentView(false);
4471 msa = viewport.getAlignmentView(false);
4477 * Decides what is submitted to a secondary structure prediction service: the
4478 * first sequence in the alignment, or in the current selection, or, if the
4479 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4480 * region or the whole alignment. (where the first sequence in the set is the
4481 * one that the prediction will be for).
4484 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4486 AlignmentView seqs = null;
4488 if ((viewport.getSelectionGroup() != null)
4489 && (viewport.getSelectionGroup().getSize() > 0))
4491 seqs = viewport.getAlignmentView(true);
4495 seqs = viewport.getAlignmentView(false);
4497 // limit sequences - JBPNote in future - could spawn multiple prediction
4499 // TODO: viewport.getAlignment().isAligned is a global state - the local
4500 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4501 if (!viewport.getAlignment().isAligned(false))
4503 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4504 // TODO: if seqs.getSequences().length>1 then should really have warned
4519 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4521 // Pick the tree file
4522 JalviewFileChooser chooser = new JalviewFileChooser(
4523 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4524 chooser.setFileView(new JalviewFileView());
4525 chooser.setDialogTitle(
4526 MessageManager.getString("label.select_newick_like_tree_file"));
4527 chooser.setToolTipText(
4528 MessageManager.getString("label.load_tree_file"));
4530 chooser.setResponseHandler(0, new Runnable()
4536 String filePath = chooser.getSelectedFile().getPath();
4537 Cache.setProperty("LAST_DIRECTORY", filePath);
4538 NewickFile fin = null;
4541 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4542 DataSourceType.FILE));
4543 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4544 } catch (Exception ex)
4546 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4549 .getString("label.problem_reading_tree_file"),
4550 JvOptionPane.WARNING_MESSAGE);
4551 ex.printStackTrace();
4553 if (fin != null && fin.hasWarningMessage())
4555 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4556 fin.getWarningMessage(),
4557 MessageManager.getString(
4558 "label.possible_problem_with_tree_file"),
4559 JvOptionPane.WARNING_MESSAGE);
4563 chooser.showOpenDialog(this);
4566 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4568 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4571 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4572 int h, int x, int y)
4574 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4578 * Add a treeviewer for the tree extracted from a Newick file object to the
4579 * current alignment view
4586 * Associated alignment input data (or null)
4595 * @return TreePanel handle
4598 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4599 AlignmentView input, int w, int h, int x, int y)
4601 TreePanel tp = null;
4607 if (nf.getTree() != null)
4609 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4610 Dimension dim = Platform.getDimIfEmbedded(tp, -1, -1);
4613 dim = new Dimension(w, h);
4617 // no offset, either
4620 tp.setSize(dim.width, dim.height);
4624 tp.setLocation(x, y);
4627 Desktop.addInternalFrame(tp, treeTitle, dim.width, dim.height);
4629 } catch (Exception ex)
4631 ex.printStackTrace();
4638 * Schedule the web services menu rebuild to the event dispatch thread.
4640 public void buildWebServicesMenu()
4642 SwingUtilities.invokeLater(() -> {
4643 Cache.log.info("Rebuiling WS menu");
4644 webService.removeAll();
4645 if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
4647 Cache.log.info("Building web service menu for slivka");
4648 SlivkaWSDiscoverer discoverer = SlivkaWSDiscoverer.getInstance();
4649 JMenu submenu = new JMenu("Slivka");
4650 buildWebServicesMenu(discoverer, submenu);
4651 webService.add(submenu);
4653 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4655 WSDiscovererI jws2servs = Jws2Discoverer.getInstance();
4656 JMenu submenu = new JMenu("JABAWS");
4657 buildLegacyWebServicesMenu(submenu);
4658 buildWebServicesMenu(jws2servs, submenu);
4659 webService.add(submenu);
4661 build_fetchdbmenu(webService);
4665 private void buildLegacyWebServicesMenu(JMenu menu)
4667 JMenu secstrmenu = new JMenu("Secondary Structure Prediction");
4668 if (Discoverer.getServices() != null && Discoverer.getServices().size() > 0)
4670 var secstrpred = Discoverer.getServices().get("SecStrPred");
4671 if (secstrpred != null)
4673 for (ext.vamsas.ServiceHandle sh : secstrpred)
4675 var menuProvider = Discoverer.getServiceClient(sh);
4676 menuProvider.attachWSMenuEntry(secstrmenu, this);
4680 menu.add(secstrmenu);
4684 * Constructs the web services menu for the given discoverer under the
4685 * specified menu. This method must be called on the EDT
4688 * the discoverer used to build the menu
4690 * parent component which the elements will be attached to
4692 private void buildWebServicesMenu(WSDiscovererI discoverer, JMenu menu)
4694 if (discoverer.hasServices())
4696 PreferredServiceRegistry.getRegistry().populateWSMenuEntry(
4697 discoverer.getServices(), sv -> buildWebServicesMenu(), menu,
4700 if (discoverer.isRunning())
4702 JMenuItem item = new JMenuItem("Service discovery in progress.");
4703 item.setEnabled(false);
4706 else if (!discoverer.hasServices())
4708 JMenuItem item = new JMenuItem("No services available.");
4709 item.setEnabled(false);
4715 * construct any groupURL type service menu entries.
4720 protected void build_urlServiceMenu(JMenu webService)
4722 // TODO: remove this code when 2.7 is released
4723 // DEBUG - alignmentView
4725 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4726 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4728 * public void actionPerformed(ActionEvent e) {
4729 * jalview.datamodel.AlignmentView
4730 * .testSelectionViews(af.viewport.getAlignment(),
4731 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4733 * }); webService.add(testAlView);
4735 // TODO: refactor to RestClient discoverer and merge menu entries for
4736 // rest-style services with other types of analysis/calculation service
4737 // SHmmr test client - still being implemented.
4738 // DEBUG - alignmentView
4740 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4743 client.attachWSMenuEntry(
4744 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4750 * Searches the alignment sequences for xRefs and builds the Show
4751 * Cross-References menu (formerly called Show Products), with database
4752 * sources for which cross-references are found (protein sources for a
4753 * nucleotide alignment and vice versa)
4755 * @return true if Show Cross-references menu should be enabled
4758 public boolean canShowProducts()
4760 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4761 AlignmentI dataset = viewport.getAlignment().getDataset();
4763 showProducts.removeAll();
4764 final boolean dna = viewport.getAlignment().isNucleotide();
4766 if (seqs == null || seqs.length == 0)
4768 // nothing to see here.
4772 boolean showp = false;
4775 List<String> ptypes = new CrossRef(seqs, dataset)
4776 .findXrefSourcesForSequences(dna);
4778 for (final String source : ptypes)
4781 final AlignFrame af = this;
4782 JMenuItem xtype = new JMenuItem(source);
4783 xtype.addActionListener(new ActionListener()
4787 public void actionPerformed(ActionEvent e)
4789 showProductsFor(af.viewport.getSequenceSelection(), dna,
4793 showProducts.add(xtype);
4795 showProducts.setVisible(showp);
4796 showProducts.setEnabled(showp);
4797 } catch (Exception e)
4800 "canShowProducts threw an exception - please report to help@jalview.org",
4808 * Finds and displays cross-references for the selected sequences (protein
4809 * products for nucleotide sequences, dna coding sequences for peptides).
4812 * the sequences to show cross-references for
4814 * true if from a nucleotide alignment (so showing proteins)
4816 * the database to show cross-references for
4819 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4820 final String source)
4822 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4827 * Construct and display a new frame containing the translation of this
4828 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4832 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4834 AlignmentI al = null;
4837 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4839 al = dna.translateCdna(codeTable);
4840 } catch (Exception ex)
4842 jalview.bin.Cache.log.error(
4843 "Exception during translation. Please report this !", ex);
4844 final String msg = MessageManager.getString(
4845 "label.error_when_translating_sequences_submit_bug_report");
4846 final String errorTitle = MessageManager
4847 .getString("label.implementation_error")
4848 + MessageManager.getString("label.translation_failed");
4849 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4850 errorTitle, JvOptionPane.ERROR_MESSAGE);
4853 if (al == null || al.getHeight() == 0)
4855 final String msg = MessageManager.getString(
4856 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4857 final String errorTitle = MessageManager
4858 .getString("label.translation_failed");
4859 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4860 errorTitle, JvOptionPane.WARNING_MESSAGE);
4864 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4865 af.setFileFormat(this.currentFileFormat);
4866 final String newTitle = MessageManager
4867 .formatMessage("label.translation_of_params", new Object[]
4868 { this.getTitle(), codeTable.getId() });
4869 af.setTitle(newTitle);
4870 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4872 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4873 AlignViewport.openSplitFrame(this, af, new Alignment(seqs));
4877 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4884 * Set the file format
4889 public void setFileFormat(FileFormatI format)
4891 this.currentFileFormat = format;
4895 * Try to load a features file onto the alignment.
4898 * contents or path to retrieve file or a File object
4900 * access mode of file (see jalview.io.AlignFile)
4901 * @return true if features file was parsed correctly.
4904 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4907 return avc.parseFeaturesFile(file, sourceType,
4908 Cache.getDefault(Preferences.RELAXEDSEQIDMATCHING, false));
4913 public void refreshFeatureUI(boolean enableIfNecessary)
4915 // note - currently this is only still here rather than in the controller
4916 // because of the featureSettings hard reference that is yet to be
4918 if (enableIfNecessary)
4920 viewport.setShowSequenceFeatures(true);
4921 showSeqFeatures.setSelected(true);
4927 public void dragEnter(DropTargetDragEvent evt)
4932 public void dragExit(DropTargetEvent evt)
4937 public void dragOver(DropTargetDragEvent evt)
4942 public void dropActionChanged(DropTargetDragEvent evt)
4947 public void drop(DropTargetDropEvent evt)
4949 // JAL-1552 - acceptDrop required before getTransferable call for
4950 // Java's Transferable for native dnd
4951 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4952 Transferable t = evt.getTransferable();
4954 final List<Object> files = new ArrayList<>();
4955 List<DataSourceType> protocols = new ArrayList<>();
4959 Desktop.transferFromDropTarget(files, protocols, evt, t);
4960 if (files.size() > 0)
4962 new Thread(new Runnable()
4968 loadDroppedFiles(files, protocols, evt, t);
4972 } catch (Exception e)
4974 e.printStackTrace();
4978 protected void loadDroppedFiles(List<Object> files,
4979 List<DataSourceType> protocols, DropTargetDropEvent evt,
4984 // check to see if any of these files have names matching sequences
4987 SequenceIdMatcher idm = new SequenceIdMatcher(
4988 viewport.getAlignment().getSequencesArray());
4990 * Object[] { String,SequenceI}
4992 ArrayList<Object[]> filesmatched = new ArrayList<>();
4993 ArrayList<Object> filesnotmatched = new ArrayList<>();
4994 for (int i = 0; i < files.size(); i++)
4997 Object fileObj = files.get(i);
4998 String fileName = fileObj.toString();
5000 DataSourceType protocol = (fileObj instanceof File
5001 ? DataSourceType.FILE
5002 : FormatAdapter.checkProtocol(fileName));
5003 if (protocol == DataSourceType.FILE)
5006 if (fileObj instanceof File)
5008 file = (File) fileObj;
5009 Platform.cacheFileData(file);
5013 file = new File(fileName);
5015 pdbfn = file.getName();
5017 else if (protocol == DataSourceType.URL)
5019 URL url = new URL(fileName);
5020 pdbfn = url.getFile();
5022 if (pdbfn.length() > 0)
5024 // attempt to find a match in the alignment
5025 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5026 int l = 0, c = pdbfn.indexOf(".");
5027 while (mtch == null && c != -1)
5032 } while ((c = pdbfn.indexOf(".", l)) > l);
5035 pdbfn = pdbfn.substring(0, l);
5037 mtch = idm.findAllIdMatches(pdbfn);
5044 type = new IdentifyFile().identify(fileObj, protocol);
5045 } catch (Exception ex)
5049 if (type != null && type.isStructureFile())
5051 filesmatched.add(new Object[] { fileObj, protocol, mtch });
5055 // File wasn't named like one of the sequences or wasn't a PDB
5057 filesnotmatched.add(fileObj);
5061 if (filesmatched.size() > 0)
5063 boolean autoAssociate = Cache
5064 .getDefault(Preferences.AUTOASSOCIATE_PDBANDSEQS, false);
5067 String msg = MessageManager.formatMessage(
5068 "label.automatically_associate_structure_files_with_sequences_same_name",
5070 { Integer.valueOf(filesmatched.size()).toString() });
5071 String ttl = MessageManager.getString(
5072 "label.automatically_associate_structure_files_by_name");
5073 int choice = JvOptionPane.showConfirmDialog(this, msg, ttl,
5074 JvOptionPane.YES_NO_OPTION);
5075 autoAssociate = choice == JvOptionPane.YES_OPTION;
5079 for (Object[] fm : filesmatched)
5081 // try and associate
5082 // TODO: may want to set a standard ID naming formalism for
5083 // associating PDB files which have no IDs.
5084 for (SequenceI toassoc : (SequenceI[]) fm[2])
5086 PDBEntry pe = AssociatePdbFileWithSeq.associatePdbWithSeq(
5087 fm[0].toString(), (DataSourceType) fm[1], toassoc,
5091 System.err.println("Associated file : " + (fm[0].toString())
5092 + " with " + toassoc.getDisplayId(true));
5096 // TODO: do we need to update overview ? only if features are
5098 alignPanel.paintAlignment(true, false);
5104 * add declined structures as sequences
5106 for (Object[] o : filesmatched)
5108 filesnotmatched.add(o[0]);
5112 if (filesnotmatched.size() > 0)
5114 if (assocfiles > 0 && (Cache
5115 .getDefault("AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
5116 || JvOptionPane.showConfirmDialog(this,
5117 "<html>" + MessageManager.formatMessage(
5118 "label.ignore_unmatched_dropped_files_info",
5120 { Integer.valueOf(filesnotmatched.size())
5123 MessageManager.getString(
5124 "label.ignore_unmatched_dropped_files"),
5125 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
5129 for (Object fn : filesnotmatched)
5131 loadJalviewDataFile(fn, null, null, null);
5135 } catch (Exception ex)
5137 ex.printStackTrace();
5142 * Attempt to load a "dropped" file or URL string, by testing in turn for
5144 * <li>an Annotation file</li>
5145 * <li>a JNet file</li>
5146 * <li>a features file</li>
5147 * <li>else try to interpret as an alignment file</li>
5151 * either a filename or a URL string.
5152 * @throws InterruptedException
5153 * @throws IOException
5156 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
5157 FileFormatI format, SequenceI assocSeq)
5159 // BH 2018 was String file
5162 if (sourceType == null)
5164 sourceType = FormatAdapter.checkProtocol(file);
5166 // if the file isn't identified, or not positively identified as some
5167 // other filetype (PFAM is default unidentified alignment file type) then
5168 // try to parse as annotation.
5169 boolean isAnnotation = (format == null
5170 || FileFormat.Pfam.equals(format))
5171 ? new AnnotationFile().annotateAlignmentView(viewport,
5177 // first see if its a T-COFFEE score file
5178 TCoffeeScoreFile tcf = null;
5181 tcf = new TCoffeeScoreFile(file, sourceType);
5184 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5188 new TCoffeeColourScheme(viewport.getAlignment()));
5189 isAnnotation = true;
5190 setStatus(MessageManager.getString(
5191 "label.successfully_pasted_tcoffee_scores_to_alignment"));
5195 // some problem - if no warning its probable that the ID matching
5196 // process didn't work
5197 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
5198 tcf.getWarningMessage() == null
5199 ? MessageManager.getString(
5200 "label.check_file_matches_sequence_ids_alignment")
5201 : tcf.getWarningMessage(),
5202 MessageManager.getString(
5203 "label.problem_reading_tcoffee_score_file"),
5204 JvOptionPane.WARNING_MESSAGE);
5211 } catch (Exception x)
5214 "Exception when processing data source as T-COFFEE score file",
5220 // try to see if its a JNet 'concise' style annotation file *before*
5222 // try to parse it as a features file
5225 format = new IdentifyFile().identify(file, sourceType);
5227 if (FileFormat.ScoreMatrix == format)
5229 ScoreMatrixFile sm = new ScoreMatrixFile(
5230 new FileParse(file, sourceType));
5232 // todo: i18n this message
5233 setStatus(MessageManager.formatMessage(
5234 "label.successfully_loaded_matrix",
5235 sm.getMatrixName()));
5237 else if (FileFormat.Jnet.equals(format))
5239 JPredFile predictions = new JPredFile(file, sourceType);
5240 new JnetAnnotationMaker();
5241 JnetAnnotationMaker.add_annotation(predictions,
5242 viewport.getAlignment(), 0, false);
5243 viewport.getAlignment().setupJPredAlignment();
5244 isAnnotation = true;
5246 // else if (IdentifyFile.FeaturesFile.equals(format))
5247 else if (FileFormat.Features.equals(format))
5249 if (parseFeaturesFile(file, sourceType))
5251 SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
5252 if (splitFrame != null)
5254 splitFrame.repaint();
5258 alignPanel.paintAlignment(true, true);
5264 new FileLoader().LoadFile(viewport, file, sourceType, format);
5270 updateForAnnotations();
5272 } catch (Exception ex)
5274 ex.printStackTrace();
5275 } catch (OutOfMemoryError oom)
5280 } catch (Exception x)
5285 + (sourceType != null
5286 ? (sourceType == DataSourceType.PASTE
5288 : "using " + sourceType + " from "
5292 ? "(parsing as '" + format + "' file)"
5294 oom, Desktop.getDesktopPane());
5299 * Do all updates necessary after an annotation file such as jnet. Also called
5300 * from Jalview.loadAppletParams for "annotations", "jnetFile"
5303 public void updateForAnnotations()
5305 alignPanel.adjustAnnotationHeight();
5306 viewport.updateSequenceIdColours();
5307 buildSortByAnnotationScoresMenu();
5308 alignPanel.paintAlignment(true, true);
5312 * Change the display state for the given feature groups -- Added by BH from
5316 * list of group strings
5318 * visible or invisible
5321 public void setFeatureGroupState(String[] groups, boolean state)
5323 jalview.api.FeatureRenderer fr = null;
5324 viewport.setShowSequenceFeatures(true);
5325 if (alignPanel != null
5326 && (fr = alignPanel.getFeatureRenderer()) != null)
5329 fr.setGroupVisibility(Arrays.asList(groups), state);
5330 alignPanel.getSeqPanel().seqCanvas.repaint();
5331 if (alignPanel.overviewPanel != null)
5333 alignPanel.overviewPanel.updateOverviewImage();
5339 * Method invoked by the ChangeListener on the tabbed pane, in other words
5340 * when a different tabbed pane is selected by the user or programmatically.
5344 public void tabSelectionChanged(int index)
5348 alignPanel = alignPanels.get(index);
5349 viewport = alignPanel.av;
5350 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5351 setMenusFromViewport(viewport);
5352 if (featureSettings != null && featureSettings.isOpen()
5353 && featureSettings.fr.getViewport() != viewport)
5355 if (viewport.isShowSequenceFeatures())
5357 // refresh the featureSettings to reflect UI change
5358 showFeatureSettingsUI();
5362 // close feature settings for this view.
5363 featureSettings.close();
5370 * 'focus' any colour slider that is open to the selected viewport
5372 if (viewport.getConservationSelected())
5374 SliderPanel.setConservationSlider(alignPanel,
5375 viewport.getResidueShading(), alignPanel.getViewName());
5379 SliderPanel.hideConservationSlider();
5381 if (viewport.getAbovePIDThreshold())
5383 SliderPanel.setPIDSliderSource(alignPanel,
5384 viewport.getResidueShading(), alignPanel.getViewName());
5388 SliderPanel.hidePIDSlider();
5392 * If there is a frame linked to this one in a SplitPane, switch it to the
5393 * same view tab index. No infinite recursion of calls should happen, since
5394 * tabSelectionChanged() should not get invoked on setting the selected
5395 * index to an unchanged value. Guard against setting an invalid index
5396 * before the new view peer tab has been created.
5398 final AlignViewportI peer = viewport.getCodingComplement();
5401 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
5402 .getAlignPanel().alignFrame;
5403 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5405 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5411 * On right mouse click on view tab, prompt for and set new view name.
5415 public void tabbedPane_mousePressed(MouseEvent e)
5417 if (e.isPopupTrigger())
5419 String msg = MessageManager.getString("label.enter_view_name");
5420 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
5421 String reply = JvOptionPane.showInputDialog(msg, ttl);
5425 viewport.setViewName(reply);
5426 // TODO warn if reply is in getExistingViewNames()?
5427 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5432 public AlignViewport getCurrentView()
5438 * Open the dialog for regex description parsing.
5442 protected void extractScores_actionPerformed(ActionEvent e)
5444 ParseProperties pp = new jalview.analysis.ParseProperties(
5445 viewport.getAlignment());
5446 // TODO: verify regex and introduce GUI dialog for version 2.5
5447 // if (pp.getScoresFromDescription("col", "score column ",
5448 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5450 if (pp.getScoresFromDescription("description column",
5451 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5453 buildSortByAnnotationScoresMenu();
5461 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5466 protected void showDbRefs_actionPerformed(ActionEvent e)
5468 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5474 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5479 protected void showNpFeats_actionPerformed(ActionEvent e)
5481 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5485 * find the viewport amongst the tabs in this alignment frame and close that
5491 public boolean closeView(AlignViewportI av)
5495 this.closeMenuItem_actionPerformed(false);
5498 Component[] comp = tabbedPane.getComponents();
5499 for (int i = 0; comp != null && i < comp.length; i++)
5501 if (comp[i] instanceof AlignmentPanel)
5503 if (((AlignmentPanel) comp[i]).av == av)
5506 closeView((AlignmentPanel) comp[i]);
5514 protected void build_fetchdbmenu(JMenu webService)
5516 // Temporary hack - DBRef Fetcher always top level ws entry.
5517 // TODO We probably want to store a sequence database checklist in
5518 // preferences and have checkboxes.. rather than individual sources selected
5520 final JMenu rfetch = new JMenu(
5521 MessageManager.getString("action.fetch_db_references"));
5522 rfetch.setToolTipText(MessageManager.getString(
5523 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5524 webService.add(rfetch);
5526 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5527 MessageManager.getString("option.trim_retrieved_seqs"));
5528 trimrs.setToolTipText(
5529 MessageManager.getString("label.trim_retrieved_sequences"));
5531 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5532 trimrs.addActionListener(new ActionListener()
5536 public void actionPerformed(ActionEvent e)
5538 trimrs.setSelected(trimrs.isSelected());
5539 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5540 Boolean.valueOf(trimrs.isSelected()).toString());
5544 JMenuItem fetchr = new JMenuItem(
5545 MessageManager.getString("label.standard_databases"));
5546 fetchr.setToolTipText(
5547 MessageManager.getString("label.fetch_embl_uniprot"));
5548 fetchr.addActionListener(new ActionListener()
5552 public void actionPerformed(ActionEvent e)
5554 new Thread(new Runnable()
5560 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5561 .getAlignment().isNucleotide();
5562 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5563 alignPanel.av.getSequenceSelection(),
5564 alignPanel.alignFrame, null,
5565 alignPanel.alignFrame.featureSettings, isNucleotide);
5566 dbRefFetcher.addListener(new FetchFinishedListenerI()
5570 public void finished()
5573 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5574 .getFeatureSettingsModels())
5577 alignPanel.av.mergeFeaturesStyle(srcSettings);
5579 AlignFrame.this.setMenusForViewport();
5582 dbRefFetcher.fetchDBRefs(false);
5590 new Thread(new Runnable()
5597 // final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5598 // .getSequenceFetcherSingleton();
5599 javax.swing.SwingUtilities.invokeLater(new Runnable()
5605 jalview.ws.SequenceFetcher sf = jalview.ws.SequenceFetcher
5607 String[] dbclasses = sf.getNonAlignmentSources();
5608 List<DbSourceProxy> otherdb;
5609 JMenu dfetch = new JMenu();
5610 JMenu ifetch = new JMenu();
5611 JMenuItem fetchr = null;
5612 int comp = 0, icomp = 0, mcomp = 15;
5613 String mname = null;
5615 for (String dbclass : dbclasses)
5617 otherdb = sf.getSourceProxy(dbclass);
5618 // add a single entry for this class, or submenu allowing 'fetch
5620 if (otherdb == null || otherdb.size() < 1)
5626 mname = "From " + dbclass;
5628 if (otherdb.size() == 1)
5630 DbSourceProxy src = otherdb.get(0);
5631 DbSourceProxy[] dassource = new DbSourceProxy[] { src };
5632 fetchr = new JMenuItem(src.getDbSource());
5633 fetchr.addActionListener(new ActionListener()
5637 public void actionPerformed(ActionEvent e)
5639 new Thread(new Runnable()
5645 boolean isNucleotide = alignPanel.alignFrame
5646 .getViewport().getAlignment()
5648 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5649 alignPanel.av.getSequenceSelection(),
5650 alignPanel.alignFrame, dassource,
5651 alignPanel.alignFrame.featureSettings,
5654 .addListener(new FetchFinishedListenerI()
5658 public void finished()
5660 FeatureSettingsModelI srcSettings = dassource[0]
5661 .getFeatureColourScheme();
5662 alignPanel.av.mergeFeaturesStyle(
5664 AlignFrame.this.setMenusForViewport();
5667 dbRefFetcher.fetchDBRefs(false);
5673 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5674 MessageManager.formatMessage(
5675 "label.fetch_retrieve_from", new Object[]
5676 { src.getDbName() })));
5682 final DbSourceProxy[] dassource = otherdb
5683 .toArray(new DbSourceProxy[0]);
5685 DbSourceProxy src = otherdb.get(0);
5686 fetchr = new JMenuItem(MessageManager
5687 .formatMessage("label.fetch_all_param", new Object[]
5688 { src.getDbSource() }));
5689 fetchr.addActionListener(new ActionListener()
5693 public void actionPerformed(ActionEvent e)
5695 new Thread(new Runnable()
5701 boolean isNucleotide = alignPanel.alignFrame
5702 .getViewport().getAlignment()
5704 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5705 alignPanel.av.getSequenceSelection(),
5706 alignPanel.alignFrame, dassource,
5707 alignPanel.alignFrame.featureSettings,
5710 .addListener(new FetchFinishedListenerI()
5714 public void finished()
5716 AlignFrame.this.setMenusForViewport();
5719 dbRefFetcher.fetchDBRefs(false);
5725 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5726 MessageManager.formatMessage(
5727 "label.fetch_retrieve_from_all_sources",
5729 { Integer.valueOf(otherdb.size())
5731 src.getDbSource(), src.getDbName() })));
5734 // and then build the rest of the individual menus
5735 ifetch = new JMenu(MessageManager.formatMessage(
5736 "label.source_from_db_source", new Object[]
5737 { src.getDbSource() }));
5739 String imname = null;
5741 for (DbSourceProxy sproxy : otherdb)
5743 String dbname = sproxy.getDbName();
5744 String sname = dbname.length() > 5
5745 ? dbname.substring(0, 5) + "..."
5747 String msname = dbname.length() > 10
5748 ? dbname.substring(0, 10) + "..."
5752 imname = MessageManager
5753 .formatMessage("label.from_msname", new Object[]
5756 fetchr = new JMenuItem(msname);
5757 final DbSourceProxy[] dassrc = { sproxy };
5758 fetchr.addActionListener(new ActionListener()
5762 public void actionPerformed(ActionEvent e)
5764 new Thread(new Runnable()
5770 boolean isNucleotide = alignPanel.alignFrame
5771 .getViewport().getAlignment()
5773 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5774 alignPanel.av.getSequenceSelection(),
5775 alignPanel.alignFrame, dassrc,
5776 alignPanel.alignFrame.featureSettings,
5779 .addListener(new FetchFinishedListenerI()
5783 public void finished()
5785 AlignFrame.this.setMenusForViewport();
5788 dbRefFetcher.fetchDBRefs(false);
5794 fetchr.setToolTipText(
5795 "<html>" + MessageManager.formatMessage(
5796 "label.fetch_retrieve_from", new Object[]
5800 if (++icomp >= mcomp || i == (otherdb.size()))
5802 ifetch.setText(MessageManager.formatMessage(
5803 "label.source_to_target", imname, sname));
5805 ifetch = new JMenu();
5813 if (comp >= mcomp || dbi >= (dbclasses.length))
5815 dfetch.setText(MessageManager.formatMessage(
5816 "label.source_to_target", mname, dbclass));
5818 dfetch = new JMenu();
5831 * Left justify the whole alignment.
5835 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5837 viewport.getAlignment().justify(false);
5838 viewport.notifyAlignment();
5842 * Right justify the whole alignment.
5846 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5848 viewport.getAlignment().justify(true);
5849 viewport.notifyAlignment();
5853 public void setShowSeqFeatures(boolean b)
5855 showSeqFeatures.setSelected(b);
5856 viewport.setShowSequenceFeatures(b);
5863 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5864 * awt.event.ActionEvent)
5868 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5870 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5871 alignPanel.paintAlignment(false, false);
5878 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5883 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5885 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5886 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5894 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5895 * .event.ActionEvent)
5899 protected void showGroupConservation_actionPerformed(ActionEvent e)
5901 viewport.setShowGroupConservation(showGroupConservation.getState());
5902 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5909 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5910 * .event.ActionEvent)
5914 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5916 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5917 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5924 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5925 * .event.ActionEvent)
5929 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5931 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5932 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5936 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5938 showSequenceLogo.setState(true);
5939 viewport.setShowSequenceLogo(true);
5940 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5941 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5945 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5947 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5954 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5955 * .event.ActionEvent)
5959 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5961 if (avc.makeGroupsFromSelection())
5963 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5964 alignPanel.updateAnnotation();
5965 alignPanel.paintAlignment(true,
5966 viewport.needToUpdateStructureViews());
5970 public void clearAlignmentSeqRep()
5972 // TODO refactor alignmentseqrep to controller
5973 if (viewport.getAlignment().hasSeqrep())
5975 viewport.getAlignment().setSeqrep(null);
5976 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5977 alignPanel.updateAnnotation();
5978 alignPanel.paintAlignment(true, true);
5983 protected void createGroup_actionPerformed(ActionEvent e)
5985 if (avc.createGroup())
5987 if (applyAutoAnnotationSettings.isSelected())
5989 alignPanel.updateAnnotation(true, false);
5991 alignPanel.alignmentChanged();
5996 protected void unGroup_actionPerformed(ActionEvent e)
6000 alignPanel.alignmentChanged();
6005 * make the given alignmentPanel the currently selected tab
6007 * @param alignmentPanel
6010 public void setDisplayedView(AlignmentPanel alignmentPanel)
6012 if (!viewport.getSequenceSetId()
6013 .equals(alignmentPanel.av.getSequenceSetId()))
6015 throw new Error(MessageManager.getString(
6016 "error.implementation_error_cannot_show_view_alignment_frame"));
6018 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
6019 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
6021 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
6026 * Action on selection of menu options to Show or Hide annotations.
6029 * @param forSequences
6030 * update sequence-related annotations
6031 * @param forAlignment
6032 * update non-sequence-related annotations
6036 protected void setAnnotationsVisibility(boolean visible,
6037 boolean forSequences, boolean forAlignment)
6039 AlignmentAnnotation[] anns = alignPanel.getAlignment()
6040 .getAlignmentAnnotation();
6045 for (AlignmentAnnotation aa : anns)
6048 * don't display non-positional annotations on an alignment
6050 if (aa.annotations == null)
6054 boolean apply = (aa.sequenceRef == null && forAlignment)
6055 || (aa.sequenceRef != null && forSequences);
6058 aa.visible = visible;
6061 alignPanel.validateAnnotationDimensions(true);
6062 alignPanel.alignmentChanged();
6066 * Store selected annotation sort order for the view and repaint.
6070 protected void sortAnnotations_actionPerformed()
6072 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
6074 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
6075 alignPanel.paintAlignment(false, false);
6080 * @return alignment panels in this alignment frame
6083 public List<? extends AlignmentViewPanel> getAlignPanels()
6085 // alignPanels is never null
6086 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
6091 * Open a new alignment window, with the cDNA associated with this (protein)
6092 * alignment, aligned as is the protein.
6095 protected void viewAsCdna_actionPerformed()
6097 // TODO no longer a menu action - refactor as required
6098 final AlignmentI alignment = getViewport().getAlignment();
6099 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
6100 if (mappings == null)
6104 List<SequenceI> cdnaSeqs = new ArrayList<>();
6105 for (SequenceI aaSeq : alignment.getSequences())
6107 for (AlignedCodonFrame acf : mappings)
6109 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
6113 * There is a cDNA mapping for this protein sequence - add to new
6114 * alignment. It will share the same dataset sequence as other mapped
6115 * cDNA (no new mappings need to be created).
6117 final Sequence newSeq = new Sequence(dnaSeq);
6118 newSeq.setDatasetSequence(dnaSeq);
6119 cdnaSeqs.add(newSeq);
6123 if (cdnaSeqs.size() == 0)
6125 // show a warning dialog no mapped cDNA
6128 AlignmentI cdna = new Alignment(
6129 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
6130 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
6131 AlignFrame.DEFAULT_HEIGHT);
6132 cdna.alignAs(alignment);
6133 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
6135 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
6136 AlignFrame.DEFAULT_HEIGHT);
6140 * Set visibility of dna/protein complement view (available when shown in a
6147 protected void showComplement_actionPerformed(boolean show)
6149 SplitContainerI sf = getSplitViewContainer();
6152 sf.setComplementVisible(this, show);
6157 * Generate the reverse (optionally complemented) of the selected sequences,
6158 * and add them to the alignment
6162 protected void showReverse_actionPerformed(boolean complement)
6164 AlignmentI al = null;
6167 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
6168 al = dna.reverseCdna(complement);
6169 viewport.addAlignment(al, "");
6170 addHistoryItem(new EditCommand(
6171 MessageManager.getString("label.add_sequences"), Action.PASTE,
6172 al.getSequencesArray(), 0, al.getWidth(),
6173 viewport.getAlignment()));
6174 } catch (Exception ex)
6176 System.err.println(ex.getMessage());
6182 * Try to run a script in the Groovy console, having first ensured that this
6183 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
6184 * be targeted at this alignment.
6188 protected void runGroovy_actionPerformed()
6190 Jalview.setCurrentAlignFrame(this);
6191 groovy.ui.Console console = Desktop.getGroovyConsole();
6192 if (console != null)
6196 console.runScript();
6197 } catch (Exception ex)
6199 System.err.println((ex.toString()));
6200 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
6201 MessageManager.getString("label.couldnt_run_groovy_script"),
6202 MessageManager.getString("label.groovy_support_failed"),
6203 JvOptionPane.ERROR_MESSAGE);
6208 System.err.println("Can't run Groovy script as console not found");
6213 * Hides columns containing (or not containing) a specified feature, provided
6214 * that would not leave all columns hidden
6216 * @param featureType
6217 * @param columnsContaining
6221 public boolean hideFeatureColumns(String featureType,
6222 boolean columnsContaining)
6224 boolean notForHiding = avc.markColumnsContainingFeatures(
6225 columnsContaining, false, false, featureType);
6228 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
6229 false, featureType))
6231 getViewport().hideSelectedColumns();
6239 protected void selectHighlightedColumns_actionPerformed(
6240 ActionEvent actionEvent)
6242 // include key modifier check in case user selects from menu
6243 avc.markHighlightedColumns(
6244 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
6245 (actionEvent.getModifiers() & (ActionEvent.META_MASK
6246 | ActionEvent.CTRL_MASK)) != 0);
6250 * Rebuilds the Colour menu, including any user-defined colours which have
6251 * been loaded either on startup or during the session
6254 public void buildColourMenu()
6256 colourMenu.removeAll();
6258 colourMenu.add(applyToAllGroups);
6259 colourMenu.add(textColour);
6260 colourMenu.addSeparator();
6262 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
6263 viewport.getAlignment(), false);
6265 colourMenu.add(annotationColour);
6266 bg.add(annotationColour);
6267 colourMenu.addSeparator();
6268 colourMenu.add(conservationMenuItem);
6269 colourMenu.add(modifyConservation);
6270 colourMenu.add(abovePIDThreshold);
6271 colourMenu.add(modifyPID);
6273 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
6274 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
6278 * Open a dialog (if not already open) that allows the user to select and
6279 * calculate PCA or Tree analysis
6282 protected void openTreePcaDialog()
6284 if (alignPanel.getCalculationDialog() == null)
6286 new CalculationChooser(AlignFrame.this);
6291 * Sets the status of the HMMER menu
6293 public void updateHMMERStatus()
6295 hmmerMenu.setEnabled(HmmerCommand.isHmmerAvailable());
6299 protected void loadVcf_actionPerformed()
6301 JalviewFileChooser chooser = new JalviewFileChooser(
6302 Cache.getProperty("LAST_DIRECTORY"));
6303 chooser.setFileView(new JalviewFileView());
6304 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
6305 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
6306 final AlignFrame us = this;
6307 chooser.setResponseHandler(0, new Runnable()
6313 String choice = chooser.getSelectedFile().getPath();
6314 Cache.setProperty("LAST_DIRECTORY", choice);
6315 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
6316 new VCFLoader(choice).loadVCF(seqs, us);
6319 chooser.showOpenDialog(null);
6323 private Rectangle lastFeatureSettingsBounds = null;
6326 public void setFeatureSettingsGeometry(Rectangle bounds)
6328 lastFeatureSettingsBounds = bounds;
6332 public Rectangle getFeatureSettingsGeometry()
6334 return lastFeatureSettingsBounds;
6337 public void scrollTo(int row, int column)
6339 alignPanel.getSeqPanel().scrollTo(row, column);
6342 public void scrollToRow(int row)
6344 alignPanel.getSeqPanel().scrollToRow(row);
6347 public void scrollToColumn(int column)
6349 alignPanel.getSeqPanel().scrollToColumn(column);
6353 * BH 2019 from JalviewLite
6355 * get sequence feature groups that are hidden or shown
6362 public String[] getFeatureGroupsOfState(boolean visible)
6364 jalview.api.FeatureRenderer fr = null;
6365 if (alignPanel != null
6366 && (fr = alignPanel.getFeatureRenderer()) != null)
6368 List<String> gps = fr.getGroups(visible);
6369 String[] _gps = gps.toArray(new String[gps.size()]);
6377 * @return list of feature groups on the view
6380 public String[] getFeatureGroups()
6382 jalview.api.FeatureRenderer fr = null;
6383 if (alignPanel != null
6384 && (fr = alignPanel.getFeatureRenderer()) != null)
6386 List<String> gps = fr.getFeatureGroups();
6387 String[] _gps = gps.toArray(new String[gps.size()]);
6393 public void select(SequenceGroup sel, ColumnSelection csel,
6394 HiddenColumns hidden)
6396 alignPanel.getSeqPanel().selection(sel, csel, hidden, null);
6404 static class PrintThread extends Thread
6408 public PrintThread(AlignmentPanel ap)
6413 static PageFormat pf;
6418 PrinterJob printJob = PrinterJob.getPrinterJob();
6422 printJob.setPrintable(ap, pf);
6426 printJob.setPrintable(ap);
6429 if (printJob.printDialog())
6434 } catch (Exception PrintException)
6436 PrintException.printStackTrace();