2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import java.util.Locale;
25 import java.io.IOException;
26 import java.util.HashSet;
29 import javax.swing.JFileChooser;
30 import javax.swing.JOptionPane;
31 import java.awt.BorderLayout;
32 import java.awt.Color;
33 import java.awt.Component;
34 import java.awt.Dimension;
35 import java.awt.Rectangle;
36 import java.awt.Toolkit;
37 import java.awt.datatransfer.Clipboard;
38 import java.awt.datatransfer.DataFlavor;
39 import java.awt.datatransfer.StringSelection;
40 import java.awt.datatransfer.Transferable;
41 import java.awt.dnd.DnDConstants;
42 import java.awt.dnd.DropTargetDragEvent;
43 import java.awt.dnd.DropTargetDropEvent;
44 import java.awt.dnd.DropTargetEvent;
45 import java.awt.dnd.DropTargetListener;
46 import java.awt.event.ActionEvent;
47 import java.awt.event.ActionListener;
48 import java.awt.event.FocusAdapter;
49 import java.awt.event.FocusEvent;
50 import java.awt.event.ItemEvent;
51 import java.awt.event.ItemListener;
52 import java.awt.event.KeyAdapter;
53 import java.awt.event.KeyEvent;
54 import java.awt.event.MouseEvent;
55 import java.awt.print.PageFormat;
56 import java.awt.print.PrinterJob;
57 import java.beans.PropertyChangeEvent;
58 import java.beans.PropertyChangeListener;
60 import java.io.FileWriter;
61 import java.io.PrintWriter;
63 import java.util.ArrayList;
64 import java.util.Arrays;
65 import java.util.Collection;
66 import java.util.Deque;
67 import java.util.Enumeration;
68 import java.util.Hashtable;
69 import java.util.List;
70 import java.util.Vector;
72 import javax.swing.ButtonGroup;
73 import javax.swing.JCheckBoxMenuItem;
74 import javax.swing.JComponent;
75 import javax.swing.JEditorPane;
76 import javax.swing.JInternalFrame;
77 import javax.swing.JLabel;
78 import javax.swing.JLayeredPane;
79 import javax.swing.JMenu;
80 import javax.swing.JMenuItem;
81 import javax.swing.JPanel;
82 import javax.swing.JScrollPane;
83 import javax.swing.SwingUtilities;
84 import javax.swing.event.InternalFrameAdapter;
85 import javax.swing.event.InternalFrameEvent;
87 import ext.vamsas.ServiceHandle;
88 import jalview.analysis.AlignmentSorter;
89 import jalview.analysis.AlignmentUtils;
90 import jalview.analysis.CrossRef;
91 import jalview.analysis.Dna;
92 import jalview.analysis.GeneticCodeI;
93 import jalview.analysis.ParseProperties;
94 import jalview.analysis.SequenceIdMatcher;
95 import jalview.api.AlignExportSettingsI;
96 import jalview.api.AlignViewControllerGuiI;
97 import jalview.api.AlignViewControllerI;
98 import jalview.api.AlignViewportI;
99 import jalview.api.AlignmentViewPanel;
100 import jalview.api.FeatureSettingsControllerI;
101 import jalview.api.FeatureSettingsModelI;
102 import jalview.api.SplitContainerI;
103 import jalview.api.ViewStyleI;
104 import jalview.api.analysis.SimilarityParamsI;
105 import jalview.bin.Cache;
106 import jalview.bin.Console;
107 import jalview.bin.Jalview;
108 import jalview.commands.CommandI;
109 import jalview.commands.EditCommand;
110 import jalview.commands.EditCommand.Action;
111 import jalview.commands.OrderCommand;
112 import jalview.commands.RemoveGapColCommand;
113 import jalview.commands.RemoveGapsCommand;
114 import jalview.commands.SlideSequencesCommand;
115 import jalview.commands.TrimRegionCommand;
116 import jalview.datamodel.AlignExportSettingsAdapter;
117 import jalview.datamodel.AlignedCodonFrame;
118 import jalview.datamodel.Alignment;
119 import jalview.datamodel.AlignmentAnnotation;
120 import jalview.datamodel.AlignmentExportData;
121 import jalview.datamodel.AlignmentI;
122 import jalview.datamodel.AlignmentOrder;
123 import jalview.datamodel.AlignmentView;
124 import jalview.datamodel.ColumnSelection;
125 import jalview.datamodel.HiddenColumns;
126 import jalview.datamodel.PDBEntry;
127 import jalview.datamodel.SeqCigar;
128 import jalview.datamodel.Sequence;
129 import jalview.datamodel.SequenceGroup;
130 import jalview.datamodel.SequenceI;
131 import jalview.gui.ColourMenuHelper.ColourChangeListener;
132 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
133 import jalview.hmmer.HMMAlign;
134 import jalview.hmmer.HMMBuild;
135 import jalview.hmmer.HMMERParamStore;
136 import jalview.hmmer.HMMERPreset;
137 import jalview.hmmer.HMMSearch;
138 import jalview.hmmer.HmmerCommand;
139 import jalview.hmmer.JackHMMER;
140 import jalview.io.AlignmentProperties;
141 import jalview.io.AnnotationFile;
142 import jalview.io.BackupFiles;
143 import jalview.io.BioJsHTMLOutput;
144 import jalview.io.DataSourceType;
145 import jalview.io.FileFormat;
146 import jalview.io.FileFormatI;
147 import jalview.io.FileFormats;
148 import jalview.io.FileLoader;
149 import jalview.io.FileParse;
150 import jalview.io.FormatAdapter;
151 import jalview.io.HtmlSvgOutput;
152 import jalview.io.IdentifyFile;
153 import jalview.io.JPredFile;
154 import jalview.io.JalviewFileChooser;
155 import jalview.io.JalviewFileView;
156 import jalview.io.JnetAnnotationMaker;
157 import jalview.io.NewickFile;
158 import jalview.io.ScoreMatrixFile;
159 import jalview.io.TCoffeeScoreFile;
160 import jalview.io.vcf.VCFLoader;
161 import jalview.jbgui.GAlignFrame;
162 import jalview.project.Jalview2XML;
163 import jalview.schemes.ColourSchemeI;
164 import jalview.schemes.ColourSchemes;
165 import jalview.schemes.ResidueColourScheme;
166 import jalview.schemes.TCoffeeColourScheme;
167 import jalview.util.HttpUtils;
168 import jalview.util.ImageMaker.TYPE;
169 import jalview.util.MessageManager;
170 import jalview.util.Platform;
171 import jalview.viewmodel.AlignmentViewport;
172 import jalview.viewmodel.ViewportRanges;
173 import jalview.ws.DBRefFetcher;
174 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
175 import jalview.ws.ServiceChangeListener;
176 import jalview.ws.WSDiscovererI;
177 import jalview.ws.api.ServiceWithParameters;
178 import jalview.ws.jws1.Discoverer;
179 import jalview.ws.jws2.Jws2Discoverer;
180 import jalview.ws.jws2.PreferredServiceRegistry;
181 import jalview.ws.params.ArgumentI;
182 import jalview.ws.params.ParamDatastoreI;
183 import jalview.ws.params.WsParamSetI;
184 import jalview.ws.seqfetcher.DbSourceProxy;
185 import jalview.ws2.client.api.WebServiceDiscovererI;
186 import jalview.ws2.client.ebi.JobDispatcherWSDiscoverer;
187 import jalview.ws2.client.slivka.SlivkaWSDiscoverer;
188 import jalview.ws2.gui.WebServicesMenuManager;
190 import java.io.IOException;
191 import java.util.HashSet;
192 import java.util.Set;
194 import javax.swing.JFileChooser;
195 import javax.swing.JOptionPane;
197 import java.awt.BorderLayout;
198 import java.awt.Color;
199 import java.awt.Component;
200 import java.awt.Dimension;
201 import java.awt.Rectangle;
202 import java.awt.Toolkit;
203 import java.awt.datatransfer.Clipboard;
204 import java.awt.datatransfer.DataFlavor;
205 import java.awt.datatransfer.StringSelection;
206 import java.awt.datatransfer.Transferable;
207 import java.awt.dnd.DnDConstants;
208 import java.awt.dnd.DropTargetDragEvent;
209 import java.awt.dnd.DropTargetDropEvent;
210 import java.awt.dnd.DropTargetEvent;
211 import java.awt.dnd.DropTargetListener;
212 import java.awt.event.ActionEvent;
213 import java.awt.event.ActionListener;
214 import java.awt.event.FocusAdapter;
215 import java.awt.event.FocusEvent;
216 import java.awt.event.ItemEvent;
217 import java.awt.event.ItemListener;
218 import java.awt.event.KeyAdapter;
219 import java.awt.event.KeyEvent;
220 import java.awt.event.MouseEvent;
221 import java.awt.print.PageFormat;
222 import java.awt.print.PrinterJob;
223 import java.beans.PropertyChangeEvent;
224 import java.beans.PropertyChangeListener;
226 import java.io.FileWriter;
227 import java.io.PrintWriter;
229 import java.util.ArrayList;
230 import java.util.Arrays;
231 import java.util.Collection;
232 import java.util.Deque;
233 import java.util.Enumeration;
234 import java.util.Hashtable;
235 import java.util.List;
236 import java.util.Vector;
238 import javax.swing.ButtonGroup;
239 import javax.swing.JCheckBoxMenuItem;
240 import javax.swing.JComponent;
241 import javax.swing.JEditorPane;
242 import javax.swing.JInternalFrame;
243 import javax.swing.JLabel;
244 import javax.swing.JLayeredPane;
245 import javax.swing.JMenu;
246 import javax.swing.JMenuItem;
247 import javax.swing.JPanel;
248 import javax.swing.JScrollPane;
249 import javax.swing.SwingUtilities;
250 import javax.swing.event.InternalFrameAdapter;
251 import javax.swing.event.InternalFrameEvent;
253 import ext.vamsas.ServiceHandle;
259 * @version $Revision$
261 @SuppressWarnings("serial")
262 public class AlignFrame extends GAlignFrame
263 implements DropTargetListener, IProgressIndicator,
264 AlignViewControllerGuiI, ColourChangeListener, ServiceChangeListener
267 public static int frameCount;
268 public static final int DEFAULT_WIDTH = 700;
270 public static final int DEFAULT_HEIGHT = 500;
273 * The currently displayed panel (selected tabbed view if more than one)
275 public AlignmentPanel alignPanel;
277 AlignViewport viewport;
279 public AlignViewControllerI avc;
281 List<AlignmentPanel> alignPanels = new ArrayList<>();
284 * Last format used to load or save alignments in this window
286 FileFormatI currentFileFormat = null;
289 * Current filename for this alignment
291 String fileName = null;
294 * TODO: remove reference to 'FileObject' in AlignFrame - not correct mapping
300 private DataSourceType protocol ;
302 * Creates a new AlignFrame object with specific width and height.
308 public AlignFrame(AlignmentI al, int width, int height)
310 this(al, null, width, height);
314 * Creates a new AlignFrame object with specific width, height and
320 * @param sequenceSetId
322 public AlignFrame(AlignmentI al, int width, int height,
323 String sequenceSetId)
325 this(al, null, width, height, sequenceSetId);
329 * Creates a new AlignFrame object with specific width, height and
335 * @param sequenceSetId
338 public AlignFrame(AlignmentI al, int width, int height,
339 String sequenceSetId, String viewId)
341 this(al, null, width, height, sequenceSetId, viewId);
345 * new alignment window with hidden columns
349 * @param hiddenColumns
350 * ColumnSelection or null
352 * Width of alignment frame
356 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
359 this(al, hiddenColumns, width, height, null);
363 * Create alignment frame for al with hiddenColumns, a specific width and
364 * height, and specific sequenceId
367 * @param hiddenColumns
370 * @param sequenceSetId
373 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
374 int height, String sequenceSetId)
376 this(al, hiddenColumns, width, height, sequenceSetId, null);
380 * Create alignment frame for al with hiddenColumns, a specific width and
381 * height, and specific sequenceId
384 * @param hiddenColumns
387 * @param sequenceSetId
392 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
393 int height, String sequenceSetId, String viewId)
396 setSize(width, height);
398 if (al.getDataset() == null)
403 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
405 // JalviewJS needs to distinguish a new panel from an old one in init()
406 // alignPanel = new AlignmentPanel(this, viewport);
407 // addAlignmentPanel(alignPanel, true);
411 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
412 HiddenColumns hiddenColumns, int width, int height)
414 setSize(width, height);
416 if (al.getDataset() == null)
421 viewport = new AlignViewport(al, hiddenColumns);
423 if (hiddenSeqs != null && hiddenSeqs.length > 0)
425 viewport.hideSequence(hiddenSeqs);
427 // alignPanel = new AlignmentPanel(this, viewport);
428 // addAlignmentPanel(alignPanel, true);
433 * Make a new AlignFrame from existing alignmentPanels
440 public AlignFrame(AlignmentPanel ap)
444 // addAlignmentPanel(ap, false);
449 * initalise the alignframe from the underlying viewport data and the
454 boolean newPanel = (alignPanel == null);
455 viewport.setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
460 // need to set this up front if NOANNOTATION is
461 // used in conjunction with SHOWOVERVIEW.
463 // I have not determined if this is appropriate for
464 // Jalview/Java, as it means we are setting this flag
465 // for all subsequent AlignFrames. For now, at least,
466 // I am setting it to be JalviewJS-only.
468 boolean showAnnotation = Jalview.getInstance().getShowAnnotation();
469 viewport.setShowAnnotation(showAnnotation);
471 alignPanel = new AlignmentPanel(this, viewport);
473 addAlignmentPanel(alignPanel, newPanel);
474 // setBackground(Color.white); // BH 2019
476 if (!Jalview.isHeadlessMode())
478 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
480 statusPanel.setVisible(Jalview.getInstance().getShowStatus());
481 alignFrameMenuBar.setVisible(Jalview.getInstance().getAllowMenuBar());
484 avc = new jalview.controller.AlignViewController(this, viewport,
486 if (viewport.getAlignmentConservationAnnotation() == null)
488 // BLOSUM62Colour.setEnabled(false);
489 conservationMenuItem.setEnabled(false);
490 modifyConservation.setEnabled(false);
491 // PIDColour.setEnabled(false);
492 // abovePIDThreshold.setEnabled(false);
493 // modifyPID.setEnabled(false);
496 String sortby = Cache.getDefault(Preferences.SORT_ALIGNMENT,
499 if (sortby.equals("Id"))
501 sortIDMenuItem_actionPerformed(null);
503 else if (sortby.equals("Pairwise Identity"))
505 sortPairwiseMenuItem_actionPerformed(null);
510 // this.alignPanel.av
511 // .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
513 setMenusFromViewport(viewport);
514 buildSortByAnnotationScoresMenu();
515 calculateTree.addActionListener(new ActionListener()
519 public void actionPerformed(ActionEvent e)
526 if (Desktop.getDesktopPane() != null)
528 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
529 addServiceListeners();
530 if (!Platform.isJS())
536 if (viewport.getWrapAlignment())
538 wrapMenuItem_actionPerformed(null);
541 if (Cache.getDefault(Preferences.SHOW_OVERVIEW, false))
543 this.overviewMenuItem_actionPerformed(null);
548 final List<AlignmentViewPanel> selviews = new ArrayList<>();
549 final List<AlignmentPanel> origview = new ArrayList<>();
550 final String menuLabel = MessageManager
551 .getString("label.copy_format_from");
552 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
553 new ViewSetProvider()
557 public AlignmentPanel[] getAllAlignmentPanels()
560 origview.add(alignPanel);
561 // make an array of all alignment panels except for this one
562 List<AlignmentPanel> aps = new ArrayList<>(
563 Arrays.asList(Desktop.getAlignmentPanels(null)));
564 aps.remove(AlignFrame.this.alignPanel);
565 return aps.toArray(new AlignmentPanel[aps.size()]);
567 }, selviews, new ItemListener()
571 public void itemStateChanged(ItemEvent e)
573 if (origview.size() > 0)
575 final AlignmentPanel ap = origview.get(0);
578 * Copy the ViewStyle of the selected panel to 'this one'.
579 * Don't change value of 'scaleProteinAsCdna' unless copying
582 ViewStyleI vs = selviews.get(0).getAlignViewport()
584 boolean fromSplitFrame = selviews.get(0)
585 .getAlignViewport().getCodingComplement() != null;
588 vs.setScaleProteinAsCdna(ap.getAlignViewport()
589 .getViewStyle().isScaleProteinAsCdna());
591 ap.getAlignViewport().setViewStyle(vs);
594 * Also rescale ViewStyle of SplitFrame complement if there is
595 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
596 * the whole ViewStyle (allow cDNA protein to have different
599 AlignViewportI complement = ap.getAlignViewport()
600 .getCodingComplement();
601 if (complement != null && vs.isScaleProteinAsCdna())
603 AlignFrame af = Desktop.getAlignFrameFor(complement);
604 ((SplitFrame) af.getSplitViewContainer())
606 af.setMenusForViewport();
610 ap.setSelected(true);
611 ap.alignFrame.setMenusForViewport();
616 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase(Locale.ROOT)
617 .indexOf("devel") > -1
618 || Cache.getDefault("VERSION", "DEVELOPMENT")
619 .toLowerCase(Locale.ROOT).indexOf("test") > -1)
621 formatMenu.add(vsel);
623 addFocusListener(new FocusAdapter()
626 public void focusGained(FocusEvent e)
628 Jalview.setCurrentAlignFrame(AlignFrame.this);
635 * Change the filename and format for the alignment, and enable the 'reload'
636 * button functionality.
644 public void setFileName(String file, FileFormatI format)
647 setFileFormat(format);
648 reload.setEnabled(true);
654 * @param file from SwingJS; may contain bytes -- for reload
655 * @param protocol from SwingJS; may be RELATIVE_URL
658 public void setFile(String fileName, File file, DataSourceType protocol, FileFormatI format)
660 this.fileName = fileName;
661 this.fileObject = file;
662 this.protocol = protocol;
663 setFileFormat(format);
664 reload.setEnabled(true);
668 * JavaScript will have this, maybe others. More dependable than a file name
669 * and maintains a reference to the actual bytes loaded.
673 public void setFileObject(File file)
675 this.fileObject = file;
679 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
682 void addKeyListener()
684 addKeyListener(new KeyAdapter()
687 public void keyPressed(KeyEvent evt)
689 if (viewport.cursorMode
690 && ((evt.getKeyCode() >= KeyEvent.VK_0
691 && evt.getKeyCode() <= KeyEvent.VK_9)
692 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
693 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
694 && Character.isDigit(evt.getKeyChar()))
696 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
699 switch (evt.getKeyCode())
702 case KeyEvent.VK_ESCAPE: // escape key
703 // alignPanel.deselectAllSequences();
704 alignPanel.deselectAllSequences();
708 case KeyEvent.VK_DOWN:
709 if (evt.isAltDown() || !viewport.cursorMode)
711 moveSelectedSequences(false);
713 if (viewport.cursorMode)
715 alignPanel.getSeqPanel().moveCursor(0, 1, evt.isShiftDown());
720 if (evt.isAltDown() || !viewport.cursorMode)
722 moveSelectedSequences(true);
724 if (viewport.cursorMode)
726 alignPanel.getSeqPanel().moveCursor(0, -1, evt.isShiftDown());
731 case KeyEvent.VK_LEFT:
732 if (evt.isAltDown() || !viewport.cursorMode)
734 slideSequences(false,
735 alignPanel.getSeqPanel().getKeyboardNo1());
739 alignPanel.getSeqPanel().moveCursor(-1, 0, evt.isShiftDown());
744 case KeyEvent.VK_RIGHT:
745 if (evt.isAltDown() || !viewport.cursorMode)
747 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
751 alignPanel.getSeqPanel().moveCursor(1, 0, evt.isShiftDown());
755 case KeyEvent.VK_SPACE:
756 if (viewport.cursorMode)
758 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
759 || evt.isShiftDown() || evt.isAltDown());
763 // case KeyEvent.VK_A:
764 // if (viewport.cursorMode)
766 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
767 // //System.out.println("A");
771 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
772 * System.out.println("closing bracket"); } break;
774 case KeyEvent.VK_DELETE:
775 case KeyEvent.VK_BACK_SPACE:
776 if (!viewport.cursorMode)
778 cut_actionPerformed();
782 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
783 || evt.isShiftDown() || evt.isAltDown());
789 if (viewport.cursorMode)
791 alignPanel.getSeqPanel().setCursorRow();
795 if (viewport.cursorMode && !evt.isControlDown())
797 alignPanel.getSeqPanel().setCursorColumn();
801 if (viewport.cursorMode)
803 alignPanel.getSeqPanel().setCursorPosition();
807 case KeyEvent.VK_ENTER:
808 case KeyEvent.VK_COMMA:
809 if (viewport.cursorMode)
811 alignPanel.getSeqPanel().setCursorRowAndColumn();
816 if (viewport.cursorMode)
818 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
822 if (viewport.cursorMode)
824 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
829 viewport.cursorMode = !viewport.cursorMode;
830 setStatus(MessageManager
831 .formatMessage("label.keyboard_editing_mode", new String[]
832 { (viewport.cursorMode ? "on" : "off") }));
833 if (viewport.cursorMode)
835 ViewportRanges ranges = viewport.getRanges();
836 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
838 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
841 alignPanel.getSeqPanel().seqCanvas.repaint();
847 Help.showHelpWindow();
848 } catch (Exception ex)
850 ex.printStackTrace();
855 boolean toggleSeqs = !evt.isControlDown();
856 boolean toggleCols = !evt.isShiftDown();
857 toggleHiddenRegions(toggleSeqs, toggleCols);
862 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
863 boolean modifyExisting = true; // always modify, don't clear
864 // evt.isShiftDown();
865 boolean invertHighlighted = evt.isAltDown();
866 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
870 case KeyEvent.VK_PAGE_UP:
871 viewport.getRanges().pageUp();
873 case KeyEvent.VK_PAGE_DOWN:
874 viewport.getRanges().pageDown();
880 public void keyReleased(KeyEvent evt)
882 switch (evt.getKeyCode())
884 case KeyEvent.VK_LEFT:
885 if (evt.isAltDown() || !viewport.cursorMode)
887 viewport.notifyAlignment();
891 case KeyEvent.VK_RIGHT:
892 if (evt.isAltDown() || !viewport.cursorMode)
894 viewport.notifyAlignment();
902 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
904 ap.alignFrame = this;
905 avc = new jalview.controller.AlignViewController(this, viewport,
910 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
912 int aSize = alignPanels.size();
914 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
916 if (aSize == 1 && ap.av.getViewName() == null)
918 this.getContentPane().add(ap, BorderLayout.CENTER);
924 setInitialTabVisible();
927 expandViews.setEnabled(true);
928 gatherViews.setEnabled(true);
929 tabbedPane.addTab(ap.av.getViewName(), ap);
931 ap.setVisible(false);
936 if (ap.av.isPadGaps())
938 ap.av.getAlignment().padGaps();
940 if (Jalview.getInstance().getStartCalculations())
942 ap.av.updateConservation(ap);
943 ap.av.updateConsensus(ap);
944 ap.av.updateStrucConsensus(ap);
945 ap.av.initInformationWorker(ap);
950 public void setInitialTabVisible()
952 expandViews.setEnabled(true);
953 gatherViews.setEnabled(true);
954 tabbedPane.setVisible(true);
955 AlignmentPanel first = alignPanels.get(0);
956 tabbedPane.addTab(first.av.getViewName(), first);
957 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
960 public AlignViewport getViewport()
966 public void servicesChanged(WSDiscovererI discoverer,
967 Collection<? extends ServiceWithParameters> services)
969 buildWebServicesMenu();
972 private WebServiceDiscovererI.ServicesChangeListener slivkaServiceChangeListener =
973 (discoverer, services) -> {
974 // run when slivka services change
975 var menu = AlignFrame.this.slivkaMenu;
976 menu.setServices(discoverer);
977 menu.setInProgress(discoverer.isRunning());
978 menu.setNoServices(services.isEmpty() && discoverer.isDone());
981 private WebServiceDiscovererI.ServicesChangeListener ebiServiceChangeListener =
982 (discoverer, services) -> {
983 // run when ebi services change
984 var menu = AlignFrame.this.ebiMenu;
985 menu.setServices(discoverer);
986 menu.setInProgress(discoverer.isRunning());
987 menu.setNoServices(services.isEmpty() && discoverer.isDone());
990 /* Set up intrinsic listeners for dynamically generated GUI bits. */
991 private void addServiceListeners()
993 if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
995 WebServiceDiscovererI discoverer = SlivkaWSDiscoverer.getInstance();
996 discoverer.addServicesChangeListener(slivkaServiceChangeListener);
998 if (Cache.getDefault("SHOW_EBI_SERVICES", true))
1000 JobDispatcherWSDiscoverer.getInstance().addServicesChangeListener(ebiServiceChangeListener);
1002 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
1004 WSDiscovererI discoverer = Jws2Discoverer.getInstance();
1005 discoverer.addServiceChangeListener(this);
1007 // legacy event listener for compatibility with jws1
1008 PropertyChangeListener legacyListener = (changeEvent) -> {
1009 buildWebServicesMenu();
1011 Desktop.getInstance().addJalviewPropertyChangeListener("services",legacyListener);
1013 addInternalFrameListener(new InternalFrameAdapter() {
1015 public void internalFrameClosed(InternalFrameEvent e) {
1016 System.out.println("deregistering discoverer listener");
1017 SlivkaWSDiscoverer.getInstance().removeServicesChangeListener(slivkaServiceChangeListener);
1018 Jws2Discoverer.getInstance().removeServiceChangeListener(AlignFrame.this);
1019 Desktop.getInstance().removeJalviewPropertyChangeListener("services", legacyListener);
1020 closeMenuItem_actionPerformed(true);
1023 buildWebServicesMenu();
1027 * Configure menu items that vary according to whether the alignment is
1028 * nucleotide or protein
1030 public void setGUINucleotide()
1032 AlignmentI al = getViewport().getAlignment();
1033 boolean nucleotide = al.isNucleotide();
1035 loadVcf.setVisible(nucleotide);
1036 showTranslation.setVisible(nucleotide);
1037 showReverse.setVisible(nucleotide);
1038 showReverseComplement.setVisible(nucleotide);
1039 conservationMenuItem.setEnabled(!nucleotide);
1041 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
1042 showGroupConservation.setEnabled(!nucleotide);
1044 showComplementMenuItem
1045 .setText(nucleotide ? MessageManager.getString("label.protein")
1046 : MessageManager.getString("label.nucleotide"));
1050 * set up menus for the current viewport. This may be called after any
1051 * operation that affects the data in the current view (selection changed,
1052 * etc) to update the menus to reflect the new state.
1055 public void setMenusForViewport()
1057 setMenusFromViewport(viewport);
1061 * Need to call this method when tabs are selected for multiple views, or when
1062 * loading from Jalview2XML.java
1067 public void setMenusFromViewport(AlignViewport av)
1069 padGapsMenuitem.setSelected(av.isPadGaps());
1070 colourTextMenuItem.setSelected(av.isShowColourText());
1071 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
1072 modifyPID.setEnabled(abovePIDThreshold.isSelected());
1073 conservationMenuItem.setSelected(av.getConservationSelected());
1074 modifyConservation.setEnabled(conservationMenuItem.isSelected());
1075 seqLimits.setSelected(av.getShowJVSuffix());
1076 idRightAlign.setSelected(av.isRightAlignIds());
1077 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
1078 renderGapsMenuItem.setSelected(av.isRenderGaps());
1079 wrapMenuItem.setSelected(av.getWrapAlignment());
1080 scaleAbove.setVisible(av.getWrapAlignment());
1081 scaleLeft.setVisible(av.getWrapAlignment());
1082 scaleRight.setVisible(av.getWrapAlignment());
1083 annotationPanelMenuItem.setState(av.isShowAnnotation());
1084 // Show/hide annotations only enabled if annotation panel is shown
1085 syncAnnotationMenuItems(av.isShowAnnotation());
1086 viewBoxesMenuItem.setSelected(av.getShowBoxes());
1087 viewTextMenuItem.setSelected(av.getShowText());
1088 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
1089 showGroupConsensus.setSelected(av.isShowGroupConsensus());
1090 showGroupConservation.setSelected(av.isShowGroupConservation());
1091 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
1092 showSequenceLogo.setSelected(av.isShowSequenceLogo());
1093 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
1094 showInformationHistogram.setSelected(av.isShowInformationHistogram());
1095 showHMMSequenceLogo.setSelected(av.isShowHMMSequenceLogo());
1096 normaliseHMMSequenceLogo.setSelected(av.isNormaliseHMMSequenceLogo());
1098 ColourMenuHelper.setColourSelected(colourMenu,
1099 av.getGlobalColourScheme());
1101 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
1102 hiddenMarkers.setState(av.getShowHiddenMarkers());
1103 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
1104 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
1105 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
1107 .setSelected(av.getAutoCalculateConsensusAndConservation());
1108 sortByTree.setSelected(av.sortByTree);
1109 listenToViewSelections.setSelected(av.followSelection);
1111 showProducts.setEnabled(canShowProducts());
1112 setGroovyEnabled(Desktop.getGroovyConsole() != null);
1114 updateEditMenuBar();
1118 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
1122 public void setGroovyEnabled(boolean b)
1124 runGroovy.setEnabled(b);
1127 private IProgressIndicator progressBar;
1132 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
1135 public void setProgressBar(String message, long id)
1137 progressBar.setProgressBar(message, id);
1141 public void addProgressBar(long id, String message)
1143 progressBar.addProgressBar(id, message);
1147 public void removeProgressBar(long id)
1149 progressBar.removeProgressBar(id);
1153 public void registerHandler(final long id,
1154 final IProgressIndicatorHandler handler)
1156 progressBar.registerHandler(id, handler);
1161 * @return true if any progress bars are still active
1164 public boolean operationInProgress()
1166 return progressBar.operationInProgress();
1170 * Sets the text of the status bar. Note that setting a null or empty value
1171 * will cause the status bar to be hidden, with possibly undesirable flicker
1172 * of the screen layout.
1175 public void setStatus(String text)
1177 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1181 * Added so Castor Mapping file can obtain Jalview Version
1183 public String getVersion()
1185 return Cache.getProperty("VERSION");
1188 public FeatureRenderer getFeatureRenderer()
1190 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1194 public void fetchSequence_actionPerformed()
1196 new SequenceFetcher(this);
1200 public void addFromFile_actionPerformed(ActionEvent e)
1202 Desktop.getInstance().inputLocalFileMenuItem_actionPerformed(viewport);
1206 public void hmmBuild_actionPerformed(boolean withDefaults)
1208 if (!alignmentIsSufficient(1))
1214 * get default parameters, and optionally show a dialog
1215 * to allow them to be modified
1217 ParamDatastoreI store = HMMERParamStore.forBuild(viewport);
1218 List<ArgumentI> args = store.getServiceParameters();
1222 WsParamSetI set = new HMMERPreset();
1223 WsJobParameters params = new WsJobParameters(store, set, args);
1224 params.showRunDialog().thenAccept((startJob) -> {
1227 var args2 = params.getJobParams();
1228 new Thread(new HMMBuild(this, args2)).start();
1234 new Thread(new HMMBuild(this, args)).start();
1239 public void hmmAlign_actionPerformed(boolean withDefaults)
1241 if (!(checkForHMM() && alignmentIsSufficient(2)))
1247 * get default parameters, and optionally show a dialog
1248 * to allow them to be modified
1250 ParamDatastoreI store = HMMERParamStore.forAlign(viewport);
1251 List<ArgumentI> args = store.getServiceParameters();
1255 WsParamSetI set = new HMMERPreset();
1256 WsJobParameters params = new WsJobParameters(store, set, args);
1257 params.showRunDialog().thenAccept((startJob) -> {
1260 var args2 = params.getJobParams();
1261 new Thread(new HMMAlign(this, args2)).start();
1267 new Thread(new HMMAlign(this, args)).start();
1272 public void hmmSearch_actionPerformed(boolean withDefaults)
1280 * get default parameters, and (if requested) show
1281 * dialog to allow modification
1283 ParamDatastoreI store = HMMERParamStore.forSearch(viewport);
1284 List<ArgumentI> args = store.getServiceParameters();
1288 WsParamSetI set = new HMMERPreset();
1289 WsJobParameters params = new WsJobParameters(store, set, args);
1290 params.showRunDialog().thenAccept((startJob) -> {
1293 var args2 = params.getJobParams();
1294 new Thread(new HMMSearch(this, args2)).start();
1295 alignPanel.repaint();
1301 new Thread(new HMMSearch(this, args)).start();
1302 alignPanel.repaint();
1307 public void jackhmmer_actionPerformed(boolean withDefaults)
1311 * get default parameters, and (if requested) show
1312 * dialog to allow modification
1315 ParamDatastoreI store = HMMERParamStore.forJackhmmer(viewport);
1316 List<ArgumentI> args = store.getServiceParameters();
1320 WsParamSetI set = new HMMERPreset();
1321 WsJobParameters params = new WsJobParameters(store, set, args);
1322 params.showRunDialog().thenAccept((startJob) -> {
1325 var args2 = params.getJobParams();
1326 new Thread(new JackHMMER(this, args2)).start();
1327 alignPanel.repaint();
1333 new Thread(new JackHMMER(this, args)).start();
1334 alignPanel.repaint();
1339 * Checks if the alignment has at least one hidden Markov model, if not shows
1340 * a dialog advising to run hmmbuild or load an HMM profile
1344 private boolean checkForHMM()
1346 if (viewport.getAlignment().getHmmSequences().isEmpty())
1348 JOptionPane.showMessageDialog(this,
1349 MessageManager.getString("warn.no_hmm"));
1356 protected void filterByEValue_actionPerformed()
1358 viewport.filterByEvalue(inputDouble("Enter E-Value Cutoff"));
1362 protected void filterByScore_actionPerformed()
1364 viewport.filterByScore(inputDouble("Enter Bit Score Threshold"));
1367 private double inputDouble(String message)
1371 while (d == null || d <= 0)
1373 str = JOptionPane.showInputDialog(this.alignPanel, message);
1376 d = Double.valueOf(str);
1377 } catch (NumberFormatException e)
1385 * Checks if the alignment contains the required number of sequences.
1390 public boolean alignmentIsSufficient(int required)
1392 if (getViewport().getSequenceSelection().length < required)
1394 JOptionPane.showMessageDialog(this,
1395 MessageManager.getString("label.not_enough_sequences"));
1402 * Opens a file browser and adds the selected file, if in Fasta, Stockholm or
1403 * Pfam format, to the list held under preference key "HMMSEARCH_DBS" (as a
1404 * comma-separated list)
1407 public void addDatabase_actionPerformed() throws IOException
1409 if (Cache.getProperty(Preferences.HMMSEARCH_DBS) == null)
1411 Cache.setProperty(Preferences.HMMSEARCH_DBS, "");
1414 String path = openFileChooser(false);
1415 if (path != null && new File(path).exists())
1417 IdentifyFile identifier = new IdentifyFile();
1418 FileFormatI format = identifier.identify(path, DataSourceType.FILE);
1419 if (format == FileFormat.Fasta || format == FileFormat.Stockholm
1420 || format == FileFormat.Pfam)
1422 String currentDbPaths = Cache
1423 .getProperty(Preferences.HMMSEARCH_DBS);
1424 currentDbPaths += Preferences.COMMA + path;
1425 Cache.setProperty(Preferences.HMMSEARCH_DBS, currentDbPaths);
1429 JOptionPane.showMessageDialog(this,
1430 MessageManager.getString("warn.invalid_format"));
1436 * Opens a file chooser, optionally restricted to selecting folders
1437 * (directories) only. Answers the path to the selected file or folder, or
1438 * null if none is chosen.
1443 protected String openFileChooser(boolean forFolder)
1445 // TODO duplicates GPreferences method - relocate to JalviewFileChooser?
1446 String choice = null;
1447 JFileChooser chooser = new JFileChooser();
1450 chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1452 chooser.setDialogTitle(
1453 MessageManager.getString("label.open_local_file"));
1454 chooser.setToolTipText(MessageManager.getString("action.open"));
1456 int value = chooser.showOpenDialog(this);
1458 if (value == JFileChooser.APPROVE_OPTION)
1460 choice = chooser.getSelectedFile().getPath();
1466 public void reload_actionPerformed(ActionEvent e)
1468 if (fileName == null && fileObject == null)
1472 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1473 // originating file's format
1474 // TODO: work out how to recover feature settings for correct view(s) when
1475 // file is reloaded.
1476 if (FileFormat.Jalview.equals(currentFileFormat))
1478 JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
1479 for (int i = 0; i < frames.length; i++)
1481 if (frames[i] instanceof AlignFrame && frames[i] != this
1482 && ((AlignFrame) frames[i]).fileName != null
1483 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1487 frames[i].setSelected(true);
1488 Desktop.getInstance().closeAssociatedWindows();
1489 } catch (java.beans.PropertyVetoException ex)
1495 Desktop.getInstance().closeAssociatedWindows();
1497 FileLoader loader = new FileLoader();
1498 loader.LoadFile(viewport, (fileObject == null ? fileName : fileObject), protocol, currentFileFormat);
1502 Rectangle bounds = this.getBounds();
1504 FileLoader loader = new FileLoader();
1506 AlignFrame newframe = null;
1508 if (fileObject == null)
1510 newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1515 newframe = loader.LoadFileWaitTillLoaded(fileObject,
1516 DataSourceType.FILE, currentFileFormat);
1519 newframe.setBounds(bounds);
1520 if (featureSettings != null && featureSettings.isShowing())
1522 final Rectangle fspos = featureSettings.frame.getBounds();
1523 // TODO: need a 'show feature settings' function that takes bounds -
1524 // need to refactor Desktop.addFrame
1525 newframe.featureSettings_actionPerformed(null);
1526 final FeatureSettings nfs = newframe.featureSettings;
1527 SwingUtilities.invokeLater(new Runnable()
1532 nfs.frame.setBounds(fspos);
1535 this.featureSettings.close();
1536 this.featureSettings = null;
1538 this.closeMenuItem_actionPerformed(true);
1543 public void addFromText_actionPerformed(ActionEvent e)
1545 Desktop.getInstance()
1546 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1550 public void addFromURL_actionPerformed(ActionEvent e)
1552 Desktop.getInstance().inputURLMenuItem_actionPerformed(viewport);
1556 public void save_actionPerformed(ActionEvent e)
1558 if (fileName == null || (currentFileFormat == null)
1559 || HttpUtils.startsWithHttpOrHttps(fileName))
1561 saveAs_actionPerformed();
1565 saveAlignment(fileName, currentFileFormat);
1570 * Saves the alignment to a file with a name chosen by the user, if necessary
1571 * warning if a file would be overwritten
1574 public void saveAs_actionPerformed()
1576 String format = currentFileFormat == null ? null
1577 : currentFileFormat.getName();
1578 JalviewFileChooser chooser = JalviewFileChooser
1579 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1581 chooser.setFileView(new JalviewFileView());
1582 chooser.setDialogTitle(
1583 MessageManager.getString("label.save_alignment_to_file"));
1584 chooser.setToolTipText(MessageManager.getString("action.save"));
1586 int value = chooser.showSaveDialog(this);
1588 if (value != JalviewFileChooser.APPROVE_OPTION)
1592 currentFileFormat = chooser.getSelectedFormat();
1593 // todo is this (2005) test now obsolete - value is never null?
1594 while (currentFileFormat == null)
1596 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
1598 .getString("label.select_file_format_before_saving"),
1599 MessageManager.getString("label.file_format_not_specified"),
1600 JvOptionPane.WARNING_MESSAGE);
1601 currentFileFormat = chooser.getSelectedFormat();
1602 value = chooser.showSaveDialog(this);
1603 if (value != JalviewFileChooser.APPROVE_OPTION)
1609 fileName = chooser.getSelectedFile().getPath();
1611 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1612 Cache.setProperty("LAST_DIRECTORY", fileName);
1613 saveAlignment(fileName, currentFileFormat);
1616 boolean lastSaveSuccessful = false;
1618 FileFormatI lastFormatSaved;
1620 String lastFilenameSaved;
1623 * Raise a dialog or status message for the last call to saveAlignment.
1625 * @return true if last call to saveAlignment(file, format) was successful.
1627 public boolean isSaveAlignmentSuccessful()
1630 if (!lastSaveSuccessful)
1632 if (!Platform.isHeadless())
1634 JvOptionPane.showInternalMessageDialog(this, MessageManager
1635 .formatMessage("label.couldnt_save_file", new Object[]
1636 { lastFilenameSaved }),
1637 MessageManager.getString("label.error_saving_file"),
1638 JvOptionPane.WARNING_MESSAGE);
1642 Console.error(MessageManager
1643 .formatMessage("label.couldnt_save_file", new Object[]
1644 { lastFilenameSaved }));
1650 setStatus(MessageManager.formatMessage(
1651 "label.successfully_saved_to_file_in_format", new Object[]
1652 { lastFilenameSaved, lastFormatSaved }));
1655 return lastSaveSuccessful;
1659 * Saves the alignment to the specified file path, in the specified format,
1660 * which may be an alignment format, or Jalview project format. If the
1661 * alignment has hidden regions, or the format is one capable of including
1662 * non-sequence data (features, annotations, groups), then the user may be
1663 * prompted to specify what to include in the output.
1668 public void saveAlignment(String file, FileFormatI format)
1670 lastSaveSuccessful = true;
1671 lastFilenameSaved = file;
1672 lastFormatSaved = format;
1674 if (FileFormat.Jalview.equals(format))
1676 String shortName = title;
1677 if (shortName.indexOf(File.separatorChar) > -1)
1679 shortName = shortName
1680 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
1682 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file,
1685 statusBar.setText(MessageManager.formatMessage(
1686 "label.successfully_saved_to_file_in_format", new Object[]
1687 { fileName, format }));
1692 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1693 Runnable cancelAction = new Runnable()
1698 lastSaveSuccessful = false;
1701 Runnable outputAction = new Runnable()
1706 // todo defer this to inside formatSequences (or later)
1707 AlignmentExportData exportData = viewport
1708 .getAlignExportData(options);
1709 String output = new FormatAdapter(alignPanel, options)
1710 .formatSequences(format, exportData.getAlignment(),
1711 exportData.getOmitHidden(),
1712 exportData.getStartEndPostions(),
1713 viewport.getAlignment().getHiddenColumns());
1716 lastSaveSuccessful = false;
1720 // create backupfiles object and get new temp filename destination
1721 boolean doBackup = BackupFiles.getEnabled();
1722 BackupFiles backupfiles = null;
1726 "ALIGNFRAME making backupfiles object for " + file);
1727 backupfiles = new BackupFiles(file);
1731 String tempFilePath = doBackup ? backupfiles.getTempFilePath()
1733 Console.trace("ALIGNFRAME setting PrintWriter");
1734 PrintWriter out = new PrintWriter(new FileWriter(tempFilePath));
1736 if (backupfiles != null)
1738 Console.trace("ALIGNFRAME about to write to temp file "
1739 + backupfiles.getTempFilePath());
1743 Console.trace("ALIGNFRAME about to close file");
1745 Console.trace("ALIGNFRAME closed file");
1746 AlignFrame.this.setTitle(file);
1747 statusBar.setText(MessageManager.formatMessage(
1748 "label.successfully_saved_to_file_in_format",
1750 { fileName, format.getName() }));
1751 lastSaveSuccessful = true;
1752 } catch (IOException e)
1754 lastSaveSuccessful = false;
1756 "ALIGNFRAME Something happened writing the temp file");
1757 Console.error(e.getMessage());
1758 Console.debug(Cache.getStackTraceString(e));
1759 } catch (Exception ex)
1761 lastSaveSuccessful = false;
1763 "ALIGNFRAME Something unexpected happened writing the temp file");
1764 Console.error(ex.getMessage());
1765 Console.debug(Cache.getStackTraceString(ex));
1770 backupfiles.setWriteSuccess(lastSaveSuccessful);
1771 Console.debug("ALIGNFRAME writing temp file was "
1772 + (lastSaveSuccessful ? "" : "NOT ") + "successful");
1773 // do the backup file roll and rename the temp file to actual file
1775 "ALIGNFRAME about to rollBackupsAndRenameTempFile");
1776 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1778 "ALIGNFRAME performed rollBackupsAndRenameTempFile "
1779 + (lastSaveSuccessful ? "" : "un")
1787 * show dialog with export options if applicable; else just do it
1789 if (AlignExportOptions.isNeeded(viewport, format))
1791 AlignExportOptions choices = new AlignExportOptions(
1792 alignPanel.getAlignViewport(), format, options);
1793 choices.setResponseAction(0, outputAction);
1794 choices.setResponseAction(1, cancelAction);
1795 choices.showDialog();
1804 * Outputs the alignment to textbox in the requested format, if necessary
1805 * first prompting the user for whether to include hidden regions or
1808 * @param fileFormatName
1811 protected void outputText_actionPerformed(String fileFormatName)
1813 FileFormatI fileFormat = FileFormats.getInstance()
1814 .forName(fileFormatName);
1815 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1816 Runnable outputAction = new Runnable()
1821 // todo defer this to inside formatSequences (or later)
1822 AlignmentExportData exportData = viewport
1823 .getAlignExportData(options);
1824 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1825 cap.setForInput(null);
1828 FileFormatI format = fileFormat;
1829 cap.setText(new FormatAdapter(alignPanel, options)
1830 .formatSequences(format, exportData.getAlignment(),
1831 exportData.getOmitHidden(),
1832 exportData.getStartEndPostions(),
1833 viewport.getAlignment().getHiddenColumns()));
1834 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1835 "label.alignment_output_command", new Object[]
1836 { fileFormat.getName() }), 600, 500);
1837 } catch (OutOfMemoryError oom)
1839 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1847 * show dialog with export options if applicable; else just do it
1849 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1851 AlignExportOptions choices = new AlignExportOptions(
1852 alignPanel.getAlignViewport(), fileFormat, options);
1853 choices.setResponseAction(0, outputAction);
1854 choices.showDialog();
1869 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1871 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1872 htmlSVG.exportHTML(null);
1876 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1878 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1879 bjs.exportHTML(null);
1883 public void createImageMap(File file, String image)
1885 alignPanel.makePNGImageMap(file, image);
1889 * Creates a PNG image of the alignment and writes it to the given file. If
1890 * the file is null, the user is prompted to choose a file.
1895 public void createPNG(File f)
1897 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1901 * Creates an EPS image of the alignment and writes it to the given file. If
1902 * the file is null, the user is prompted to choose a file.
1907 public void createEPS(File f)
1909 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1913 * Creates an SVG image of the alignment and writes it to the given file. If
1914 * the file is null, the user is prompted to choose a file.
1919 public void createSVG(File f)
1921 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1925 public void pageSetup_actionPerformed(ActionEvent e)
1927 PrinterJob printJob = PrinterJob.getPrinterJob();
1928 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1938 public void printMenuItem_actionPerformed(ActionEvent e)
1940 // Putting in a thread avoids Swing painting problems
1941 PrintThread thread = new PrintThread(alignPanel);
1946 public void exportFeatures_actionPerformed(ActionEvent e)
1948 new AnnotationExporter(alignPanel).exportFeatures();
1952 public void exportAnnotations_actionPerformed(ActionEvent e)
1954 new AnnotationExporter(alignPanel).exportAnnotations();
1958 public void associatedData_actionPerformed(ActionEvent e)
1959 throws IOException, InterruptedException
1961 final JalviewFileChooser chooser = new JalviewFileChooser(
1962 Cache.getProperty("LAST_DIRECTORY"));
1963 chooser.setFileView(new JalviewFileView());
1964 String tooltip = MessageManager
1965 .getString("label.load_jalview_annotations");
1966 chooser.setDialogTitle(tooltip);
1967 chooser.setToolTipText(tooltip);
1968 chooser.setResponseHandler(0, new Runnable()
1973 String choice = chooser.getSelectedFile().getPath();
1974 Cache.setProperty("LAST_DIRECTORY", choice);
1975 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1979 chooser.showOpenDialog(this);
1983 * Close the current view or all views in the alignment frame. If the frame
1984 * only contains one view then the alignment will be removed from memory.
1986 * @param closeAllTabs
1989 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1991 if (alignPanels != null && alignPanels.size() < 2)
1993 closeAllTabs = true;
1998 if (alignPanels != null)
2002 if (this.isClosed())
2004 // really close all the windows - otherwise wait till
2005 // setClosed(true) is called
2006 for (int i = 0; i < alignPanels.size(); i++)
2008 AlignmentPanel ap = alignPanels.get(i);
2015 closeView(alignPanel);
2020 if (featureSettings != null && featureSettings.isOpen())
2022 featureSettings.close();
2023 featureSettings = null;
2026 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
2027 * be called recursively, with the frame now in 'closed' state
2029 this.setClosed(true);
2031 } catch (Exception ex)
2033 ex.printStackTrace();
2038 * Close the specified panel and close up tabs appropriately.
2040 * @param panelToClose
2042 public void closeView(AlignmentPanel panelToClose)
2044 int index = tabbedPane.getSelectedIndex();
2045 int closedindex = tabbedPane.indexOfComponent(panelToClose);
2046 alignPanels.remove(panelToClose);
2047 panelToClose.closePanel();
2048 panelToClose = null;
2050 tabbedPane.removeTabAt(closedindex);
2051 tabbedPane.validate();
2053 if (index > closedindex || index == tabbedPane.getTabCount())
2055 // modify currently selected tab index if necessary.
2059 this.tabSelectionChanged(index);
2065 void updateEditMenuBar()
2068 if (viewport.getHistoryList().size() > 0)
2070 undoMenuItem.setEnabled(true);
2071 CommandI command = viewport.getHistoryList().peek();
2072 undoMenuItem.setText(MessageManager
2073 .formatMessage("label.undo_command", new Object[]
2074 { command.getDescription() }));
2078 undoMenuItem.setEnabled(false);
2079 undoMenuItem.setText(MessageManager.getString("action.undo"));
2082 if (viewport.getRedoList().size() > 0)
2084 redoMenuItem.setEnabled(true);
2086 CommandI command = viewport.getRedoList().peek();
2087 redoMenuItem.setText(MessageManager
2088 .formatMessage("label.redo_command", new Object[]
2089 { command.getDescription() }));
2093 redoMenuItem.setEnabled(false);
2094 redoMenuItem.setText(MessageManager.getString("action.redo"));
2099 public void addHistoryItem(CommandI command)
2101 if (command.getSize() > 0)
2103 viewport.addToHistoryList(command);
2104 viewport.clearRedoList();
2105 updateEditMenuBar();
2106 viewport.updateHiddenColumns();
2107 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
2108 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2109 // viewport.getColumnSelection()
2110 // .getHiddenColumns().size() > 0);
2116 * @return alignment objects for all views
2118 AlignmentI[] getViewAlignments()
2120 if (alignPanels != null)
2122 AlignmentI[] als = new AlignmentI[alignPanels.size()];
2124 for (AlignmentPanel ap : alignPanels)
2126 als[i++] = ap.av.getAlignment();
2130 if (viewport != null)
2132 return new AlignmentI[] { viewport.getAlignment() };
2144 protected void undoMenuItem_actionPerformed(ActionEvent e)
2146 if (viewport.getHistoryList().isEmpty())
2150 CommandI command = viewport.getHistoryList().pop();
2151 viewport.addToRedoList(command);
2152 command.undoCommand(getViewAlignments());
2154 AlignmentViewport originalSource = getOriginatingSource(command);
2155 updateEditMenuBar();
2157 if (originalSource != null)
2159 if (originalSource != viewport)
2162 "Implementation worry: mismatch of viewport origin for undo");
2164 originalSource.updateHiddenColumns();
2165 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
2167 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2168 // viewport.getColumnSelection()
2169 // .getHiddenColumns().size() > 0);
2170 originalSource.notifyAlignment();
2181 protected void redoMenuItem_actionPerformed(ActionEvent e)
2183 if (viewport.getRedoList().size() < 1)
2188 CommandI command = viewport.getRedoList().pop();
2189 viewport.addToHistoryList(command);
2190 command.doCommand(getViewAlignments());
2192 AlignmentViewport originalSource = getOriginatingSource(command);
2193 updateEditMenuBar();
2195 if (originalSource != null)
2198 if (originalSource != viewport)
2201 "Implementation worry: mismatch of viewport origin for redo");
2203 originalSource.updateHiddenColumns();
2204 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
2206 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2207 // viewport.getColumnSelection()
2208 // .getHiddenColumns().size() > 0);
2209 originalSource.notifyAlignment();
2213 AlignmentViewport getOriginatingSource(CommandI command)
2215 AlignmentViewport originalSource = null;
2216 // For sequence removal and addition, we need to fire
2217 // the property change event FROM the viewport where the
2218 // original alignment was altered
2219 AlignmentI al = null;
2220 if (command instanceof EditCommand)
2222 EditCommand editCommand = (EditCommand) command;
2223 al = editCommand.getAlignment();
2224 List<Component> comps = PaintRefresher.components
2225 .get(viewport.getSequenceSetId());
2227 for (Component comp : comps)
2229 if (comp instanceof AlignmentPanel)
2231 if (al == ((AlignmentPanel) comp).av.getAlignment())
2233 originalSource = ((AlignmentPanel) comp).av;
2240 if (originalSource == null)
2242 // The original view is closed, we must validate
2243 // the current view against the closed view first
2246 PaintRefresher.validateSequences(al, viewport.getAlignment());
2249 originalSource = viewport;
2252 return originalSource;
2256 * Calls AlignmentI.moveSelectedSequencesByOne with current sequence selection
2257 * or the sequence under cursor in keyboard mode
2262 public void moveSelectedSequences(boolean up)
2264 SequenceGroup sg = viewport.getSelectionGroup();
2268 if (viewport.cursorMode)
2270 sg = new SequenceGroup();
2271 sg.addSequence(viewport.getAlignment().getSequenceAt(
2272 alignPanel.getSeqPanel().seqCanvas.cursorY), false);
2280 if (sg.getSize() < 1)
2285 // TODO: JAL-3733 - add an event to the undo buffer for this !
2287 viewport.getAlignment().moveSelectedSequencesByOne(sg,
2288 viewport.getHiddenRepSequences(), up);
2289 alignPanel.paintAlignment(true, false);
2292 synchronized void slideSequences(boolean right, int size)
2294 List<SequenceI> sg = new ArrayList<>();
2295 if (viewport.cursorMode)
2297 sg.add(viewport.getAlignment()
2298 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
2300 else if (viewport.getSelectionGroup() != null
2301 && viewport.getSelectionGroup().getSize() != viewport
2302 .getAlignment().getHeight())
2304 sg = viewport.getSelectionGroup()
2305 .getSequences(viewport.getHiddenRepSequences());
2313 List<SequenceI> invertGroup = new ArrayList<>();
2315 for (SequenceI seq : viewport.getAlignment().getSequences())
2317 if (!sg.contains(seq))
2319 invertGroup.add(seq);
2323 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
2325 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
2326 for (int i = 0; i < invertGroup.size(); i++)
2328 seqs2[i] = invertGroup.get(i);
2331 SlideSequencesCommand ssc;
2334 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
2335 viewport.getGapCharacter());
2339 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
2340 viewport.getGapCharacter());
2343 int groupAdjustment = 0;
2344 if (ssc.getGapsInsertedBegin() && right)
2346 if (viewport.cursorMode)
2348 alignPanel.getSeqPanel().moveCursor(size, 0);
2352 groupAdjustment = size;
2355 else if (!ssc.getGapsInsertedBegin() && !right)
2357 if (viewport.cursorMode)
2359 alignPanel.getSeqPanel().moveCursor(-size, 0);
2363 groupAdjustment = -size;
2367 if (groupAdjustment != 0)
2369 viewport.getSelectionGroup().setStartRes(
2370 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
2371 viewport.getSelectionGroup().setEndRes(
2372 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
2376 * just extend the last slide command if compatible; but not if in
2377 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
2379 boolean appendHistoryItem = false;
2380 Deque<CommandI> historyList = viewport.getHistoryList();
2381 boolean inSplitFrame = getSplitViewContainer() != null;
2382 if (!inSplitFrame && historyList != null && historyList.size() > 0
2383 && historyList.peek() instanceof SlideSequencesCommand)
2385 appendHistoryItem = ssc.appendSlideCommand(
2386 (SlideSequencesCommand) historyList.peek());
2389 if (!appendHistoryItem)
2391 addHistoryItem(ssc);
2404 protected void copy_actionPerformed()
2406 if (viewport.getSelectionGroup() == null)
2410 // TODO: preserve the ordering of displayed alignment annotation in any
2411 // internal paste (particularly sequence associated annotation)
2412 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2413 String[] omitHidden = null;
2415 if (viewport.hasHiddenColumns())
2417 omitHidden = viewport.getViewAsString(true);
2420 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2421 seqs, omitHidden, null);
2423 StringSelection ss = new StringSelection(output);
2425 Desktop d = Desktop.getInstance();
2428 d.internalCopy = true;
2429 // Its really worth setting the clipboard contents
2430 // to empty before setting the large StringSelection!!
2431 Toolkit.getDefaultToolkit().getSystemClipboard()
2432 .setContents(new StringSelection(""), null);
2434 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2436 } catch (OutOfMemoryError er)
2438 new OOMWarning("copying region", er);
2442 HiddenColumns hiddenColumns = null;
2443 if (viewport.hasHiddenColumns())
2445 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2446 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2448 // create new HiddenColumns object with copy of hidden regions
2449 // between startRes and endRes, offset by startRes
2450 hiddenColumns = new HiddenColumns(
2451 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2452 hiddenCutoff, hiddenOffset);
2455 d.jalviewClipboard = new Object[] { seqs,
2456 viewport.getAlignment().getDataset(), hiddenColumns };
2457 setStatus(MessageManager.formatMessage(
2458 "label.copied_sequences_to_clipboard", new Object[]
2459 { Integer.valueOf(seqs.length).toString() }));
2467 * @throws InterruptedException
2468 * @throws IOException
2471 protected void pasteNew_actionPerformed(ActionEvent e)
2472 throws IOException, InterruptedException
2482 * @throws InterruptedException
2483 * @throws IOException
2486 protected void pasteThis_actionPerformed(ActionEvent e)
2487 throws IOException, InterruptedException
2493 * Paste contents of Jalview clipboard
2495 * @param newAlignment
2496 * true to paste to a new alignment, otherwise add to this.
2497 * @throws InterruptedException
2498 * @throws IOException
2500 void paste(boolean newAlignment) throws IOException, InterruptedException
2502 boolean externalPaste = true;
2505 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2506 Transferable contents = c.getContents(this);
2508 if (contents == null)
2517 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2518 if (str.length() < 1)
2523 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2525 } catch (OutOfMemoryError er)
2527 new OOMWarning("Out of memory pasting sequences!!", er);
2531 SequenceI[] sequences;
2532 boolean annotationAdded = false;
2533 AlignmentI alignment = null;
2535 Desktop d = Desktop.getInstance();
2537 if (d.jalviewClipboard != null)
2539 // The clipboard was filled from within Jalview, we must use the
2541 // And dataset from the copied alignment
2542 SequenceI[] newseq = (SequenceI[]) d.jalviewClipboard[0];
2543 // be doubly sure that we create *new* sequence objects.
2544 sequences = new SequenceI[newseq.length];
2545 for (int i = 0; i < newseq.length; i++)
2547 sequences[i] = new Sequence(newseq[i]);
2549 alignment = new Alignment(sequences);
2550 externalPaste = false;
2554 // parse the clipboard as an alignment.
2555 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2557 sequences = alignment.getSequencesArray();
2561 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2567 if (d.jalviewClipboard != null)
2569 // dataset is inherited
2570 alignment.setDataset((Alignment) d.jalviewClipboard[1]);
2574 // new dataset is constructed
2575 alignment.setDataset(null);
2577 alwidth = alignment.getWidth() + 1;
2581 AlignmentI pastedal = alignment; // preserve pasted alignment object
2582 // Add pasted sequences and dataset into existing alignment.
2583 alignment = viewport.getAlignment();
2584 alwidth = alignment.getWidth() + 1;
2585 // decide if we need to import sequences from an existing dataset
2586 boolean importDs = d.jalviewClipboard != null
2587 && d.jalviewClipboard[1] != alignment.getDataset();
2588 // importDs==true instructs us to copy over new dataset sequences from
2589 // an existing alignment
2590 Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2592 // minimum dataset set
2594 for (int i = 0; i < sequences.length; i++)
2598 newDs.addElement(null);
2600 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2602 if (importDs && ds != null)
2604 if (!newDs.contains(ds))
2606 newDs.setElementAt(ds, i);
2607 ds = new Sequence(ds);
2608 // update with new dataset sequence
2609 sequences[i].setDatasetSequence(ds);
2613 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2618 // copy and derive new dataset sequence
2619 sequences[i] = sequences[i].deriveSequence();
2620 alignment.getDataset()
2621 .addSequence(sequences[i].getDatasetSequence());
2622 // TODO: avoid creation of duplicate dataset sequences with a
2623 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2625 alignment.addSequence(sequences[i]); // merges dataset
2629 newDs.clear(); // tidy up
2631 if (alignment.getAlignmentAnnotation() != null)
2633 for (AlignmentAnnotation alan : alignment
2634 .getAlignmentAnnotation())
2636 if (alan.graphGroup > fgroup)
2638 fgroup = alan.graphGroup;
2642 if (pastedal.getAlignmentAnnotation() != null)
2644 // Add any annotation attached to alignment.
2645 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2646 for (int i = 0; i < alann.length; i++)
2648 annotationAdded = true;
2649 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2651 AlignmentAnnotation newann = new AlignmentAnnotation(
2653 if (newann.graphGroup > -1)
2655 if (newGraphGroups.size() <= newann.graphGroup
2656 || newGraphGroups.get(newann.graphGroup) == null)
2658 for (int q = newGraphGroups
2659 .size(); q <= newann.graphGroup; q++)
2661 newGraphGroups.add(q, null);
2663 newGraphGroups.set(newann.graphGroup,
2664 Integer.valueOf(++fgroup));
2666 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2670 newann.padAnnotation(alwidth);
2671 alignment.addAnnotation(newann);
2681 addHistoryItem(new EditCommand(
2682 MessageManager.getString("label.add_sequences"),
2683 Action.PASTE, sequences, 0, alignment.getWidth(),
2686 // Add any annotations attached to sequences
2687 for (int i = 0; i < sequences.length; i++)
2689 if (sequences[i].getAnnotation() != null)
2691 AlignmentAnnotation newann;
2692 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2694 annotationAdded = true;
2695 newann = sequences[i].getAnnotation()[a];
2696 newann.adjustForAlignment();
2697 newann.padAnnotation(alwidth);
2698 if (newann.graphGroup > -1)
2700 if (newann.graphGroup > -1)
2702 if (newGraphGroups.size() <= newann.graphGroup
2703 || newGraphGroups.get(newann.graphGroup) == null)
2705 for (int q = newGraphGroups
2706 .size(); q <= newann.graphGroup; q++)
2708 newGraphGroups.add(q, null);
2710 newGraphGroups.set(newann.graphGroup,
2711 Integer.valueOf(++fgroup));
2713 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2717 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2721 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2729 // propagate alignment changed.
2730 viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2731 if (annotationAdded)
2733 // Duplicate sequence annotation in all views.
2734 AlignmentI[] alview = this.getViewAlignments();
2735 for (int i = 0; i < sequences.length; i++)
2737 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2742 for (int avnum = 0; avnum < alview.length; avnum++)
2744 if (alview[avnum] != alignment)
2746 // duplicate in a view other than the one with input focus
2747 int avwidth = alview[avnum].getWidth() + 1;
2748 // this relies on sann being preserved after we
2749 // modify the sequence's annotation array for each duplication
2750 for (int a = 0; a < sann.length; a++)
2752 AlignmentAnnotation newann = new AlignmentAnnotation(
2754 sequences[i].addAlignmentAnnotation(newann);
2755 newann.padAnnotation(avwidth);
2756 alview[avnum].addAnnotation(newann); // annotation was
2757 // duplicated earlier
2758 // TODO JAL-1145 graphGroups are not updated for sequence
2759 // annotation added to several views. This may cause
2761 alview[avnum].setAnnotationIndex(newann, a);
2766 buildSortByAnnotationScoresMenu();
2768 viewport.notifyAlignment();
2769 if (alignPanels != null)
2771 for (AlignmentPanel ap : alignPanels)
2773 ap.validateAnnotationDimensions(false);
2778 alignPanel.validateAnnotationDimensions(false);
2784 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2786 String newtitle = new String("Copied sequences");
2788 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2790 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2791 af.viewport.setHiddenColumns(hc);
2794 // >>>This is a fix for the moment, until a better solution is
2796 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2797 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2798 .getFeatureRenderer());
2800 // TODO: maintain provenance of an alignment, rather than just make the
2801 // title a concatenation of operations.
2804 if (title.startsWith("Copied sequences"))
2810 newtitle = newtitle.concat("- from " + title);
2815 newtitle = new String("Pasted sequences");
2818 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2823 } catch (Exception ex)
2825 ex.printStackTrace();
2826 System.out.println("Exception whilst pasting: " + ex);
2827 // could be anything being pasted in here
2833 protected void expand_newalign(ActionEvent e)
2837 AlignmentI alignment = AlignmentUtils
2838 .expandContext(getViewport().getAlignment(), -1);
2839 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2841 String newtitle = new String("Flanking alignment");
2843 Desktop d = Desktop.getInstance();
2844 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2846 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2847 af.viewport.setHiddenColumns(hc);
2850 // >>>This is a fix for the moment, until a better solution is
2852 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2853 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2854 .getFeatureRenderer());
2856 // TODO: maintain provenance of an alignment, rather than just make the
2857 // title a concatenation of operations.
2859 if (title.startsWith("Copied sequences"))
2865 newtitle = newtitle.concat("- from " + title);
2869 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2871 } catch (Exception ex)
2873 ex.printStackTrace();
2874 System.out.println("Exception whilst pasting: " + ex);
2875 // could be anything being pasted in here
2876 } catch (OutOfMemoryError oom)
2878 new OOMWarning("Viewing flanking region of alignment", oom);
2883 * Action Cut (delete and copy) the selected region
2886 protected void cut_actionPerformed()
2888 copy_actionPerformed();
2889 delete_actionPerformed();
2893 * Performs menu option to Delete the currently selected region
2896 protected void delete_actionPerformed()
2899 SequenceGroup sg = viewport.getSelectionGroup();
2905 Runnable okAction = new Runnable()
2910 SequenceI[] cut = sg.getSequences()
2911 .toArray(new SequenceI[sg.getSize()]);
2913 addHistoryItem(new EditCommand(
2914 MessageManager.getString("label.cut_sequences"), Action.CUT,
2915 cut, sg.getStartRes(),
2916 sg.getEndRes() - sg.getStartRes() + 1,
2917 viewport.getAlignment()));
2919 viewport.setSelectionGroup(null);
2920 viewport.sendSelection();
2921 viewport.getAlignment().deleteGroup(sg);
2923 viewport.notifyAlignment();
2924 if (viewport.getAlignment().getHeight() < 1)
2928 AlignFrame.this.setClosed(true);
2929 } catch (Exception ex)
2939 * If the cut affects all sequences, prompt for confirmation
2941 boolean wholeHeight = sg.getSize() == viewport.getAlignment()
2943 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2944 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2945 if (wholeHeight && wholeWidth)
2947 JvOptionPane dialog = JvOptionPane
2948 .newOptionDialog(Desktop.getDesktopPane());
2949 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2950 Object[] options = new Object[] {
2951 MessageManager.getString("action.ok"),
2952 MessageManager.getString("action.cancel") };
2953 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2954 MessageManager.getString("label.delete_all"),
2955 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2956 options, options[0]);
2971 protected void deleteGroups_actionPerformed(ActionEvent e)
2973 if (avc.deleteGroups())
2975 updateAll(viewport.getSequenceSetId());
2979 private void updateAll(String id)
2983 // this will force a non-fast repaint of both the IdPanel and SeqPanel
2984 alignPanel.getIdPanel().getIdCanvas().setNoFastPaint();
2985 alignPanel.getSeqPanel().seqCanvas.setNoFastPaint();
2986 alignPanel.repaint();
2991 PaintRefresher.Refresh(this, id);
2992 alignPanel.paintAlignment(true, true);
2994 alignPanel.updateAnnotation();
3004 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
3006 alignPanel.selectAllSequences();
3016 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
3018 alignPanel.deselectAllSequences();
3028 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
3030 SequenceGroup sg = viewport.getSelectionGroup();
3034 alignPanel.selectAllSequences();
3039 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
3041 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
3043 // JAL-2034 - should delegate to
3044 // alignPanel to decide if overview needs
3047 alignPanel.paintAlignment(true, false);
3048 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
3049 viewport.sendSelection();
3053 public void invertColSel_actionPerformed(ActionEvent e)
3055 viewport.invertColumnSelection();
3056 alignPanel.paintAlignment(true, false);
3057 viewport.sendSelection();
3067 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
3069 trimAlignment(true);
3079 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
3081 trimAlignment(false);
3084 void trimAlignment(boolean trimLeft)
3086 ColumnSelection colSel = viewport.getColumnSelection();
3089 if (!colSel.isEmpty())
3093 column = colSel.getMin();
3097 column = colSel.getMax();
3101 if (viewport.getSelectionGroup() != null)
3103 seqs = viewport.getSelectionGroup()
3104 .getSequencesAsArray(viewport.getHiddenRepSequences());
3108 seqs = viewport.getAlignment().getSequencesArray();
3111 TrimRegionCommand trimRegion;
3114 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
3115 column, viewport.getAlignment());
3116 viewport.getRanges().setStartRes(0);
3120 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
3121 column, viewport.getAlignment());
3124 setStatus(MessageManager.formatMessage("label.removed_columns",
3126 { Integer.valueOf(trimRegion.getSize()).toString() }));
3128 addHistoryItem(trimRegion);
3130 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3132 if ((trimLeft && !sg.adjustForRemoveLeft(column))
3133 || (!trimLeft && !sg.adjustForRemoveRight(column)))
3135 viewport.getAlignment().deleteGroup(sg);
3139 viewport.notifyAlignment();
3150 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
3152 int start = 0, end = viewport.getAlignment().getWidth() - 1;
3155 if (viewport.getSelectionGroup() != null)
3157 seqs = viewport.getSelectionGroup()
3158 .getSequencesAsArray(viewport.getHiddenRepSequences());
3159 start = viewport.getSelectionGroup().getStartRes();
3160 end = viewport.getSelectionGroup().getEndRes();
3164 seqs = viewport.getAlignment().getSequencesArray();
3167 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
3168 "Remove Gapped Columns", seqs, start, end,
3169 viewport.getAlignment());
3171 addHistoryItem(removeGapCols);
3173 setStatus(MessageManager.formatMessage("label.removed_empty_columns",
3175 { Integer.valueOf(removeGapCols.getSize()).toString() }));
3177 // This is to maintain viewport position on first residue
3178 // of first sequence
3179 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3180 ViewportRanges ranges = viewport.getRanges();
3181 int startRes = seq.findPosition(ranges.getStartRes());
3182 // ShiftList shifts;
3183 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
3184 // edit.alColumnChanges=shifts.getInverse();
3185 // if (viewport.hasHiddenColumns)
3186 // viewport.getColumnSelection().compensateForEdits(shifts);
3187 ranges.setStartRes(seq.findIndex(startRes) - 1);
3188 viewport.notifyAlignment();
3199 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
3201 int start = 0, end = viewport.getAlignment().getWidth() - 1;
3204 if (viewport.getSelectionGroup() != null)
3206 seqs = viewport.getSelectionGroup()
3207 .getSequencesAsArray(viewport.getHiddenRepSequences());
3208 start = viewport.getSelectionGroup().getStartRes();
3209 end = viewport.getSelectionGroup().getEndRes();
3213 seqs = viewport.getAlignment().getSequencesArray();
3216 // This is to maintain viewport position on first residue
3217 // of first sequence
3218 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3219 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
3221 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
3222 viewport.getAlignment()));
3224 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
3226 viewport.notifyAlignment();
3237 public void padGapsMenuitem_actionPerformed(ActionEvent e)
3239 viewport.setPadGaps(padGapsMenuitem.isSelected());
3240 viewport.notifyAlignment();
3244 * Opens a Finder dialog
3249 public void findMenuItem_actionPerformed(ActionEvent e)
3251 new Finder(alignPanel, false, null);
3255 * Create a new view of the current alignment.
3258 public void newView_actionPerformed(ActionEvent e)
3260 newView(null, true);
3264 * Creates and shows a new view of the current alignment.
3267 * title of newly created view; if null, one will be generated
3268 * @param copyAnnotation
3269 * if true then duplicate all annnotation, groups and settings
3270 * @return new alignment panel, already displayed.
3272 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
3275 * Create a new AlignmentPanel (with its own, new Viewport)
3277 AlignmentPanel newap = new jalview.project.Jalview2XML()
3278 .copyAlignPanel(alignPanel);
3279 if (!copyAnnotation)
3282 * remove all groups and annotation except for the automatic stuff
3284 newap.av.getAlignment().deleteAllGroups();
3285 newap.av.getAlignment().deleteAllAnnotations(false);
3288 newap.av.setGatherViewsHere(false);
3290 if (viewport.getViewName() == null)
3292 viewport.setViewName(
3293 MessageManager.getString("label.view_name_original"));
3297 * Views share the same edits undo and redo stacks
3299 newap.av.setHistoryList(viewport.getHistoryList());
3300 newap.av.setRedoList(viewport.getRedoList());
3303 * copy any visualisation settings that are not saved in the project
3305 newap.av.setColourAppliesToAllGroups(
3306 viewport.getColourAppliesToAllGroups());
3309 * Views share the same mappings; need to deregister any new mappings
3310 * created by copyAlignPanel, and register the new reference to the shared
3313 newap.av.replaceMappings(viewport.getAlignment());
3316 * start up cDNA consensus (if applicable) now mappings are in place
3318 if (newap.av.initComplementConsensus())
3320 newap.refresh(true); // adjust layout of annotations
3323 newap.av.setViewName(getNewViewName(viewTitle));
3325 addAlignmentPanel(newap, true);
3326 newap.alignmentChanged();
3328 if (alignPanels.size() == 2)
3330 viewport.setGatherViewsHere(true);
3332 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
3337 * Make a new name for the view, ensuring it is unique within the current
3338 * sequenceSetId. (This used to be essential for Jalview Project archives, but
3339 * these now use viewId. Unique view names are still desirable for usability.)
3344 protected String getNewViewName(String viewTitle)
3346 int index = Desktop.getViewCount(viewport.getSequenceSetId());
3347 boolean addFirstIndex = false;
3348 if (viewTitle == null || viewTitle.trim().length() == 0)
3350 viewTitle = MessageManager.getString("action.view");
3351 addFirstIndex = true;
3355 index = 1;// we count from 1 if given a specific name
3357 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
3359 List<Component> comps = PaintRefresher.components
3360 .get(viewport.getSequenceSetId());
3362 List<String> existingNames = getExistingViewNames(comps);
3364 while (existingNames.contains(newViewName))
3366 newViewName = viewTitle + " " + (++index);
3372 * Returns a list of distinct view names found in the given list of
3373 * components. View names are held on the viewport of an AlignmentPanel.
3378 protected List<String> getExistingViewNames(List<Component> comps)
3380 List<String> existingNames = new ArrayList<>();
3381 for (Component comp : comps)
3383 if (comp instanceof AlignmentPanel)
3385 AlignmentPanel ap = (AlignmentPanel) comp;
3386 if (!existingNames.contains(ap.av.getViewName()))
3388 existingNames.add(ap.av.getViewName());
3392 return existingNames;
3396 * Explode tabbed views into separate windows.
3399 public void expandViews_actionPerformed(ActionEvent e)
3401 Desktop.explodeViews(this);
3405 * Gather views in separate windows back into a tabbed presentation.
3408 public void gatherViews_actionPerformed(ActionEvent e)
3410 Desktop.getInstance().gatherViews(this);
3420 public void font_actionPerformed(ActionEvent e)
3422 new FontChooser(alignPanel);
3432 protected void seqLimit_actionPerformed(ActionEvent e)
3434 viewport.setShowJVSuffix(seqLimits.isSelected());
3436 alignPanel.getIdPanel().getIdCanvas()
3437 .setPreferredSize(alignPanel.calculateIdWidth());
3438 alignPanel.paintAlignment(true, false);
3442 public void idRightAlign_actionPerformed(ActionEvent e)
3444 viewport.setRightAlignIds(idRightAlign.isSelected());
3445 alignPanel.paintAlignment(false, false);
3449 public void centreColumnLabels_actionPerformed(ActionEvent e)
3451 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3452 alignPanel.paintAlignment(false, false);
3458 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3461 protected void followHighlight_actionPerformed()
3464 * Set the 'follow' flag on the Viewport (and scroll to position if now
3467 final boolean state = this.followHighlightMenuItem.getState();
3468 viewport.setFollowHighlight(state);
3471 alignPanel.scrollToPosition(viewport.getSearchResults());
3482 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3484 viewport.setColourText(colourTextMenuItem.isSelected());
3485 alignPanel.paintAlignment(false, false);
3495 public void wrapMenuItem_actionPerformed(ActionEvent e)
3497 scaleAbove.setVisible(wrapMenuItem.isSelected());
3498 scaleLeft.setVisible(wrapMenuItem.isSelected());
3499 scaleRight.setVisible(wrapMenuItem.isSelected());
3500 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3501 alignPanel.updateLayout();
3505 public void showAllSeqs_actionPerformed(ActionEvent e)
3507 viewport.showAllHiddenSeqs();
3511 public void showAllColumns_actionPerformed(ActionEvent e)
3513 viewport.showAllHiddenColumns();
3514 alignPanel.paintAlignment(true, true);
3515 viewport.sendSelection();
3519 public void hideSelSequences_actionPerformed(ActionEvent e)
3521 viewport.hideAllSelectedSeqs();
3525 * called by key handler and the hide all/show all menu items
3530 protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3533 boolean hide = false;
3534 SequenceGroup sg = viewport.getSelectionGroup();
3535 if (!toggleSeqs && !toggleCols)
3537 // Hide everything by the current selection - this is a hack - we do the
3538 // invert and then hide
3539 // first check that there will be visible columns after the invert.
3540 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3541 && sg.getStartRes() <= sg.getEndRes()))
3543 // now invert the sequence set, if required - empty selection implies
3544 // that no hiding is required.
3547 invertSequenceMenuItem_actionPerformed(null);
3548 sg = viewport.getSelectionGroup();
3552 viewport.expandColSelection(sg, true);
3553 // finally invert the column selection and get the new sequence
3555 invertColSel_actionPerformed(null);
3562 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3564 hideSelSequences_actionPerformed(null);
3567 else if (!(toggleCols && viewport.hasSelectedColumns()))
3569 showAllSeqs_actionPerformed(null);
3575 if (viewport.hasSelectedColumns())
3577 hideSelColumns_actionPerformed(null);
3580 viewport.setSelectionGroup(sg);
3585 showAllColumns_actionPerformed(null);
3594 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3595 * event.ActionEvent)
3598 public void hideAllButSelection_actionPerformed(ActionEvent e)
3600 toggleHiddenRegions(false, false);
3601 viewport.sendSelection();
3608 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3612 public void hideAllSelection_actionPerformed(ActionEvent e)
3614 SequenceGroup sg = viewport.getSelectionGroup();
3615 viewport.expandColSelection(sg, false);
3616 viewport.hideAllSelectedSeqs();
3617 viewport.hideSelectedColumns();
3618 alignPanel.updateLayout();
3619 alignPanel.paintAlignment(true, true);
3620 viewport.sendSelection();
3627 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3631 public void showAllhidden_actionPerformed(ActionEvent e)
3633 viewport.showAllHiddenColumns();
3634 viewport.showAllHiddenSeqs();
3635 alignPanel.paintAlignment(true, true);
3636 viewport.sendSelection();
3640 public void hideSelColumns_actionPerformed(ActionEvent e)
3642 viewport.hideSelectedColumns();
3643 alignPanel.updateLayout();
3644 alignPanel.paintAlignment(true, true);
3645 viewport.sendSelection();
3649 public void hiddenMarkers_actionPerformed(ActionEvent e)
3651 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3662 protected void scaleAbove_actionPerformed(ActionEvent e)
3664 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3665 alignPanel.updateLayout();
3666 alignPanel.paintAlignment(true, false);
3676 protected void scaleLeft_actionPerformed(ActionEvent e)
3678 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3679 alignPanel.updateLayout();
3680 alignPanel.paintAlignment(true, false);
3690 protected void scaleRight_actionPerformed(ActionEvent e)
3692 viewport.setScaleRightWrapped(scaleRight.isSelected());
3693 alignPanel.updateLayout();
3694 alignPanel.paintAlignment(true, false);
3704 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3706 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3707 alignPanel.paintAlignment(false, false);
3717 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3719 viewport.setShowText(viewTextMenuItem.isSelected());
3720 alignPanel.paintAlignment(false, false);
3730 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3732 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3733 alignPanel.paintAlignment(false, false);
3736 public FeatureSettings featureSettings;
3739 public FeatureSettingsControllerI getFeatureSettingsUI()
3741 return featureSettings;
3745 public void featureSettings_actionPerformed(ActionEvent e)
3747 showFeatureSettingsUI();
3751 public FeatureSettingsControllerI showFeatureSettingsUI()
3753 if (featureSettings != null)
3755 featureSettings.closeOldSettings();
3756 featureSettings = null;
3758 if (!showSeqFeatures.isSelected())
3760 // make sure features are actually displayed
3761 showSeqFeatures.setSelected(true);
3762 showSeqFeatures_actionPerformed(null);
3764 featureSettings = new FeatureSettings(this);
3765 return featureSettings;
3769 * Set or clear 'Show Sequence Features'
3775 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3777 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3778 alignPanel.paintAlignment(true, true);
3782 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3783 * the annotations panel as a whole.
3785 * The options to show/hide all annotations should be enabled when the panel
3786 * is shown, and disabled when the panel is hidden.
3791 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3793 final boolean setVisible = annotationPanelMenuItem.isSelected();
3794 viewport.setShowAnnotation(setVisible);
3795 syncAnnotationMenuItems(setVisible);
3796 alignPanel.updateLayout();
3798 SwingUtilities.invokeLater(new Runnable() {
3803 alignPanel.updateScrollBarsFromRanges();
3809 private void syncAnnotationMenuItems(boolean setVisible)
3811 showAllSeqAnnotations.setEnabled(setVisible);
3812 hideAllSeqAnnotations.setEnabled(setVisible);
3813 showAllAlAnnotations.setEnabled(setVisible);
3814 hideAllAlAnnotations.setEnabled(setVisible);
3818 public void alignmentProperties()
3821 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3824 String content = MessageManager.formatMessage("label.html_content",
3826 { contents.toString() });
3829 if (Platform.isJS())
3831 JLabel textLabel = new JLabel();
3832 textLabel.setText(content);
3833 textLabel.setBackground(Color.WHITE);
3835 pane = new JPanel(new BorderLayout());
3836 ((JPanel) pane).setOpaque(true);
3837 pane.setBackground(Color.WHITE);
3838 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3847 JEditorPane editPane = new JEditorPane("text/html", "");
3848 editPane.setEditable(false);
3849 editPane.setText(content);
3853 JInternalFrame frame = new JInternalFrame();
3855 frame.getContentPane().add(new JScrollPane(pane));
3857 Desktop.addInternalFrame(frame, MessageManager
3858 .formatMessage("label.alignment_properties", new Object[]
3859 { getTitle() }), 500, 400);
3869 public void overviewMenuItem_actionPerformed(ActionEvent e)
3871 if (alignPanel.overviewPanel != null)
3876 JInternalFrame frame = new JInternalFrame();
3877 // BH 2019.07.26 we allow for an embedded
3878 // undecorated overview with defined size
3879 frame.setName(Platform.getAppID("overview"));
3881 Dimension dim = Platform.getDimIfEmbedded(frame, -1, -1);
3882 if (dim != null && dim.width == 0)
3884 dim = null; // hidden, not embedded
3886 OverviewPanel overview = new OverviewPanel(alignPanel, dim);
3887 frame.setContentPane(overview);
3890 dim = new Dimension();
3891 // was frame.getSize(), but that is 0,0 at this point;
3895 // we are imbedding, and so we have an undecorated frame
3896 // and we can set the the frame dimensions accordingly.
3898 // allowing for unresizable option using, style="resize:none"
3899 boolean resizable = (Platform.getEmbeddedAttribute(frame,
3900 "resize") != "none");
3901 Desktop.addInternalFrame(frame, MessageManager
3902 .formatMessage("label.overview_params", new Object[]
3903 { this.getTitle() }), Desktop.FRAME_MAKE_VISIBLE, dim.width,
3904 dim.height, resizable, Desktop.FRAME_ALLOW_ANY_SIZE);
3906 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3907 frame.addInternalFrameListener(
3908 new javax.swing.event.InternalFrameAdapter()
3911 public void internalFrameClosed(
3912 javax.swing.event.InternalFrameEvent evt)
3915 alignPanel.setOverviewPanel(null);
3918 if (getKeyListeners().length > 0)
3920 frame.addKeyListener(getKeyListeners()[0]);
3923 alignPanel.setOverviewPanel(overview);
3927 public void textColour_actionPerformed()
3929 new TextColourChooser().chooseColour(alignPanel, null);
3933 * public void covariationColour_actionPerformed() {
3935 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3939 public void annotationColour_actionPerformed()
3941 new AnnotationColourChooser(viewport, alignPanel);
3945 public void annotationColumn_actionPerformed(ActionEvent e)
3947 new AnnotationColumnChooser(viewport, alignPanel);
3951 * Action on the user checking or unchecking the option to apply the selected
3952 * colour scheme to all groups. If unchecked, groups may have their own
3953 * independent colour schemes.
3958 public void applyToAllGroups_actionPerformed(boolean selected)
3960 viewport.setColourAppliesToAllGroups(selected);
3964 * Action on user selecting a colour from the colour menu
3967 * the name (not the menu item label!) of the colour scheme
3970 public void changeColour_actionPerformed(String name)
3973 * 'User Defined' opens a panel to configure or load a
3974 * user-defined colour scheme
3976 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3978 new UserDefinedColours(alignPanel);
3983 * otherwise set the chosen colour scheme (or null for 'None')
3985 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3986 viewport, viewport.getAlignment(),
3987 viewport.getHiddenRepSequences());
3992 * Actions on setting or changing the alignment colour scheme
3997 public void changeColour(ColourSchemeI cs)
3999 // TODO: pull up to controller method
4000 ColourMenuHelper.setColourSelected(colourMenu, cs);
4002 viewport.setGlobalColourScheme(cs);
4004 alignPanel.paintAlignment(true, true);
4008 * Show the PID threshold slider panel
4011 protected void modifyPID_actionPerformed()
4013 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
4014 alignPanel.getViewName());
4015 SliderPanel.showPIDSlider();
4019 * Show the Conservation slider panel
4022 protected void modifyConservation_actionPerformed()
4024 SliderPanel.setConservationSlider(alignPanel,
4025 viewport.getResidueShading(), alignPanel.getViewName());
4026 SliderPanel.showConservationSlider();
4030 * Action on selecting or deselecting (Colour) By Conservation
4033 public void conservationMenuItem_actionPerformed(boolean selected)
4035 modifyConservation.setEnabled(selected);
4036 viewport.setConservationSelected(selected);
4037 viewport.getResidueShading().setConservationApplied(selected);
4039 changeColour(viewport.getGlobalColourScheme());
4042 modifyConservation_actionPerformed();
4046 SliderPanel.hideConservationSlider();
4051 * Action on selecting or deselecting (Colour) Above PID Threshold
4054 public void abovePIDThreshold_actionPerformed(boolean selected)
4056 modifyPID.setEnabled(selected);
4057 viewport.setAbovePIDThreshold(selected);
4060 viewport.getResidueShading().setThreshold(0,
4061 viewport.isIgnoreGapsConsensus());
4064 changeColour(viewport.getGlobalColourScheme());
4067 modifyPID_actionPerformed();
4071 SliderPanel.hidePIDSlider();
4082 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
4084 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4085 AlignmentSorter.sortByPID(viewport.getAlignment(),
4086 viewport.getAlignment().getSequenceAt(0));
4087 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
4088 viewport.getAlignment()));
4089 alignPanel.paintAlignment(true, false);
4099 public void sortIDMenuItem_actionPerformed(ActionEvent e)
4101 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4102 AlignmentSorter.sortByID(viewport.getAlignment());
4104 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
4105 alignPanel.paintAlignment(true, false);
4115 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
4117 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4118 AlignmentSorter.sortByLength(viewport.getAlignment());
4119 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
4120 viewport.getAlignment()));
4121 alignPanel.paintAlignment(true, false);
4131 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
4133 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4134 AlignmentSorter.sortByGroup(viewport.getAlignment());
4135 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4136 viewport.getAlignment()));
4138 alignPanel.paintAlignment(true, false);
4142 public void sortEValueMenuItem_actionPerformed(ActionEvent e)
4144 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4145 AlignmentSorter.sortByEValue(viewport.getAlignment());
4146 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4147 viewport.getAlignment()));
4148 alignPanel.paintAlignment(true, false);
4153 public void sortBitScoreMenuItem_actionPerformed(ActionEvent e)
4155 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4156 AlignmentSorter.sortByBitScore(viewport.getAlignment());
4157 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4158 viewport.getAlignment()));
4159 alignPanel.paintAlignment(true, false);
4169 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
4171 new RedundancyPanel(alignPanel, this);
4181 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
4183 if ((viewport.getSelectionGroup() == null)
4184 || (viewport.getSelectionGroup().getSize() < 2))
4186 JvOptionPane.showInternalMessageDialog(this,
4187 MessageManager.getString(
4188 "label.you_must_select_least_two_sequences"),
4189 MessageManager.getString("label.invalid_selection"),
4190 JvOptionPane.WARNING_MESSAGE);
4194 JInternalFrame frame = new JInternalFrame();
4195 frame.setContentPane(new PairwiseAlignPanel(viewport));
4196 Desktop.addInternalFrame(frame,
4197 MessageManager.getString("action.pairwise_alignment"), 600,
4203 public void autoCalculate_actionPerformed(ActionEvent e)
4205 viewport.setAutoCalculateConsensusAndConservation(
4206 autoCalculate.isSelected());
4207 if (viewport.getAutoCalculateConsensusAndConservation())
4209 viewport.notifyAlignment();
4214 public void sortByTreeOption_actionPerformed(ActionEvent e)
4216 viewport.sortByTree = sortByTree.isSelected();
4220 protected void listenToViewSelections_actionPerformed(ActionEvent e)
4222 viewport.followSelection = listenToViewSelections.isSelected();
4226 * Constructs a tree panel and adds it to the desktop
4229 * tree type (NJ or AV)
4231 * name of score model used to compute the tree
4233 * parameters for the distance or similarity calculation
4235 void newTreePanel(String type, String modelName,
4236 SimilarityParamsI options)
4238 String frameTitle = "";
4241 boolean onSelection = false;
4242 if (viewport.getSelectionGroup() != null
4243 && viewport.getSelectionGroup().getSize() > 0)
4245 SequenceGroup sg = viewport.getSelectionGroup();
4247 /* Decide if the selection is a column region */
4248 for (SequenceI _s : sg.getSequences())
4250 if (_s.getLength() < sg.getEndRes())
4252 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4253 MessageManager.getString(
4254 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
4255 MessageManager.getString(
4256 "label.sequences_selection_not_aligned"),
4257 JvOptionPane.WARNING_MESSAGE);
4266 if (viewport.getAlignment().getHeight() < 2)
4272 tp = new TreePanel(alignPanel, type, modelName, options);
4273 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
4275 frameTitle += " from ";
4277 if (viewport.getViewName() != null)
4279 frameTitle += viewport.getViewName() + " of ";
4282 frameTitle += this.title;
4284 Dimension dim = Platform.getDimIfEmbedded(tp, 600, 500);
4285 Desktop.addInternalFrame(tp, frameTitle, dim.width, dim.height);
4296 public void addSortByOrderMenuItem(String title,
4297 final AlignmentOrder order)
4299 final JMenuItem item = new JMenuItem(MessageManager
4300 .formatMessage("action.by_title_param", new Object[]
4303 item.addActionListener(new java.awt.event.ActionListener()
4306 public void actionPerformed(ActionEvent e)
4308 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4310 // TODO: JBPNote - have to map order entries to curent SequenceI
4312 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4314 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
4315 viewport.getAlignment()));
4317 alignPanel.paintAlignment(true, false);
4323 * Add a new sort by annotation score menu item
4326 * the menu to add the option to
4328 * the label used to retrieve scores for each sequence on the
4331 public void addSortByAnnotScoreMenuItem(JMenu sort,
4332 final String scoreLabel)
4334 final JMenuItem item = new JMenuItem(scoreLabel);
4336 item.addActionListener(new java.awt.event.ActionListener()
4339 public void actionPerformed(ActionEvent e)
4341 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4342 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4343 viewport.getAlignment());// ,viewport.getSelectionGroup());
4344 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4345 viewport.getAlignment()));
4346 alignPanel.paintAlignment(true, false);
4352 * last hash for alignment's annotation array - used to minimise cost of
4355 protected int _annotationScoreVectorHash;
4358 * search the alignment and rebuild the sort by annotation score submenu the
4359 * last alignment annotation vector hash is stored to minimize cost of
4360 * rebuilding in subsequence calls.
4364 public void buildSortByAnnotationScoresMenu()
4366 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4371 if (viewport.getAlignment().getAlignmentAnnotation()
4372 .hashCode() == _annotationScoreVectorHash)
4377 sortByAnnotScore.removeAll();
4378 Set<String> scoreSorts = new HashSet<>();
4379 for (SequenceI sqa : viewport.getAlignment().getSequences())
4381 AlignmentAnnotation[] anns = sqa.getAnnotation();
4382 for (int i = 0; anns != null && i < anns.length; i++)
4384 AlignmentAnnotation aa = anns[i];
4385 if (aa != null && aa.hasScore() && aa.sequenceRef != null)
4387 scoreSorts.add(aa.label);
4391 for (String label : scoreSorts)
4393 addSortByAnnotScoreMenuItem(sortByAnnotScore, label);
4395 sortByAnnotScore.setVisible(!scoreSorts.isEmpty());
4397 _annotationScoreVectorHash = viewport.getAlignment()
4398 .getAlignmentAnnotation().hashCode();
4402 * Enable (or, if desired, make visible) the By Tree
4403 * submenu only if it has at least one element (or will have).
4407 protected void enableSortMenuOptions()
4409 List<TreePanel> treePanels = getTreePanels();
4410 sortByTreeMenu.setEnabled(!treePanels.isEmpty());
4414 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4415 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4416 * call. Listeners are added to remove the menu item when the treePanel is
4417 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4421 public void buildTreeSortMenu()
4423 sortByTreeMenu.removeAll();
4425 List<TreePanel> treePanels = getTreePanels();
4427 for (final TreePanel tp : treePanels)
4429 final JMenuItem item = new JMenuItem(tp.getTitle());
4430 item.addActionListener(new java.awt.event.ActionListener()
4433 public void actionPerformed(ActionEvent e)
4435 tp.sortByTree_actionPerformed();
4436 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4441 sortByTreeMenu.add(item);
4445 private List<TreePanel> getTreePanels()
4447 List<Component> comps = PaintRefresher.components
4448 .get(viewport.getSequenceSetId());
4449 List<TreePanel> treePanels = new ArrayList<>();
4450 for (Component comp : comps)
4452 if (comp instanceof TreePanel)
4454 treePanels.add((TreePanel) comp);
4459 public boolean sortBy(AlignmentOrder alorder, String undoname)
4461 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4462 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4463 if (undoname != null)
4465 addHistoryItem(new OrderCommand(undoname, oldOrder,
4466 viewport.getAlignment()));
4468 alignPanel.paintAlignment(true, false);
4473 * Work out whether the whole set of sequences or just the selected set will
4474 * be submitted for multiple alignment.
4477 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4479 // Now, check we have enough sequences
4480 AlignmentView msa = null;
4482 if ((viewport.getSelectionGroup() != null)
4483 && (viewport.getSelectionGroup().getSize() > 1))
4485 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4486 // some common interface!
4488 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4489 * SequenceI[sz = seqs.getSize(false)];
4491 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4492 * seqs.getSequenceAt(i); }
4494 msa = viewport.getAlignmentView(true);
4496 else if (viewport.getSelectionGroup() != null
4497 && viewport.getSelectionGroup().getSize() == 1)
4499 int option = JvOptionPane.showConfirmDialog(this,
4500 MessageManager.getString("warn.oneseq_msainput_selection"),
4501 MessageManager.getString("label.invalid_selection"),
4502 JvOptionPane.OK_CANCEL_OPTION);
4503 if (option == JvOptionPane.OK_OPTION)
4505 msa = viewport.getAlignmentView(false);
4510 msa = viewport.getAlignmentView(false);
4516 * Decides what is submitted to a secondary structure prediction service: the
4517 * first sequence in the alignment, or in the current selection, or, if the
4518 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4519 * region or the whole alignment. (where the first sequence in the set is the
4520 * one that the prediction will be for).
4522 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4524 AlignmentView seqs = null;
4526 if ((viewport.getSelectionGroup() != null)
4527 && (viewport.getSelectionGroup().getSize() > 0))
4529 seqs = viewport.getAlignmentView(true);
4533 seqs = viewport.getAlignmentView(false);
4535 // limit sequences - JBPNote in future - could spawn multiple prediction
4537 // TODO: viewport.getAlignment().isAligned is a global state - the local
4538 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4539 if (!viewport.getAlignment().isAligned(false))
4541 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4542 // TODO: if seqs.getSequences().length>1 then should really have warned
4556 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4558 // Pick the tree file
4559 JalviewFileChooser chooser = new JalviewFileChooser(
4560 Cache.getProperty("LAST_DIRECTORY"));
4561 chooser.setFileView(new JalviewFileView());
4562 chooser.setDialogTitle(
4563 MessageManager.getString("label.select_newick_like_tree_file"));
4564 chooser.setToolTipText(
4565 MessageManager.getString("label.load_tree_file"));
4567 chooser.setResponseHandler(0, new Runnable()
4572 String filePath = chooser.getSelectedFile().getPath();
4573 Cache.setProperty("LAST_DIRECTORY", filePath);
4574 NewickFile fin = null;
4577 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4578 DataSourceType.FILE));
4579 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4580 } catch (Exception ex)
4582 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4585 .getString("label.problem_reading_tree_file"),
4586 JvOptionPane.WARNING_MESSAGE);
4587 ex.printStackTrace();
4589 if (fin != null && fin.hasWarningMessage())
4591 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4592 fin.getWarningMessage(),
4593 MessageManager.getString(
4594 "label.possible_problem_with_tree_file"),
4595 JvOptionPane.WARNING_MESSAGE);
4599 chooser.showOpenDialog(this);
4602 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4604 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4607 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4608 int h, int x, int y)
4610 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4614 * Add a treeviewer for the tree extracted from a Newick file object to the
4615 * current alignment view
4622 * Associated alignment input data (or null)
4631 * @return TreePanel handle
4633 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4634 AlignmentView input, int w, int h, int x, int y)
4636 TreePanel tp = null;
4642 if (nf.getTree() != null)
4644 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4646 Dimension dim = Platform.getDimIfEmbedded(tp, -1, -1);
4649 dim = new Dimension(w, h);
4653 // no offset, either
4656 tp.setSize(dim.width, dim.height);
4660 tp.setLocation(x, y);
4663 Desktop.addInternalFrame(tp, treeTitle, dim.width, dim.height);
4665 } catch (Exception ex)
4667 ex.printStackTrace();
4673 private WebServicesMenuManager slivkaMenu = new WebServicesMenuManager("slivka", this);
4674 private WebServicesMenuManager ebiMenu = new WebServicesMenuManager("job dispatcher", this);
4677 * Schedule the web services menu rebuild to the event dispatch thread.
4679 public void buildWebServicesMenu()
4681 SwingUtilities.invokeLater(() -> {
4682 Console.info("Rebuiling WS menu");
4683 webService.removeAll();
4684 if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
4686 Console.info("Building web service menu for slivka");
4687 SlivkaWSDiscoverer discoverer = SlivkaWSDiscoverer.getInstance();
4688 slivkaMenu.setServices(discoverer);
4689 slivkaMenu.setInProgress(discoverer.isRunning());
4690 slivkaMenu.setNoServices(discoverer.isDone() && !discoverer.hasServices());
4691 webService.add(slivkaMenu.getMenu());
4693 if (Cache.getDefault("SHOW_EBI_SERVICES", true))
4695 Console.info("Building web services menu for jobs dispatcher");
4696 JobDispatcherWSDiscoverer discoverer = JobDispatcherWSDiscoverer.getInstance();
4697 ebiMenu.setServices(discoverer);
4698 ebiMenu.setInProgress(discoverer.isRunning());
4699 ebiMenu.setNoServices(discoverer.isDone() && !discoverer.hasServices());
4700 webService.add(ebiMenu.getMenu());
4702 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4704 WSDiscovererI jws2servs = Jws2Discoverer.getInstance();
4705 JMenu submenu = new JMenu("JABAWS");
4706 buildLegacyWebServicesMenu(submenu);
4707 buildWebServicesMenu(jws2servs, submenu);
4708 webService.add(submenu);
4710 build_urlServiceMenu(webService);
4711 build_fetchdbmenu(webService);
4715 private void buildLegacyWebServicesMenu(JMenu menu)
4717 JMenu secstrmenu = new JMenu("Secondary Structure Prediction");
4718 if (Discoverer.getServices() != null && Discoverer.getServices().size() > 0)
4720 var secstrpred = Discoverer.getServices().get("SecStrPred");
4721 if (secstrpred != null)
4723 for (ext.vamsas.ServiceHandle sh : secstrpred)
4725 var menuProvider = Discoverer.getServiceClient(sh);
4726 menuProvider.attachWSMenuEntry(secstrmenu, this);
4730 menu.add(secstrmenu);
4734 * Constructs the web services menu for the given discoverer under the
4735 * specified menu. This method must be called on the EDT
4738 * the discoverer used to build the menu
4740 * parent component which the elements will be attached to
4742 private void buildWebServicesMenu(WSDiscovererI discoverer, JMenu menu)
4744 if (discoverer.hasServices())
4746 PreferredServiceRegistry.getRegistry().populateWSMenuEntry(
4747 discoverer.getServices(), sv -> buildWebServicesMenu(), menu,
4750 if (discoverer.isRunning())
4752 JMenuItem item = new JMenuItem("Service discovery in progress.");
4753 item.setEnabled(false);
4756 else if (!discoverer.hasServices())
4758 JMenuItem item = new JMenuItem("No services available.");
4759 item.setEnabled(false);
4765 * construct any groupURL type service menu entries.
4769 protected void build_urlServiceMenu(JMenu webService)
4771 // TODO: remove this code when 2.7 is released
4772 // DEBUG - alignmentView
4774 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4775 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4777 * public void actionPerformed(ActionEvent e) {
4778 * jalview.datamodel.AlignmentView
4779 * .testSelectionViews(af.viewport.getAlignment(),
4780 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4782 * }); webService.add(testAlView);
4784 // TODO: refactor to RestClient discoverer and merge menu entries for
4785 // rest-style services with other types of analysis/calculation service
4786 // SHmmr test client - still being implemented.
4787 // DEBUG - alignmentView
4789 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4792 client.attachWSMenuEntry(
4793 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4799 * Searches the alignment sequences for xRefs and builds the Show
4800 * Cross-References menu (formerly called Show Products), with database
4801 * sources for which cross-references are found (protein sources for a
4802 * nucleotide alignment and vice versa)
4804 * @return true if Show Cross-references menu should be enabled
4806 public boolean canShowProducts()
4808 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4809 AlignmentI dataset = viewport.getAlignment().getDataset();
4811 showProducts.removeAll();
4812 final boolean dna = viewport.getAlignment().isNucleotide();
4814 if (seqs == null || seqs.length == 0)
4816 // nothing to see here.
4820 boolean showp = false;
4823 List<String> ptypes = new CrossRef(seqs, dataset)
4824 .findXrefSourcesForSequences(dna);
4826 for (final String source : ptypes)
4829 final AlignFrame af = this;
4830 JMenuItem xtype = new JMenuItem(source);
4831 xtype.addActionListener(new ActionListener()
4834 public void actionPerformed(ActionEvent e)
4836 showProductsFor(af.viewport.getSequenceSelection(), dna,
4840 showProducts.add(xtype);
4842 showProducts.setVisible(showp);
4843 showProducts.setEnabled(showp);
4844 } catch (Exception e)
4847 "canShowProducts threw an exception - please report to help@jalview.org",
4855 * Finds and displays cross-references for the selected sequences (protein
4856 * products for nucleotide sequences, dna coding sequences for peptides).
4859 * the sequences to show cross-references for
4861 * true if from a nucleotide alignment (so showing proteins)
4863 * the database to show cross-references for
4865 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4866 final String source)
4868 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4873 * Construct and display a new frame containing the translation of this
4874 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4877 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4879 AlignmentI al = null;
4882 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4884 al = dna.translateCdna(codeTable);
4885 } catch (Exception ex)
4887 Console.error("Exception during translation. Please report this !",
4889 final String msg = MessageManager.getString(
4890 "label.error_when_translating_sequences_submit_bug_report");
4891 final String errorTitle = MessageManager
4892 .getString("label.implementation_error")
4893 + MessageManager.getString("label.translation_failed");
4894 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4895 errorTitle, JvOptionPane.ERROR_MESSAGE);
4898 if (al == null || al.getHeight() == 0)
4900 final String msg = MessageManager.getString(
4901 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4902 final String errorTitle = MessageManager
4903 .getString("label.translation_failed");
4904 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4905 errorTitle, JvOptionPane.WARNING_MESSAGE);
4909 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4910 af.setFileFormat(this.currentFileFormat);
4911 final String newTitle = MessageManager
4912 .formatMessage("label.translation_of_params", new Object[]
4913 { this.getTitle(), codeTable.getId() });
4914 af.setTitle(newTitle);
4915 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4917 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4918 AlignViewport.openSplitFrame(this, af, new Alignment(seqs));
4922 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4929 * Set the file format
4933 public void setFileFormat(FileFormatI format)
4935 this.currentFileFormat = format;
4939 * Try to load a features file onto the alignment.
4942 * contents or path to retrieve file or a File object
4944 * access mode of file (see jalview.io.AlignFile)
4945 * @return true if features file was parsed correctly.
4947 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4950 return avc.parseFeaturesFile(file, sourceType,
4951 Cache.getDefault(Preferences.RELAXEDSEQIDMATCHING, false));
4956 public void refreshFeatureUI(boolean enableIfNecessary)
4958 // note - currently this is only still here rather than in the controller
4959 // because of the featureSettings hard reference that is yet to be
4961 if (enableIfNecessary)
4963 viewport.setShowSequenceFeatures(true);
4964 showSeqFeatures.setSelected(true);
4970 public void dragEnter(DropTargetDragEvent evt)
4975 public void dragExit(DropTargetEvent evt)
4980 public void dragOver(DropTargetDragEvent evt)
4985 public void dropActionChanged(DropTargetDragEvent evt)
4990 public void drop(DropTargetDropEvent evt)
4992 // JAL-1552 - acceptDrop required before getTransferable call for
4993 // Java's Transferable for native dnd
4994 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4995 Transferable t = evt.getTransferable();
4997 final List<Object> files = new ArrayList<>();
4998 List<DataSourceType> protocols = new ArrayList<>();
5002 Desktop.transferFromDropTarget(files, protocols, evt, t);
5003 if (files.size() > 0)
5005 new Thread(new Runnable()
5011 loadDroppedFiles(files, protocols, evt, t);
5015 } catch (Exception e)
5017 e.printStackTrace();
5021 protected void loadDroppedFiles(List<Object> files,
5022 List<DataSourceType> protocols, DropTargetDropEvent evt,
5027 // check to see if any of these files have names matching sequences
5030 SequenceIdMatcher idm = new SequenceIdMatcher(
5031 viewport.getAlignment().getSequencesArray());
5033 * Object[] { String,SequenceI}
5035 ArrayList<Object[]> filesmatched = new ArrayList<>();
5036 ArrayList<Object> filesnotmatched = new ArrayList<>();
5037 for (int i = 0; i < files.size(); i++)
5040 Object fileObj = files.get(i);
5041 String fileName = fileObj.toString();
5043 DataSourceType protocol = (fileObj instanceof File
5044 ? DataSourceType.FILE
5045 : FormatAdapter.checkProtocol(fileName));
5046 if (protocol == DataSourceType.FILE)
5049 if (fileObj instanceof File)
5051 file = (File) fileObj;
5052 Platform.cacheFileData(file);
5056 file = new File(fileName);
5058 pdbfn = file.getName();
5060 else if (protocol == DataSourceType.URL)
5062 URL url = new URL(fileName);
5063 pdbfn = url.getFile();
5065 if (pdbfn.length() > 0)
5067 // attempt to find a match in the alignment
5068 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5069 int l = 0, c = pdbfn.indexOf(".");
5070 while (mtch == null && c != -1)
5075 } while ((c = pdbfn.indexOf(".", l)) > l);
5078 pdbfn = pdbfn.substring(0, l);
5080 mtch = idm.findAllIdMatches(pdbfn);
5087 type = new IdentifyFile().identify(fileObj, protocol);
5088 } catch (Exception ex)
5092 if (type != null && type.isStructureFile())
5094 filesmatched.add(new Object[] { fileObj, protocol, mtch });
5098 // File wasn't named like one of the sequences or wasn't a PDB
5100 filesnotmatched.add(fileObj);
5104 if (filesmatched.size() > 0)
5106 boolean autoAssociate = Cache
5107 .getDefault(Preferences.AUTOASSOCIATE_PDBANDSEQS, false);
5110 String msg = MessageManager.formatMessage(
5111 "label.automatically_associate_structure_files_with_sequences_same_name",
5113 { Integer.valueOf(filesmatched.size()).toString() });
5114 String ttl = MessageManager.getString(
5115 "label.automatically_associate_structure_files_by_name");
5116 int choice = JvOptionPane.showConfirmDialog(this, msg, ttl,
5117 JvOptionPane.YES_NO_OPTION);
5118 autoAssociate = choice == JvOptionPane.YES_OPTION;
5122 for (Object[] fm : filesmatched)
5124 // try and associate
5125 // TODO: may want to set a standard ID naming formalism for
5126 // associating PDB files which have no IDs.
5127 for (SequenceI toassoc : (SequenceI[]) fm[2])
5129 PDBEntry pe = AssociatePdbFileWithSeq.associatePdbWithSeq(
5130 fm[0].toString(), (DataSourceType) fm[1], toassoc,
5134 System.err.println("Associated file : " + (fm[0].toString())
5135 + " with " + toassoc.getDisplayId(true));
5140 // TODO: do we need to update overview ? only if features are
5142 alignPanel.paintAlignment(true, false);
5148 * add declined structures as sequences
5150 for (Object[] o : filesmatched)
5152 filesnotmatched.add(o[0]);
5156 if (filesnotmatched.size() > 0)
5158 if (assocfiles > 0 && (Cache
5159 .getDefault("AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
5160 || JvOptionPane.showConfirmDialog(this,
5161 "<html>" + MessageManager.formatMessage(
5162 "label.ignore_unmatched_dropped_files_info",
5164 { Integer.valueOf(filesnotmatched.size())
5167 MessageManager.getString(
5168 "label.ignore_unmatched_dropped_files"),
5169 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
5173 for (Object fn : filesnotmatched)
5175 loadJalviewDataFile(fn, null, null, null);
5179 } catch (Exception ex)
5181 ex.printStackTrace();
5186 * Attempt to load a "dropped" file or URL string, by testing in turn for
5188 * <li>an Annotation file</li>
5189 * <li>a JNet file</li>
5190 * <li>a features file</li>
5191 * <li>else try to interpret as an alignment file</li>
5195 * either a filename or a URL string.
5196 * @throws InterruptedException
5197 * @throws IOException
5199 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
5200 FileFormatI format, SequenceI assocSeq)
5202 // BH 2018 was String file
5205 if (sourceType == null)
5207 sourceType = FormatAdapter.checkProtocol(file);
5209 // if the file isn't identified, or not positively identified as some
5210 // other filetype (PFAM is default unidentified alignment file type) then
5211 // try to parse as annotation.
5212 boolean isAnnotation = (format == null
5213 || FileFormat.Pfam.equals(format))
5214 ? new AnnotationFile().annotateAlignmentView(viewport,
5220 // first see if its a T-COFFEE score file
5221 TCoffeeScoreFile tcf = null;
5224 tcf = new TCoffeeScoreFile(file, sourceType);
5227 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5231 new TCoffeeColourScheme(viewport.getAlignment()));
5232 isAnnotation = true;
5233 setStatus(MessageManager.getString(
5234 "label.successfully_pasted_tcoffee_scores_to_alignment"));
5238 // some problem - if no warning its probable that the ID matching
5239 // process didn't work
5240 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
5241 tcf.getWarningMessage() == null
5242 ? MessageManager.getString(
5243 "label.check_file_matches_sequence_ids_alignment")
5244 : tcf.getWarningMessage(),
5245 MessageManager.getString(
5246 "label.problem_reading_tcoffee_score_file"),
5247 JvOptionPane.WARNING_MESSAGE);
5254 } catch (Exception x)
5257 "Exception when processing data source as T-COFFEE score file",
5263 // try to see if its a JNet 'concise' style annotation file *before*
5265 // try to parse it as a features file
5268 format = new IdentifyFile().identify(file, sourceType);
5270 if (FileFormat.ScoreMatrix == format)
5272 ScoreMatrixFile sm = new ScoreMatrixFile(
5273 new FileParse(file, sourceType));
5275 // todo: i18n this message
5276 setStatus(MessageManager.formatMessage(
5277 "label.successfully_loaded_matrix",
5278 sm.getMatrixName()));
5280 else if (FileFormat.Jnet.equals(format))
5282 JPredFile predictions = new JPredFile(file, sourceType);
5283 new JnetAnnotationMaker();
5284 JnetAnnotationMaker.add_annotation(predictions,
5285 viewport.getAlignment(), 0, false);
5286 viewport.getAlignment().setupJPredAlignment();
5287 isAnnotation = true;
5289 // else if (IdentifyFile.FeaturesFile.equals(format))
5290 else if (FileFormat.Features.equals(format))
5292 if (parseFeaturesFile(file, sourceType))
5294 SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
5295 if (splitFrame != null)
5297 splitFrame.repaint();
5301 alignPanel.paintAlignment(true, true);
5307 new FileLoader().LoadFile(viewport, file, sourceType, format);
5314 updateForAnnotations();
5316 } catch (Exception ex)
5318 ex.printStackTrace();
5319 } catch (OutOfMemoryError oom)
5324 } catch (Exception x)
5329 + (sourceType != null
5330 ? (sourceType == DataSourceType.PASTE
5332 : "using " + sourceType + " from "
5336 ? "(parsing as '" + format + "' file)"
5338 oom, Desktop.getDesktopPane());
5343 * Do all updates necessary after an annotation file such as jnet. Also called
5344 * from Jalview.loadAppletParams for "annotations", "jnetFile"
5347 public void updateForAnnotations()
5349 alignPanel.adjustAnnotationHeight();
5350 viewport.updateSequenceIdColours();
5351 buildSortByAnnotationScoresMenu();
5352 alignPanel.paintAlignment(true, true);
5356 * Change the display state for the given feature groups -- Added by BH from
5360 * list of group strings
5362 * visible or invisible
5365 public void setFeatureGroupState(String[] groups, boolean state)
5367 jalview.api.FeatureRenderer fr = null;
5368 viewport.setShowSequenceFeatures(true);
5369 if (alignPanel != null
5370 && (fr = alignPanel.getFeatureRenderer()) != null)
5373 fr.setGroupVisibility(Arrays.asList(groups), state);
5374 alignPanel.getSeqPanel().seqCanvas.repaint();
5375 if (alignPanel.overviewPanel != null)
5377 alignPanel.overviewPanel.updateOverviewImage();
5383 * Method invoked by the ChangeListener on the tabbed pane, in other words
5384 * when a different tabbed pane is selected by the user or programmatically.
5387 public void tabSelectionChanged(int index)
5391 alignPanel = alignPanels.get(index);
5392 viewport = alignPanel.av;
5393 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5394 setMenusFromViewport(viewport);
5395 if (featureSettings != null && featureSettings.isOpen()
5396 && featureSettings.fr.getViewport() != viewport)
5398 if (viewport.isShowSequenceFeatures())
5400 // refresh the featureSettings to reflect UI change
5401 showFeatureSettingsUI();
5405 // close feature settings for this view.
5406 featureSettings.close();
5413 * 'focus' any colour slider that is open to the selected viewport
5415 if (viewport.getConservationSelected())
5417 SliderPanel.setConservationSlider(alignPanel,
5418 viewport.getResidueShading(), alignPanel.getViewName());
5422 SliderPanel.hideConservationSlider();
5424 if (viewport.getAbovePIDThreshold())
5426 SliderPanel.setPIDSliderSource(alignPanel,
5427 viewport.getResidueShading(), alignPanel.getViewName());
5431 SliderPanel.hidePIDSlider();
5435 * If there is a frame linked to this one in a SplitPane, switch it to the
5436 * same view tab index. No infinite recursion of calls should happen, since
5437 * tabSelectionChanged() should not get invoked on setting the selected
5438 * index to an unchanged value. Guard against setting an invalid index
5439 * before the new view peer tab has been created.
5441 final AlignViewportI peer = viewport.getCodingComplement();
5444 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
5445 .getAlignPanel().alignFrame;
5446 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5448 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5454 * On right mouse click on view tab, prompt for and set new view name.
5457 public void tabbedPane_mousePressed(MouseEvent e)
5459 if (e.isPopupTrigger())
5461 String msg = MessageManager.getString("label.enter_view_name");
5462 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
5463 String reply = JvOptionPane.showInputDialog(msg, ttl);
5467 viewport.setViewName(reply);
5468 // TODO warn if reply is in getExistingViewNames()?
5469 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5474 public AlignViewport getCurrentView()
5480 * Open the dialog for regex description parsing.
5483 protected void extractScores_actionPerformed(ActionEvent e)
5485 ParseProperties pp = new jalview.analysis.ParseProperties(
5486 viewport.getAlignment());
5487 // TODO: verify regex and introduce GUI dialog for version 2.5
5488 // if (pp.getScoresFromDescription("col", "score column ",
5489 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5491 if (pp.getScoresFromDescription("description column",
5492 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5494 buildSortByAnnotationScoresMenu();
5502 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5506 protected void showDbRefs_actionPerformed(ActionEvent e)
5508 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5514 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5518 protected void showNpFeats_actionPerformed(ActionEvent e)
5520 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5524 * find the viewport amongst the tabs in this alignment frame and close that
5529 public boolean closeView(AlignViewportI av)
5533 this.closeMenuItem_actionPerformed(false);
5536 Component[] comp = tabbedPane.getComponents();
5537 for (int i = 0; comp != null && i < comp.length; i++)
5539 if (comp[i] instanceof AlignmentPanel)
5541 if (((AlignmentPanel) comp[i]).av == av)
5544 closeView((AlignmentPanel) comp[i]);
5552 protected void build_fetchdbmenu(JMenu webService)
5554 // Temporary hack - DBRef Fetcher always top level ws entry.
5555 // TODO We probably want to store a sequence database checklist in
5556 // preferences and have checkboxes.. rather than individual sources selected
5558 final JMenu rfetch = new JMenu(
5559 MessageManager.getString("action.fetch_db_references"));
5560 rfetch.setToolTipText(MessageManager.getString(
5561 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5562 webService.add(rfetch);
5564 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5565 MessageManager.getString("option.trim_retrieved_seqs"));
5566 trimrs.setToolTipText(
5567 MessageManager.getString("label.trim_retrieved_sequences"));
5569 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5570 trimrs.addActionListener(new ActionListener()
5573 public void actionPerformed(ActionEvent e)
5575 trimrs.setSelected(trimrs.isSelected());
5576 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5577 Boolean.valueOf(trimrs.isSelected()).toString());
5581 JMenuItem fetchr = new JMenuItem(
5582 MessageManager.getString("label.standard_databases"));
5583 fetchr.setToolTipText(
5584 MessageManager.getString("label.fetch_embl_uniprot"));
5585 fetchr.addActionListener(new ActionListener()
5589 public void actionPerformed(ActionEvent e)
5591 new Thread(new Runnable()
5596 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5597 .getAlignment().isNucleotide();
5598 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5599 alignPanel.av.getSequenceSelection(),
5600 alignPanel.alignFrame, null,
5601 alignPanel.alignFrame.featureSettings, isNucleotide);
5602 dbRefFetcher.addListener(new FetchFinishedListenerI()
5605 public void finished()
5608 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5609 .getFeatureSettingsModels())
5612 alignPanel.av.mergeFeaturesStyle(srcSettings);
5614 AlignFrame.this.setMenusForViewport();
5617 dbRefFetcher.fetchDBRefs(false);
5625 new Thread(new Runnable()
5631 // final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5632 // .getSequenceFetcherSingleton();
5633 javax.swing.SwingUtilities.invokeLater(new Runnable()
5638 jalview.ws.SequenceFetcher sf = jalview.ws.SequenceFetcher
5640 String[] dbclasses = sf.getNonAlignmentSources();
5641 List<DbSourceProxy> otherdb;
5642 JMenu dfetch = new JMenu();
5643 JMenu ifetch = new JMenu();
5644 JMenuItem fetchr = null;
5645 int comp = 0, icomp = 0, mcomp = 15;
5646 String mname = null;
5648 for (String dbclass : dbclasses)
5650 otherdb = sf.getSourceProxy(dbclass);
5651 // add a single entry for this class, or submenu allowing 'fetch
5653 if (otherdb == null || otherdb.size() < 1)
5659 mname = "From " + dbclass;
5661 if (otherdb.size() == 1)
5663 DbSourceProxy src = otherdb.get(0);
5664 DbSourceProxy[] dassource = new DbSourceProxy[] { src };
5665 fetchr = new JMenuItem(src.getDbSource());
5666 fetchr.addActionListener(new ActionListener()
5670 public void actionPerformed(ActionEvent e)
5672 new Thread(new Runnable()
5678 boolean isNucleotide = alignPanel.alignFrame
5679 .getViewport().getAlignment()
5681 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5682 alignPanel.av.getSequenceSelection(),
5683 alignPanel.alignFrame, dassource,
5684 alignPanel.alignFrame.featureSettings,
5687 .addListener(new FetchFinishedListenerI()
5690 public void finished()
5692 FeatureSettingsModelI srcSettings = dassource[0]
5693 .getFeatureColourScheme();
5694 alignPanel.av.mergeFeaturesStyle(
5696 AlignFrame.this.setMenusForViewport();
5699 dbRefFetcher.fetchDBRefs(false);
5705 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5706 MessageManager.formatMessage(
5707 "label.fetch_retrieve_from", new Object[]
5708 { src.getDbName() })));
5714 final DbSourceProxy[] dassource = otherdb
5715 .toArray(new DbSourceProxy[0]);
5717 DbSourceProxy src = otherdb.get(0);
5718 fetchr = new JMenuItem(MessageManager
5719 .formatMessage("label.fetch_all_param", new Object[]
5720 { src.getDbSource() }));
5721 fetchr.addActionListener(new ActionListener()
5724 public void actionPerformed(ActionEvent e)
5726 new Thread(new Runnable()
5732 boolean isNucleotide = alignPanel.alignFrame
5733 .getViewport().getAlignment()
5735 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5736 alignPanel.av.getSequenceSelection(),
5737 alignPanel.alignFrame, dassource,
5738 alignPanel.alignFrame.featureSettings,
5741 .addListener(new FetchFinishedListenerI()
5744 public void finished()
5746 AlignFrame.this.setMenusForViewport();
5749 dbRefFetcher.fetchDBRefs(false);
5755 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5756 MessageManager.formatMessage(
5757 "label.fetch_retrieve_from_all_sources",
5759 { Integer.valueOf(otherdb.size())
5761 src.getDbSource(), src.getDbName() })));
5764 // and then build the rest of the individual menus
5765 ifetch = new JMenu(MessageManager.formatMessage(
5766 "label.source_from_db_source", new Object[]
5767 { src.getDbSource() }));
5769 String imname = null;
5771 for (DbSourceProxy sproxy : otherdb)
5773 String dbname = sproxy.getDbName();
5774 String sname = dbname.length() > 5
5775 ? dbname.substring(0, 5) + "..."
5777 String msname = dbname.length() > 10
5778 ? dbname.substring(0, 10) + "..."
5782 imname = MessageManager
5783 .formatMessage("label.from_msname", new Object[]
5786 fetchr = new JMenuItem(msname);
5787 final DbSourceProxy[] dassrc = { sproxy };
5788 fetchr.addActionListener(new ActionListener()
5792 public void actionPerformed(ActionEvent e)
5794 new Thread(new Runnable()
5800 boolean isNucleotide = alignPanel.alignFrame
5801 .getViewport().getAlignment()
5803 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5804 alignPanel.av.getSequenceSelection(),
5805 alignPanel.alignFrame, dassrc,
5806 alignPanel.alignFrame.featureSettings,
5809 .addListener(new FetchFinishedListenerI()
5812 public void finished()
5814 AlignFrame.this.setMenusForViewport();
5817 dbRefFetcher.fetchDBRefs(false);
5823 fetchr.setToolTipText(
5824 "<html>" + MessageManager.formatMessage(
5825 "label.fetch_retrieve_from", new Object[]
5829 if (++icomp >= mcomp || i == (otherdb.size()))
5831 ifetch.setText(MessageManager.formatMessage(
5832 "label.source_to_target", imname, sname));
5834 ifetch = new JMenu();
5842 if (comp >= mcomp || dbi >= (dbclasses.length))
5844 dfetch.setText(MessageManager.formatMessage(
5845 "label.source_to_target", mname, dbclass));
5847 dfetch = new JMenu();
5860 * Left justify the whole alignment.
5863 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5865 viewport.getAlignment().justify(false);
5866 viewport.notifyAlignment();
5870 * Right justify the whole alignment.
5873 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5875 viewport.getAlignment().justify(true);
5876 viewport.notifyAlignment();
5880 public void setShowSeqFeatures(boolean b)
5882 showSeqFeatures.setSelected(b);
5883 viewport.setShowSequenceFeatures(b);
5890 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5891 * awt.event.ActionEvent)
5894 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5896 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5897 alignPanel.paintAlignment(false, false);
5904 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5908 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5910 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5911 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5919 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5920 * .event.ActionEvent)
5923 protected void showGroupConservation_actionPerformed(ActionEvent e)
5925 viewport.setShowGroupConservation(showGroupConservation.getState());
5926 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5933 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5934 * .event.ActionEvent)
5937 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5939 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5940 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5947 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5948 * .event.ActionEvent)
5951 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5953 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5954 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5958 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5960 showSequenceLogo.setState(true);
5961 viewport.setShowSequenceLogo(true);
5962 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5963 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5967 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5969 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5976 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5977 * .event.ActionEvent)
5980 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5982 if (avc.makeGroupsFromSelection())
5984 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5985 alignPanel.updateAnnotation();
5986 alignPanel.paintAlignment(true,
5987 viewport.needToUpdateStructureViews());
5991 public void clearAlignmentSeqRep()
5993 // TODO refactor alignmentseqrep to controller
5994 if (viewport.getAlignment().hasSeqrep())
5996 viewport.getAlignment().setSeqrep(null);
5997 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5998 alignPanel.updateAnnotation();
5999 alignPanel.paintAlignment(true, true);
6004 protected void createGroup_actionPerformed(ActionEvent e)
6006 if (avc.createGroup())
6008 if (applyAutoAnnotationSettings.isSelected())
6010 alignPanel.updateAnnotation(true, false);
6012 alignPanel.alignmentChanged();
6017 protected void unGroup_actionPerformed(ActionEvent e)
6021 alignPanel.alignmentChanged();
6026 * make the given alignmentPanel the currently selected tab
6028 * @param alignmentPanel
6030 public void setDisplayedView(AlignmentPanel alignmentPanel)
6032 if (!viewport.getSequenceSetId()
6033 .equals(alignmentPanel.av.getSequenceSetId()))
6035 throw new Error(MessageManager.getString(
6036 "error.implementation_error_cannot_show_view_alignment_frame"));
6038 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
6039 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
6041 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
6046 * Action on selection of menu options to Show or Hide annotations.
6049 * @param forSequences
6050 * update sequence-related annotations
6051 * @param forAlignment
6052 * update non-sequence-related annotations
6055 protected void setAnnotationsVisibility(boolean visible,
6056 boolean forSequences, boolean forAlignment)
6058 AlignmentAnnotation[] anns = alignPanel.getAlignment()
6059 .getAlignmentAnnotation();
6064 for (AlignmentAnnotation aa : anns)
6067 * don't display non-positional annotations on an alignment
6069 if (aa.annotations == null)
6073 boolean apply = (aa.sequenceRef == null && forAlignment)
6074 || (aa.sequenceRef != null && forSequences);
6077 aa.visible = visible;
6080 alignPanel.validateAnnotationDimensions(true);
6081 alignPanel.alignmentChanged();
6085 * Store selected annotation sort order for the view and repaint.
6088 protected void sortAnnotations_actionPerformed()
6090 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
6092 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
6093 alignPanel.paintAlignment(false, false);
6098 * @return alignment panels in this alignment frame
6100 public List<? extends AlignmentViewPanel> getAlignPanels()
6102 // alignPanels is never null
6103 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
6108 * Open a new alignment window, with the cDNA associated with this (protein)
6109 * alignment, aligned as is the protein.
6111 protected void viewAsCdna_actionPerformed()
6113 // TODO no longer a menu action - refactor as required
6114 final AlignmentI alignment = getViewport().getAlignment();
6115 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
6116 if (mappings == null)
6120 List<SequenceI> cdnaSeqs = new ArrayList<>();
6121 for (SequenceI aaSeq : alignment.getSequences())
6123 for (AlignedCodonFrame acf : mappings)
6125 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
6129 * There is a cDNA mapping for this protein sequence - add to new
6130 * alignment. It will share the same dataset sequence as other mapped
6131 * cDNA (no new mappings need to be created).
6133 final Sequence newSeq = new Sequence(dnaSeq);
6134 newSeq.setDatasetSequence(dnaSeq);
6135 cdnaSeqs.add(newSeq);
6139 if (cdnaSeqs.size() == 0)
6141 // show a warning dialog no mapped cDNA
6144 AlignmentI cdna = new Alignment(
6145 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
6146 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
6147 AlignFrame.DEFAULT_HEIGHT);
6148 cdna.alignAs(alignment);
6149 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
6151 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
6152 AlignFrame.DEFAULT_HEIGHT);
6156 * Set visibility of dna/protein complement view (available when shown in a
6162 protected void showComplement_actionPerformed(boolean show)
6164 SplitContainerI sf = getSplitViewContainer();
6167 sf.setComplementVisible(this, show);
6172 * Generate the reverse (optionally complemented) of the selected sequences,
6173 * and add them to the alignment
6176 protected void showReverse_actionPerformed(boolean complement)
6178 AlignmentI al = null;
6181 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
6182 al = dna.reverseCdna(complement);
6183 viewport.addAlignment(al, "");
6184 addHistoryItem(new EditCommand(
6185 MessageManager.getString("label.add_sequences"), Action.PASTE,
6186 al.getSequencesArray(), 0, al.getWidth(),
6187 viewport.getAlignment()));
6188 } catch (Exception ex)
6190 System.err.println(ex.getMessage());
6196 * Try to run a script in the Groovy console, having first ensured that this
6197 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
6198 * be targeted at this alignment.
6201 protected void runGroovy_actionPerformed()
6203 Jalview.setCurrentAlignFrame(this);
6204 groovy.ui.Console console = Desktop.getGroovyConsole();
6205 if (console != null)
6209 console.runScript();
6210 } catch (Exception ex)
6212 System.err.println((ex.toString()));
6213 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
6214 MessageManager.getString("label.couldnt_run_groovy_script"),
6215 MessageManager.getString("label.groovy_support_failed"),
6216 JvOptionPane.ERROR_MESSAGE);
6221 System.err.println("Can't run Groovy script as console not found");
6226 * Hides columns containing (or not containing) a specified feature, provided
6227 * that would not leave all columns hidden
6229 * @param featureType
6230 * @param columnsContaining
6233 public boolean hideFeatureColumns(String featureType,
6234 boolean columnsContaining)
6236 boolean notForHiding = avc.markColumnsContainingFeatures(
6237 columnsContaining, false, false, featureType);
6240 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
6241 false, featureType))
6243 getViewport().hideSelectedColumns();
6251 protected void selectHighlightedColumns_actionPerformed(
6252 ActionEvent actionEvent)
6254 // include key modifier check in case user selects from menu
6255 avc.markHighlightedColumns(
6256 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
6257 (actionEvent.getModifiers() & (ActionEvent.META_MASK
6258 | ActionEvent.CTRL_MASK)) != 0);
6262 * Rebuilds the Colour menu, including any user-defined colours which have
6263 * been loaded either on startup or during the session
6265 public void buildColourMenu()
6267 colourMenu.removeAll();
6269 colourMenu.add(applyToAllGroups);
6270 colourMenu.add(textColour);
6271 colourMenu.addSeparator();
6273 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
6274 viewport.getAlignment(), false);
6276 colourMenu.add(annotationColour);
6277 bg.add(annotationColour);
6278 colourMenu.addSeparator();
6279 colourMenu.add(conservationMenuItem);
6280 colourMenu.add(modifyConservation);
6281 colourMenu.add(abovePIDThreshold);
6282 colourMenu.add(modifyPID);
6284 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
6285 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
6289 * Open a dialog (if not already open) that allows the user to select and
6290 * calculate PCA or Tree analysis
6292 protected void openTreePcaDialog()
6294 if (alignPanel.getCalculationDialog() == null)
6296 new CalculationChooser(AlignFrame.this);
6301 * Sets the status of the HMMER menu
6303 public void updateHMMERStatus()
6305 hmmerMenu.setEnabled(HmmerCommand.isHmmerAvailable());
6308 protected void loadVcf_actionPerformed()
6310 JalviewFileChooser chooser = new JalviewFileChooser(
6311 Cache.getProperty("LAST_DIRECTORY"));
6312 chooser.setFileView(new JalviewFileView());
6313 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
6314 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
6315 final AlignFrame us = this;
6316 chooser.setResponseHandler(0, new Runnable()
6321 String choice = chooser.getSelectedFile().getPath();
6322 Cache.setProperty("LAST_DIRECTORY", choice);
6323 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
6324 new VCFLoader(choice).loadVCF(seqs, us);
6327 chooser.showOpenDialog(null);
6331 private Rectangle lastFeatureSettingsBounds = null;
6334 public void setFeatureSettingsGeometry(Rectangle bounds)
6336 lastFeatureSettingsBounds = bounds;
6340 public Rectangle getFeatureSettingsGeometry()
6342 return lastFeatureSettingsBounds;
6345 public void scrollTo(int row, int column)
6347 alignPanel.getSeqPanel().scrollTo(row, column);
6350 public void scrollToRow(int row)
6352 alignPanel.getSeqPanel().scrollToRow(row);
6355 public void scrollToColumn(int column)
6357 alignPanel.getSeqPanel().scrollToColumn(column);
6361 * BH 2019 from JalviewLite
6363 * get sequence feature groups that are hidden or shown
6370 public String[] getFeatureGroupsOfState(boolean visible)
6372 jalview.api.FeatureRenderer fr = null;
6373 if (alignPanel != null
6374 && (fr = alignPanel.getFeatureRenderer()) != null)
6376 List<String> gps = fr.getGroups(visible);
6377 String[] _gps = gps.toArray(new String[gps.size()]);
6385 * @return list of feature groups on the view
6388 public String[] getFeatureGroups()
6390 jalview.api.FeatureRenderer fr = null;
6391 if (alignPanel != null
6392 && (fr = alignPanel.getFeatureRenderer()) != null)
6394 List<String> gps = fr.getFeatureGroups();
6395 String[] _gps = gps.toArray(new String[gps.size()]);
6401 public void select(SequenceGroup sel, ColumnSelection csel,
6402 HiddenColumns hidden)
6404 alignPanel.getSeqPanel().selection(sel, csel, hidden, null);
6412 static class PrintThread extends Thread
6416 public PrintThread(AlignmentPanel ap)
6421 static PageFormat pf;
6426 PrinterJob printJob = PrinterJob.getPrinterJob();
6430 printJob.setPrintable(ap, pf);
6434 printJob.setPrintable(ap);
6437 if (printJob.printDialog())
6442 } catch (Exception PrintException)
6444 PrintException.printStackTrace();