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.ws.slivkaws.SlivkaWSDiscoverer;
186 import java.io.IOException;
187 import java.util.HashSet;
188 import java.util.Set;
190 import javax.swing.JFileChooser;
191 import javax.swing.JOptionPane;
193 import java.awt.BorderLayout;
194 import java.awt.Color;
195 import java.awt.Component;
196 import java.awt.Dimension;
197 import java.awt.Rectangle;
198 import java.awt.Toolkit;
199 import java.awt.datatransfer.Clipboard;
200 import java.awt.datatransfer.DataFlavor;
201 import java.awt.datatransfer.StringSelection;
202 import java.awt.datatransfer.Transferable;
203 import java.awt.dnd.DnDConstants;
204 import java.awt.dnd.DropTargetDragEvent;
205 import java.awt.dnd.DropTargetDropEvent;
206 import java.awt.dnd.DropTargetEvent;
207 import java.awt.dnd.DropTargetListener;
208 import java.awt.event.ActionEvent;
209 import java.awt.event.ActionListener;
210 import java.awt.event.FocusAdapter;
211 import java.awt.event.FocusEvent;
212 import java.awt.event.ItemEvent;
213 import java.awt.event.ItemListener;
214 import java.awt.event.KeyAdapter;
215 import java.awt.event.KeyEvent;
216 import java.awt.event.MouseEvent;
217 import java.awt.print.PageFormat;
218 import java.awt.print.PrinterJob;
219 import java.beans.PropertyChangeEvent;
220 import java.beans.PropertyChangeListener;
222 import java.io.FileWriter;
223 import java.io.PrintWriter;
225 import java.util.ArrayList;
226 import java.util.Arrays;
227 import java.util.Collection;
228 import java.util.Deque;
229 import java.util.Enumeration;
230 import java.util.Hashtable;
231 import java.util.List;
232 import java.util.Vector;
234 import javax.swing.ButtonGroup;
235 import javax.swing.JCheckBoxMenuItem;
236 import javax.swing.JComponent;
237 import javax.swing.JEditorPane;
238 import javax.swing.JInternalFrame;
239 import javax.swing.JLabel;
240 import javax.swing.JLayeredPane;
241 import javax.swing.JMenu;
242 import javax.swing.JMenuItem;
243 import javax.swing.JPanel;
244 import javax.swing.JScrollPane;
245 import javax.swing.SwingUtilities;
246 import javax.swing.event.InternalFrameAdapter;
247 import javax.swing.event.InternalFrameEvent;
249 import ext.vamsas.ServiceHandle;
255 * @version $Revision$
257 @SuppressWarnings("serial")
258 public class AlignFrame extends GAlignFrame
259 implements DropTargetListener, IProgressIndicator,
260 AlignViewControllerGuiI, ColourChangeListener, ServiceChangeListener
263 public static int frameCount;
264 public static final int DEFAULT_WIDTH = 700;
266 public static final int DEFAULT_HEIGHT = 500;
269 * The currently displayed panel (selected tabbed view if more than one)
271 public AlignmentPanel alignPanel;
273 AlignViewport viewport;
275 public AlignViewControllerI avc;
277 List<AlignmentPanel> alignPanels = new ArrayList<>();
280 * Last format used to load or save alignments in this window
282 FileFormatI currentFileFormat = null;
285 * Current filename for this alignment
287 String fileName = null;
290 * TODO: remove reference to 'FileObject' in AlignFrame - not correct mapping
296 private DataSourceType protocol ;
298 * Creates a new AlignFrame object with specific width and height.
304 public AlignFrame(AlignmentI al, int width, int height)
306 this(al, null, width, height);
310 * Creates a new AlignFrame object with specific width, height and
316 * @param sequenceSetId
318 public AlignFrame(AlignmentI al, int width, int height,
319 String sequenceSetId)
321 this(al, null, width, height, sequenceSetId);
325 * Creates a new AlignFrame object with specific width, height and
331 * @param sequenceSetId
334 public AlignFrame(AlignmentI al, int width, int height,
335 String sequenceSetId, String viewId)
337 this(al, null, width, height, sequenceSetId, viewId);
341 * new alignment window with hidden columns
345 * @param hiddenColumns
346 * ColumnSelection or null
348 * Width of alignment frame
352 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
355 this(al, hiddenColumns, width, height, null);
359 * Create alignment frame for al with hiddenColumns, a specific width and
360 * height, and specific sequenceId
363 * @param hiddenColumns
366 * @param sequenceSetId
369 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
370 int height, String sequenceSetId)
372 this(al, hiddenColumns, width, height, sequenceSetId, null);
376 * Create alignment frame for al with hiddenColumns, a specific width and
377 * height, and specific sequenceId
380 * @param hiddenColumns
383 * @param sequenceSetId
388 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
389 int height, String sequenceSetId, String viewId)
392 setSize(width, height);
394 if (al.getDataset() == null)
399 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
401 // JalviewJS needs to distinguish a new panel from an old one in init()
402 // alignPanel = new AlignmentPanel(this, viewport);
403 // addAlignmentPanel(alignPanel, true);
407 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
408 HiddenColumns hiddenColumns, int width, int height)
410 setSize(width, height);
412 if (al.getDataset() == null)
417 viewport = new AlignViewport(al, hiddenColumns);
419 if (hiddenSeqs != null && hiddenSeqs.length > 0)
421 viewport.hideSequence(hiddenSeqs);
423 // alignPanel = new AlignmentPanel(this, viewport);
424 // addAlignmentPanel(alignPanel, true);
429 * Make a new AlignFrame from existing alignmentPanels
436 public AlignFrame(AlignmentPanel ap)
440 // addAlignmentPanel(ap, false);
445 * initalise the alignframe from the underlying viewport data and the
450 boolean newPanel = (alignPanel == null);
451 viewport.setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
456 // need to set this up front if NOANNOTATION is
457 // used in conjunction with SHOWOVERVIEW.
459 // I have not determined if this is appropriate for
460 // Jalview/Java, as it means we are setting this flag
461 // for all subsequent AlignFrames. For now, at least,
462 // I am setting it to be JalviewJS-only.
464 boolean showAnnotation = Jalview.getInstance().getShowAnnotation();
465 viewport.setShowAnnotation(showAnnotation);
467 alignPanel = new AlignmentPanel(this, viewport);
469 addAlignmentPanel(alignPanel, newPanel);
470 // setBackground(Color.white); // BH 2019
472 if (!Jalview.isHeadlessMode())
474 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
476 statusPanel.setVisible(Jalview.getInstance().getShowStatus());
477 alignFrameMenuBar.setVisible(Jalview.getInstance().getAllowMenuBar());
480 avc = new jalview.controller.AlignViewController(this, viewport,
482 if (viewport.getAlignmentConservationAnnotation() == null)
484 // BLOSUM62Colour.setEnabled(false);
485 conservationMenuItem.setEnabled(false);
486 modifyConservation.setEnabled(false);
487 // PIDColour.setEnabled(false);
488 // abovePIDThreshold.setEnabled(false);
489 // modifyPID.setEnabled(false);
492 String sortby = Cache.getDefault(Preferences.SORT_ALIGNMENT,
495 if (sortby.equals("Id"))
497 sortIDMenuItem_actionPerformed(null);
499 else if (sortby.equals("Pairwise Identity"))
501 sortPairwiseMenuItem_actionPerformed(null);
506 // this.alignPanel.av
507 // .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
509 setMenusFromViewport(viewport);
510 buildSortByAnnotationScoresMenu();
511 calculateTree.addActionListener(new ActionListener()
515 public void actionPerformed(ActionEvent e)
522 if (Desktop.getDesktopPane() != null)
524 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
525 addServiceListeners();
526 if (!Platform.isJS())
532 if (viewport.getWrapAlignment())
534 wrapMenuItem_actionPerformed(null);
537 if (Cache.getDefault(Preferences.SHOW_OVERVIEW, false))
539 this.overviewMenuItem_actionPerformed(null);
544 final List<AlignmentViewPanel> selviews = new ArrayList<>();
545 final List<AlignmentPanel> origview = new ArrayList<>();
546 final String menuLabel = MessageManager
547 .getString("label.copy_format_from");
548 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
549 new ViewSetProvider()
553 public AlignmentPanel[] getAllAlignmentPanels()
556 origview.add(alignPanel);
557 // make an array of all alignment panels except for this one
558 List<AlignmentPanel> aps = new ArrayList<>(
559 Arrays.asList(Desktop.getAlignmentPanels(null)));
560 aps.remove(AlignFrame.this.alignPanel);
561 return aps.toArray(new AlignmentPanel[aps.size()]);
563 }, selviews, new ItemListener()
567 public void itemStateChanged(ItemEvent e)
569 if (origview.size() > 0)
571 final AlignmentPanel ap = origview.get(0);
574 * Copy the ViewStyle of the selected panel to 'this one'.
575 * Don't change value of 'scaleProteinAsCdna' unless copying
578 ViewStyleI vs = selviews.get(0).getAlignViewport()
580 boolean fromSplitFrame = selviews.get(0)
581 .getAlignViewport().getCodingComplement() != null;
584 vs.setScaleProteinAsCdna(ap.getAlignViewport()
585 .getViewStyle().isScaleProteinAsCdna());
587 ap.getAlignViewport().setViewStyle(vs);
590 * Also rescale ViewStyle of SplitFrame complement if there is
591 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
592 * the whole ViewStyle (allow cDNA protein to have different
595 AlignViewportI complement = ap.getAlignViewport()
596 .getCodingComplement();
597 if (complement != null && vs.isScaleProteinAsCdna())
599 AlignFrame af = Desktop.getAlignFrameFor(complement);
600 ((SplitFrame) af.getSplitViewContainer())
602 af.setMenusForViewport();
606 ap.setSelected(true);
607 ap.alignFrame.setMenusForViewport();
612 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase(Locale.ROOT)
613 .indexOf("devel") > -1
614 || Cache.getDefault("VERSION", "DEVELOPMENT")
615 .toLowerCase(Locale.ROOT).indexOf("test") > -1)
617 formatMenu.add(vsel);
619 addFocusListener(new FocusAdapter()
622 public void focusGained(FocusEvent e)
624 Jalview.setCurrentAlignFrame(AlignFrame.this);
631 * Change the filename and format for the alignment, and enable the 'reload'
632 * button functionality.
640 public void setFileName(String file, FileFormatI format)
643 setFileFormat(format);
644 reload.setEnabled(true);
650 * @param file from SwingJS; may contain bytes -- for reload
651 * @param protocol from SwingJS; may be RELATIVE_URL
654 public void setFile(String fileName, File file, DataSourceType protocol, FileFormatI format)
656 this.fileName = fileName;
657 this.fileObject = file;
658 this.protocol = protocol;
659 setFileFormat(format);
660 reload.setEnabled(true);
664 * JavaScript will have this, maybe others. More dependable than a file name
665 * and maintains a reference to the actual bytes loaded.
669 public void setFileObject(File file)
671 this.fileObject = file;
675 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
678 void addKeyListener()
680 addKeyListener(new KeyAdapter()
683 public void keyPressed(KeyEvent evt)
685 if (viewport.cursorMode
686 && ((evt.getKeyCode() >= KeyEvent.VK_0
687 && evt.getKeyCode() <= KeyEvent.VK_9)
688 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
689 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
690 && Character.isDigit(evt.getKeyChar()))
692 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
695 switch (evt.getKeyCode())
698 case KeyEvent.VK_ESCAPE: // escape key
699 // alignPanel.deselectAllSequences();
700 alignPanel.deselectAllSequences();
704 case KeyEvent.VK_DOWN:
705 if (evt.isAltDown() || !viewport.cursorMode)
707 moveSelectedSequences(false);
709 if (viewport.cursorMode)
711 alignPanel.getSeqPanel().moveCursor(0, 1, evt.isShiftDown());
716 if (evt.isAltDown() || !viewport.cursorMode)
718 moveSelectedSequences(true);
720 if (viewport.cursorMode)
722 alignPanel.getSeqPanel().moveCursor(0, -1, evt.isShiftDown());
727 case KeyEvent.VK_LEFT:
728 if (evt.isAltDown() || !viewport.cursorMode)
730 slideSequences(false,
731 alignPanel.getSeqPanel().getKeyboardNo1());
735 alignPanel.getSeqPanel().moveCursor(-1, 0, evt.isShiftDown());
740 case KeyEvent.VK_RIGHT:
741 if (evt.isAltDown() || !viewport.cursorMode)
743 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
747 alignPanel.getSeqPanel().moveCursor(1, 0, evt.isShiftDown());
751 case KeyEvent.VK_SPACE:
752 if (viewport.cursorMode)
754 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
755 || evt.isShiftDown() || evt.isAltDown());
759 // case KeyEvent.VK_A:
760 // if (viewport.cursorMode)
762 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
763 // //System.out.println("A");
767 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
768 * System.out.println("closing bracket"); } break;
770 case KeyEvent.VK_DELETE:
771 case KeyEvent.VK_BACK_SPACE:
772 if (!viewport.cursorMode)
774 cut_actionPerformed();
778 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
779 || evt.isShiftDown() || evt.isAltDown());
785 if (viewport.cursorMode)
787 alignPanel.getSeqPanel().setCursorRow();
791 if (viewport.cursorMode && !evt.isControlDown())
793 alignPanel.getSeqPanel().setCursorColumn();
797 if (viewport.cursorMode)
799 alignPanel.getSeqPanel().setCursorPosition();
803 case KeyEvent.VK_ENTER:
804 case KeyEvent.VK_COMMA:
805 if (viewport.cursorMode)
807 alignPanel.getSeqPanel().setCursorRowAndColumn();
812 if (viewport.cursorMode)
814 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
818 if (viewport.cursorMode)
820 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
825 viewport.cursorMode = !viewport.cursorMode;
826 setStatus(MessageManager
827 .formatMessage("label.keyboard_editing_mode", new String[]
828 { (viewport.cursorMode ? "on" : "off") }));
829 if (viewport.cursorMode)
831 ViewportRanges ranges = viewport.getRanges();
832 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
834 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
837 alignPanel.getSeqPanel().seqCanvas.repaint();
843 Help.showHelpWindow();
844 } catch (Exception ex)
846 ex.printStackTrace();
851 boolean toggleSeqs = !evt.isControlDown();
852 boolean toggleCols = !evt.isShiftDown();
853 toggleHiddenRegions(toggleSeqs, toggleCols);
858 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
859 boolean modifyExisting = true; // always modify, don't clear
860 // evt.isShiftDown();
861 boolean invertHighlighted = evt.isAltDown();
862 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
866 case KeyEvent.VK_PAGE_UP:
867 viewport.getRanges().pageUp();
869 case KeyEvent.VK_PAGE_DOWN:
870 viewport.getRanges().pageDown();
876 public void keyReleased(KeyEvent evt)
878 switch (evt.getKeyCode())
880 case KeyEvent.VK_LEFT:
881 if (evt.isAltDown() || !viewport.cursorMode)
883 viewport.notifyAlignment();
887 case KeyEvent.VK_RIGHT:
888 if (evt.isAltDown() || !viewport.cursorMode)
890 viewport.notifyAlignment();
898 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
900 ap.alignFrame = this;
901 avc = new jalview.controller.AlignViewController(this, viewport,
906 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
908 int aSize = alignPanels.size();
910 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
912 if (aSize == 1 && ap.av.getViewName() == null)
914 this.getContentPane().add(ap, BorderLayout.CENTER);
920 setInitialTabVisible();
923 expandViews.setEnabled(true);
924 gatherViews.setEnabled(true);
925 tabbedPane.addTab(ap.av.getViewName(), ap);
927 ap.setVisible(false);
932 if (ap.av.isPadGaps())
934 ap.av.getAlignment().padGaps();
936 if (Jalview.getInstance().getStartCalculations())
938 ap.av.updateConservation(ap);
939 ap.av.updateConsensus(ap);
940 ap.av.updateStrucConsensus(ap);
941 ap.av.initInformationWorker(ap);
946 public void setInitialTabVisible()
948 expandViews.setEnabled(true);
949 gatherViews.setEnabled(true);
950 tabbedPane.setVisible(true);
951 AlignmentPanel first = alignPanels.get(0);
952 tabbedPane.addTab(first.av.getViewName(), first);
953 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
956 public AlignViewport getViewport()
962 public void servicesChanged(WSDiscovererI discoverer,
963 Collection<? extends ServiceWithParameters> services)
965 buildWebServicesMenu();
967 /* Set up intrinsic listeners for dynamically generated GUI bits. */
968 private void addServiceListeners()
970 if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
972 WSDiscovererI discoverer = SlivkaWSDiscoverer.getInstance();
973 discoverer.addServiceChangeListener(this);
975 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
977 WSDiscovererI discoverer = Jws2Discoverer.getInstance();
978 discoverer.addServiceChangeListener(this);
980 // legacy event listener for compatibility with jws1
981 PropertyChangeListener legacyListener = (changeEvent) -> {
982 buildWebServicesMenu();
984 Desktop.getInstance().addJalviewPropertyChangeListener("services",legacyListener);
986 addInternalFrameListener(new InternalFrameAdapter() {
988 public void internalFrameClosed(InternalFrameEvent e) {
989 System.out.println("deregistering discoverer listener");
990 SlivkaWSDiscoverer.getInstance().removeServiceChangeListener(AlignFrame.this);
991 Jws2Discoverer.getInstance().removeServiceChangeListener(AlignFrame.this);
992 Desktop.getInstance().removeJalviewPropertyChangeListener("services", legacyListener);
993 closeMenuItem_actionPerformed(true);
996 buildWebServicesMenu();
1000 * Configure menu items that vary according to whether the alignment is
1001 * nucleotide or protein
1003 public void setGUINucleotide()
1005 AlignmentI al = getViewport().getAlignment();
1006 boolean nucleotide = al.isNucleotide();
1008 loadVcf.setVisible(nucleotide);
1009 showTranslation.setVisible(nucleotide);
1010 showReverse.setVisible(nucleotide);
1011 showReverseComplement.setVisible(nucleotide);
1012 conservationMenuItem.setEnabled(!nucleotide);
1014 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
1015 showGroupConservation.setEnabled(!nucleotide);
1017 showComplementMenuItem
1018 .setText(nucleotide ? MessageManager.getString("label.protein")
1019 : MessageManager.getString("label.nucleotide"));
1023 * set up menus for the current viewport. This may be called after any
1024 * operation that affects the data in the current view (selection changed,
1025 * etc) to update the menus to reflect the new state.
1028 public void setMenusForViewport()
1030 setMenusFromViewport(viewport);
1034 * Need to call this method when tabs are selected for multiple views, or when
1035 * loading from Jalview2XML.java
1040 public void setMenusFromViewport(AlignViewport av)
1042 padGapsMenuitem.setSelected(av.isPadGaps());
1043 colourTextMenuItem.setSelected(av.isShowColourText());
1044 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
1045 modifyPID.setEnabled(abovePIDThreshold.isSelected());
1046 conservationMenuItem.setSelected(av.getConservationSelected());
1047 modifyConservation.setEnabled(conservationMenuItem.isSelected());
1048 seqLimits.setSelected(av.getShowJVSuffix());
1049 idRightAlign.setSelected(av.isRightAlignIds());
1050 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
1051 renderGapsMenuItem.setSelected(av.isRenderGaps());
1052 wrapMenuItem.setSelected(av.getWrapAlignment());
1053 scaleAbove.setVisible(av.getWrapAlignment());
1054 scaleLeft.setVisible(av.getWrapAlignment());
1055 scaleRight.setVisible(av.getWrapAlignment());
1056 annotationPanelMenuItem.setState(av.isShowAnnotation());
1057 // Show/hide annotations only enabled if annotation panel is shown
1058 syncAnnotationMenuItems(av.isShowAnnotation());
1059 viewBoxesMenuItem.setSelected(av.getShowBoxes());
1060 viewTextMenuItem.setSelected(av.getShowText());
1061 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
1062 showGroupConsensus.setSelected(av.isShowGroupConsensus());
1063 showGroupConservation.setSelected(av.isShowGroupConservation());
1064 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
1065 showSequenceLogo.setSelected(av.isShowSequenceLogo());
1066 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
1067 showInformationHistogram.setSelected(av.isShowInformationHistogram());
1068 showHMMSequenceLogo.setSelected(av.isShowHMMSequenceLogo());
1069 normaliseHMMSequenceLogo.setSelected(av.isNormaliseHMMSequenceLogo());
1071 ColourMenuHelper.setColourSelected(colourMenu,
1072 av.getGlobalColourScheme());
1074 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
1075 hiddenMarkers.setState(av.getShowHiddenMarkers());
1076 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
1077 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
1078 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
1080 .setSelected(av.getAutoCalculateConsensusAndConservation());
1081 sortByTree.setSelected(av.sortByTree);
1082 listenToViewSelections.setSelected(av.followSelection);
1084 showProducts.setEnabled(canShowProducts());
1085 setGroovyEnabled(Desktop.getGroovyConsole() != null);
1087 updateEditMenuBar();
1091 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
1095 public void setGroovyEnabled(boolean b)
1097 runGroovy.setEnabled(b);
1100 private IProgressIndicator progressBar;
1105 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
1108 public void setProgressBar(String message, long id)
1110 progressBar.setProgressBar(message, id);
1114 public void removeProgressBar(long id)
1116 progressBar.removeProgressBar(id);
1120 public void registerHandler(final long id,
1121 final IProgressIndicatorHandler handler)
1123 progressBar.registerHandler(id, handler);
1128 * @return true if any progress bars are still active
1131 public boolean operationInProgress()
1133 return progressBar.operationInProgress();
1137 * Sets the text of the status bar. Note that setting a null or empty value
1138 * will cause the status bar to be hidden, with possibly undesirable flicker
1139 * of the screen layout.
1142 public void setStatus(String text)
1144 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1148 * Added so Castor Mapping file can obtain Jalview Version
1150 public String getVersion()
1152 return Cache.getProperty("VERSION");
1155 public FeatureRenderer getFeatureRenderer()
1157 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1161 public void fetchSequence_actionPerformed()
1163 new SequenceFetcher(this);
1167 public void addFromFile_actionPerformed(ActionEvent e)
1169 Desktop.getInstance().inputLocalFileMenuItem_actionPerformed(viewport);
1173 public void hmmBuild_actionPerformed(boolean withDefaults)
1175 if (!alignmentIsSufficient(1))
1181 * get default parameters, and optionally show a dialog
1182 * to allow them to be modified
1184 ParamDatastoreI store = HMMERParamStore.forBuild(viewport);
1185 List<ArgumentI> args = store.getServiceParameters();
1189 WsParamSetI set = new HMMERPreset();
1190 WsJobParameters params = new WsJobParameters(store, set, args);
1191 params.showRunDialog().thenAccept((startJob) -> {
1194 var args2 = params.getJobParams();
1195 new Thread(new HMMBuild(this, args2)).start();
1201 new Thread(new HMMBuild(this, args)).start();
1206 public void hmmAlign_actionPerformed(boolean withDefaults)
1208 if (!(checkForHMM() && alignmentIsSufficient(2)))
1214 * get default parameters, and optionally show a dialog
1215 * to allow them to be modified
1217 ParamDatastoreI store = HMMERParamStore.forAlign(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 HMMAlign(this, args2)).start();
1234 new Thread(new HMMAlign(this, args)).start();
1239 public void hmmSearch_actionPerformed(boolean withDefaults)
1247 * get default parameters, and (if requested) show
1248 * dialog to allow modification
1250 ParamDatastoreI store = HMMERParamStore.forSearch(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 HMMSearch(this, args2)).start();
1262 alignPanel.repaint();
1268 new Thread(new HMMSearch(this, args)).start();
1269 alignPanel.repaint();
1274 public void jackhmmer_actionPerformed(boolean withDefaults)
1278 * get default parameters, and (if requested) show
1279 * dialog to allow modification
1282 ParamDatastoreI store = HMMERParamStore.forJackhmmer(viewport);
1283 List<ArgumentI> args = store.getServiceParameters();
1287 WsParamSetI set = new HMMERPreset();
1288 WsJobParameters params = new WsJobParameters(store, set, args);
1289 params.showRunDialog().thenAccept((startJob) -> {
1292 var args2 = params.getJobParams();
1293 new Thread(new JackHMMER(this, args2)).start();
1294 alignPanel.repaint();
1300 new Thread(new JackHMMER(this, args)).start();
1301 alignPanel.repaint();
1306 * Checks if the alignment has at least one hidden Markov model, if not shows
1307 * a dialog advising to run hmmbuild or load an HMM profile
1311 private boolean checkForHMM()
1313 if (viewport.getAlignment().getHmmSequences().isEmpty())
1315 JOptionPane.showMessageDialog(this,
1316 MessageManager.getString("warn.no_hmm"));
1323 protected void filterByEValue_actionPerformed()
1325 viewport.filterByEvalue(inputDouble("Enter E-Value Cutoff"));
1329 protected void filterByScore_actionPerformed()
1331 viewport.filterByScore(inputDouble("Enter Bit Score Threshold"));
1334 private double inputDouble(String message)
1338 while (d == null || d <= 0)
1340 str = JOptionPane.showInputDialog(this.alignPanel, message);
1343 d = Double.valueOf(str);
1344 } catch (NumberFormatException e)
1352 * Checks if the alignment contains the required number of sequences.
1357 public boolean alignmentIsSufficient(int required)
1359 if (getViewport().getSequenceSelection().length < required)
1361 JOptionPane.showMessageDialog(this,
1362 MessageManager.getString("label.not_enough_sequences"));
1369 * Opens a file browser and adds the selected file, if in Fasta, Stockholm or
1370 * Pfam format, to the list held under preference key "HMMSEARCH_DBS" (as a
1371 * comma-separated list)
1374 public void addDatabase_actionPerformed() throws IOException
1376 if (Cache.getProperty(Preferences.HMMSEARCH_DBS) == null)
1378 Cache.setProperty(Preferences.HMMSEARCH_DBS, "");
1381 String path = openFileChooser(false);
1382 if (path != null && new File(path).exists())
1384 IdentifyFile identifier = new IdentifyFile();
1385 FileFormatI format = identifier.identify(path, DataSourceType.FILE);
1386 if (format == FileFormat.Fasta || format == FileFormat.Stockholm
1387 || format == FileFormat.Pfam)
1389 String currentDbPaths = Cache
1390 .getProperty(Preferences.HMMSEARCH_DBS);
1391 currentDbPaths += Preferences.COMMA + path;
1392 Cache.setProperty(Preferences.HMMSEARCH_DBS, currentDbPaths);
1396 JOptionPane.showMessageDialog(this,
1397 MessageManager.getString("warn.invalid_format"));
1403 * Opens a file chooser, optionally restricted to selecting folders
1404 * (directories) only. Answers the path to the selected file or folder, or
1405 * null if none is chosen.
1410 protected String openFileChooser(boolean forFolder)
1412 // TODO duplicates GPreferences method - relocate to JalviewFileChooser?
1413 String choice = null;
1414 JFileChooser chooser = new JFileChooser();
1417 chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1419 chooser.setDialogTitle(
1420 MessageManager.getString("label.open_local_file"));
1421 chooser.setToolTipText(MessageManager.getString("action.open"));
1423 int value = chooser.showOpenDialog(this);
1425 if (value == JFileChooser.APPROVE_OPTION)
1427 choice = chooser.getSelectedFile().getPath();
1433 public void reload_actionPerformed(ActionEvent e)
1435 if (fileName == null && fileObject == null)
1439 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1440 // originating file's format
1441 // TODO: work out how to recover feature settings for correct view(s) when
1442 // file is reloaded.
1443 if (FileFormat.Jalview.equals(currentFileFormat))
1445 JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
1446 for (int i = 0; i < frames.length; i++)
1448 if (frames[i] instanceof AlignFrame && frames[i] != this
1449 && ((AlignFrame) frames[i]).fileName != null
1450 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1454 frames[i].setSelected(true);
1455 Desktop.getInstance().closeAssociatedWindows();
1456 } catch (java.beans.PropertyVetoException ex)
1462 Desktop.getInstance().closeAssociatedWindows();
1464 FileLoader loader = new FileLoader();
1465 loader.LoadFile(viewport, (fileObject == null ? fileName : fileObject), protocol, currentFileFormat);
1469 Rectangle bounds = this.getBounds();
1471 FileLoader loader = new FileLoader();
1473 AlignFrame newframe = null;
1475 if (fileObject == null)
1477 newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1482 newframe = loader.LoadFileWaitTillLoaded(fileObject,
1483 DataSourceType.FILE, currentFileFormat);
1486 newframe.setBounds(bounds);
1487 if (featureSettings != null && featureSettings.isShowing())
1489 final Rectangle fspos = featureSettings.frame.getBounds();
1490 // TODO: need a 'show feature settings' function that takes bounds -
1491 // need to refactor Desktop.addFrame
1492 newframe.featureSettings_actionPerformed(null);
1493 final FeatureSettings nfs = newframe.featureSettings;
1494 SwingUtilities.invokeLater(new Runnable()
1499 nfs.frame.setBounds(fspos);
1502 this.featureSettings.close();
1503 this.featureSettings = null;
1505 this.closeMenuItem_actionPerformed(true);
1510 public void addFromText_actionPerformed(ActionEvent e)
1512 Desktop.getInstance()
1513 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1517 public void addFromURL_actionPerformed(ActionEvent e)
1519 Desktop.getInstance().inputURLMenuItem_actionPerformed(viewport);
1523 public void save_actionPerformed(ActionEvent e)
1525 if (fileName == null || (currentFileFormat == null)
1526 || HttpUtils.startsWithHttpOrHttps(fileName))
1528 saveAs_actionPerformed();
1532 saveAlignment(fileName, currentFileFormat);
1537 * Saves the alignment to a file with a name chosen by the user, if necessary
1538 * warning if a file would be overwritten
1541 public void saveAs_actionPerformed()
1543 String format = currentFileFormat == null ? null
1544 : currentFileFormat.getName();
1545 JalviewFileChooser chooser = JalviewFileChooser
1546 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1548 chooser.setFileView(new JalviewFileView());
1549 chooser.setDialogTitle(
1550 MessageManager.getString("label.save_alignment_to_file"));
1551 chooser.setToolTipText(MessageManager.getString("action.save"));
1553 int value = chooser.showSaveDialog(this);
1555 if (value != JalviewFileChooser.APPROVE_OPTION)
1559 currentFileFormat = chooser.getSelectedFormat();
1560 // todo is this (2005) test now obsolete - value is never null?
1561 while (currentFileFormat == null)
1563 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
1565 .getString("label.select_file_format_before_saving"),
1566 MessageManager.getString("label.file_format_not_specified"),
1567 JvOptionPane.WARNING_MESSAGE);
1568 currentFileFormat = chooser.getSelectedFormat();
1569 value = chooser.showSaveDialog(this);
1570 if (value != JalviewFileChooser.APPROVE_OPTION)
1576 fileName = chooser.getSelectedFile().getPath();
1578 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1579 Cache.setProperty("LAST_DIRECTORY", fileName);
1580 saveAlignment(fileName, currentFileFormat);
1583 boolean lastSaveSuccessful = false;
1585 FileFormatI lastFormatSaved;
1587 String lastFilenameSaved;
1590 * Raise a dialog or status message for the last call to saveAlignment.
1592 * @return true if last call to saveAlignment(file, format) was successful.
1594 public boolean isSaveAlignmentSuccessful()
1597 if (!lastSaveSuccessful)
1599 if (!Platform.isHeadless())
1601 JvOptionPane.showInternalMessageDialog(this, MessageManager
1602 .formatMessage("label.couldnt_save_file", new Object[]
1603 { lastFilenameSaved }),
1604 MessageManager.getString("label.error_saving_file"),
1605 JvOptionPane.WARNING_MESSAGE);
1609 Console.error(MessageManager
1610 .formatMessage("label.couldnt_save_file", new Object[]
1611 { lastFilenameSaved }));
1617 setStatus(MessageManager.formatMessage(
1618 "label.successfully_saved_to_file_in_format", new Object[]
1619 { lastFilenameSaved, lastFormatSaved }));
1622 return lastSaveSuccessful;
1626 * Saves the alignment to the specified file path, in the specified format,
1627 * which may be an alignment format, or Jalview project format. If the
1628 * alignment has hidden regions, or the format is one capable of including
1629 * non-sequence data (features, annotations, groups), then the user may be
1630 * prompted to specify what to include in the output.
1635 public void saveAlignment(String file, FileFormatI format)
1637 lastSaveSuccessful = true;
1638 lastFilenameSaved = file;
1639 lastFormatSaved = format;
1641 if (FileFormat.Jalview.equals(format))
1643 String shortName = title;
1644 if (shortName.indexOf(File.separatorChar) > -1)
1646 shortName = shortName
1647 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
1649 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file,
1652 statusBar.setText(MessageManager.formatMessage(
1653 "label.successfully_saved_to_file_in_format", new Object[]
1654 { fileName, format }));
1659 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1660 Runnable cancelAction = new Runnable()
1665 lastSaveSuccessful = false;
1668 Runnable outputAction = new Runnable()
1673 // todo defer this to inside formatSequences (or later)
1674 AlignmentExportData exportData = viewport
1675 .getAlignExportData(options);
1676 String output = new FormatAdapter(alignPanel, options)
1677 .formatSequences(format, exportData.getAlignment(),
1678 exportData.getOmitHidden(),
1679 exportData.getStartEndPostions(),
1680 viewport.getAlignment().getHiddenColumns());
1683 lastSaveSuccessful = false;
1687 // create backupfiles object and get new temp filename destination
1688 boolean doBackup = BackupFiles.getEnabled();
1689 BackupFiles backupfiles = null;
1693 "ALIGNFRAME making backupfiles object for " + file);
1694 backupfiles = new BackupFiles(file);
1698 String tempFilePath = doBackup ? backupfiles.getTempFilePath()
1700 Console.trace("ALIGNFRAME setting PrintWriter");
1701 PrintWriter out = new PrintWriter(new FileWriter(tempFilePath));
1703 if (backupfiles != null)
1705 Console.trace("ALIGNFRAME about to write to temp file "
1706 + backupfiles.getTempFilePath());
1710 Console.trace("ALIGNFRAME about to close file");
1712 Console.trace("ALIGNFRAME closed file");
1713 AlignFrame.this.setTitle(file);
1714 statusBar.setText(MessageManager.formatMessage(
1715 "label.successfully_saved_to_file_in_format",
1717 { fileName, format.getName() }));
1718 lastSaveSuccessful = true;
1719 } catch (IOException e)
1721 lastSaveSuccessful = false;
1723 "ALIGNFRAME Something happened writing the temp file");
1724 Console.error(e.getMessage());
1725 Console.debug(Cache.getStackTraceString(e));
1726 } catch (Exception ex)
1728 lastSaveSuccessful = false;
1730 "ALIGNFRAME Something unexpected happened writing the temp file");
1731 Console.error(ex.getMessage());
1732 Console.debug(Cache.getStackTraceString(ex));
1737 backupfiles.setWriteSuccess(lastSaveSuccessful);
1738 Console.debug("ALIGNFRAME writing temp file was "
1739 + (lastSaveSuccessful ? "" : "NOT ") + "successful");
1740 // do the backup file roll and rename the temp file to actual file
1742 "ALIGNFRAME about to rollBackupsAndRenameTempFile");
1743 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1745 "ALIGNFRAME performed rollBackupsAndRenameTempFile "
1746 + (lastSaveSuccessful ? "" : "un")
1754 * show dialog with export options if applicable; else just do it
1756 if (AlignExportOptions.isNeeded(viewport, format))
1758 AlignExportOptions choices = new AlignExportOptions(
1759 alignPanel.getAlignViewport(), format, options);
1760 choices.setResponseAction(0, outputAction);
1761 choices.setResponseAction(1, cancelAction);
1762 choices.showDialog();
1771 * Outputs the alignment to textbox in the requested format, if necessary
1772 * first prompting the user for whether to include hidden regions or
1775 * @param fileFormatName
1778 protected void outputText_actionPerformed(String fileFormatName)
1780 FileFormatI fileFormat = FileFormats.getInstance()
1781 .forName(fileFormatName);
1782 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1783 Runnable outputAction = new Runnable()
1788 // todo defer this to inside formatSequences (or later)
1789 AlignmentExportData exportData = viewport
1790 .getAlignExportData(options);
1791 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1792 cap.setForInput(null);
1795 FileFormatI format = fileFormat;
1796 cap.setText(new FormatAdapter(alignPanel, options)
1797 .formatSequences(format, exportData.getAlignment(),
1798 exportData.getOmitHidden(),
1799 exportData.getStartEndPostions(),
1800 viewport.getAlignment().getHiddenColumns()));
1801 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1802 "label.alignment_output_command", new Object[]
1803 { fileFormat.getName() }), 600, 500);
1804 } catch (OutOfMemoryError oom)
1806 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1814 * show dialog with export options if applicable; else just do it
1816 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1818 AlignExportOptions choices = new AlignExportOptions(
1819 alignPanel.getAlignViewport(), fileFormat, options);
1820 choices.setResponseAction(0, outputAction);
1821 choices.showDialog();
1836 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1838 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1839 htmlSVG.exportHTML(null);
1843 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1845 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1846 bjs.exportHTML(null);
1850 public void createImageMap(File file, String image)
1852 alignPanel.makePNGImageMap(file, image);
1856 * Creates a PNG image of the alignment and writes it to the given file. If
1857 * the file is null, the user is prompted to choose a file.
1862 public void createPNG(File f)
1864 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1868 * Creates an EPS image of the alignment and writes it to the given file. If
1869 * the file is null, the user is prompted to choose a file.
1874 public void createEPS(File f)
1876 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1880 * Creates an SVG image of the alignment and writes it to the given file. If
1881 * the file is null, the user is prompted to choose a file.
1886 public void createSVG(File f)
1888 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1892 public void pageSetup_actionPerformed(ActionEvent e)
1894 PrinterJob printJob = PrinterJob.getPrinterJob();
1895 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1905 public void printMenuItem_actionPerformed(ActionEvent e)
1907 // Putting in a thread avoids Swing painting problems
1908 PrintThread thread = new PrintThread(alignPanel);
1913 public void exportFeatures_actionPerformed(ActionEvent e)
1915 new AnnotationExporter(alignPanel).exportFeatures();
1919 public void exportAnnotations_actionPerformed(ActionEvent e)
1921 new AnnotationExporter(alignPanel).exportAnnotations();
1925 public void associatedData_actionPerformed(ActionEvent e)
1926 throws IOException, InterruptedException
1928 final JalviewFileChooser chooser = new JalviewFileChooser(
1929 Cache.getProperty("LAST_DIRECTORY"));
1930 chooser.setFileView(new JalviewFileView());
1931 String tooltip = MessageManager
1932 .getString("label.load_jalview_annotations");
1933 chooser.setDialogTitle(tooltip);
1934 chooser.setToolTipText(tooltip);
1935 chooser.setResponseHandler(0, new Runnable()
1940 String choice = chooser.getSelectedFile().getPath();
1941 Cache.setProperty("LAST_DIRECTORY", choice);
1942 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1946 chooser.showOpenDialog(this);
1950 * Close the current view or all views in the alignment frame. If the frame
1951 * only contains one view then the alignment will be removed from memory.
1953 * @param closeAllTabs
1956 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1958 if (alignPanels != null && alignPanels.size() < 2)
1960 closeAllTabs = true;
1965 if (alignPanels != null)
1969 if (this.isClosed())
1971 // really close all the windows - otherwise wait till
1972 // setClosed(true) is called
1973 for (int i = 0; i < alignPanels.size(); i++)
1975 AlignmentPanel ap = alignPanels.get(i);
1982 closeView(alignPanel);
1987 if (featureSettings != null && featureSettings.isOpen())
1989 featureSettings.close();
1990 featureSettings = null;
1993 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1994 * be called recursively, with the frame now in 'closed' state
1996 this.setClosed(true);
1998 } catch (Exception ex)
2000 ex.printStackTrace();
2005 * Close the specified panel and close up tabs appropriately.
2007 * @param panelToClose
2009 public void closeView(AlignmentPanel panelToClose)
2011 int index = tabbedPane.getSelectedIndex();
2012 int closedindex = tabbedPane.indexOfComponent(panelToClose);
2013 alignPanels.remove(panelToClose);
2014 panelToClose.closePanel();
2015 panelToClose = null;
2017 tabbedPane.removeTabAt(closedindex);
2018 tabbedPane.validate();
2020 if (index > closedindex || index == tabbedPane.getTabCount())
2022 // modify currently selected tab index if necessary.
2026 this.tabSelectionChanged(index);
2032 void updateEditMenuBar()
2035 if (viewport.getHistoryList().size() > 0)
2037 undoMenuItem.setEnabled(true);
2038 CommandI command = viewport.getHistoryList().peek();
2039 undoMenuItem.setText(MessageManager
2040 .formatMessage("label.undo_command", new Object[]
2041 { command.getDescription() }));
2045 undoMenuItem.setEnabled(false);
2046 undoMenuItem.setText(MessageManager.getString("action.undo"));
2049 if (viewport.getRedoList().size() > 0)
2051 redoMenuItem.setEnabled(true);
2053 CommandI command = viewport.getRedoList().peek();
2054 redoMenuItem.setText(MessageManager
2055 .formatMessage("label.redo_command", new Object[]
2056 { command.getDescription() }));
2060 redoMenuItem.setEnabled(false);
2061 redoMenuItem.setText(MessageManager.getString("action.redo"));
2066 public void addHistoryItem(CommandI command)
2068 if (command.getSize() > 0)
2070 viewport.addToHistoryList(command);
2071 viewport.clearRedoList();
2072 updateEditMenuBar();
2073 viewport.updateHiddenColumns();
2074 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
2075 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2076 // viewport.getColumnSelection()
2077 // .getHiddenColumns().size() > 0);
2083 * @return alignment objects for all views
2085 AlignmentI[] getViewAlignments()
2087 if (alignPanels != null)
2089 AlignmentI[] als = new AlignmentI[alignPanels.size()];
2091 for (AlignmentPanel ap : alignPanels)
2093 als[i++] = ap.av.getAlignment();
2097 if (viewport != null)
2099 return new AlignmentI[] { viewport.getAlignment() };
2111 protected void undoMenuItem_actionPerformed(ActionEvent e)
2113 if (viewport.getHistoryList().isEmpty())
2117 CommandI command = viewport.getHistoryList().pop();
2118 viewport.addToRedoList(command);
2119 command.undoCommand(getViewAlignments());
2121 AlignmentViewport originalSource = getOriginatingSource(command);
2122 updateEditMenuBar();
2124 if (originalSource != null)
2126 if (originalSource != viewport)
2129 "Implementation worry: mismatch of viewport origin for undo");
2131 originalSource.updateHiddenColumns();
2132 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
2134 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2135 // viewport.getColumnSelection()
2136 // .getHiddenColumns().size() > 0);
2137 originalSource.notifyAlignment();
2148 protected void redoMenuItem_actionPerformed(ActionEvent e)
2150 if (viewport.getRedoList().size() < 1)
2155 CommandI command = viewport.getRedoList().pop();
2156 viewport.addToHistoryList(command);
2157 command.doCommand(getViewAlignments());
2159 AlignmentViewport originalSource = getOriginatingSource(command);
2160 updateEditMenuBar();
2162 if (originalSource != null)
2165 if (originalSource != viewport)
2168 "Implementation worry: mismatch of viewport origin for redo");
2170 originalSource.updateHiddenColumns();
2171 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
2173 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2174 // viewport.getColumnSelection()
2175 // .getHiddenColumns().size() > 0);
2176 originalSource.notifyAlignment();
2180 AlignmentViewport getOriginatingSource(CommandI command)
2182 AlignmentViewport originalSource = null;
2183 // For sequence removal and addition, we need to fire
2184 // the property change event FROM the viewport where the
2185 // original alignment was altered
2186 AlignmentI al = null;
2187 if (command instanceof EditCommand)
2189 EditCommand editCommand = (EditCommand) command;
2190 al = editCommand.getAlignment();
2191 List<Component> comps = PaintRefresher.components
2192 .get(viewport.getSequenceSetId());
2194 for (Component comp : comps)
2196 if (comp instanceof AlignmentPanel)
2198 if (al == ((AlignmentPanel) comp).av.getAlignment())
2200 originalSource = ((AlignmentPanel) comp).av;
2207 if (originalSource == null)
2209 // The original view is closed, we must validate
2210 // the current view against the closed view first
2213 PaintRefresher.validateSequences(al, viewport.getAlignment());
2216 originalSource = viewport;
2219 return originalSource;
2223 * Calls AlignmentI.moveSelectedSequencesByOne with current sequence selection
2224 * or the sequence under cursor in keyboard mode
2229 public void moveSelectedSequences(boolean up)
2231 SequenceGroup sg = viewport.getSelectionGroup();
2235 if (viewport.cursorMode)
2237 sg = new SequenceGroup();
2238 sg.addSequence(viewport.getAlignment().getSequenceAt(
2239 alignPanel.getSeqPanel().seqCanvas.cursorY), false);
2247 if (sg.getSize() < 1)
2252 // TODO: JAL-3733 - add an event to the undo buffer for this !
2254 viewport.getAlignment().moveSelectedSequencesByOne(sg,
2255 viewport.getHiddenRepSequences(), up);
2256 alignPanel.paintAlignment(true, false);
2259 synchronized void slideSequences(boolean right, int size)
2261 List<SequenceI> sg = new ArrayList<>();
2262 if (viewport.cursorMode)
2264 sg.add(viewport.getAlignment()
2265 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
2267 else if (viewport.getSelectionGroup() != null
2268 && viewport.getSelectionGroup().getSize() != viewport
2269 .getAlignment().getHeight())
2271 sg = viewport.getSelectionGroup()
2272 .getSequences(viewport.getHiddenRepSequences());
2280 List<SequenceI> invertGroup = new ArrayList<>();
2282 for (SequenceI seq : viewport.getAlignment().getSequences())
2284 if (!sg.contains(seq))
2286 invertGroup.add(seq);
2290 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
2292 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
2293 for (int i = 0; i < invertGroup.size(); i++)
2295 seqs2[i] = invertGroup.get(i);
2298 SlideSequencesCommand ssc;
2301 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
2302 viewport.getGapCharacter());
2306 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
2307 viewport.getGapCharacter());
2310 int groupAdjustment = 0;
2311 if (ssc.getGapsInsertedBegin() && right)
2313 if (viewport.cursorMode)
2315 alignPanel.getSeqPanel().moveCursor(size, 0);
2319 groupAdjustment = size;
2322 else if (!ssc.getGapsInsertedBegin() && !right)
2324 if (viewport.cursorMode)
2326 alignPanel.getSeqPanel().moveCursor(-size, 0);
2330 groupAdjustment = -size;
2334 if (groupAdjustment != 0)
2336 viewport.getSelectionGroup().setStartRes(
2337 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
2338 viewport.getSelectionGroup().setEndRes(
2339 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
2343 * just extend the last slide command if compatible; but not if in
2344 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
2346 boolean appendHistoryItem = false;
2347 Deque<CommandI> historyList = viewport.getHistoryList();
2348 boolean inSplitFrame = getSplitViewContainer() != null;
2349 if (!inSplitFrame && historyList != null && historyList.size() > 0
2350 && historyList.peek() instanceof SlideSequencesCommand)
2352 appendHistoryItem = ssc.appendSlideCommand(
2353 (SlideSequencesCommand) historyList.peek());
2356 if (!appendHistoryItem)
2358 addHistoryItem(ssc);
2371 protected void copy_actionPerformed()
2373 if (viewport.getSelectionGroup() == null)
2377 // TODO: preserve the ordering of displayed alignment annotation in any
2378 // internal paste (particularly sequence associated annotation)
2379 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2380 String[] omitHidden = null;
2382 if (viewport.hasHiddenColumns())
2384 omitHidden = viewport.getViewAsString(true);
2387 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2388 seqs, omitHidden, null);
2390 StringSelection ss = new StringSelection(output);
2392 Desktop d = Desktop.getInstance();
2395 d.internalCopy = true;
2396 // Its really worth setting the clipboard contents
2397 // to empty before setting the large StringSelection!!
2398 Toolkit.getDefaultToolkit().getSystemClipboard()
2399 .setContents(new StringSelection(""), null);
2401 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2403 } catch (OutOfMemoryError er)
2405 new OOMWarning("copying region", er);
2409 HiddenColumns hiddenColumns = null;
2410 if (viewport.hasHiddenColumns())
2412 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2413 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2415 // create new HiddenColumns object with copy of hidden regions
2416 // between startRes and endRes, offset by startRes
2417 hiddenColumns = new HiddenColumns(
2418 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2419 hiddenCutoff, hiddenOffset);
2422 d.jalviewClipboard = new Object[] { seqs,
2423 viewport.getAlignment().getDataset(), hiddenColumns };
2424 setStatus(MessageManager.formatMessage(
2425 "label.copied_sequences_to_clipboard", new Object[]
2426 { Integer.valueOf(seqs.length).toString() }));
2434 * @throws InterruptedException
2435 * @throws IOException
2438 protected void pasteNew_actionPerformed(ActionEvent e)
2439 throws IOException, InterruptedException
2449 * @throws InterruptedException
2450 * @throws IOException
2453 protected void pasteThis_actionPerformed(ActionEvent e)
2454 throws IOException, InterruptedException
2460 * Paste contents of Jalview clipboard
2462 * @param newAlignment
2463 * true to paste to a new alignment, otherwise add to this.
2464 * @throws InterruptedException
2465 * @throws IOException
2467 void paste(boolean newAlignment) throws IOException, InterruptedException
2469 boolean externalPaste = true;
2472 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2473 Transferable contents = c.getContents(this);
2475 if (contents == null)
2484 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2485 if (str.length() < 1)
2490 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2492 } catch (OutOfMemoryError er)
2494 new OOMWarning("Out of memory pasting sequences!!", er);
2498 SequenceI[] sequences;
2499 boolean annotationAdded = false;
2500 AlignmentI alignment = null;
2502 Desktop d = Desktop.getInstance();
2504 if (d.jalviewClipboard != null)
2506 // The clipboard was filled from within Jalview, we must use the
2508 // And dataset from the copied alignment
2509 SequenceI[] newseq = (SequenceI[]) d.jalviewClipboard[0];
2510 // be doubly sure that we create *new* sequence objects.
2511 sequences = new SequenceI[newseq.length];
2512 for (int i = 0; i < newseq.length; i++)
2514 sequences[i] = new Sequence(newseq[i]);
2516 alignment = new Alignment(sequences);
2517 externalPaste = false;
2521 // parse the clipboard as an alignment.
2522 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2524 sequences = alignment.getSequencesArray();
2528 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2534 if (d.jalviewClipboard != null)
2536 // dataset is inherited
2537 alignment.setDataset((Alignment) d.jalviewClipboard[1]);
2541 // new dataset is constructed
2542 alignment.setDataset(null);
2544 alwidth = alignment.getWidth() + 1;
2548 AlignmentI pastedal = alignment; // preserve pasted alignment object
2549 // Add pasted sequences and dataset into existing alignment.
2550 alignment = viewport.getAlignment();
2551 alwidth = alignment.getWidth() + 1;
2552 // decide if we need to import sequences from an existing dataset
2553 boolean importDs = d.jalviewClipboard != null
2554 && d.jalviewClipboard[1] != alignment.getDataset();
2555 // importDs==true instructs us to copy over new dataset sequences from
2556 // an existing alignment
2557 Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2559 // minimum dataset set
2561 for (int i = 0; i < sequences.length; i++)
2565 newDs.addElement(null);
2567 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2569 if (importDs && ds != null)
2571 if (!newDs.contains(ds))
2573 newDs.setElementAt(ds, i);
2574 ds = new Sequence(ds);
2575 // update with new dataset sequence
2576 sequences[i].setDatasetSequence(ds);
2580 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2585 // copy and derive new dataset sequence
2586 sequences[i] = sequences[i].deriveSequence();
2587 alignment.getDataset()
2588 .addSequence(sequences[i].getDatasetSequence());
2589 // TODO: avoid creation of duplicate dataset sequences with a
2590 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2592 alignment.addSequence(sequences[i]); // merges dataset
2596 newDs.clear(); // tidy up
2598 if (alignment.getAlignmentAnnotation() != null)
2600 for (AlignmentAnnotation alan : alignment
2601 .getAlignmentAnnotation())
2603 if (alan.graphGroup > fgroup)
2605 fgroup = alan.graphGroup;
2609 if (pastedal.getAlignmentAnnotation() != null)
2611 // Add any annotation attached to alignment.
2612 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2613 for (int i = 0; i < alann.length; i++)
2615 annotationAdded = true;
2616 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2618 AlignmentAnnotation newann = new AlignmentAnnotation(
2620 if (newann.graphGroup > -1)
2622 if (newGraphGroups.size() <= newann.graphGroup
2623 || newGraphGroups.get(newann.graphGroup) == null)
2625 for (int q = newGraphGroups
2626 .size(); q <= newann.graphGroup; q++)
2628 newGraphGroups.add(q, null);
2630 newGraphGroups.set(newann.graphGroup,
2631 Integer.valueOf(++fgroup));
2633 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2637 newann.padAnnotation(alwidth);
2638 alignment.addAnnotation(newann);
2648 addHistoryItem(new EditCommand(
2649 MessageManager.getString("label.add_sequences"),
2650 Action.PASTE, sequences, 0, alignment.getWidth(),
2653 // Add any annotations attached to sequences
2654 for (int i = 0; i < sequences.length; i++)
2656 if (sequences[i].getAnnotation() != null)
2658 AlignmentAnnotation newann;
2659 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2661 annotationAdded = true;
2662 newann = sequences[i].getAnnotation()[a];
2663 newann.adjustForAlignment();
2664 newann.padAnnotation(alwidth);
2665 if (newann.graphGroup > -1)
2667 if (newann.graphGroup > -1)
2669 if (newGraphGroups.size() <= newann.graphGroup
2670 || newGraphGroups.get(newann.graphGroup) == null)
2672 for (int q = newGraphGroups
2673 .size(); q <= newann.graphGroup; q++)
2675 newGraphGroups.add(q, null);
2677 newGraphGroups.set(newann.graphGroup,
2678 Integer.valueOf(++fgroup));
2680 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2684 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2688 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2696 // propagate alignment changed.
2697 viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2698 if (annotationAdded)
2700 // Duplicate sequence annotation in all views.
2701 AlignmentI[] alview = this.getViewAlignments();
2702 for (int i = 0; i < sequences.length; i++)
2704 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2709 for (int avnum = 0; avnum < alview.length; avnum++)
2711 if (alview[avnum] != alignment)
2713 // duplicate in a view other than the one with input focus
2714 int avwidth = alview[avnum].getWidth() + 1;
2715 // this relies on sann being preserved after we
2716 // modify the sequence's annotation array for each duplication
2717 for (int a = 0; a < sann.length; a++)
2719 AlignmentAnnotation newann = new AlignmentAnnotation(
2721 sequences[i].addAlignmentAnnotation(newann);
2722 newann.padAnnotation(avwidth);
2723 alview[avnum].addAnnotation(newann); // annotation was
2724 // duplicated earlier
2725 // TODO JAL-1145 graphGroups are not updated for sequence
2726 // annotation added to several views. This may cause
2728 alview[avnum].setAnnotationIndex(newann, a);
2733 buildSortByAnnotationScoresMenu();
2735 viewport.notifyAlignment();
2736 if (alignPanels != null)
2738 for (AlignmentPanel ap : alignPanels)
2740 ap.validateAnnotationDimensions(false);
2745 alignPanel.validateAnnotationDimensions(false);
2751 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2753 String newtitle = new String("Copied sequences");
2755 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2757 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2758 af.viewport.setHiddenColumns(hc);
2761 // >>>This is a fix for the moment, until a better solution is
2763 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2764 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2765 .getFeatureRenderer());
2767 // TODO: maintain provenance of an alignment, rather than just make the
2768 // title a concatenation of operations.
2771 if (title.startsWith("Copied sequences"))
2777 newtitle = newtitle.concat("- from " + title);
2782 newtitle = new String("Pasted sequences");
2785 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2790 } catch (Exception ex)
2792 ex.printStackTrace();
2793 System.out.println("Exception whilst pasting: " + ex);
2794 // could be anything being pasted in here
2800 protected void expand_newalign(ActionEvent e)
2804 AlignmentI alignment = AlignmentUtils
2805 .expandContext(getViewport().getAlignment(), -1);
2806 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2808 String newtitle = new String("Flanking alignment");
2810 Desktop d = Desktop.getInstance();
2811 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2813 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2814 af.viewport.setHiddenColumns(hc);
2817 // >>>This is a fix for the moment, until a better solution is
2819 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2820 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2821 .getFeatureRenderer());
2823 // TODO: maintain provenance of an alignment, rather than just make the
2824 // title a concatenation of operations.
2826 if (title.startsWith("Copied sequences"))
2832 newtitle = newtitle.concat("- from " + title);
2836 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2838 } catch (Exception ex)
2840 ex.printStackTrace();
2841 System.out.println("Exception whilst pasting: " + ex);
2842 // could be anything being pasted in here
2843 } catch (OutOfMemoryError oom)
2845 new OOMWarning("Viewing flanking region of alignment", oom);
2850 * Action Cut (delete and copy) the selected region
2853 protected void cut_actionPerformed()
2855 copy_actionPerformed();
2856 delete_actionPerformed();
2860 * Performs menu option to Delete the currently selected region
2863 protected void delete_actionPerformed()
2866 SequenceGroup sg = viewport.getSelectionGroup();
2872 Runnable okAction = new Runnable()
2877 SequenceI[] cut = sg.getSequences()
2878 .toArray(new SequenceI[sg.getSize()]);
2880 addHistoryItem(new EditCommand(
2881 MessageManager.getString("label.cut_sequences"), Action.CUT,
2882 cut, sg.getStartRes(),
2883 sg.getEndRes() - sg.getStartRes() + 1,
2884 viewport.getAlignment()));
2886 viewport.setSelectionGroup(null);
2887 viewport.sendSelection();
2888 viewport.getAlignment().deleteGroup(sg);
2890 viewport.notifyAlignment();
2891 if (viewport.getAlignment().getHeight() < 1)
2895 AlignFrame.this.setClosed(true);
2896 } catch (Exception ex)
2906 * If the cut affects all sequences, prompt for confirmation
2908 boolean wholeHeight = sg.getSize() == viewport.getAlignment()
2910 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2911 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2912 if (wholeHeight && wholeWidth)
2914 JvOptionPane dialog = JvOptionPane
2915 .newOptionDialog(Desktop.getDesktopPane());
2916 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2917 Object[] options = new Object[] {
2918 MessageManager.getString("action.ok"),
2919 MessageManager.getString("action.cancel") };
2920 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2921 MessageManager.getString("label.delete_all"),
2922 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2923 options, options[0]);
2938 protected void deleteGroups_actionPerformed(ActionEvent e)
2940 if (avc.deleteGroups())
2942 updateAll(viewport.getSequenceSetId());
2946 private void updateAll(String id)
2950 // this will force a non-fast repaint of both the IdPanel and SeqPanel
2951 alignPanel.getIdPanel().getIdCanvas().setNoFastPaint();
2952 alignPanel.getSeqPanel().seqCanvas.setNoFastPaint();
2953 alignPanel.repaint();
2958 PaintRefresher.Refresh(this, id);
2959 alignPanel.paintAlignment(true, true);
2961 alignPanel.updateAnnotation();
2971 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2973 alignPanel.selectAllSequences();
2983 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2985 alignPanel.deselectAllSequences();
2995 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2997 SequenceGroup sg = viewport.getSelectionGroup();
3001 alignPanel.selectAllSequences();
3006 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
3008 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
3010 // JAL-2034 - should delegate to
3011 // alignPanel to decide if overview needs
3014 alignPanel.paintAlignment(true, false);
3015 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
3016 viewport.sendSelection();
3020 public void invertColSel_actionPerformed(ActionEvent e)
3022 viewport.invertColumnSelection();
3023 alignPanel.paintAlignment(true, false);
3024 viewport.sendSelection();
3034 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
3036 trimAlignment(true);
3046 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
3048 trimAlignment(false);
3051 void trimAlignment(boolean trimLeft)
3053 ColumnSelection colSel = viewport.getColumnSelection();
3056 if (!colSel.isEmpty())
3060 column = colSel.getMin();
3064 column = colSel.getMax();
3068 if (viewport.getSelectionGroup() != null)
3070 seqs = viewport.getSelectionGroup()
3071 .getSequencesAsArray(viewport.getHiddenRepSequences());
3075 seqs = viewport.getAlignment().getSequencesArray();
3078 TrimRegionCommand trimRegion;
3081 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
3082 column, viewport.getAlignment());
3083 viewport.getRanges().setStartRes(0);
3087 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
3088 column, viewport.getAlignment());
3091 setStatus(MessageManager.formatMessage("label.removed_columns",
3093 { Integer.valueOf(trimRegion.getSize()).toString() }));
3095 addHistoryItem(trimRegion);
3097 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3099 if ((trimLeft && !sg.adjustForRemoveLeft(column))
3100 || (!trimLeft && !sg.adjustForRemoveRight(column)))
3102 viewport.getAlignment().deleteGroup(sg);
3106 viewport.notifyAlignment();
3117 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
3119 int start = 0, end = viewport.getAlignment().getWidth() - 1;
3122 if (viewport.getSelectionGroup() != null)
3124 seqs = viewport.getSelectionGroup()
3125 .getSequencesAsArray(viewport.getHiddenRepSequences());
3126 start = viewport.getSelectionGroup().getStartRes();
3127 end = viewport.getSelectionGroup().getEndRes();
3131 seqs = viewport.getAlignment().getSequencesArray();
3134 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
3135 "Remove Gapped Columns", seqs, start, end,
3136 viewport.getAlignment());
3138 addHistoryItem(removeGapCols);
3140 setStatus(MessageManager.formatMessage("label.removed_empty_columns",
3142 { Integer.valueOf(removeGapCols.getSize()).toString() }));
3144 // This is to maintain viewport position on first residue
3145 // of first sequence
3146 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3147 ViewportRanges ranges = viewport.getRanges();
3148 int startRes = seq.findPosition(ranges.getStartRes());
3149 // ShiftList shifts;
3150 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
3151 // edit.alColumnChanges=shifts.getInverse();
3152 // if (viewport.hasHiddenColumns)
3153 // viewport.getColumnSelection().compensateForEdits(shifts);
3154 ranges.setStartRes(seq.findIndex(startRes) - 1);
3155 viewport.notifyAlignment();
3166 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
3168 int start = 0, end = viewport.getAlignment().getWidth() - 1;
3171 if (viewport.getSelectionGroup() != null)
3173 seqs = viewport.getSelectionGroup()
3174 .getSequencesAsArray(viewport.getHiddenRepSequences());
3175 start = viewport.getSelectionGroup().getStartRes();
3176 end = viewport.getSelectionGroup().getEndRes();
3180 seqs = viewport.getAlignment().getSequencesArray();
3183 // This is to maintain viewport position on first residue
3184 // of first sequence
3185 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3186 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
3188 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
3189 viewport.getAlignment()));
3191 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
3193 viewport.notifyAlignment();
3204 public void padGapsMenuitem_actionPerformed(ActionEvent e)
3206 viewport.setPadGaps(padGapsMenuitem.isSelected());
3207 viewport.notifyAlignment();
3211 * Opens a Finder dialog
3216 public void findMenuItem_actionPerformed(ActionEvent e)
3218 new Finder(alignPanel, false, null);
3222 * Create a new view of the current alignment.
3225 public void newView_actionPerformed(ActionEvent e)
3227 newView(null, true);
3231 * Creates and shows a new view of the current alignment.
3234 * title of newly created view; if null, one will be generated
3235 * @param copyAnnotation
3236 * if true then duplicate all annnotation, groups and settings
3237 * @return new alignment panel, already displayed.
3239 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
3242 * Create a new AlignmentPanel (with its own, new Viewport)
3244 AlignmentPanel newap = new jalview.project.Jalview2XML()
3245 .copyAlignPanel(alignPanel);
3246 if (!copyAnnotation)
3249 * remove all groups and annotation except for the automatic stuff
3251 newap.av.getAlignment().deleteAllGroups();
3252 newap.av.getAlignment().deleteAllAnnotations(false);
3255 newap.av.setGatherViewsHere(false);
3257 if (viewport.getViewName() == null)
3259 viewport.setViewName(
3260 MessageManager.getString("label.view_name_original"));
3264 * Views share the same edits undo and redo stacks
3266 newap.av.setHistoryList(viewport.getHistoryList());
3267 newap.av.setRedoList(viewport.getRedoList());
3270 * copy any visualisation settings that are not saved in the project
3272 newap.av.setColourAppliesToAllGroups(
3273 viewport.getColourAppliesToAllGroups());
3276 * Views share the same mappings; need to deregister any new mappings
3277 * created by copyAlignPanel, and register the new reference to the shared
3280 newap.av.replaceMappings(viewport.getAlignment());
3283 * start up cDNA consensus (if applicable) now mappings are in place
3285 if (newap.av.initComplementConsensus())
3287 newap.refresh(true); // adjust layout of annotations
3290 newap.av.setViewName(getNewViewName(viewTitle));
3292 addAlignmentPanel(newap, true);
3293 newap.alignmentChanged();
3295 if (alignPanels.size() == 2)
3297 viewport.setGatherViewsHere(true);
3299 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
3304 * Make a new name for the view, ensuring it is unique within the current
3305 * sequenceSetId. (This used to be essential for Jalview Project archives, but
3306 * these now use viewId. Unique view names are still desirable for usability.)
3311 protected String getNewViewName(String viewTitle)
3313 int index = Desktop.getViewCount(viewport.getSequenceSetId());
3314 boolean addFirstIndex = false;
3315 if (viewTitle == null || viewTitle.trim().length() == 0)
3317 viewTitle = MessageManager.getString("action.view");
3318 addFirstIndex = true;
3322 index = 1;// we count from 1 if given a specific name
3324 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
3326 List<Component> comps = PaintRefresher.components
3327 .get(viewport.getSequenceSetId());
3329 List<String> existingNames = getExistingViewNames(comps);
3331 while (existingNames.contains(newViewName))
3333 newViewName = viewTitle + " " + (++index);
3339 * Returns a list of distinct view names found in the given list of
3340 * components. View names are held on the viewport of an AlignmentPanel.
3345 protected List<String> getExistingViewNames(List<Component> comps)
3347 List<String> existingNames = new ArrayList<>();
3348 for (Component comp : comps)
3350 if (comp instanceof AlignmentPanel)
3352 AlignmentPanel ap = (AlignmentPanel) comp;
3353 if (!existingNames.contains(ap.av.getViewName()))
3355 existingNames.add(ap.av.getViewName());
3359 return existingNames;
3363 * Explode tabbed views into separate windows.
3366 public void expandViews_actionPerformed(ActionEvent e)
3368 Desktop.explodeViews(this);
3372 * Gather views in separate windows back into a tabbed presentation.
3375 public void gatherViews_actionPerformed(ActionEvent e)
3377 Desktop.getInstance().gatherViews(this);
3387 public void font_actionPerformed(ActionEvent e)
3389 new FontChooser(alignPanel);
3399 protected void seqLimit_actionPerformed(ActionEvent e)
3401 viewport.setShowJVSuffix(seqLimits.isSelected());
3403 alignPanel.getIdPanel().getIdCanvas()
3404 .setPreferredSize(alignPanel.calculateIdWidth());
3405 alignPanel.paintAlignment(true, false);
3409 public void idRightAlign_actionPerformed(ActionEvent e)
3411 viewport.setRightAlignIds(idRightAlign.isSelected());
3412 alignPanel.paintAlignment(false, false);
3416 public void centreColumnLabels_actionPerformed(ActionEvent e)
3418 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3419 alignPanel.paintAlignment(false, false);
3425 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3428 protected void followHighlight_actionPerformed()
3431 * Set the 'follow' flag on the Viewport (and scroll to position if now
3434 final boolean state = this.followHighlightMenuItem.getState();
3435 viewport.setFollowHighlight(state);
3438 alignPanel.scrollToPosition(viewport.getSearchResults());
3449 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3451 viewport.setColourText(colourTextMenuItem.isSelected());
3452 alignPanel.paintAlignment(false, false);
3462 public void wrapMenuItem_actionPerformed(ActionEvent e)
3464 scaleAbove.setVisible(wrapMenuItem.isSelected());
3465 scaleLeft.setVisible(wrapMenuItem.isSelected());
3466 scaleRight.setVisible(wrapMenuItem.isSelected());
3467 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3468 alignPanel.updateLayout();
3472 public void showAllSeqs_actionPerformed(ActionEvent e)
3474 viewport.showAllHiddenSeqs();
3478 public void showAllColumns_actionPerformed(ActionEvent e)
3480 viewport.showAllHiddenColumns();
3481 alignPanel.paintAlignment(true, true);
3482 viewport.sendSelection();
3486 public void hideSelSequences_actionPerformed(ActionEvent e)
3488 viewport.hideAllSelectedSeqs();
3492 * called by key handler and the hide all/show all menu items
3497 protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3500 boolean hide = false;
3501 SequenceGroup sg = viewport.getSelectionGroup();
3502 if (!toggleSeqs && !toggleCols)
3504 // Hide everything by the current selection - this is a hack - we do the
3505 // invert and then hide
3506 // first check that there will be visible columns after the invert.
3507 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3508 && sg.getStartRes() <= sg.getEndRes()))
3510 // now invert the sequence set, if required - empty selection implies
3511 // that no hiding is required.
3514 invertSequenceMenuItem_actionPerformed(null);
3515 sg = viewport.getSelectionGroup();
3519 viewport.expandColSelection(sg, true);
3520 // finally invert the column selection and get the new sequence
3522 invertColSel_actionPerformed(null);
3529 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3531 hideSelSequences_actionPerformed(null);
3534 else if (!(toggleCols && viewport.hasSelectedColumns()))
3536 showAllSeqs_actionPerformed(null);
3542 if (viewport.hasSelectedColumns())
3544 hideSelColumns_actionPerformed(null);
3547 viewport.setSelectionGroup(sg);
3552 showAllColumns_actionPerformed(null);
3561 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3562 * event.ActionEvent)
3565 public void hideAllButSelection_actionPerformed(ActionEvent e)
3567 toggleHiddenRegions(false, false);
3568 viewport.sendSelection();
3575 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3579 public void hideAllSelection_actionPerformed(ActionEvent e)
3581 SequenceGroup sg = viewport.getSelectionGroup();
3582 viewport.expandColSelection(sg, false);
3583 viewport.hideAllSelectedSeqs();
3584 viewport.hideSelectedColumns();
3585 alignPanel.updateLayout();
3586 alignPanel.paintAlignment(true, true);
3587 viewport.sendSelection();
3594 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3598 public void showAllhidden_actionPerformed(ActionEvent e)
3600 viewport.showAllHiddenColumns();
3601 viewport.showAllHiddenSeqs();
3602 alignPanel.paintAlignment(true, true);
3603 viewport.sendSelection();
3607 public void hideSelColumns_actionPerformed(ActionEvent e)
3609 viewport.hideSelectedColumns();
3610 alignPanel.updateLayout();
3611 alignPanel.paintAlignment(true, true);
3612 viewport.sendSelection();
3616 public void hiddenMarkers_actionPerformed(ActionEvent e)
3618 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3629 protected void scaleAbove_actionPerformed(ActionEvent e)
3631 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3632 alignPanel.updateLayout();
3633 alignPanel.paintAlignment(true, false);
3643 protected void scaleLeft_actionPerformed(ActionEvent e)
3645 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3646 alignPanel.updateLayout();
3647 alignPanel.paintAlignment(true, false);
3657 protected void scaleRight_actionPerformed(ActionEvent e)
3659 viewport.setScaleRightWrapped(scaleRight.isSelected());
3660 alignPanel.updateLayout();
3661 alignPanel.paintAlignment(true, false);
3671 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3673 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3674 alignPanel.paintAlignment(false, false);
3684 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3686 viewport.setShowText(viewTextMenuItem.isSelected());
3687 alignPanel.paintAlignment(false, false);
3697 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3699 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3700 alignPanel.paintAlignment(false, false);
3703 public FeatureSettings featureSettings;
3706 public FeatureSettingsControllerI getFeatureSettingsUI()
3708 return featureSettings;
3712 public void featureSettings_actionPerformed(ActionEvent e)
3714 showFeatureSettingsUI();
3718 public FeatureSettingsControllerI showFeatureSettingsUI()
3720 if (featureSettings != null)
3722 featureSettings.closeOldSettings();
3723 featureSettings = null;
3725 if (!showSeqFeatures.isSelected())
3727 // make sure features are actually displayed
3728 showSeqFeatures.setSelected(true);
3729 showSeqFeatures_actionPerformed(null);
3731 featureSettings = new FeatureSettings(this);
3732 return featureSettings;
3736 * Set or clear 'Show Sequence Features'
3742 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3744 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3745 alignPanel.paintAlignment(true, true);
3749 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3750 * the annotations panel as a whole.
3752 * The options to show/hide all annotations should be enabled when the panel
3753 * is shown, and disabled when the panel is hidden.
3758 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3760 final boolean setVisible = annotationPanelMenuItem.isSelected();
3761 viewport.setShowAnnotation(setVisible);
3762 syncAnnotationMenuItems(setVisible);
3763 alignPanel.updateLayout();
3765 SwingUtilities.invokeLater(new Runnable() {
3770 alignPanel.updateScrollBarsFromRanges();
3776 private void syncAnnotationMenuItems(boolean setVisible)
3778 showAllSeqAnnotations.setEnabled(setVisible);
3779 hideAllSeqAnnotations.setEnabled(setVisible);
3780 showAllAlAnnotations.setEnabled(setVisible);
3781 hideAllAlAnnotations.setEnabled(setVisible);
3785 public void alignmentProperties()
3788 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3791 String content = MessageManager.formatMessage("label.html_content",
3793 { contents.toString() });
3796 if (Platform.isJS())
3798 JLabel textLabel = new JLabel();
3799 textLabel.setText(content);
3800 textLabel.setBackground(Color.WHITE);
3802 pane = new JPanel(new BorderLayout());
3803 ((JPanel) pane).setOpaque(true);
3804 pane.setBackground(Color.WHITE);
3805 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3814 JEditorPane editPane = new JEditorPane("text/html", "");
3815 editPane.setEditable(false);
3816 editPane.setText(content);
3820 JInternalFrame frame = new JInternalFrame();
3822 frame.getContentPane().add(new JScrollPane(pane));
3824 Desktop.addInternalFrame(frame, MessageManager
3825 .formatMessage("label.alignment_properties", new Object[]
3826 { getTitle() }), 500, 400);
3836 public void overviewMenuItem_actionPerformed(ActionEvent e)
3838 if (alignPanel.overviewPanel != null)
3843 JInternalFrame frame = new JInternalFrame();
3844 // BH 2019.07.26 we allow for an embedded
3845 // undecorated overview with defined size
3846 frame.setName(Platform.getAppID("overview"));
3848 Dimension dim = Platform.getDimIfEmbedded(frame, -1, -1);
3849 if (dim != null && dim.width == 0)
3851 dim = null; // hidden, not embedded
3853 OverviewPanel overview = new OverviewPanel(alignPanel, dim);
3854 frame.setContentPane(overview);
3857 dim = new Dimension();
3858 // was frame.getSize(), but that is 0,0 at this point;
3862 // we are imbedding, and so we have an undecorated frame
3863 // and we can set the the frame dimensions accordingly.
3865 // allowing for unresizable option using, style="resize:none"
3866 boolean resizable = (Platform.getEmbeddedAttribute(frame,
3867 "resize") != "none");
3868 Desktop.addInternalFrame(frame, MessageManager
3869 .formatMessage("label.overview_params", new Object[]
3870 { this.getTitle() }), Desktop.FRAME_MAKE_VISIBLE, dim.width,
3871 dim.height, resizable, Desktop.FRAME_ALLOW_ANY_SIZE);
3873 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3874 frame.addInternalFrameListener(
3875 new javax.swing.event.InternalFrameAdapter()
3878 public void internalFrameClosed(
3879 javax.swing.event.InternalFrameEvent evt)
3882 alignPanel.setOverviewPanel(null);
3885 if (getKeyListeners().length > 0)
3887 frame.addKeyListener(getKeyListeners()[0]);
3890 alignPanel.setOverviewPanel(overview);
3894 public void textColour_actionPerformed()
3896 new TextColourChooser().chooseColour(alignPanel, null);
3900 * public void covariationColour_actionPerformed() {
3902 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3906 public void annotationColour_actionPerformed()
3908 new AnnotationColourChooser(viewport, alignPanel);
3912 public void annotationColumn_actionPerformed(ActionEvent e)
3914 new AnnotationColumnChooser(viewport, alignPanel);
3918 * Action on the user checking or unchecking the option to apply the selected
3919 * colour scheme to all groups. If unchecked, groups may have their own
3920 * independent colour schemes.
3925 public void applyToAllGroups_actionPerformed(boolean selected)
3927 viewport.setColourAppliesToAllGroups(selected);
3931 * Action on user selecting a colour from the colour menu
3934 * the name (not the menu item label!) of the colour scheme
3937 public void changeColour_actionPerformed(String name)
3940 * 'User Defined' opens a panel to configure or load a
3941 * user-defined colour scheme
3943 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3945 new UserDefinedColours(alignPanel);
3950 * otherwise set the chosen colour scheme (or null for 'None')
3952 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3953 viewport, viewport.getAlignment(),
3954 viewport.getHiddenRepSequences());
3959 * Actions on setting or changing the alignment colour scheme
3964 public void changeColour(ColourSchemeI cs)
3966 // TODO: pull up to controller method
3967 ColourMenuHelper.setColourSelected(colourMenu, cs);
3969 viewport.setGlobalColourScheme(cs);
3971 alignPanel.paintAlignment(true, true);
3975 * Show the PID threshold slider panel
3978 protected void modifyPID_actionPerformed()
3980 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3981 alignPanel.getViewName());
3982 SliderPanel.showPIDSlider();
3986 * Show the Conservation slider panel
3989 protected void modifyConservation_actionPerformed()
3991 SliderPanel.setConservationSlider(alignPanel,
3992 viewport.getResidueShading(), alignPanel.getViewName());
3993 SliderPanel.showConservationSlider();
3997 * Action on selecting or deselecting (Colour) By Conservation
4000 public void conservationMenuItem_actionPerformed(boolean selected)
4002 modifyConservation.setEnabled(selected);
4003 viewport.setConservationSelected(selected);
4004 viewport.getResidueShading().setConservationApplied(selected);
4006 changeColour(viewport.getGlobalColourScheme());
4009 modifyConservation_actionPerformed();
4013 SliderPanel.hideConservationSlider();
4018 * Action on selecting or deselecting (Colour) Above PID Threshold
4021 public void abovePIDThreshold_actionPerformed(boolean selected)
4023 modifyPID.setEnabled(selected);
4024 viewport.setAbovePIDThreshold(selected);
4027 viewport.getResidueShading().setThreshold(0,
4028 viewport.isIgnoreGapsConsensus());
4031 changeColour(viewport.getGlobalColourScheme());
4034 modifyPID_actionPerformed();
4038 SliderPanel.hidePIDSlider();
4049 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
4051 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4052 AlignmentSorter.sortByPID(viewport.getAlignment(),
4053 viewport.getAlignment().getSequenceAt(0));
4054 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
4055 viewport.getAlignment()));
4056 alignPanel.paintAlignment(true, false);
4066 public void sortIDMenuItem_actionPerformed(ActionEvent e)
4068 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4069 AlignmentSorter.sortByID(viewport.getAlignment());
4071 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
4072 alignPanel.paintAlignment(true, false);
4082 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
4084 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4085 AlignmentSorter.sortByLength(viewport.getAlignment());
4086 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
4087 viewport.getAlignment()));
4088 alignPanel.paintAlignment(true, false);
4098 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
4100 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4101 AlignmentSorter.sortByGroup(viewport.getAlignment());
4102 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4103 viewport.getAlignment()));
4105 alignPanel.paintAlignment(true, false);
4109 public void sortEValueMenuItem_actionPerformed(ActionEvent e)
4111 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4112 AlignmentSorter.sortByEValue(viewport.getAlignment());
4113 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4114 viewport.getAlignment()));
4115 alignPanel.paintAlignment(true, false);
4120 public void sortBitScoreMenuItem_actionPerformed(ActionEvent e)
4122 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4123 AlignmentSorter.sortByBitScore(viewport.getAlignment());
4124 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4125 viewport.getAlignment()));
4126 alignPanel.paintAlignment(true, false);
4136 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
4138 new RedundancyPanel(alignPanel, this);
4148 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
4150 if ((viewport.getSelectionGroup() == null)
4151 || (viewport.getSelectionGroup().getSize() < 2))
4153 JvOptionPane.showInternalMessageDialog(this,
4154 MessageManager.getString(
4155 "label.you_must_select_least_two_sequences"),
4156 MessageManager.getString("label.invalid_selection"),
4157 JvOptionPane.WARNING_MESSAGE);
4161 JInternalFrame frame = new JInternalFrame();
4162 frame.setContentPane(new PairwiseAlignPanel(viewport));
4163 Desktop.addInternalFrame(frame,
4164 MessageManager.getString("action.pairwise_alignment"), 600,
4170 public void autoCalculate_actionPerformed(ActionEvent e)
4172 viewport.setAutoCalculateConsensusAndConservation(
4173 autoCalculate.isSelected());
4174 if (viewport.getAutoCalculateConsensusAndConservation())
4176 viewport.notifyAlignment();
4181 public void sortByTreeOption_actionPerformed(ActionEvent e)
4183 viewport.sortByTree = sortByTree.isSelected();
4187 protected void listenToViewSelections_actionPerformed(ActionEvent e)
4189 viewport.followSelection = listenToViewSelections.isSelected();
4193 * Constructs a tree panel and adds it to the desktop
4196 * tree type (NJ or AV)
4198 * name of score model used to compute the tree
4200 * parameters for the distance or similarity calculation
4202 void newTreePanel(String type, String modelName,
4203 SimilarityParamsI options)
4205 String frameTitle = "";
4208 boolean onSelection = false;
4209 if (viewport.getSelectionGroup() != null
4210 && viewport.getSelectionGroup().getSize() > 0)
4212 SequenceGroup sg = viewport.getSelectionGroup();
4214 /* Decide if the selection is a column region */
4215 for (SequenceI _s : sg.getSequences())
4217 if (_s.getLength() < sg.getEndRes())
4219 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4220 MessageManager.getString(
4221 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
4222 MessageManager.getString(
4223 "label.sequences_selection_not_aligned"),
4224 JvOptionPane.WARNING_MESSAGE);
4233 if (viewport.getAlignment().getHeight() < 2)
4239 tp = new TreePanel(alignPanel, type, modelName, options);
4240 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
4242 frameTitle += " from ";
4244 if (viewport.getViewName() != null)
4246 frameTitle += viewport.getViewName() + " of ";
4249 frameTitle += this.title;
4251 Dimension dim = Platform.getDimIfEmbedded(tp, 600, 500);
4252 Desktop.addInternalFrame(tp, frameTitle, dim.width, dim.height);
4263 public void addSortByOrderMenuItem(String title,
4264 final AlignmentOrder order)
4266 final JMenuItem item = new JMenuItem(MessageManager
4267 .formatMessage("action.by_title_param", new Object[]
4270 item.addActionListener(new java.awt.event.ActionListener()
4273 public void actionPerformed(ActionEvent e)
4275 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4277 // TODO: JBPNote - have to map order entries to curent SequenceI
4279 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4281 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
4282 viewport.getAlignment()));
4284 alignPanel.paintAlignment(true, false);
4290 * Add a new sort by annotation score menu item
4293 * the menu to add the option to
4295 * the label used to retrieve scores for each sequence on the
4298 public void addSortByAnnotScoreMenuItem(JMenu sort,
4299 final String scoreLabel)
4301 final JMenuItem item = new JMenuItem(scoreLabel);
4303 item.addActionListener(new java.awt.event.ActionListener()
4306 public void actionPerformed(ActionEvent e)
4308 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4309 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4310 viewport.getAlignment());// ,viewport.getSelectionGroup());
4311 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4312 viewport.getAlignment()));
4313 alignPanel.paintAlignment(true, false);
4319 * last hash for alignment's annotation array - used to minimise cost of
4322 protected int _annotationScoreVectorHash;
4325 * search the alignment and rebuild the sort by annotation score submenu the
4326 * last alignment annotation vector hash is stored to minimize cost of
4327 * rebuilding in subsequence calls.
4331 public void buildSortByAnnotationScoresMenu()
4333 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4338 if (viewport.getAlignment().getAlignmentAnnotation()
4339 .hashCode() == _annotationScoreVectorHash)
4344 sortByAnnotScore.removeAll();
4345 Set<String> scoreSorts = new HashSet<>();
4346 for (SequenceI sqa : viewport.getAlignment().getSequences())
4348 AlignmentAnnotation[] anns = sqa.getAnnotation();
4349 for (int i = 0; anns != null && i < anns.length; i++)
4351 AlignmentAnnotation aa = anns[i];
4352 if (aa != null && aa.hasScore() && aa.sequenceRef != null)
4354 scoreSorts.add(aa.label);
4358 for (String label : scoreSorts)
4360 addSortByAnnotScoreMenuItem(sortByAnnotScore, label);
4362 sortByAnnotScore.setVisible(!scoreSorts.isEmpty());
4364 _annotationScoreVectorHash = viewport.getAlignment()
4365 .getAlignmentAnnotation().hashCode();
4369 * Enable (or, if desired, make visible) the By Tree
4370 * submenu only if it has at least one element (or will have).
4374 protected void enableSortMenuOptions()
4376 List<TreePanel> treePanels = getTreePanels();
4377 sortByTreeMenu.setEnabled(!treePanels.isEmpty());
4381 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4382 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4383 * call. Listeners are added to remove the menu item when the treePanel is
4384 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4388 public void buildTreeSortMenu()
4390 sortByTreeMenu.removeAll();
4392 List<TreePanel> treePanels = getTreePanels();
4394 for (final TreePanel tp : treePanels)
4396 final JMenuItem item = new JMenuItem(tp.getTitle());
4397 item.addActionListener(new java.awt.event.ActionListener()
4400 public void actionPerformed(ActionEvent e)
4402 tp.sortByTree_actionPerformed();
4403 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4408 sortByTreeMenu.add(item);
4412 private List<TreePanel> getTreePanels()
4414 List<Component> comps = PaintRefresher.components
4415 .get(viewport.getSequenceSetId());
4416 List<TreePanel> treePanels = new ArrayList<>();
4417 for (Component comp : comps)
4419 if (comp instanceof TreePanel)
4421 treePanels.add((TreePanel) comp);
4426 public boolean sortBy(AlignmentOrder alorder, String undoname)
4428 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4429 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4430 if (undoname != null)
4432 addHistoryItem(new OrderCommand(undoname, oldOrder,
4433 viewport.getAlignment()));
4435 alignPanel.paintAlignment(true, false);
4440 * Work out whether the whole set of sequences or just the selected set will
4441 * be submitted for multiple alignment.
4444 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4446 // Now, check we have enough sequences
4447 AlignmentView msa = null;
4449 if ((viewport.getSelectionGroup() != null)
4450 && (viewport.getSelectionGroup().getSize() > 1))
4452 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4453 // some common interface!
4455 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4456 * SequenceI[sz = seqs.getSize(false)];
4458 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4459 * seqs.getSequenceAt(i); }
4461 msa = viewport.getAlignmentView(true);
4463 else if (viewport.getSelectionGroup() != null
4464 && viewport.getSelectionGroup().getSize() == 1)
4466 int option = JvOptionPane.showConfirmDialog(this,
4467 MessageManager.getString("warn.oneseq_msainput_selection"),
4468 MessageManager.getString("label.invalid_selection"),
4469 JvOptionPane.OK_CANCEL_OPTION);
4470 if (option == JvOptionPane.OK_OPTION)
4472 msa = viewport.getAlignmentView(false);
4477 msa = viewport.getAlignmentView(false);
4483 * Decides what is submitted to a secondary structure prediction service: the
4484 * first sequence in the alignment, or in the current selection, or, if the
4485 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4486 * region or the whole alignment. (where the first sequence in the set is the
4487 * one that the prediction will be for).
4489 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4491 AlignmentView seqs = null;
4493 if ((viewport.getSelectionGroup() != null)
4494 && (viewport.getSelectionGroup().getSize() > 0))
4496 seqs = viewport.getAlignmentView(true);
4500 seqs = viewport.getAlignmentView(false);
4502 // limit sequences - JBPNote in future - could spawn multiple prediction
4504 // TODO: viewport.getAlignment().isAligned is a global state - the local
4505 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4506 if (!viewport.getAlignment().isAligned(false))
4508 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4509 // TODO: if seqs.getSequences().length>1 then should really have warned
4523 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4525 // Pick the tree file
4526 JalviewFileChooser chooser = new JalviewFileChooser(
4527 Cache.getProperty("LAST_DIRECTORY"));
4528 chooser.setFileView(new JalviewFileView());
4529 chooser.setDialogTitle(
4530 MessageManager.getString("label.select_newick_like_tree_file"));
4531 chooser.setToolTipText(
4532 MessageManager.getString("label.load_tree_file"));
4534 chooser.setResponseHandler(0, new Runnable()
4539 String filePath = chooser.getSelectedFile().getPath();
4540 Cache.setProperty("LAST_DIRECTORY", filePath);
4541 NewickFile fin = null;
4544 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4545 DataSourceType.FILE));
4546 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4547 } catch (Exception ex)
4549 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4552 .getString("label.problem_reading_tree_file"),
4553 JvOptionPane.WARNING_MESSAGE);
4554 ex.printStackTrace();
4556 if (fin != null && fin.hasWarningMessage())
4558 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4559 fin.getWarningMessage(),
4560 MessageManager.getString(
4561 "label.possible_problem_with_tree_file"),
4562 JvOptionPane.WARNING_MESSAGE);
4566 chooser.showOpenDialog(this);
4569 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4571 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4574 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4575 int h, int x, int y)
4577 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4581 * Add a treeviewer for the tree extracted from a Newick file object to the
4582 * current alignment view
4589 * Associated alignment input data (or null)
4598 * @return TreePanel handle
4600 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4601 AlignmentView input, int w, int h, int x, int y)
4603 TreePanel tp = null;
4609 if (nf.getTree() != null)
4611 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4613 Dimension dim = Platform.getDimIfEmbedded(tp, -1, -1);
4616 dim = new Dimension(w, h);
4620 // no offset, either
4623 tp.setSize(dim.width, dim.height);
4627 tp.setLocation(x, y);
4630 Desktop.addInternalFrame(tp, treeTitle, dim.width, dim.height);
4632 } catch (Exception ex)
4634 ex.printStackTrace();
4642 * Schedule the web services menu rebuild to the event dispatch thread.
4644 public void buildWebServicesMenu()
4646 SwingUtilities.invokeLater(() -> {
4647 Console.info("Rebuiling WS menu");
4648 webService.removeAll();
4649 if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
4651 Console.info("Building web service menu for slivka");
4652 SlivkaWSDiscoverer discoverer = SlivkaWSDiscoverer.getInstance();
4653 JMenu submenu = new JMenu("Slivka");
4654 buildWebServicesMenu(discoverer, submenu);
4655 webService.add(submenu);
4657 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4659 WSDiscovererI jws2servs = Jws2Discoverer.getInstance();
4660 JMenu submenu = new JMenu("JABAWS");
4661 buildLegacyWebServicesMenu(submenu);
4662 buildWebServicesMenu(jws2servs, submenu);
4663 webService.add(submenu);
4665 build_fetchdbmenu(webService);
4669 private void buildLegacyWebServicesMenu(JMenu menu)
4671 JMenu secstrmenu = new JMenu("Secondary Structure Prediction");
4672 if (Discoverer.getServices() != null && Discoverer.getServices().size() > 0)
4674 var secstrpred = Discoverer.getServices().get("SecStrPred");
4675 if (secstrpred != null)
4677 for (ext.vamsas.ServiceHandle sh : secstrpred)
4679 var menuProvider = Discoverer.getServiceClient(sh);
4680 menuProvider.attachWSMenuEntry(secstrmenu, this);
4684 menu.add(secstrmenu);
4688 * Constructs the web services menu for the given discoverer under the
4689 * specified menu. This method must be called on the EDT
4692 * the discoverer used to build the menu
4694 * parent component which the elements will be attached to
4696 private void buildWebServicesMenu(WSDiscovererI discoverer, JMenu menu)
4698 if (discoverer.hasServices())
4700 PreferredServiceRegistry.getRegistry().populateWSMenuEntry(
4701 discoverer.getServices(), sv -> buildWebServicesMenu(), menu,
4704 if (discoverer.isRunning())
4706 JMenuItem item = new JMenuItem("Service discovery in progress.");
4707 item.setEnabled(false);
4710 else if (!discoverer.hasServices())
4712 JMenuItem item = new JMenuItem("No services available.");
4713 item.setEnabled(false);
4719 * construct any groupURL type service menu entries.
4723 protected void build_urlServiceMenu(JMenu webService)
4725 // TODO: remove this code when 2.7 is released
4726 // DEBUG - alignmentView
4728 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4729 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4731 * public void actionPerformed(ActionEvent e) {
4732 * jalview.datamodel.AlignmentView
4733 * .testSelectionViews(af.viewport.getAlignment(),
4734 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4736 * }); webService.add(testAlView);
4738 // TODO: refactor to RestClient discoverer and merge menu entries for
4739 // rest-style services with other types of analysis/calculation service
4740 // SHmmr test client - still being implemented.
4741 // DEBUG - alignmentView
4743 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4746 client.attachWSMenuEntry(
4747 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4753 * Searches the alignment sequences for xRefs and builds the Show
4754 * Cross-References menu (formerly called Show Products), with database
4755 * sources for which cross-references are found (protein sources for a
4756 * nucleotide alignment and vice versa)
4758 * @return true if Show Cross-references menu should be enabled
4760 public boolean canShowProducts()
4762 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4763 AlignmentI dataset = viewport.getAlignment().getDataset();
4765 showProducts.removeAll();
4766 final boolean dna = viewport.getAlignment().isNucleotide();
4768 if (seqs == null || seqs.length == 0)
4770 // nothing to see here.
4774 boolean showp = false;
4777 List<String> ptypes = new CrossRef(seqs, dataset)
4778 .findXrefSourcesForSequences(dna);
4780 for (final String source : ptypes)
4783 final AlignFrame af = this;
4784 JMenuItem xtype = new JMenuItem(source);
4785 xtype.addActionListener(new ActionListener()
4788 public void actionPerformed(ActionEvent e)
4790 showProductsFor(af.viewport.getSequenceSelection(), dna,
4794 showProducts.add(xtype);
4796 showProducts.setVisible(showp);
4797 showProducts.setEnabled(showp);
4798 } catch (Exception e)
4801 "canShowProducts threw an exception - please report to help@jalview.org",
4809 * Finds and displays cross-references for the selected sequences (protein
4810 * products for nucleotide sequences, dna coding sequences for peptides).
4813 * the sequences to show cross-references for
4815 * true if from a nucleotide alignment (so showing proteins)
4817 * the database to show cross-references for
4819 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4820 final String source)
4822 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4827 * Construct and display a new frame containing the translation of this
4828 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4831 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4833 AlignmentI al = null;
4836 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4838 al = dna.translateCdna(codeTable);
4839 } catch (Exception ex)
4841 Console.error("Exception during translation. Please report this !",
4843 final String msg = MessageManager.getString(
4844 "label.error_when_translating_sequences_submit_bug_report");
4845 final String errorTitle = MessageManager
4846 .getString("label.implementation_error")
4847 + MessageManager.getString("label.translation_failed");
4848 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4849 errorTitle, JvOptionPane.ERROR_MESSAGE);
4852 if (al == null || al.getHeight() == 0)
4854 final String msg = MessageManager.getString(
4855 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4856 final String errorTitle = MessageManager
4857 .getString("label.translation_failed");
4858 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4859 errorTitle, JvOptionPane.WARNING_MESSAGE);
4863 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4864 af.setFileFormat(this.currentFileFormat);
4865 final String newTitle = MessageManager
4866 .formatMessage("label.translation_of_params", new Object[]
4867 { this.getTitle(), codeTable.getId() });
4868 af.setTitle(newTitle);
4869 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4871 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4872 AlignViewport.openSplitFrame(this, af, new Alignment(seqs));
4876 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4883 * Set the file format
4887 public void setFileFormat(FileFormatI format)
4889 this.currentFileFormat = format;
4893 * Try to load a features file onto the alignment.
4896 * contents or path to retrieve file or a File object
4898 * access mode of file (see jalview.io.AlignFile)
4899 * @return true if features file was parsed correctly.
4901 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4904 return avc.parseFeaturesFile(file, sourceType,
4905 Cache.getDefault(Preferences.RELAXEDSEQIDMATCHING, false));
4910 public void refreshFeatureUI(boolean enableIfNecessary)
4912 // note - currently this is only still here rather than in the controller
4913 // because of the featureSettings hard reference that is yet to be
4915 if (enableIfNecessary)
4917 viewport.setShowSequenceFeatures(true);
4918 showSeqFeatures.setSelected(true);
4924 public void dragEnter(DropTargetDragEvent evt)
4929 public void dragExit(DropTargetEvent evt)
4934 public void dragOver(DropTargetDragEvent evt)
4939 public void dropActionChanged(DropTargetDragEvent evt)
4944 public void drop(DropTargetDropEvent evt)
4946 // JAL-1552 - acceptDrop required before getTransferable call for
4947 // Java's Transferable for native dnd
4948 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4949 Transferable t = evt.getTransferable();
4951 final List<Object> files = new ArrayList<>();
4952 List<DataSourceType> protocols = new ArrayList<>();
4956 Desktop.transferFromDropTarget(files, protocols, evt, t);
4957 if (files.size() > 0)
4959 new Thread(new Runnable()
4965 loadDroppedFiles(files, protocols, evt, t);
4969 } catch (Exception e)
4971 e.printStackTrace();
4975 protected void loadDroppedFiles(List<Object> files,
4976 List<DataSourceType> protocols, DropTargetDropEvent evt,
4981 // check to see if any of these files have names matching sequences
4984 SequenceIdMatcher idm = new SequenceIdMatcher(
4985 viewport.getAlignment().getSequencesArray());
4987 * Object[] { String,SequenceI}
4989 ArrayList<Object[]> filesmatched = new ArrayList<>();
4990 ArrayList<Object> filesnotmatched = new ArrayList<>();
4991 for (int i = 0; i < files.size(); i++)
4994 Object fileObj = files.get(i);
4995 String fileName = fileObj.toString();
4997 DataSourceType protocol = (fileObj instanceof File
4998 ? DataSourceType.FILE
4999 : FormatAdapter.checkProtocol(fileName));
5000 if (protocol == DataSourceType.FILE)
5003 if (fileObj instanceof File)
5005 file = (File) fileObj;
5006 Platform.cacheFileData(file);
5010 file = new File(fileName);
5012 pdbfn = file.getName();
5014 else if (protocol == DataSourceType.URL)
5016 URL url = new URL(fileName);
5017 pdbfn = url.getFile();
5019 if (pdbfn.length() > 0)
5021 // attempt to find a match in the alignment
5022 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5023 int l = 0, c = pdbfn.indexOf(".");
5024 while (mtch == null && c != -1)
5029 } while ((c = pdbfn.indexOf(".", l)) > l);
5032 pdbfn = pdbfn.substring(0, l);
5034 mtch = idm.findAllIdMatches(pdbfn);
5041 type = new IdentifyFile().identify(fileObj, protocol);
5042 } catch (Exception ex)
5046 if (type != null && type.isStructureFile())
5048 filesmatched.add(new Object[] { fileObj, protocol, mtch });
5052 // File wasn't named like one of the sequences or wasn't a PDB
5054 filesnotmatched.add(fileObj);
5058 if (filesmatched.size() > 0)
5060 boolean autoAssociate = Cache
5061 .getDefault(Preferences.AUTOASSOCIATE_PDBANDSEQS, false);
5064 String msg = MessageManager.formatMessage(
5065 "label.automatically_associate_structure_files_with_sequences_same_name",
5067 { Integer.valueOf(filesmatched.size()).toString() });
5068 String ttl = MessageManager.getString(
5069 "label.automatically_associate_structure_files_by_name");
5070 int choice = JvOptionPane.showConfirmDialog(this, msg, ttl,
5071 JvOptionPane.YES_NO_OPTION);
5072 autoAssociate = choice == JvOptionPane.YES_OPTION;
5076 for (Object[] fm : filesmatched)
5078 // try and associate
5079 // TODO: may want to set a standard ID naming formalism for
5080 // associating PDB files which have no IDs.
5081 for (SequenceI toassoc : (SequenceI[]) fm[2])
5083 PDBEntry pe = AssociatePdbFileWithSeq.associatePdbWithSeq(
5084 fm[0].toString(), (DataSourceType) fm[1], toassoc,
5088 System.err.println("Associated file : " + (fm[0].toString())
5089 + " with " + toassoc.getDisplayId(true));
5094 // TODO: do we need to update overview ? only if features are
5096 alignPanel.paintAlignment(true, false);
5102 * add declined structures as sequences
5104 for (Object[] o : filesmatched)
5106 filesnotmatched.add(o[0]);
5110 if (filesnotmatched.size() > 0)
5112 if (assocfiles > 0 && (Cache
5113 .getDefault("AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
5114 || JvOptionPane.showConfirmDialog(this,
5115 "<html>" + MessageManager.formatMessage(
5116 "label.ignore_unmatched_dropped_files_info",
5118 { Integer.valueOf(filesnotmatched.size())
5121 MessageManager.getString(
5122 "label.ignore_unmatched_dropped_files"),
5123 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
5127 for (Object fn : filesnotmatched)
5129 loadJalviewDataFile(fn, null, null, null);
5133 } catch (Exception ex)
5135 ex.printStackTrace();
5140 * Attempt to load a "dropped" file or URL string, by testing in turn for
5142 * <li>an Annotation file</li>
5143 * <li>a JNet file</li>
5144 * <li>a features file</li>
5145 * <li>else try to interpret as an alignment file</li>
5149 * either a filename or a URL string.
5150 * @throws InterruptedException
5151 * @throws IOException
5153 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
5154 FileFormatI format, SequenceI assocSeq)
5156 // BH 2018 was String file
5159 if (sourceType == null)
5161 sourceType = FormatAdapter.checkProtocol(file);
5163 // if the file isn't identified, or not positively identified as some
5164 // other filetype (PFAM is default unidentified alignment file type) then
5165 // try to parse as annotation.
5166 boolean isAnnotation = (format == null
5167 || FileFormat.Pfam.equals(format))
5168 ? new AnnotationFile().annotateAlignmentView(viewport,
5174 // first see if its a T-COFFEE score file
5175 TCoffeeScoreFile tcf = null;
5178 tcf = new TCoffeeScoreFile(file, sourceType);
5181 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5185 new TCoffeeColourScheme(viewport.getAlignment()));
5186 isAnnotation = true;
5187 setStatus(MessageManager.getString(
5188 "label.successfully_pasted_tcoffee_scores_to_alignment"));
5192 // some problem - if no warning its probable that the ID matching
5193 // process didn't work
5194 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
5195 tcf.getWarningMessage() == null
5196 ? MessageManager.getString(
5197 "label.check_file_matches_sequence_ids_alignment")
5198 : tcf.getWarningMessage(),
5199 MessageManager.getString(
5200 "label.problem_reading_tcoffee_score_file"),
5201 JvOptionPane.WARNING_MESSAGE);
5208 } catch (Exception x)
5211 "Exception when processing data source as T-COFFEE score file",
5217 // try to see if its a JNet 'concise' style annotation file *before*
5219 // try to parse it as a features file
5222 format = new IdentifyFile().identify(file, sourceType);
5224 if (FileFormat.ScoreMatrix == format)
5226 ScoreMatrixFile sm = new ScoreMatrixFile(
5227 new FileParse(file, sourceType));
5229 // todo: i18n this message
5230 setStatus(MessageManager.formatMessage(
5231 "label.successfully_loaded_matrix",
5232 sm.getMatrixName()));
5234 else if (FileFormat.Jnet.equals(format))
5236 JPredFile predictions = new JPredFile(file, sourceType);
5237 new JnetAnnotationMaker();
5238 JnetAnnotationMaker.add_annotation(predictions,
5239 viewport.getAlignment(), 0, false);
5240 viewport.getAlignment().setupJPredAlignment();
5241 isAnnotation = true;
5243 // else if (IdentifyFile.FeaturesFile.equals(format))
5244 else if (FileFormat.Features.equals(format))
5246 if (parseFeaturesFile(file, sourceType))
5248 SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
5249 if (splitFrame != null)
5251 splitFrame.repaint();
5255 alignPanel.paintAlignment(true, true);
5261 new FileLoader().LoadFile(viewport, file, sourceType, format);
5268 updateForAnnotations();
5270 } catch (Exception ex)
5272 ex.printStackTrace();
5273 } catch (OutOfMemoryError oom)
5278 } catch (Exception x)
5283 + (sourceType != null
5284 ? (sourceType == DataSourceType.PASTE
5286 : "using " + sourceType + " from "
5290 ? "(parsing as '" + format + "' file)"
5292 oom, Desktop.getDesktopPane());
5297 * Do all updates necessary after an annotation file such as jnet. Also called
5298 * from Jalview.loadAppletParams for "annotations", "jnetFile"
5301 public void updateForAnnotations()
5303 alignPanel.adjustAnnotationHeight();
5304 viewport.updateSequenceIdColours();
5305 buildSortByAnnotationScoresMenu();
5306 alignPanel.paintAlignment(true, true);
5310 * Change the display state for the given feature groups -- Added by BH from
5314 * list of group strings
5316 * visible or invisible
5319 public void setFeatureGroupState(String[] groups, boolean state)
5321 jalview.api.FeatureRenderer fr = null;
5322 viewport.setShowSequenceFeatures(true);
5323 if (alignPanel != null
5324 && (fr = alignPanel.getFeatureRenderer()) != null)
5327 fr.setGroupVisibility(Arrays.asList(groups), state);
5328 alignPanel.getSeqPanel().seqCanvas.repaint();
5329 if (alignPanel.overviewPanel != null)
5331 alignPanel.overviewPanel.updateOverviewImage();
5337 * Method invoked by the ChangeListener on the tabbed pane, in other words
5338 * when a different tabbed pane is selected by the user or programmatically.
5341 public void tabSelectionChanged(int index)
5345 alignPanel = alignPanels.get(index);
5346 viewport = alignPanel.av;
5347 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5348 setMenusFromViewport(viewport);
5349 if (featureSettings != null && featureSettings.isOpen()
5350 && featureSettings.fr.getViewport() != viewport)
5352 if (viewport.isShowSequenceFeatures())
5354 // refresh the featureSettings to reflect UI change
5355 showFeatureSettingsUI();
5359 // close feature settings for this view.
5360 featureSettings.close();
5367 * 'focus' any colour slider that is open to the selected viewport
5369 if (viewport.getConservationSelected())
5371 SliderPanel.setConservationSlider(alignPanel,
5372 viewport.getResidueShading(), alignPanel.getViewName());
5376 SliderPanel.hideConservationSlider();
5378 if (viewport.getAbovePIDThreshold())
5380 SliderPanel.setPIDSliderSource(alignPanel,
5381 viewport.getResidueShading(), alignPanel.getViewName());
5385 SliderPanel.hidePIDSlider();
5389 * If there is a frame linked to this one in a SplitPane, switch it to the
5390 * same view tab index. No infinite recursion of calls should happen, since
5391 * tabSelectionChanged() should not get invoked on setting the selected
5392 * index to an unchanged value. Guard against setting an invalid index
5393 * before the new view peer tab has been created.
5395 final AlignViewportI peer = viewport.getCodingComplement();
5398 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
5399 .getAlignPanel().alignFrame;
5400 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5402 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5408 * On right mouse click on view tab, prompt for and set new view name.
5411 public void tabbedPane_mousePressed(MouseEvent e)
5413 if (e.isPopupTrigger())
5415 String msg = MessageManager.getString("label.enter_view_name");
5416 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
5417 String reply = JvOptionPane.showInputDialog(msg, ttl);
5421 viewport.setViewName(reply);
5422 // TODO warn if reply is in getExistingViewNames()?
5423 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5428 public AlignViewport getCurrentView()
5434 * Open the dialog for regex description parsing.
5437 protected void extractScores_actionPerformed(ActionEvent e)
5439 ParseProperties pp = new jalview.analysis.ParseProperties(
5440 viewport.getAlignment());
5441 // TODO: verify regex and introduce GUI dialog for version 2.5
5442 // if (pp.getScoresFromDescription("col", "score column ",
5443 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5445 if (pp.getScoresFromDescription("description column",
5446 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5448 buildSortByAnnotationScoresMenu();
5456 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5460 protected void showDbRefs_actionPerformed(ActionEvent e)
5462 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5468 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5472 protected void showNpFeats_actionPerformed(ActionEvent e)
5474 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5478 * find the viewport amongst the tabs in this alignment frame and close that
5483 public boolean closeView(AlignViewportI av)
5487 this.closeMenuItem_actionPerformed(false);
5490 Component[] comp = tabbedPane.getComponents();
5491 for (int i = 0; comp != null && i < comp.length; i++)
5493 if (comp[i] instanceof AlignmentPanel)
5495 if (((AlignmentPanel) comp[i]).av == av)
5498 closeView((AlignmentPanel) comp[i]);
5506 protected void build_fetchdbmenu(JMenu webService)
5508 // Temporary hack - DBRef Fetcher always top level ws entry.
5509 // TODO We probably want to store a sequence database checklist in
5510 // preferences and have checkboxes.. rather than individual sources selected
5512 final JMenu rfetch = new JMenu(
5513 MessageManager.getString("action.fetch_db_references"));
5514 rfetch.setToolTipText(MessageManager.getString(
5515 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5516 webService.add(rfetch);
5518 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5519 MessageManager.getString("option.trim_retrieved_seqs"));
5520 trimrs.setToolTipText(
5521 MessageManager.getString("label.trim_retrieved_sequences"));
5523 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5524 trimrs.addActionListener(new ActionListener()
5527 public void actionPerformed(ActionEvent e)
5529 trimrs.setSelected(trimrs.isSelected());
5530 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5531 Boolean.valueOf(trimrs.isSelected()).toString());
5535 JMenuItem fetchr = new JMenuItem(
5536 MessageManager.getString("label.standard_databases"));
5537 fetchr.setToolTipText(
5538 MessageManager.getString("label.fetch_embl_uniprot"));
5539 fetchr.addActionListener(new ActionListener()
5543 public void actionPerformed(ActionEvent e)
5545 new Thread(new Runnable()
5550 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5551 .getAlignment().isNucleotide();
5552 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5553 alignPanel.av.getSequenceSelection(),
5554 alignPanel.alignFrame, null,
5555 alignPanel.alignFrame.featureSettings, isNucleotide);
5556 dbRefFetcher.addListener(new FetchFinishedListenerI()
5559 public void finished()
5562 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5563 .getFeatureSettingsModels())
5566 alignPanel.av.mergeFeaturesStyle(srcSettings);
5568 AlignFrame.this.setMenusForViewport();
5571 dbRefFetcher.fetchDBRefs(false);
5579 new Thread(new Runnable()
5585 // final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5586 // .getSequenceFetcherSingleton();
5587 javax.swing.SwingUtilities.invokeLater(new Runnable()
5592 jalview.ws.SequenceFetcher sf = jalview.ws.SequenceFetcher
5594 String[] dbclasses = sf.getNonAlignmentSources();
5595 List<DbSourceProxy> otherdb;
5596 JMenu dfetch = new JMenu();
5597 JMenu ifetch = new JMenu();
5598 JMenuItem fetchr = null;
5599 int comp = 0, icomp = 0, mcomp = 15;
5600 String mname = null;
5602 for (String dbclass : dbclasses)
5604 otherdb = sf.getSourceProxy(dbclass);
5605 // add a single entry for this class, or submenu allowing 'fetch
5607 if (otherdb == null || otherdb.size() < 1)
5613 mname = "From " + dbclass;
5615 if (otherdb.size() == 1)
5617 DbSourceProxy src = otherdb.get(0);
5618 DbSourceProxy[] dassource = new DbSourceProxy[] { src };
5619 fetchr = new JMenuItem(src.getDbSource());
5620 fetchr.addActionListener(new ActionListener()
5624 public void actionPerformed(ActionEvent e)
5626 new Thread(new Runnable()
5632 boolean isNucleotide = alignPanel.alignFrame
5633 .getViewport().getAlignment()
5635 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5636 alignPanel.av.getSequenceSelection(),
5637 alignPanel.alignFrame, dassource,
5638 alignPanel.alignFrame.featureSettings,
5641 .addListener(new FetchFinishedListenerI()
5644 public void finished()
5646 FeatureSettingsModelI srcSettings = dassource[0]
5647 .getFeatureColourScheme();
5648 alignPanel.av.mergeFeaturesStyle(
5650 AlignFrame.this.setMenusForViewport();
5653 dbRefFetcher.fetchDBRefs(false);
5659 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5660 MessageManager.formatMessage(
5661 "label.fetch_retrieve_from", new Object[]
5662 { src.getDbName() })));
5668 final DbSourceProxy[] dassource = otherdb
5669 .toArray(new DbSourceProxy[0]);
5671 DbSourceProxy src = otherdb.get(0);
5672 fetchr = new JMenuItem(MessageManager
5673 .formatMessage("label.fetch_all_param", new Object[]
5674 { src.getDbSource() }));
5675 fetchr.addActionListener(new ActionListener()
5678 public void actionPerformed(ActionEvent e)
5680 new Thread(new Runnable()
5686 boolean isNucleotide = alignPanel.alignFrame
5687 .getViewport().getAlignment()
5689 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5690 alignPanel.av.getSequenceSelection(),
5691 alignPanel.alignFrame, dassource,
5692 alignPanel.alignFrame.featureSettings,
5695 .addListener(new FetchFinishedListenerI()
5698 public void finished()
5700 AlignFrame.this.setMenusForViewport();
5703 dbRefFetcher.fetchDBRefs(false);
5709 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5710 MessageManager.formatMessage(
5711 "label.fetch_retrieve_from_all_sources",
5713 { Integer.valueOf(otherdb.size())
5715 src.getDbSource(), src.getDbName() })));
5718 // and then build the rest of the individual menus
5719 ifetch = new JMenu(MessageManager.formatMessage(
5720 "label.source_from_db_source", new Object[]
5721 { src.getDbSource() }));
5723 String imname = null;
5725 for (DbSourceProxy sproxy : otherdb)
5727 String dbname = sproxy.getDbName();
5728 String sname = dbname.length() > 5
5729 ? dbname.substring(0, 5) + "..."
5731 String msname = dbname.length() > 10
5732 ? dbname.substring(0, 10) + "..."
5736 imname = MessageManager
5737 .formatMessage("label.from_msname", new Object[]
5740 fetchr = new JMenuItem(msname);
5741 final DbSourceProxy[] dassrc = { sproxy };
5742 fetchr.addActionListener(new ActionListener()
5746 public void actionPerformed(ActionEvent e)
5748 new Thread(new Runnable()
5754 boolean isNucleotide = alignPanel.alignFrame
5755 .getViewport().getAlignment()
5757 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5758 alignPanel.av.getSequenceSelection(),
5759 alignPanel.alignFrame, dassrc,
5760 alignPanel.alignFrame.featureSettings,
5763 .addListener(new FetchFinishedListenerI()
5766 public void finished()
5768 AlignFrame.this.setMenusForViewport();
5771 dbRefFetcher.fetchDBRefs(false);
5777 fetchr.setToolTipText(
5778 "<html>" + MessageManager.formatMessage(
5779 "label.fetch_retrieve_from", new Object[]
5783 if (++icomp >= mcomp || i == (otherdb.size()))
5785 ifetch.setText(MessageManager.formatMessage(
5786 "label.source_to_target", imname, sname));
5788 ifetch = new JMenu();
5796 if (comp >= mcomp || dbi >= (dbclasses.length))
5798 dfetch.setText(MessageManager.formatMessage(
5799 "label.source_to_target", mname, dbclass));
5801 dfetch = new JMenu();
5814 * Left justify the whole alignment.
5817 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5819 viewport.getAlignment().justify(false);
5820 viewport.notifyAlignment();
5824 * Right justify the whole alignment.
5827 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5829 viewport.getAlignment().justify(true);
5830 viewport.notifyAlignment();
5834 public void setShowSeqFeatures(boolean b)
5836 showSeqFeatures.setSelected(b);
5837 viewport.setShowSequenceFeatures(b);
5844 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5845 * awt.event.ActionEvent)
5848 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5850 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5851 alignPanel.paintAlignment(false, false);
5858 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5862 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5864 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5865 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5873 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5874 * .event.ActionEvent)
5877 protected void showGroupConservation_actionPerformed(ActionEvent e)
5879 viewport.setShowGroupConservation(showGroupConservation.getState());
5880 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5887 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5888 * .event.ActionEvent)
5891 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5893 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5894 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5901 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5902 * .event.ActionEvent)
5905 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5907 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5908 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5912 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5914 showSequenceLogo.setState(true);
5915 viewport.setShowSequenceLogo(true);
5916 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5917 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5921 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5923 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5930 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5931 * .event.ActionEvent)
5934 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5936 if (avc.makeGroupsFromSelection())
5938 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5939 alignPanel.updateAnnotation();
5940 alignPanel.paintAlignment(true,
5941 viewport.needToUpdateStructureViews());
5945 public void clearAlignmentSeqRep()
5947 // TODO refactor alignmentseqrep to controller
5948 if (viewport.getAlignment().hasSeqrep())
5950 viewport.getAlignment().setSeqrep(null);
5951 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5952 alignPanel.updateAnnotation();
5953 alignPanel.paintAlignment(true, true);
5958 protected void createGroup_actionPerformed(ActionEvent e)
5960 if (avc.createGroup())
5962 if (applyAutoAnnotationSettings.isSelected())
5964 alignPanel.updateAnnotation(true, false);
5966 alignPanel.alignmentChanged();
5971 protected void unGroup_actionPerformed(ActionEvent e)
5975 alignPanel.alignmentChanged();
5980 * make the given alignmentPanel the currently selected tab
5982 * @param alignmentPanel
5984 public void setDisplayedView(AlignmentPanel alignmentPanel)
5986 if (!viewport.getSequenceSetId()
5987 .equals(alignmentPanel.av.getSequenceSetId()))
5989 throw new Error(MessageManager.getString(
5990 "error.implementation_error_cannot_show_view_alignment_frame"));
5992 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5993 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5995 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
6000 * Action on selection of menu options to Show or Hide annotations.
6003 * @param forSequences
6004 * update sequence-related annotations
6005 * @param forAlignment
6006 * update non-sequence-related annotations
6009 protected void setAnnotationsVisibility(boolean visible,
6010 boolean forSequences, boolean forAlignment)
6012 AlignmentAnnotation[] anns = alignPanel.getAlignment()
6013 .getAlignmentAnnotation();
6018 for (AlignmentAnnotation aa : anns)
6021 * don't display non-positional annotations on an alignment
6023 if (aa.annotations == null)
6027 boolean apply = (aa.sequenceRef == null && forAlignment)
6028 || (aa.sequenceRef != null && forSequences);
6031 aa.visible = visible;
6034 alignPanel.validateAnnotationDimensions(true);
6035 alignPanel.alignmentChanged();
6039 * Store selected annotation sort order for the view and repaint.
6042 protected void sortAnnotations_actionPerformed()
6044 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
6046 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
6047 alignPanel.paintAlignment(false, false);
6052 * @return alignment panels in this alignment frame
6054 public List<? extends AlignmentViewPanel> getAlignPanels()
6056 // alignPanels is never null
6057 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
6062 * Open a new alignment window, with the cDNA associated with this (protein)
6063 * alignment, aligned as is the protein.
6065 protected void viewAsCdna_actionPerformed()
6067 // TODO no longer a menu action - refactor as required
6068 final AlignmentI alignment = getViewport().getAlignment();
6069 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
6070 if (mappings == null)
6074 List<SequenceI> cdnaSeqs = new ArrayList<>();
6075 for (SequenceI aaSeq : alignment.getSequences())
6077 for (AlignedCodonFrame acf : mappings)
6079 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
6083 * There is a cDNA mapping for this protein sequence - add to new
6084 * alignment. It will share the same dataset sequence as other mapped
6085 * cDNA (no new mappings need to be created).
6087 final Sequence newSeq = new Sequence(dnaSeq);
6088 newSeq.setDatasetSequence(dnaSeq);
6089 cdnaSeqs.add(newSeq);
6093 if (cdnaSeqs.size() == 0)
6095 // show a warning dialog no mapped cDNA
6098 AlignmentI cdna = new Alignment(
6099 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
6100 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
6101 AlignFrame.DEFAULT_HEIGHT);
6102 cdna.alignAs(alignment);
6103 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
6105 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
6106 AlignFrame.DEFAULT_HEIGHT);
6110 * Set visibility of dna/protein complement view (available when shown in a
6116 protected void showComplement_actionPerformed(boolean show)
6118 SplitContainerI sf = getSplitViewContainer();
6121 sf.setComplementVisible(this, show);
6126 * Generate the reverse (optionally complemented) of the selected sequences,
6127 * and add them to the alignment
6130 protected void showReverse_actionPerformed(boolean complement)
6132 AlignmentI al = null;
6135 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
6136 al = dna.reverseCdna(complement);
6137 viewport.addAlignment(al, "");
6138 addHistoryItem(new EditCommand(
6139 MessageManager.getString("label.add_sequences"), Action.PASTE,
6140 al.getSequencesArray(), 0, al.getWidth(),
6141 viewport.getAlignment()));
6142 } catch (Exception ex)
6144 System.err.println(ex.getMessage());
6150 * Try to run a script in the Groovy console, having first ensured that this
6151 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
6152 * be targeted at this alignment.
6155 protected void runGroovy_actionPerformed()
6157 Jalview.setCurrentAlignFrame(this);
6158 groovy.ui.Console console = Desktop.getGroovyConsole();
6159 if (console != null)
6163 console.runScript();
6164 } catch (Exception ex)
6166 System.err.println((ex.toString()));
6167 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
6168 MessageManager.getString("label.couldnt_run_groovy_script"),
6169 MessageManager.getString("label.groovy_support_failed"),
6170 JvOptionPane.ERROR_MESSAGE);
6175 System.err.println("Can't run Groovy script as console not found");
6180 * Hides columns containing (or not containing) a specified feature, provided
6181 * that would not leave all columns hidden
6183 * @param featureType
6184 * @param columnsContaining
6187 public boolean hideFeatureColumns(String featureType,
6188 boolean columnsContaining)
6190 boolean notForHiding = avc.markColumnsContainingFeatures(
6191 columnsContaining, false, false, featureType);
6194 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
6195 false, featureType))
6197 getViewport().hideSelectedColumns();
6205 protected void selectHighlightedColumns_actionPerformed(
6206 ActionEvent actionEvent)
6208 // include key modifier check in case user selects from menu
6209 avc.markHighlightedColumns(
6210 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
6211 (actionEvent.getModifiers() & (ActionEvent.META_MASK
6212 | ActionEvent.CTRL_MASK)) != 0);
6216 * Rebuilds the Colour menu, including any user-defined colours which have
6217 * been loaded either on startup or during the session
6219 public void buildColourMenu()
6221 colourMenu.removeAll();
6223 colourMenu.add(applyToAllGroups);
6224 colourMenu.add(textColour);
6225 colourMenu.addSeparator();
6227 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
6228 viewport.getAlignment(), false);
6230 colourMenu.add(annotationColour);
6231 bg.add(annotationColour);
6232 colourMenu.addSeparator();
6233 colourMenu.add(conservationMenuItem);
6234 colourMenu.add(modifyConservation);
6235 colourMenu.add(abovePIDThreshold);
6236 colourMenu.add(modifyPID);
6238 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
6239 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
6243 * Open a dialog (if not already open) that allows the user to select and
6244 * calculate PCA or Tree analysis
6246 protected void openTreePcaDialog()
6248 if (alignPanel.getCalculationDialog() == null)
6250 new CalculationChooser(AlignFrame.this);
6255 * Sets the status of the HMMER menu
6257 public void updateHMMERStatus()
6259 hmmerMenu.setEnabled(HmmerCommand.isHmmerAvailable());
6262 protected void loadVcf_actionPerformed()
6264 JalviewFileChooser chooser = new JalviewFileChooser(
6265 Cache.getProperty("LAST_DIRECTORY"));
6266 chooser.setFileView(new JalviewFileView());
6267 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
6268 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
6269 final AlignFrame us = this;
6270 chooser.setResponseHandler(0, new Runnable()
6275 String choice = chooser.getSelectedFile().getPath();
6276 Cache.setProperty("LAST_DIRECTORY", choice);
6277 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
6278 new VCFLoader(choice).loadVCF(seqs, us);
6281 chooser.showOpenDialog(null);
6285 private Rectangle lastFeatureSettingsBounds = null;
6288 public void setFeatureSettingsGeometry(Rectangle bounds)
6290 lastFeatureSettingsBounds = bounds;
6294 public Rectangle getFeatureSettingsGeometry()
6296 return lastFeatureSettingsBounds;
6299 public void scrollTo(int row, int column)
6301 alignPanel.getSeqPanel().scrollTo(row, column);
6304 public void scrollToRow(int row)
6306 alignPanel.getSeqPanel().scrollToRow(row);
6309 public void scrollToColumn(int column)
6311 alignPanel.getSeqPanel().scrollToColumn(column);
6315 * BH 2019 from JalviewLite
6317 * get sequence feature groups that are hidden or shown
6324 public String[] getFeatureGroupsOfState(boolean visible)
6326 jalview.api.FeatureRenderer fr = null;
6327 if (alignPanel != null
6328 && (fr = alignPanel.getFeatureRenderer()) != null)
6330 List<String> gps = fr.getGroups(visible);
6331 String[] _gps = gps.toArray(new String[gps.size()]);
6339 * @return list of feature groups on the view
6342 public String[] getFeatureGroups()
6344 jalview.api.FeatureRenderer fr = null;
6345 if (alignPanel != null
6346 && (fr = alignPanel.getFeatureRenderer()) != null)
6348 List<String> gps = fr.getFeatureGroups();
6349 String[] _gps = gps.toArray(new String[gps.size()]);
6355 public void select(SequenceGroup sel, ColumnSelection csel,
6356 HiddenColumns hidden)
6358 alignPanel.getSeqPanel().selection(sel, csel, hidden, null);
6366 static class PrintThread extends Thread
6370 public PrintThread(AlignmentPanel ap)
6375 static PageFormat pf;
6380 PrinterJob printJob = PrinterJob.getPrinterJob();
6384 printJob.setPrintable(ap, pf);
6388 printJob.setPrintable(ap);
6391 if (printJob.printDialog())
6396 } catch (Exception PrintException)
6398 PrintException.printStackTrace();