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;
32 import java.awt.BorderLayout;
33 import java.awt.Color;
34 import java.awt.Component;
35 import java.awt.Dimension;
36 import java.awt.Rectangle;
37 import java.awt.Toolkit;
38 import java.awt.datatransfer.Clipboard;
39 import java.awt.datatransfer.DataFlavor;
40 import java.awt.datatransfer.StringSelection;
41 import java.awt.datatransfer.Transferable;
42 import java.awt.dnd.DnDConstants;
43 import java.awt.dnd.DropTargetDragEvent;
44 import java.awt.dnd.DropTargetDropEvent;
45 import java.awt.dnd.DropTargetEvent;
46 import java.awt.dnd.DropTargetListener;
47 import java.awt.event.ActionEvent;
48 import java.awt.event.ActionListener;
49 import java.awt.event.FocusAdapter;
50 import java.awt.event.FocusEvent;
51 import java.awt.event.ItemEvent;
52 import java.awt.event.ItemListener;
53 import java.awt.event.KeyAdapter;
54 import java.awt.event.KeyEvent;
55 import java.awt.event.MouseEvent;
56 import java.awt.print.PageFormat;
57 import java.awt.print.PrinterJob;
58 import java.beans.PropertyChangeEvent;
59 import java.beans.PropertyChangeListener;
61 import java.io.FileWriter;
62 import java.io.PrintWriter;
64 import java.util.ArrayList;
65 import java.util.Arrays;
66 import java.util.Collection;
67 import java.util.Deque;
68 import java.util.Enumeration;
69 import java.util.Hashtable;
70 import java.util.List;
71 import java.util.Vector;
73 import javax.swing.ButtonGroup;
74 import javax.swing.JCheckBoxMenuItem;
75 import javax.swing.JComponent;
76 import javax.swing.JEditorPane;
77 import javax.swing.JInternalFrame;
78 import javax.swing.JLabel;
79 import javax.swing.JLayeredPane;
80 import javax.swing.JMenu;
81 import javax.swing.JMenuItem;
82 import javax.swing.JPanel;
83 import javax.swing.JScrollPane;
84 import javax.swing.SwingUtilities;
85 import javax.swing.event.InternalFrameAdapter;
86 import javax.swing.event.InternalFrameEvent;
88 import ext.vamsas.ServiceHandle;
89 import jalview.analysis.AlignmentSorter;
90 import jalview.analysis.AlignmentUtils;
91 import jalview.analysis.CrossRef;
92 import jalview.analysis.Dna;
93 import jalview.analysis.GeneticCodeI;
94 import jalview.analysis.ParseProperties;
95 import jalview.analysis.SequenceIdMatcher;
96 import jalview.api.AlignExportSettingsI;
97 import jalview.api.AlignViewControllerGuiI;
98 import jalview.api.AlignViewControllerI;
99 import jalview.api.AlignViewportI;
100 import jalview.api.AlignmentViewPanel;
101 import jalview.api.FeatureSettingsControllerI;
102 import jalview.api.FeatureSettingsModelI;
103 import jalview.api.SplitContainerI;
104 import jalview.api.ViewStyleI;
105 import jalview.api.analysis.SimilarityParamsI;
106 import jalview.bin.Cache;
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);
471 // 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 = jalview.bin.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 (jalview.bin.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").toLowerCase(Locale.ROOT)
615 .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 jalview.bin.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 Cache.log.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,
1651 statusBar.setText(MessageManager.formatMessage(
1652 "label.successfully_saved_to_file_in_format", new Object[]
1653 { fileName, format }));
1657 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1658 Runnable cancelAction = new Runnable()
1663 lastSaveSuccessful = false;
1666 Runnable outputAction = new Runnable()
1671 // todo defer this to inside formatSequences (or later)
1672 AlignmentExportData exportData = viewport
1673 .getAlignExportData(options);
1674 String output = new FormatAdapter(alignPanel, options)
1675 .formatSequences(format, exportData.getAlignment(),
1676 exportData.getOmitHidden(),
1677 exportData.getStartEndPostions(),
1678 viewport.getAlignment().getHiddenColumns());
1681 lastSaveSuccessful = false;
1685 // create backupfiles object and get new temp filename destination
1686 boolean doBackup = BackupFiles.getEnabled();
1687 BackupFiles backupfiles = null;
1691 "ALIGNFRAME making backupfiles object for " + file);
1692 backupfiles = new BackupFiles(file);
1696 String tempFilePath = doBackup ? backupfiles.getTempFilePath()
1698 Cache.log.trace("ALIGNFRAME setting PrintWriter");
1699 PrintWriter out = new PrintWriter(new FileWriter(tempFilePath));
1701 if (backupfiles != null)
1703 Cache.log.trace("ALIGNFRAME about to write to temp file "
1704 + backupfiles.getTempFilePath());
1708 Cache.log.trace("ALIGNFRAME about to close file");
1710 Cache.log.trace("ALIGNFRAME closed file");
1711 AlignFrame.this.setTitle(file);
1712 statusBar.setText(MessageManager.formatMessage(
1713 "label.successfully_saved_to_file_in_format",
1715 { fileName, format.getName() }));
1716 lastSaveSuccessful = true;
1717 } catch (IOException e)
1719 lastSaveSuccessful = false;
1721 "ALIGNFRAME Something happened writing the temp file");
1722 Cache.log.error(e.getMessage());
1723 Cache.log.debug(Cache.getStackTraceString(e));
1724 } catch (Exception ex)
1726 lastSaveSuccessful = false;
1728 "ALIGNFRAME Something unexpected happened writing the temp file");
1729 Cache.log.error(ex.getMessage());
1730 Cache.log.debug(Cache.getStackTraceString(ex));
1735 backupfiles.setWriteSuccess(lastSaveSuccessful);
1736 Cache.log.debug("ALIGNFRAME writing temp file was "
1737 + (lastSaveSuccessful ? "" : "NOT ") + "successful");
1738 // do the backup file roll and rename the temp file to actual file
1740 "ALIGNFRAME about to rollBackupsAndRenameTempFile");
1741 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1743 "ALIGNFRAME performed rollBackupsAndRenameTempFile "
1744 + (lastSaveSuccessful ? "" : "un")
1752 * show dialog with export options if applicable; else just do it
1754 if (AlignExportOptions.isNeeded(viewport, format))
1756 AlignExportOptions choices = new AlignExportOptions(
1757 alignPanel.getAlignViewport(), format, options);
1758 choices.setResponseAction(0, outputAction);
1759 choices.setResponseAction(1, cancelAction);
1760 choices.showDialog();
1769 * Outputs the alignment to textbox in the requested format, if necessary
1770 * first prompting the user for whether to include hidden regions or
1773 * @param fileFormatName
1776 protected void outputText_actionPerformed(String fileFormatName)
1778 FileFormatI fileFormat = FileFormats.getInstance()
1779 .forName(fileFormatName);
1780 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1781 Runnable outputAction = new Runnable()
1786 // todo defer this to inside formatSequences (or later)
1787 AlignmentExportData exportData = viewport
1788 .getAlignExportData(options);
1789 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1790 cap.setForInput(null);
1793 FileFormatI format = fileFormat;
1794 cap.setText(new FormatAdapter(alignPanel, options)
1795 .formatSequences(format, exportData.getAlignment(),
1796 exportData.getOmitHidden(),
1797 exportData.getStartEndPostions(),
1798 viewport.getAlignment().getHiddenColumns()));
1799 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1800 "label.alignment_output_command", new Object[]
1801 { fileFormat.getName() }), 600, 500);
1802 } catch (OutOfMemoryError oom)
1804 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1812 * show dialog with export options if applicable; else just do it
1814 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1816 AlignExportOptions choices = new AlignExportOptions(
1817 alignPanel.getAlignViewport(), fileFormat, options);
1818 choices.setResponseAction(0, outputAction);
1819 choices.showDialog();
1834 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1836 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1837 htmlSVG.exportHTML(null);
1841 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1843 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1844 bjs.exportHTML(null);
1848 public void createImageMap(File file, String image)
1850 alignPanel.makePNGImageMap(file, image);
1854 * Creates a PNG image of the alignment and writes it to the given file. If
1855 * the file is null, the user is prompted to choose a file.
1860 public void createPNG(File f)
1862 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1866 * Creates an EPS image of the alignment and writes it to the given file. If
1867 * the file is null, the user is prompted to choose a file.
1872 public void createEPS(File f)
1874 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1878 * Creates an SVG image of the alignment and writes it to the given file. If
1879 * the file is null, the user is prompted to choose a file.
1884 public void createSVG(File f)
1886 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1890 public void pageSetup_actionPerformed(ActionEvent e)
1892 PrinterJob printJob = PrinterJob.getPrinterJob();
1893 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1903 public void printMenuItem_actionPerformed(ActionEvent e)
1905 // Putting in a thread avoids Swing painting problems
1906 PrintThread thread = new PrintThread(alignPanel);
1911 public void exportFeatures_actionPerformed(ActionEvent e)
1913 new AnnotationExporter(alignPanel).exportFeatures();
1917 public void exportAnnotations_actionPerformed(ActionEvent e)
1919 new AnnotationExporter(alignPanel).exportAnnotations();
1923 public void associatedData_actionPerformed(ActionEvent e)
1924 throws IOException, InterruptedException
1926 final JalviewFileChooser chooser = new JalviewFileChooser(
1927 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1928 chooser.setFileView(new JalviewFileView());
1929 String tooltip = MessageManager
1930 .getString("label.load_jalview_annotations");
1931 chooser.setDialogTitle(tooltip);
1932 chooser.setToolTipText(tooltip);
1933 chooser.setResponseHandler(0, new Runnable()
1938 String choice = chooser.getSelectedFile().getPath();
1939 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1940 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1944 chooser.showOpenDialog(this);
1948 * Close the current view or all views in the alignment frame. If the frame
1949 * only contains one view then the alignment will be removed from memory.
1951 * @param closeAllTabs
1954 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1956 if (alignPanels != null && alignPanels.size() < 2)
1958 closeAllTabs = true;
1963 if (alignPanels != null)
1967 if (this.isClosed())
1969 // really close all the windows - otherwise wait till
1970 // setClosed(true) is called
1971 for (int i = 0; i < alignPanels.size(); i++)
1973 AlignmentPanel ap = alignPanels.get(i);
1980 closeView(alignPanel);
1985 if (featureSettings != null && featureSettings.isOpen())
1987 featureSettings.close();
1988 featureSettings = null;
1991 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1992 * be called recursively, with the frame now in 'closed' state
1994 this.setClosed(true);
1996 } catch (Exception ex)
1998 ex.printStackTrace();
2003 * Close the specified panel and close up tabs appropriately.
2005 * @param panelToClose
2007 public void closeView(AlignmentPanel panelToClose)
2009 int index = tabbedPane.getSelectedIndex();
2010 int closedindex = tabbedPane.indexOfComponent(panelToClose);
2011 alignPanels.remove(panelToClose);
2012 panelToClose.closePanel();
2013 panelToClose = null;
2015 tabbedPane.removeTabAt(closedindex);
2016 tabbedPane.validate();
2018 if (index > closedindex || index == tabbedPane.getTabCount())
2020 // modify currently selected tab index if necessary.
2024 this.tabSelectionChanged(index);
2030 void updateEditMenuBar()
2033 if (viewport.getHistoryList().size() > 0)
2035 undoMenuItem.setEnabled(true);
2036 CommandI command = viewport.getHistoryList().peek();
2037 undoMenuItem.setText(MessageManager
2038 .formatMessage("label.undo_command", new Object[]
2039 { command.getDescription() }));
2043 undoMenuItem.setEnabled(false);
2044 undoMenuItem.setText(MessageManager.getString("action.undo"));
2047 if (viewport.getRedoList().size() > 0)
2049 redoMenuItem.setEnabled(true);
2051 CommandI command = viewport.getRedoList().peek();
2052 redoMenuItem.setText(MessageManager
2053 .formatMessage("label.redo_command", new Object[]
2054 { command.getDescription() }));
2058 redoMenuItem.setEnabled(false);
2059 redoMenuItem.setText(MessageManager.getString("action.redo"));
2064 public void addHistoryItem(CommandI command)
2066 if (command.getSize() > 0)
2068 viewport.addToHistoryList(command);
2069 viewport.clearRedoList();
2070 updateEditMenuBar();
2071 viewport.updateHiddenColumns();
2072 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
2073 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2074 // viewport.getColumnSelection()
2075 // .getHiddenColumns().size() > 0);
2081 * @return alignment objects for all views
2083 AlignmentI[] getViewAlignments()
2085 if (alignPanels != null)
2087 AlignmentI[] als = new AlignmentI[alignPanels.size()];
2089 for (AlignmentPanel ap : alignPanels)
2091 als[i++] = ap.av.getAlignment();
2095 if (viewport != null)
2097 return new AlignmentI[] { viewport.getAlignment() };
2109 protected void undoMenuItem_actionPerformed(ActionEvent e)
2111 if (viewport.getHistoryList().isEmpty())
2115 CommandI command = viewport.getHistoryList().pop();
2116 viewport.addToRedoList(command);
2117 command.undoCommand(getViewAlignments());
2119 AlignmentViewport originalSource = getOriginatingSource(command);
2120 updateEditMenuBar();
2122 if (originalSource != null)
2124 if (originalSource != viewport)
2127 "Implementation worry: mismatch of viewport origin for undo");
2129 originalSource.updateHiddenColumns();
2130 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
2132 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2133 // viewport.getColumnSelection()
2134 // .getHiddenColumns().size() > 0);
2135 originalSource.notifyAlignment();
2146 protected void redoMenuItem_actionPerformed(ActionEvent e)
2148 if (viewport.getRedoList().size() < 1)
2153 CommandI command = viewport.getRedoList().pop();
2154 viewport.addToHistoryList(command);
2155 command.doCommand(getViewAlignments());
2157 AlignmentViewport originalSource = getOriginatingSource(command);
2158 updateEditMenuBar();
2160 if (originalSource != null)
2163 if (originalSource != viewport)
2166 "Implementation worry: mismatch of viewport origin for redo");
2168 originalSource.updateHiddenColumns();
2169 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
2171 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2172 // viewport.getColumnSelection()
2173 // .getHiddenColumns().size() > 0);
2174 originalSource.notifyAlignment();
2178 AlignmentViewport getOriginatingSource(CommandI command)
2180 AlignmentViewport originalSource = null;
2181 // For sequence removal and addition, we need to fire
2182 // the property change event FROM the viewport where the
2183 // original alignment was altered
2184 AlignmentI al = null;
2185 if (command instanceof EditCommand)
2187 EditCommand editCommand = (EditCommand) command;
2188 al = editCommand.getAlignment();
2189 List<Component> comps = PaintRefresher.components
2190 .get(viewport.getSequenceSetId());
2192 for (Component comp : comps)
2194 if (comp instanceof AlignmentPanel)
2196 if (al == ((AlignmentPanel) comp).av.getAlignment())
2198 originalSource = ((AlignmentPanel) comp).av;
2205 if (originalSource == null)
2207 // The original view is closed, we must validate
2208 // the current view against the closed view first
2211 PaintRefresher.validateSequences(al, viewport.getAlignment());
2214 originalSource = viewport;
2217 return originalSource;
2221 * Calls AlignmentI.moveSelectedSequencesByOne with current sequence selection
2222 * or the sequence under cursor in keyboard mode
2227 public void moveSelectedSequences(boolean up)
2229 SequenceGroup sg = viewport.getSelectionGroup();
2233 if (viewport.cursorMode)
2235 sg = new SequenceGroup();
2236 sg.addSequence(viewport.getAlignment().getSequenceAt(
2237 alignPanel.getSeqPanel().seqCanvas.cursorY), false);
2245 if (sg.getSize() < 1)
2249 // TODO: JAL-3733 - add an event to the undo buffer for this !
2250 viewport.getAlignment().moveSelectedSequencesByOne(sg,
2251 viewport.getHiddenRepSequences(), up);
2252 alignPanel.paintAlignment(true, false);
2255 synchronized void slideSequences(boolean right, int size)
2257 List<SequenceI> sg = new ArrayList<>();
2258 if (viewport.cursorMode)
2260 sg.add(viewport.getAlignment()
2261 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
2263 else if (viewport.getSelectionGroup() != null
2264 && viewport.getSelectionGroup().getSize() != viewport
2265 .getAlignment().getHeight())
2267 sg = viewport.getSelectionGroup()
2268 .getSequences(viewport.getHiddenRepSequences());
2276 List<SequenceI> invertGroup = new ArrayList<>();
2278 for (SequenceI seq : viewport.getAlignment().getSequences())
2280 if (!sg.contains(seq))
2282 invertGroup.add(seq);
2286 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
2288 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
2289 for (int i = 0; i < invertGroup.size(); i++)
2291 seqs2[i] = invertGroup.get(i);
2294 SlideSequencesCommand ssc;
2297 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
2298 viewport.getGapCharacter());
2302 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
2303 viewport.getGapCharacter());
2306 int groupAdjustment = 0;
2307 if (ssc.getGapsInsertedBegin() && right)
2309 if (viewport.cursorMode)
2311 alignPanel.getSeqPanel().moveCursor(size, 0);
2315 groupAdjustment = size;
2318 else if (!ssc.getGapsInsertedBegin() && !right)
2320 if (viewport.cursorMode)
2322 alignPanel.getSeqPanel().moveCursor(-size, 0);
2326 groupAdjustment = -size;
2330 if (groupAdjustment != 0)
2332 viewport.getSelectionGroup().setStartRes(
2333 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
2334 viewport.getSelectionGroup().setEndRes(
2335 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
2339 * just extend the last slide command if compatible; but not if in
2340 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
2342 boolean appendHistoryItem = false;
2343 Deque<CommandI> historyList = viewport.getHistoryList();
2344 boolean inSplitFrame = getSplitViewContainer() != null;
2345 if (!inSplitFrame && historyList != null && historyList.size() > 0
2346 && historyList.peek() instanceof SlideSequencesCommand)
2348 appendHistoryItem = ssc.appendSlideCommand(
2349 (SlideSequencesCommand) historyList.peek());
2352 if (!appendHistoryItem)
2354 addHistoryItem(ssc);
2367 protected void copy_actionPerformed()
2369 if (viewport.getSelectionGroup() == null)
2373 // TODO: preserve the ordering of displayed alignment annotation in any
2374 // internal paste (particularly sequence associated annotation)
2375 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2376 String[] omitHidden = null;
2378 if (viewport.hasHiddenColumns())
2380 omitHidden = viewport.getViewAsString(true);
2383 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2384 seqs, omitHidden, null);
2386 StringSelection ss = new StringSelection(output);
2388 Desktop d = Desktop.getInstance();
2391 d.internalCopy = true;
2392 // Its really worth setting the clipboard contents
2393 // to empty before setting the large StringSelection!!
2394 Toolkit.getDefaultToolkit().getSystemClipboard()
2395 .setContents(new StringSelection(""), null);
2397 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2399 } catch (OutOfMemoryError er)
2401 new OOMWarning("copying region", er);
2405 HiddenColumns hiddenColumns = null;
2406 if (viewport.hasHiddenColumns())
2408 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2409 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2411 // create new HiddenColumns object with copy of hidden regions
2412 // between startRes and endRes, offset by startRes
2413 hiddenColumns = new HiddenColumns(
2414 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2415 hiddenCutoff, hiddenOffset);
2418 d.jalviewClipboard = new Object[] { seqs,
2419 viewport.getAlignment().getDataset(), hiddenColumns };
2420 setStatus(MessageManager.formatMessage(
2421 "label.copied_sequences_to_clipboard", new Object[]
2422 { Integer.valueOf(seqs.length).toString() }));
2430 * @throws InterruptedException
2431 * @throws IOException
2434 protected void pasteNew_actionPerformed(ActionEvent e)
2435 throws IOException, InterruptedException
2445 * @throws InterruptedException
2446 * @throws IOException
2449 protected void pasteThis_actionPerformed(ActionEvent e)
2450 throws IOException, InterruptedException
2456 * Paste contents of Jalview clipboard
2458 * @param newAlignment
2459 * true to paste to a new alignment, otherwise add to this.
2460 * @throws InterruptedException
2461 * @throws IOException
2463 void paste(boolean newAlignment) throws IOException, InterruptedException
2465 boolean externalPaste = true;
2468 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2469 Transferable contents = c.getContents(this);
2471 if (contents == null)
2480 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2481 if (str.length() < 1)
2486 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2488 } catch (OutOfMemoryError er)
2490 new OOMWarning("Out of memory pasting sequences!!", er);
2494 SequenceI[] sequences;
2495 boolean annotationAdded = false;
2496 AlignmentI alignment = null;
2498 Desktop d = Desktop.getInstance();
2500 if (d.jalviewClipboard != null)
2502 // The clipboard was filled from within Jalview, we must use the
2504 // And dataset from the copied alignment
2505 SequenceI[] newseq = (SequenceI[]) d.jalviewClipboard[0];
2506 // be doubly sure that we create *new* sequence objects.
2507 sequences = new SequenceI[newseq.length];
2508 for (int i = 0; i < newseq.length; i++)
2510 sequences[i] = new Sequence(newseq[i]);
2512 alignment = new Alignment(sequences);
2513 externalPaste = false;
2517 // parse the clipboard as an alignment.
2518 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2520 sequences = alignment.getSequencesArray();
2524 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2530 if (d.jalviewClipboard != null)
2532 // dataset is inherited
2533 alignment.setDataset((Alignment) d.jalviewClipboard[1]);
2537 // new dataset is constructed
2538 alignment.setDataset(null);
2540 alwidth = alignment.getWidth() + 1;
2544 AlignmentI pastedal = alignment; // preserve pasted alignment object
2545 // Add pasted sequences and dataset into existing alignment.
2546 alignment = viewport.getAlignment();
2547 alwidth = alignment.getWidth() + 1;
2548 // decide if we need to import sequences from an existing dataset
2549 boolean importDs = d.jalviewClipboard != null
2550 && d.jalviewClipboard[1] != alignment.getDataset();
2551 // importDs==true instructs us to copy over new dataset sequences from
2552 // an existing alignment
2553 Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2555 // minimum dataset set
2557 for (int i = 0; i < sequences.length; i++)
2561 newDs.addElement(null);
2563 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2565 if (importDs && ds != null)
2567 if (!newDs.contains(ds))
2569 newDs.setElementAt(ds, i);
2570 ds = new Sequence(ds);
2571 // update with new dataset sequence
2572 sequences[i].setDatasetSequence(ds);
2576 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2581 // copy and derive new dataset sequence
2582 sequences[i] = sequences[i].deriveSequence();
2583 alignment.getDataset()
2584 .addSequence(sequences[i].getDatasetSequence());
2585 // TODO: avoid creation of duplicate dataset sequences with a
2586 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2588 alignment.addSequence(sequences[i]); // merges dataset
2592 newDs.clear(); // tidy up
2594 if (alignment.getAlignmentAnnotation() != null)
2596 for (AlignmentAnnotation alan : alignment
2597 .getAlignmentAnnotation())
2599 if (alan.graphGroup > fgroup)
2601 fgroup = alan.graphGroup;
2605 if (pastedal.getAlignmentAnnotation() != null)
2607 // Add any annotation attached to alignment.
2608 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2609 for (int i = 0; i < alann.length; i++)
2611 annotationAdded = true;
2612 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2614 AlignmentAnnotation newann = new AlignmentAnnotation(
2616 if (newann.graphGroup > -1)
2618 if (newGraphGroups.size() <= newann.graphGroup
2619 || newGraphGroups.get(newann.graphGroup) == null)
2621 for (int q = newGraphGroups
2622 .size(); q <= newann.graphGroup; q++)
2624 newGraphGroups.add(q, null);
2626 newGraphGroups.set(newann.graphGroup,
2627 Integer.valueOf(++fgroup));
2629 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2633 newann.padAnnotation(alwidth);
2634 alignment.addAnnotation(newann);
2644 addHistoryItem(new EditCommand(
2645 MessageManager.getString("label.add_sequences"),
2646 Action.PASTE, sequences, 0, alignment.getWidth(),
2649 // Add any annotations attached to sequences
2650 for (int i = 0; i < sequences.length; i++)
2652 if (sequences[i].getAnnotation() != null)
2654 AlignmentAnnotation newann;
2655 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2657 annotationAdded = true;
2658 newann = sequences[i].getAnnotation()[a];
2659 newann.adjustForAlignment();
2660 newann.padAnnotation(alwidth);
2661 if (newann.graphGroup > -1)
2663 if (newann.graphGroup > -1)
2665 if (newGraphGroups.size() <= newann.graphGroup
2666 || newGraphGroups.get(newann.graphGroup) == null)
2668 for (int q = newGraphGroups
2669 .size(); q <= newann.graphGroup; q++)
2671 newGraphGroups.add(q, null);
2673 newGraphGroups.set(newann.graphGroup,
2674 Integer.valueOf(++fgroup));
2676 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2680 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2684 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2692 // propagate alignment changed.
2693 viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2694 if (annotationAdded)
2696 // Duplicate sequence annotation in all views.
2697 AlignmentI[] alview = this.getViewAlignments();
2698 for (int i = 0; i < sequences.length; i++)
2700 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2705 for (int avnum = 0; avnum < alview.length; avnum++)
2707 if (alview[avnum] != alignment)
2709 // duplicate in a view other than the one with input focus
2710 int avwidth = alview[avnum].getWidth() + 1;
2711 // this relies on sann being preserved after we
2712 // modify the sequence's annotation array for each duplication
2713 for (int a = 0; a < sann.length; a++)
2715 AlignmentAnnotation newann = new AlignmentAnnotation(
2717 sequences[i].addAlignmentAnnotation(newann);
2718 newann.padAnnotation(avwidth);
2719 alview[avnum].addAnnotation(newann); // annotation was
2720 // duplicated earlier
2721 // TODO JAL-1145 graphGroups are not updated for sequence
2722 // annotation added to several views. This may cause
2724 alview[avnum].setAnnotationIndex(newann, a);
2729 buildSortByAnnotationScoresMenu();
2731 viewport.notifyAlignment();
2732 if (alignPanels != null)
2734 for (AlignmentPanel ap : alignPanels)
2736 ap.validateAnnotationDimensions(false);
2741 alignPanel.validateAnnotationDimensions(false);
2747 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2749 String newtitle = new String("Copied sequences");
2751 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2753 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2754 af.viewport.setHiddenColumns(hc);
2757 // >>>This is a fix for the moment, until a better solution is
2759 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2760 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2761 .getFeatureRenderer());
2763 // TODO: maintain provenance of an alignment, rather than just make the
2764 // title a concatenation of operations.
2767 if (title.startsWith("Copied sequences"))
2773 newtitle = newtitle.concat("- from " + title);
2778 newtitle = new String("Pasted sequences");
2781 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2786 } catch (Exception ex)
2788 ex.printStackTrace();
2789 System.out.println("Exception whilst pasting: " + ex);
2790 // could be anything being pasted in here
2796 protected void expand_newalign(ActionEvent e)
2800 AlignmentI alignment = AlignmentUtils
2801 .expandContext(getViewport().getAlignment(), -1);
2802 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2804 String newtitle = new String("Flanking alignment");
2806 Desktop d = Desktop.getInstance();
2807 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2809 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2810 af.viewport.setHiddenColumns(hc);
2813 // >>>This is a fix for the moment, until a better solution is
2815 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2816 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2817 .getFeatureRenderer());
2819 // TODO: maintain provenance of an alignment, rather than just make the
2820 // title a concatenation of operations.
2822 if (title.startsWith("Copied sequences"))
2828 newtitle = newtitle.concat("- from " + title);
2832 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2834 } catch (Exception ex)
2836 ex.printStackTrace();
2837 System.out.println("Exception whilst pasting: " + ex);
2838 // could be anything being pasted in here
2839 } catch (OutOfMemoryError oom)
2841 new OOMWarning("Viewing flanking region of alignment", oom);
2846 * Action Cut (delete and copy) the selected region
2849 protected void cut_actionPerformed()
2851 copy_actionPerformed();
2852 delete_actionPerformed();
2856 * Performs menu option to Delete the currently selected region
2859 protected void delete_actionPerformed()
2862 SequenceGroup sg = viewport.getSelectionGroup();
2868 Runnable okAction = new Runnable()
2874 SequenceI[] cut = sg.getSequences()
2875 .toArray(new SequenceI[sg.getSize()]);
2877 addHistoryItem(new EditCommand(
2878 MessageManager.getString("label.cut_sequences"), Action.CUT,
2879 cut, sg.getStartRes(),
2880 sg.getEndRes() - sg.getStartRes() + 1,
2881 viewport.getAlignment()));
2883 viewport.setSelectionGroup(null);
2884 viewport.sendSelection();
2885 viewport.getAlignment().deleteGroup(sg);
2887 viewport.notifyAlignment();
2889 if (viewport.getAlignment().getHeight() < 1)
2893 AlignFrame.this.setClosed(true);
2894 } catch (Exception ex)
2904 * If the cut affects all sequences, prompt for confirmation
2906 boolean wholeHeight = sg.getSize() == viewport.getAlignment()
2908 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2909 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2910 if (wholeHeight && wholeWidth)
2912 JvOptionPane dialog = JvOptionPane
2913 .newOptionDialog(Desktop.getDesktopPane());
2914 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2915 Object[] options = new Object[] {
2916 MessageManager.getString("action.ok"),
2917 MessageManager.getString("action.cancel") };
2918 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2919 MessageManager.getString("label.delete_all"),
2920 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2921 options, options[0]);
2936 protected void deleteGroups_actionPerformed(ActionEvent e)
2938 if (avc.deleteGroups())
2940 updateAll(viewport.getSequenceSetId());
2944 private void updateAll(String id)
2948 // this will force a non-fast repaint of both the IdPanel and SeqPanel
2949 alignPanel.getIdPanel().getIdCanvas().setNoFastPaint();
2950 alignPanel.getSeqPanel().seqCanvas.setNoFastPaint();
2951 alignPanel.repaint();
2956 PaintRefresher.Refresh(this, id);
2957 alignPanel.paintAlignment(true, true);
2959 alignPanel.updateAnnotation();
2969 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2971 alignPanel.selectAllSequences();
2981 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2983 alignPanel.deselectAllSequences();
2993 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2995 SequenceGroup sg = viewport.getSelectionGroup();
2999 alignPanel.selectAllSequences();
3004 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
3006 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
3008 // JAL-2034 - should delegate to
3009 // alignPanel to decide if overview needs
3012 alignPanel.paintAlignment(true, false);
3013 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
3014 viewport.sendSelection();
3018 public void invertColSel_actionPerformed(ActionEvent e)
3020 viewport.invertColumnSelection();
3021 alignPanel.paintAlignment(true, false);
3022 viewport.sendSelection();
3032 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
3034 trimAlignment(true);
3044 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
3046 trimAlignment(false);
3049 void trimAlignment(boolean trimLeft)
3051 ColumnSelection colSel = viewport.getColumnSelection();
3054 if (!colSel.isEmpty())
3058 column = colSel.getMin();
3062 column = colSel.getMax();
3066 if (viewport.getSelectionGroup() != null)
3068 seqs = viewport.getSelectionGroup()
3069 .getSequencesAsArray(viewport.getHiddenRepSequences());
3073 seqs = viewport.getAlignment().getSequencesArray();
3076 TrimRegionCommand trimRegion;
3079 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
3080 column, viewport.getAlignment());
3081 viewport.getRanges().setStartRes(0);
3085 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
3086 column, viewport.getAlignment());
3089 setStatus(MessageManager.formatMessage("label.removed_columns",
3091 { Integer.valueOf(trimRegion.getSize()).toString() }));
3093 addHistoryItem(trimRegion);
3095 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3097 if ((trimLeft && !sg.adjustForRemoveLeft(column))
3098 || (!trimLeft && !sg.adjustForRemoveRight(column)))
3100 viewport.getAlignment().deleteGroup(sg);
3104 viewport.notifyAlignment();
3115 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
3117 int start = 0, end = viewport.getAlignment().getWidth() - 1;
3120 if (viewport.getSelectionGroup() != null)
3122 seqs = viewport.getSelectionGroup()
3123 .getSequencesAsArray(viewport.getHiddenRepSequences());
3124 start = viewport.getSelectionGroup().getStartRes();
3125 end = viewport.getSelectionGroup().getEndRes();
3129 seqs = viewport.getAlignment().getSequencesArray();
3132 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
3133 "Remove Gapped Columns", seqs, start, end,
3134 viewport.getAlignment());
3136 addHistoryItem(removeGapCols);
3138 setStatus(MessageManager.formatMessage("label.removed_empty_columns",
3140 { Integer.valueOf(removeGapCols.getSize()).toString() }));
3142 // This is to maintain viewport position on first residue
3143 // of first sequence
3144 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3145 ViewportRanges ranges = viewport.getRanges();
3146 int startRes = seq.findPosition(ranges.getStartRes());
3147 // ShiftList shifts;
3148 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
3149 // edit.alColumnChanges=shifts.getInverse();
3150 // if (viewport.hasHiddenColumns)
3151 // viewport.getColumnSelection().compensateForEdits(shifts);
3152 ranges.setStartRes(seq.findIndex(startRes) - 1);
3153 viewport.notifyAlignment();
3164 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
3166 int start = 0, end = viewport.getAlignment().getWidth() - 1;
3169 if (viewport.getSelectionGroup() != null)
3171 seqs = viewport.getSelectionGroup()
3172 .getSequencesAsArray(viewport.getHiddenRepSequences());
3173 start = viewport.getSelectionGroup().getStartRes();
3174 end = viewport.getSelectionGroup().getEndRes();
3178 seqs = viewport.getAlignment().getSequencesArray();
3181 // This is to maintain viewport position on first residue
3182 // of first sequence
3183 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3184 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
3186 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
3187 viewport.getAlignment()));
3189 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
3191 viewport.notifyAlignment();
3202 public void padGapsMenuitem_actionPerformed(ActionEvent e)
3204 viewport.setPadGaps(padGapsMenuitem.isSelected());
3205 viewport.notifyAlignment();
3209 * Opens a Finder dialog
3214 public void findMenuItem_actionPerformed(ActionEvent e)
3216 new Finder(alignPanel, false, null);
3220 * Create a new view of the current alignment.
3223 public void newView_actionPerformed(ActionEvent e)
3225 newView(null, true);
3229 * Creates and shows a new view of the current alignment.
3232 * title of newly created view; if null, one will be generated
3233 * @param copyAnnotation
3234 * if true then duplicate all annnotation, groups and settings
3235 * @return new alignment panel, already displayed.
3237 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
3240 * Create a new AlignmentPanel (with its own, new Viewport)
3242 AlignmentPanel newap = new jalview.project.Jalview2XML()
3243 .copyAlignPanel(alignPanel);
3244 if (!copyAnnotation)
3247 * remove all groups and annotation except for the automatic stuff
3249 newap.av.getAlignment().deleteAllGroups();
3250 newap.av.getAlignment().deleteAllAnnotations(false);
3253 newap.av.setGatherViewsHere(false);
3255 if (viewport.getViewName() == null)
3257 viewport.setViewName(
3258 MessageManager.getString("label.view_name_original"));
3262 * Views share the same edits undo and redo stacks
3264 newap.av.setHistoryList(viewport.getHistoryList());
3265 newap.av.setRedoList(viewport.getRedoList());
3268 * copy any visualisation settings that are not saved in the project
3270 newap.av.setColourAppliesToAllGroups(
3271 viewport.getColourAppliesToAllGroups());
3274 * Views share the same mappings; need to deregister any new mappings
3275 * created by copyAlignPanel, and register the new reference to the shared
3278 newap.av.replaceMappings(viewport.getAlignment());
3281 * start up cDNA consensus (if applicable) now mappings are in place
3283 if (newap.av.initComplementConsensus())
3285 newap.refresh(true); // adjust layout of annotations
3288 newap.av.setViewName(getNewViewName(viewTitle));
3290 addAlignmentPanel(newap, true);
3291 newap.alignmentChanged();
3293 if (alignPanels.size() == 2)
3295 viewport.setGatherViewsHere(true);
3297 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
3302 * Make a new name for the view, ensuring it is unique within the current
3303 * sequenceSetId. (This used to be essential for Jalview Project archives, but
3304 * these now use viewId. Unique view names are still desirable for usability.)
3309 protected String getNewViewName(String viewTitle)
3311 int index = Desktop.getViewCount(viewport.getSequenceSetId());
3312 boolean addFirstIndex = false;
3313 if (viewTitle == null || viewTitle.trim().length() == 0)
3315 viewTitle = MessageManager.getString("action.view");
3316 addFirstIndex = true;
3320 index = 1;// we count from 1 if given a specific name
3322 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
3324 List<Component> comps = PaintRefresher.components
3325 .get(viewport.getSequenceSetId());
3327 List<String> existingNames = getExistingViewNames(comps);
3329 while (existingNames.contains(newViewName))
3331 newViewName = viewTitle + " " + (++index);
3337 * Returns a list of distinct view names found in the given list of
3338 * components. View names are held on the viewport of an AlignmentPanel.
3343 protected List<String> getExistingViewNames(List<Component> comps)
3345 List<String> existingNames = new ArrayList<>();
3346 for (Component comp : comps)
3348 if (comp instanceof AlignmentPanel)
3350 AlignmentPanel ap = (AlignmentPanel) comp;
3351 if (!existingNames.contains(ap.av.getViewName()))
3353 existingNames.add(ap.av.getViewName());
3357 return existingNames;
3361 * Explode tabbed views into separate windows.
3364 public void expandViews_actionPerformed(ActionEvent e)
3366 Desktop.explodeViews(this);
3370 * Gather views in separate windows back into a tabbed presentation.
3373 public void gatherViews_actionPerformed(ActionEvent e)
3375 Desktop.getInstance().gatherViews(this);
3385 public void font_actionPerformed(ActionEvent e)
3387 new FontChooser(alignPanel);
3397 protected void seqLimit_actionPerformed(ActionEvent e)
3399 viewport.setShowJVSuffix(seqLimits.isSelected());
3401 alignPanel.getIdPanel().getIdCanvas()
3402 .setPreferredSize(alignPanel.calculateIdWidth());
3403 alignPanel.paintAlignment(true, false);
3407 public void idRightAlign_actionPerformed(ActionEvent e)
3409 viewport.setRightAlignIds(idRightAlign.isSelected());
3410 alignPanel.paintAlignment(false, false);
3414 public void centreColumnLabels_actionPerformed(ActionEvent e)
3416 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3417 alignPanel.paintAlignment(false, false);
3423 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3426 protected void followHighlight_actionPerformed()
3429 * Set the 'follow' flag on the Viewport (and scroll to position if now
3432 final boolean state = this.followHighlightMenuItem.getState();
3433 viewport.setFollowHighlight(state);
3436 alignPanel.scrollToPosition(viewport.getSearchResults());
3447 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3449 viewport.setColourText(colourTextMenuItem.isSelected());
3450 alignPanel.paintAlignment(false, false);
3460 public void wrapMenuItem_actionPerformed(ActionEvent e)
3462 scaleAbove.setVisible(wrapMenuItem.isSelected());
3463 scaleLeft.setVisible(wrapMenuItem.isSelected());
3464 scaleRight.setVisible(wrapMenuItem.isSelected());
3465 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3466 alignPanel.updateLayout();
3470 public void showAllSeqs_actionPerformed(ActionEvent e)
3472 viewport.showAllHiddenSeqs();
3476 public void showAllColumns_actionPerformed(ActionEvent e)
3478 viewport.showAllHiddenColumns();
3479 alignPanel.paintAlignment(true, true);
3480 viewport.sendSelection();
3484 public void hideSelSequences_actionPerformed(ActionEvent e)
3486 viewport.hideAllSelectedSeqs();
3490 * called by key handler and the hide all/show all menu items
3495 protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3498 boolean hide = false;
3499 SequenceGroup sg = viewport.getSelectionGroup();
3500 if (!toggleSeqs && !toggleCols)
3502 // Hide everything by the current selection - this is a hack - we do the
3503 // invert and then hide
3504 // first check that there will be visible columns after the invert.
3505 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3506 && sg.getStartRes() <= sg.getEndRes()))
3508 // now invert the sequence set, if required - empty selection implies
3509 // that no hiding is required.
3512 invertSequenceMenuItem_actionPerformed(null);
3513 sg = viewport.getSelectionGroup();
3517 viewport.expandColSelection(sg, true);
3518 // finally invert the column selection and get the new sequence
3520 invertColSel_actionPerformed(null);
3527 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3529 hideSelSequences_actionPerformed(null);
3532 else if (!(toggleCols && viewport.hasSelectedColumns()))
3534 showAllSeqs_actionPerformed(null);
3540 if (viewport.hasSelectedColumns())
3542 hideSelColumns_actionPerformed(null);
3545 viewport.setSelectionGroup(sg);
3550 showAllColumns_actionPerformed(null);
3559 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3560 * event.ActionEvent)
3563 public void hideAllButSelection_actionPerformed(ActionEvent e)
3565 toggleHiddenRegions(false, false);
3566 viewport.sendSelection();
3573 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3577 public void hideAllSelection_actionPerformed(ActionEvent e)
3579 SequenceGroup sg = viewport.getSelectionGroup();
3580 viewport.expandColSelection(sg, false);
3581 viewport.hideAllSelectedSeqs();
3582 viewport.hideSelectedColumns();
3583 alignPanel.updateLayout();
3584 alignPanel.paintAlignment(true, true);
3585 viewport.sendSelection();
3592 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3596 public void showAllhidden_actionPerformed(ActionEvent e)
3598 viewport.showAllHiddenColumns();
3599 viewport.showAllHiddenSeqs();
3600 alignPanel.paintAlignment(true, true);
3601 viewport.sendSelection();
3605 public void hideSelColumns_actionPerformed(ActionEvent e)
3607 viewport.hideSelectedColumns();
3608 alignPanel.updateLayout();
3609 alignPanel.paintAlignment(true, true);
3610 viewport.sendSelection();
3614 public void hiddenMarkers_actionPerformed(ActionEvent e)
3616 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3627 protected void scaleAbove_actionPerformed(ActionEvent e)
3629 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3630 alignPanel.updateLayout();
3631 alignPanel.paintAlignment(true, false);
3641 protected void scaleLeft_actionPerformed(ActionEvent e)
3643 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3644 alignPanel.updateLayout();
3645 alignPanel.paintAlignment(true, false);
3655 protected void scaleRight_actionPerformed(ActionEvent e)
3657 viewport.setScaleRightWrapped(scaleRight.isSelected());
3658 alignPanel.updateLayout();
3659 alignPanel.paintAlignment(true, false);
3669 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3671 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3672 alignPanel.paintAlignment(false, false);
3682 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3684 viewport.setShowText(viewTextMenuItem.isSelected());
3685 alignPanel.paintAlignment(false, false);
3695 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3697 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3698 alignPanel.paintAlignment(false, false);
3701 public FeatureSettings featureSettings;
3704 public FeatureSettingsControllerI getFeatureSettingsUI()
3706 return featureSettings;
3710 public void featureSettings_actionPerformed(ActionEvent e)
3712 showFeatureSettingsUI();
3716 public FeatureSettingsControllerI showFeatureSettingsUI()
3718 if (featureSettings != null)
3720 featureSettings.closeOldSettings();
3721 featureSettings = null;
3723 if (!showSeqFeatures.isSelected())
3725 // make sure features are actually displayed
3726 showSeqFeatures.setSelected(true);
3727 showSeqFeatures_actionPerformed(null);
3729 featureSettings = new FeatureSettings(this);
3730 return featureSettings;
3734 * Set or clear 'Show Sequence Features'
3740 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3742 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3743 alignPanel.paintAlignment(true, true);
3747 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3748 * the annotations panel as a whole.
3750 * The options to show/hide all annotations should be enabled when the panel
3751 * is shown, and disabled when the panel is hidden.
3756 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3758 final boolean setVisible = annotationPanelMenuItem.isSelected();
3759 viewport.setShowAnnotation(setVisible);
3760 syncAnnotationMenuItems(setVisible);
3761 alignPanel.updateLayout();
3763 SwingUtilities.invokeLater(new Runnable() {
3768 alignPanel.updateScrollBarsFromRanges();
3774 private void syncAnnotationMenuItems(boolean setVisible)
3776 showAllSeqAnnotations.setEnabled(setVisible);
3777 hideAllSeqAnnotations.setEnabled(setVisible);
3778 showAllAlAnnotations.setEnabled(setVisible);
3779 hideAllAlAnnotations.setEnabled(setVisible);
3783 public void alignmentProperties()
3786 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3789 String content = MessageManager.formatMessage("label.html_content",
3791 { contents.toString() });
3794 if (Platform.isJS())
3796 JLabel textLabel = new JLabel();
3797 textLabel.setText(content);
3798 textLabel.setBackground(Color.WHITE);
3799 pane = new JPanel(new BorderLayout());
3800 ((JPanel) pane).setOpaque(true);
3801 pane.setBackground(Color.WHITE);
3802 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3811 JEditorPane editPane = new JEditorPane("text/html", "");
3812 editPane.setEditable(false);
3813 editPane.setText(content);
3817 JInternalFrame frame = new JInternalFrame();
3819 frame.getContentPane().add(new JScrollPane(pane));
3821 Desktop.addInternalFrame(frame, MessageManager
3822 .formatMessage("label.alignment_properties", new Object[]
3823 { getTitle() }), 500, 400);
3833 public void overviewMenuItem_actionPerformed(ActionEvent e)
3835 if (alignPanel.overviewPanel != null)
3840 JInternalFrame frame = new JInternalFrame();
3841 // BH 2019.07.26 we allow for an embedded
3842 // undecorated overview with defined size
3843 frame.setName(Platform.getAppID("overview"));
3845 Dimension dim = Platform.getDimIfEmbedded(frame, -1, -1);
3846 if (dim != null && dim.width == 0)
3848 dim = null; // hidden, not embedded
3850 OverviewPanel overview = new OverviewPanel(alignPanel, dim);
3851 frame.setContentPane(overview);
3854 dim = new Dimension();
3855 // was frame.getSize(), but that is 0,0 at this point;
3859 // we are imbedding, and so we have an undecorated frame
3860 // and we can set the the frame dimensions accordingly.
3862 // allowing for unresizable option using, style="resize:none"
3863 boolean resizable = (Platform.getEmbeddedAttribute(frame,
3864 "resize") != "none");
3865 Desktop.addInternalFrame(frame, MessageManager
3866 .formatMessage("label.overview_params", new Object[]
3867 { this.getTitle() }), Desktop.FRAME_MAKE_VISIBLE, dim.width,
3868 dim.height, resizable, Desktop.FRAME_ALLOW_ANY_SIZE);
3870 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3871 frame.addInternalFrameListener(
3872 new javax.swing.event.InternalFrameAdapter()
3875 public void internalFrameClosed(
3876 javax.swing.event.InternalFrameEvent evt)
3879 alignPanel.setOverviewPanel(null);
3882 if (getKeyListeners().length > 0)
3884 frame.addKeyListener(getKeyListeners()[0]);
3887 alignPanel.setOverviewPanel(overview);
3891 public void textColour_actionPerformed()
3893 new TextColourChooser().chooseColour(alignPanel, null);
3897 * public void covariationColour_actionPerformed() {
3899 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3903 public void annotationColour_actionPerformed()
3905 new AnnotationColourChooser(viewport, alignPanel);
3909 public void annotationColumn_actionPerformed(ActionEvent e)
3911 new AnnotationColumnChooser(viewport, alignPanel);
3915 * Action on the user checking or unchecking the option to apply the selected
3916 * colour scheme to all groups. If unchecked, groups may have their own
3917 * independent colour schemes.
3922 public void applyToAllGroups_actionPerformed(boolean selected)
3924 viewport.setColourAppliesToAllGroups(selected);
3928 * Action on user selecting a colour from the colour menu
3931 * the name (not the menu item label!) of the colour scheme
3934 public void changeColour_actionPerformed(String name)
3937 * 'User Defined' opens a panel to configure or load a
3938 * user-defined colour scheme
3940 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3942 new UserDefinedColours(alignPanel);
3947 * otherwise set the chosen colour scheme (or null for 'None')
3949 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3950 viewport, viewport.getAlignment(),
3951 viewport.getHiddenRepSequences());
3956 * Actions on setting or changing the alignment colour scheme
3961 public void changeColour(ColourSchemeI cs)
3963 // TODO: pull up to controller method
3964 ColourMenuHelper.setColourSelected(colourMenu, cs);
3966 viewport.setGlobalColourScheme(cs);
3968 alignPanel.paintAlignment(true, true);
3972 * Show the PID threshold slider panel
3975 protected void modifyPID_actionPerformed()
3977 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3978 alignPanel.getViewName());
3979 SliderPanel.showPIDSlider();
3983 * Show the Conservation slider panel
3986 protected void modifyConservation_actionPerformed()
3988 SliderPanel.setConservationSlider(alignPanel,
3989 viewport.getResidueShading(), alignPanel.getViewName());
3990 SliderPanel.showConservationSlider();
3994 * Action on selecting or deselecting (Colour) By Conservation
3997 public void conservationMenuItem_actionPerformed(boolean selected)
3999 modifyConservation.setEnabled(selected);
4000 viewport.setConservationSelected(selected);
4001 viewport.getResidueShading().setConservationApplied(selected);
4003 changeColour(viewport.getGlobalColourScheme());
4006 modifyConservation_actionPerformed();
4010 SliderPanel.hideConservationSlider();
4015 * Action on selecting or deselecting (Colour) Above PID Threshold
4018 public void abovePIDThreshold_actionPerformed(boolean selected)
4020 modifyPID.setEnabled(selected);
4021 viewport.setAbovePIDThreshold(selected);
4024 viewport.getResidueShading().setThreshold(0,
4025 viewport.isIgnoreGapsConsensus());
4028 changeColour(viewport.getGlobalColourScheme());
4031 modifyPID_actionPerformed();
4035 SliderPanel.hidePIDSlider();
4046 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
4048 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4049 AlignmentSorter.sortByPID(viewport.getAlignment(),
4050 viewport.getAlignment().getSequenceAt(0));
4051 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
4052 viewport.getAlignment()));
4053 alignPanel.paintAlignment(true, false);
4063 public void sortIDMenuItem_actionPerformed(ActionEvent e)
4065 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4066 AlignmentSorter.sortByID(viewport.getAlignment());
4068 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
4069 alignPanel.paintAlignment(true, false);
4079 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
4081 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4082 AlignmentSorter.sortByLength(viewport.getAlignment());
4083 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
4084 viewport.getAlignment()));
4085 alignPanel.paintAlignment(true, false);
4095 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
4097 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4098 AlignmentSorter.sortByGroup(viewport.getAlignment());
4099 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4100 viewport.getAlignment()));
4102 alignPanel.paintAlignment(true, false);
4106 public void sortEValueMenuItem_actionPerformed(ActionEvent e)
4108 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4109 AlignmentSorter.sortByEValue(viewport.getAlignment());
4110 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4111 viewport.getAlignment()));
4112 alignPanel.paintAlignment(true, false);
4117 public void sortBitScoreMenuItem_actionPerformed(ActionEvent e)
4119 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4120 AlignmentSorter.sortByBitScore(viewport.getAlignment());
4121 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4122 viewport.getAlignment()));
4123 alignPanel.paintAlignment(true, false);
4133 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
4135 new RedundancyPanel(alignPanel, this);
4145 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
4147 if ((viewport.getSelectionGroup() == null)
4148 || (viewport.getSelectionGroup().getSize() < 2))
4150 JvOptionPane.showInternalMessageDialog(this,
4151 MessageManager.getString(
4152 "label.you_must_select_least_two_sequences"),
4153 MessageManager.getString("label.invalid_selection"),
4154 JvOptionPane.WARNING_MESSAGE);
4158 JInternalFrame frame = new JInternalFrame();
4159 frame.setContentPane(new PairwiseAlignPanel(viewport));
4160 Desktop.addInternalFrame(frame,
4161 MessageManager.getString("action.pairwise_alignment"), 600,
4167 public void autoCalculate_actionPerformed(ActionEvent e)
4169 viewport.setAutoCalculateConsensusAndConservation(
4170 autoCalculate.isSelected());
4171 if (viewport.getAutoCalculateConsensusAndConservation())
4173 viewport.notifyAlignment();
4178 public void sortByTreeOption_actionPerformed(ActionEvent e)
4180 viewport.sortByTree = sortByTree.isSelected();
4184 protected void listenToViewSelections_actionPerformed(ActionEvent e)
4186 viewport.followSelection = listenToViewSelections.isSelected();
4190 * Constructs a tree panel and adds it to the desktop
4193 * tree type (NJ or AV)
4195 * name of score model used to compute the tree
4197 * parameters for the distance or similarity calculation
4199 void newTreePanel(String type, String modelName,
4200 SimilarityParamsI options)
4202 String frameTitle = "";
4205 boolean onSelection = false;
4206 if (viewport.getSelectionGroup() != null
4207 && viewport.getSelectionGroup().getSize() > 0)
4209 SequenceGroup sg = viewport.getSelectionGroup();
4211 /* Decide if the selection is a column region */
4212 for (SequenceI _s : sg.getSequences())
4214 if (_s.getLength() < sg.getEndRes())
4216 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4217 MessageManager.getString(
4218 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
4219 MessageManager.getString(
4220 "label.sequences_selection_not_aligned"),
4221 JvOptionPane.WARNING_MESSAGE);
4230 if (viewport.getAlignment().getHeight() < 2)
4236 tp = new TreePanel(alignPanel, type, modelName, options);
4237 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
4239 frameTitle += " from ";
4241 if (viewport.getViewName() != null)
4243 frameTitle += viewport.getViewName() + " of ";
4246 frameTitle += this.title;
4248 Dimension dim = Platform.getDimIfEmbedded(tp, 600, 500);
4249 Desktop.addInternalFrame(tp, frameTitle, dim.width, dim.height);
4260 public void addSortByOrderMenuItem(String title,
4261 final AlignmentOrder order)
4263 final JMenuItem item = new JMenuItem(MessageManager
4264 .formatMessage("action.by_title_param", new Object[]
4267 item.addActionListener(new java.awt.event.ActionListener()
4270 public void actionPerformed(ActionEvent e)
4272 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4274 // TODO: JBPNote - have to map order entries to curent SequenceI
4276 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4278 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
4279 viewport.getAlignment()));
4281 alignPanel.paintAlignment(true, false);
4287 * Add a new sort by annotation score menu item
4290 * the menu to add the option to
4292 * the label used to retrieve scores for each sequence on the
4295 public void addSortByAnnotScoreMenuItem(JMenu sort,
4296 final String scoreLabel)
4298 final JMenuItem item = new JMenuItem(scoreLabel);
4300 item.addActionListener(new java.awt.event.ActionListener()
4303 public void actionPerformed(ActionEvent e)
4305 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4306 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4307 viewport.getAlignment());// ,viewport.getSelectionGroup());
4308 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4309 viewport.getAlignment()));
4310 alignPanel.paintAlignment(true, false);
4316 * last hash for alignment's annotation array - used to minimise cost of
4319 protected int _annotationScoreVectorHash;
4322 * search the alignment and rebuild the sort by annotation score submenu the
4323 * last alignment annotation vector hash is stored to minimize cost of
4324 * rebuilding in subsequence calls.
4328 public void buildSortByAnnotationScoresMenu()
4330 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4335 if (viewport.getAlignment().getAlignmentAnnotation()
4336 .hashCode() == _annotationScoreVectorHash)
4341 sortByAnnotScore.removeAll();
4342 Set<String> scoreSorts = new HashSet<>();
4343 for (SequenceI sqa : viewport.getAlignment().getSequences())
4345 AlignmentAnnotation[] anns = sqa.getAnnotation();
4346 for (int i = 0; anns != null && i < anns.length; i++)
4348 AlignmentAnnotation aa = anns[i];
4349 if (aa != null && aa.hasScore() && aa.sequenceRef != null)
4351 scoreSorts.add(aa.label);
4355 for (String label : scoreSorts)
4357 addSortByAnnotScoreMenuItem(sortByAnnotScore, label);
4359 sortByAnnotScore.setVisible(!scoreSorts.isEmpty());
4361 _annotationScoreVectorHash = viewport.getAlignment()
4362 .getAlignmentAnnotation().hashCode();
4366 * Enable (or, if desired, make visible) the By Tree
4367 * submenu only if it has at least one element (or will have).
4371 protected void enableSortMenuOptions()
4373 List<TreePanel> treePanels = getTreePanels();
4374 sortByTreeMenu.setEnabled(!treePanels.isEmpty());
4378 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4379 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4380 * call. Listeners are added to remove the menu item when the treePanel is
4381 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4385 public void buildTreeSortMenu()
4387 sortByTreeMenu.removeAll();
4389 List<TreePanel> treePanels = getTreePanels();
4391 for (final TreePanel tp : treePanels)
4393 final JMenuItem item = new JMenuItem(tp.getTitle());
4394 item.addActionListener(new java.awt.event.ActionListener()
4397 public void actionPerformed(ActionEvent e)
4399 tp.sortByTree_actionPerformed();
4400 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4405 sortByTreeMenu.add(item);
4409 private List<TreePanel> getTreePanels()
4411 List<Component> comps = PaintRefresher.components
4412 .get(viewport.getSequenceSetId());
4413 List<TreePanel> treePanels = new ArrayList<>();
4414 for (Component comp : comps)
4416 if (comp instanceof TreePanel)
4418 treePanels.add((TreePanel) comp);
4423 public boolean sortBy(AlignmentOrder alorder, String undoname)
4425 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4426 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4427 if (undoname != null)
4429 addHistoryItem(new OrderCommand(undoname, oldOrder,
4430 viewport.getAlignment()));
4432 alignPanel.paintAlignment(true, false);
4437 * Work out whether the whole set of sequences or just the selected set will
4438 * be submitted for multiple alignment.
4441 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4443 // Now, check we have enough sequences
4444 AlignmentView msa = null;
4446 if ((viewport.getSelectionGroup() != null)
4447 && (viewport.getSelectionGroup().getSize() > 1))
4449 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4450 // some common interface!
4452 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4453 * SequenceI[sz = seqs.getSize(false)];
4455 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4456 * seqs.getSequenceAt(i); }
4458 msa = viewport.getAlignmentView(true);
4460 else if (viewport.getSelectionGroup() != null
4461 && viewport.getSelectionGroup().getSize() == 1)
4463 int option = JvOptionPane.showConfirmDialog(this,
4464 MessageManager.getString("warn.oneseq_msainput_selection"),
4465 MessageManager.getString("label.invalid_selection"),
4466 JvOptionPane.OK_CANCEL_OPTION);
4467 if (option == JvOptionPane.OK_OPTION)
4469 msa = viewport.getAlignmentView(false);
4474 msa = viewport.getAlignmentView(false);
4480 * Decides what is submitted to a secondary structure prediction service: the
4481 * first sequence in the alignment, or in the current selection, or, if the
4482 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4483 * region or the whole alignment. (where the first sequence in the set is the
4484 * one that the prediction will be for).
4486 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4488 AlignmentView seqs = null;
4490 if ((viewport.getSelectionGroup() != null)
4491 && (viewport.getSelectionGroup().getSize() > 0))
4493 seqs = viewport.getAlignmentView(true);
4497 seqs = viewport.getAlignmentView(false);
4499 // limit sequences - JBPNote in future - could spawn multiple prediction
4501 // TODO: viewport.getAlignment().isAligned is a global state - the local
4502 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4503 if (!viewport.getAlignment().isAligned(false))
4505 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4506 // TODO: if seqs.getSequences().length>1 then should really have warned
4520 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4522 // Pick the tree file
4523 JalviewFileChooser chooser = new JalviewFileChooser(
4524 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4525 chooser.setFileView(new JalviewFileView());
4526 chooser.setDialogTitle(
4527 MessageManager.getString("label.select_newick_like_tree_file"));
4528 chooser.setToolTipText(
4529 MessageManager.getString("label.load_tree_file"));
4531 chooser.setResponseHandler(0, new Runnable()
4536 String filePath = chooser.getSelectedFile().getPath();
4537 Cache.setProperty("LAST_DIRECTORY", filePath);
4538 NewickFile fin = null;
4541 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4542 DataSourceType.FILE));
4543 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4544 } catch (Exception ex)
4546 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4549 .getString("label.problem_reading_tree_file"),
4550 JvOptionPane.WARNING_MESSAGE);
4551 ex.printStackTrace();
4553 if (fin != null && fin.hasWarningMessage())
4555 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4556 fin.getWarningMessage(),
4557 MessageManager.getString(
4558 "label.possible_problem_with_tree_file"),
4559 JvOptionPane.WARNING_MESSAGE);
4563 chooser.showOpenDialog(this);
4566 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4568 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4571 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4572 int h, int x, int y)
4574 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4578 * Add a treeviewer for the tree extracted from a Newick file object to the
4579 * current alignment view
4586 * Associated alignment input data (or null)
4595 * @return TreePanel handle
4597 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4598 AlignmentView input, int w, int h, int x, int y)
4600 TreePanel tp = null;
4606 if (nf.getTree() != null)
4608 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4610 Dimension dim = Platform.getDimIfEmbedded(tp, -1, -1);
4613 dim = new Dimension(w, h);
4617 // no offset, either
4620 tp.setSize(dim.width, dim.height);
4624 tp.setLocation(x, y);
4627 Desktop.addInternalFrame(tp, treeTitle, dim.width, dim.height);
4629 } catch (Exception ex)
4631 ex.printStackTrace();
4639 * Schedule the web services menu rebuild to the event dispatch thread.
4641 public void buildWebServicesMenu()
4643 SwingUtilities.invokeLater(() -> {
4644 Cache.log.info("Rebuiling WS menu");
4645 webService.removeAll();
4646 if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
4648 Cache.log.info("Building web service menu for slivka");
4649 SlivkaWSDiscoverer discoverer = SlivkaWSDiscoverer.getInstance();
4650 JMenu submenu = new JMenu("Slivka");
4651 buildWebServicesMenu(discoverer, submenu);
4652 webService.add(submenu);
4654 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4656 WSDiscovererI jws2servs = Jws2Discoverer.getInstance();
4657 JMenu submenu = new JMenu("JABAWS");
4658 buildLegacyWebServicesMenu(submenu);
4659 buildWebServicesMenu(jws2servs, submenu);
4660 webService.add(submenu);
4662 build_fetchdbmenu(webService);
4666 private void buildLegacyWebServicesMenu(JMenu menu)
4668 JMenu secstrmenu = new JMenu("Secondary Structure Prediction");
4669 if (Discoverer.getServices() != null && Discoverer.getServices().size() > 0)
4671 var secstrpred = Discoverer.getServices().get("SecStrPred");
4672 if (secstrpred != null)
4674 for (ext.vamsas.ServiceHandle sh : secstrpred)
4676 var menuProvider = Discoverer.getServiceClient(sh);
4677 menuProvider.attachWSMenuEntry(secstrmenu, this);
4681 menu.add(secstrmenu);
4685 * Constructs the web services menu for the given discoverer under the
4686 * specified menu. This method must be called on the EDT
4689 * the discoverer used to build the menu
4691 * parent component which the elements will be attached to
4693 private void buildWebServicesMenu(WSDiscovererI discoverer, JMenu menu)
4695 if (discoverer.hasServices())
4697 PreferredServiceRegistry.getRegistry().populateWSMenuEntry(
4698 discoverer.getServices(), sv -> buildWebServicesMenu(), menu,
4701 if (discoverer.isRunning())
4703 JMenuItem item = new JMenuItem("Service discovery in progress.");
4704 item.setEnabled(false);
4707 else if (!discoverer.hasServices())
4709 JMenuItem item = new JMenuItem("No services available.");
4710 item.setEnabled(false);
4716 * construct any groupURL type service menu entries.
4720 protected void build_urlServiceMenu(JMenu webService)
4722 // TODO: remove this code when 2.7 is released
4723 // DEBUG - alignmentView
4725 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4726 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4728 * public void actionPerformed(ActionEvent e) {
4729 * jalview.datamodel.AlignmentView
4730 * .testSelectionViews(af.viewport.getAlignment(),
4731 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4733 * }); webService.add(testAlView);
4735 // TODO: refactor to RestClient discoverer and merge menu entries for
4736 // rest-style services with other types of analysis/calculation service
4737 // SHmmr test client - still being implemented.
4738 // DEBUG - alignmentView
4740 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4743 client.attachWSMenuEntry(
4744 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4750 * Searches the alignment sequences for xRefs and builds the Show
4751 * Cross-References menu (formerly called Show Products), with database
4752 * sources for which cross-references are found (protein sources for a
4753 * nucleotide alignment and vice versa)
4755 * @return true if Show Cross-references menu should be enabled
4757 public boolean canShowProducts()
4759 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4760 AlignmentI dataset = viewport.getAlignment().getDataset();
4762 showProducts.removeAll();
4763 final boolean dna = viewport.getAlignment().isNucleotide();
4765 if (seqs == null || seqs.length == 0)
4767 // nothing to see here.
4771 boolean showp = false;
4774 List<String> ptypes = new CrossRef(seqs, dataset)
4775 .findXrefSourcesForSequences(dna);
4777 for (final String source : ptypes)
4780 final AlignFrame af = this;
4781 JMenuItem xtype = new JMenuItem(source);
4782 xtype.addActionListener(new ActionListener()
4785 public void actionPerformed(ActionEvent e)
4787 showProductsFor(af.viewport.getSequenceSelection(), dna,
4791 showProducts.add(xtype);
4793 showProducts.setVisible(showp);
4794 showProducts.setEnabled(showp);
4795 } catch (Exception e)
4798 "canShowProducts threw an exception - please report to help@jalview.org",
4806 * Finds and displays cross-references for the selected sequences (protein
4807 * products for nucleotide sequences, dna coding sequences for peptides).
4810 * the sequences to show cross-references for
4812 * true if from a nucleotide alignment (so showing proteins)
4814 * the database to show cross-references for
4816 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4817 final String source)
4819 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4824 * Construct and display a new frame containing the translation of this
4825 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4828 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4830 AlignmentI al = null;
4833 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4835 al = dna.translateCdna(codeTable);
4836 } catch (Exception ex)
4838 jalview.bin.Cache.log.error(
4839 "Exception during translation. Please report this !", ex);
4840 final String msg = MessageManager.getString(
4841 "label.error_when_translating_sequences_submit_bug_report");
4842 final String errorTitle = MessageManager
4843 .getString("label.implementation_error")
4844 + MessageManager.getString("label.translation_failed");
4845 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4846 errorTitle, JvOptionPane.ERROR_MESSAGE);
4849 if (al == null || al.getHeight() == 0)
4851 final String msg = MessageManager.getString(
4852 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4853 final String errorTitle = MessageManager
4854 .getString("label.translation_failed");
4855 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4856 errorTitle, JvOptionPane.WARNING_MESSAGE);
4860 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4861 af.setFileFormat(this.currentFileFormat);
4862 final String newTitle = MessageManager
4863 .formatMessage("label.translation_of_params", new Object[]
4864 { this.getTitle(), codeTable.getId() });
4865 af.setTitle(newTitle);
4866 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4868 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4869 AlignViewport.openSplitFrame(this, af, new Alignment(seqs));
4873 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4880 * Set the file format
4884 public void setFileFormat(FileFormatI format)
4886 this.currentFileFormat = format;
4890 * Try to load a features file onto the alignment.
4893 * contents or path to retrieve file or a File object
4895 * access mode of file (see jalview.io.AlignFile)
4896 * @return true if features file was parsed correctly.
4898 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4901 return avc.parseFeaturesFile(file, sourceType,
4902 Cache.getDefault(Preferences.RELAXEDSEQIDMATCHING, false));
4907 public void refreshFeatureUI(boolean enableIfNecessary)
4909 // note - currently this is only still here rather than in the controller
4910 // because of the featureSettings hard reference that is yet to be
4912 if (enableIfNecessary)
4914 viewport.setShowSequenceFeatures(true);
4915 showSeqFeatures.setSelected(true);
4921 public void dragEnter(DropTargetDragEvent evt)
4926 public void dragExit(DropTargetEvent evt)
4931 public void dragOver(DropTargetDragEvent evt)
4936 public void dropActionChanged(DropTargetDragEvent evt)
4941 public void drop(DropTargetDropEvent evt)
4943 // JAL-1552 - acceptDrop required before getTransferable call for
4944 // Java's Transferable for native dnd
4945 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4946 Transferable t = evt.getTransferable();
4948 final List<Object> files = new ArrayList<>();
4949 List<DataSourceType> protocols = new ArrayList<>();
4953 Desktop.transferFromDropTarget(files, protocols, evt, t);
4954 if (files.size() > 0)
4956 new Thread(new Runnable()
4962 loadDroppedFiles(files, protocols, evt, t);
4966 } catch (Exception e)
4968 e.printStackTrace();
4972 protected void loadDroppedFiles(List<Object> files,
4973 List<DataSourceType> protocols, DropTargetDropEvent evt,
4978 // check to see if any of these files have names matching sequences
4981 SequenceIdMatcher idm = new SequenceIdMatcher(
4982 viewport.getAlignment().getSequencesArray());
4984 * Object[] { String,SequenceI}
4986 ArrayList<Object[]> filesmatched = new ArrayList<>();
4987 ArrayList<Object> filesnotmatched = new ArrayList<>();
4988 for (int i = 0; i < files.size(); i++)
4991 Object fileObj = files.get(i);
4992 String fileName = fileObj.toString();
4994 DataSourceType protocol = (fileObj instanceof File
4995 ? DataSourceType.FILE
4996 : FormatAdapter.checkProtocol(fileName));
4997 if (protocol == DataSourceType.FILE)
5000 if (fileObj instanceof File)
5002 file = (File) fileObj;
5003 Platform.cacheFileData(file);
5007 file = new File(fileName);
5009 pdbfn = file.getName();
5011 else if (protocol == DataSourceType.URL)
5013 URL url = new URL(fileName);
5014 pdbfn = url.getFile();
5016 if (pdbfn.length() > 0)
5018 // attempt to find a match in the alignment
5019 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5020 int l = 0, c = pdbfn.indexOf(".");
5021 while (mtch == null && c != -1)
5026 } while ((c = pdbfn.indexOf(".", l)) > l);
5029 pdbfn = pdbfn.substring(0, l);
5031 mtch = idm.findAllIdMatches(pdbfn);
5038 type = new IdentifyFile().identify(fileObj, protocol);
5039 } catch (Exception ex)
5043 if (type != null && type.isStructureFile())
5045 filesmatched.add(new Object[] { fileObj, protocol, mtch });
5049 // File wasn't named like one of the sequences or wasn't a PDB
5051 filesnotmatched.add(fileObj);
5055 if (filesmatched.size() > 0)
5057 boolean autoAssociate = Cache
5058 .getDefault(Preferences.AUTOASSOCIATE_PDBANDSEQS, false);
5061 String msg = MessageManager.formatMessage(
5062 "label.automatically_associate_structure_files_with_sequences_same_name",
5064 { Integer.valueOf(filesmatched.size()).toString() });
5065 String ttl = MessageManager.getString(
5066 "label.automatically_associate_structure_files_by_name");
5067 int choice = JvOptionPane.showConfirmDialog(this, msg, ttl,
5068 JvOptionPane.YES_NO_OPTION);
5069 autoAssociate = choice == JvOptionPane.YES_OPTION;
5073 for (Object[] fm : filesmatched)
5075 // try and associate
5076 // TODO: may want to set a standard ID naming formalism for
5077 // associating PDB files which have no IDs.
5078 for (SequenceI toassoc : (SequenceI[]) fm[2])
5080 PDBEntry pe = AssociatePdbFileWithSeq.associatePdbWithSeq(
5081 fm[0].toString(), (DataSourceType) fm[1], toassoc,
5085 System.err.println("Associated file : " + (fm[0].toString())
5086 + " with " + toassoc.getDisplayId(true));
5091 // TODO: do we need to update overview ? only if features are
5093 alignPanel.paintAlignment(true, false);
5099 * add declined structures as sequences
5101 for (Object[] o : filesmatched)
5103 filesnotmatched.add(o[0]);
5107 if (filesnotmatched.size() > 0)
5109 if (assocfiles > 0 && (Cache
5110 .getDefault("AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
5111 || JvOptionPane.showConfirmDialog(this,
5112 "<html>" + MessageManager.formatMessage(
5113 "label.ignore_unmatched_dropped_files_info",
5115 { Integer.valueOf(filesnotmatched.size())
5118 MessageManager.getString(
5119 "label.ignore_unmatched_dropped_files"),
5120 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
5124 for (Object fn : filesnotmatched)
5126 loadJalviewDataFile(fn, null, null, null);
5130 } catch (Exception ex)
5132 ex.printStackTrace();
5137 * Attempt to load a "dropped" file or URL string, by testing in turn for
5139 * <li>an Annotation file</li>
5140 * <li>a JNet file</li>
5141 * <li>a features file</li>
5142 * <li>else try to interpret as an alignment file</li>
5146 * either a filename or a URL string.
5147 * @throws InterruptedException
5148 * @throws IOException
5150 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
5151 FileFormatI format, SequenceI assocSeq)
5153 // BH 2018 was String file
5156 if (sourceType == null)
5158 sourceType = FormatAdapter.checkProtocol(file);
5160 // if the file isn't identified, or not positively identified as some
5161 // other filetype (PFAM is default unidentified alignment file type) then
5162 // try to parse as annotation.
5163 boolean isAnnotation = (format == null
5164 || FileFormat.Pfam.equals(format))
5165 ? new AnnotationFile().annotateAlignmentView(viewport,
5171 // first see if its a T-COFFEE score file
5172 TCoffeeScoreFile tcf = null;
5175 tcf = new TCoffeeScoreFile(file, sourceType);
5178 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5182 new TCoffeeColourScheme(viewport.getAlignment()));
5183 isAnnotation = true;
5184 setStatus(MessageManager.getString(
5185 "label.successfully_pasted_tcoffee_scores_to_alignment"));
5189 // some problem - if no warning its probable that the ID matching
5190 // process didn't work
5191 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
5192 tcf.getWarningMessage() == null
5193 ? MessageManager.getString(
5194 "label.check_file_matches_sequence_ids_alignment")
5195 : tcf.getWarningMessage(),
5196 MessageManager.getString(
5197 "label.problem_reading_tcoffee_score_file"),
5198 JvOptionPane.WARNING_MESSAGE);
5205 } catch (Exception x)
5208 "Exception when processing data source as T-COFFEE score file",
5214 // try to see if its a JNet 'concise' style annotation file *before*
5216 // try to parse it as a features file
5219 format = new IdentifyFile().identify(file, sourceType);
5221 if (FileFormat.ScoreMatrix == format)
5223 ScoreMatrixFile sm = new ScoreMatrixFile(
5224 new FileParse(file, sourceType));
5226 // todo: i18n this message
5227 setStatus(MessageManager.formatMessage(
5228 "label.successfully_loaded_matrix",
5229 sm.getMatrixName()));
5231 else if (FileFormat.Jnet.equals(format))
5233 JPredFile predictions = new JPredFile(file, sourceType);
5234 new JnetAnnotationMaker();
5235 JnetAnnotationMaker.add_annotation(predictions,
5236 viewport.getAlignment(), 0, false);
5237 viewport.getAlignment().setupJPredAlignment();
5238 isAnnotation = true;
5240 // else if (IdentifyFile.FeaturesFile.equals(format))
5241 else if (FileFormat.Features.equals(format))
5243 if (parseFeaturesFile(file, sourceType))
5245 SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
5246 if (splitFrame != null)
5248 splitFrame.repaint();
5252 alignPanel.paintAlignment(true, true);
5258 new FileLoader().LoadFile(viewport, file, sourceType, format);
5265 updateForAnnotations();
5267 } catch (Exception ex)
5269 ex.printStackTrace();
5270 } catch (OutOfMemoryError oom)
5275 } catch (Exception x)
5280 + (sourceType != null
5281 ? (sourceType == DataSourceType.PASTE
5283 : "using " + sourceType + " from "
5287 ? "(parsing as '" + format + "' file)"
5289 oom, Desktop.getDesktopPane());
5294 * Do all updates necessary after an annotation file such as jnet. Also called
5295 * from Jalview.loadAppletParams for "annotations", "jnetFile"
5298 public void updateForAnnotations()
5300 alignPanel.adjustAnnotationHeight();
5301 viewport.updateSequenceIdColours();
5302 buildSortByAnnotationScoresMenu();
5303 alignPanel.paintAlignment(true, true);
5307 * Change the display state for the given feature groups -- Added by BH from
5311 * list of group strings
5313 * visible or invisible
5316 public void setFeatureGroupState(String[] groups, boolean state)
5318 jalview.api.FeatureRenderer fr = null;
5319 viewport.setShowSequenceFeatures(true);
5320 if (alignPanel != null
5321 && (fr = alignPanel.getFeatureRenderer()) != null)
5324 fr.setGroupVisibility(Arrays.asList(groups), state);
5325 alignPanel.getSeqPanel().seqCanvas.repaint();
5326 if (alignPanel.overviewPanel != null)
5328 alignPanel.overviewPanel.updateOverviewImage();
5334 * Method invoked by the ChangeListener on the tabbed pane, in other words
5335 * when a different tabbed pane is selected by the user or programmatically.
5338 public void tabSelectionChanged(int index)
5342 alignPanel = alignPanels.get(index);
5343 viewport = alignPanel.av;
5344 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5345 setMenusFromViewport(viewport);
5346 if (featureSettings != null && featureSettings.isOpen()
5347 && featureSettings.fr.getViewport() != viewport)
5349 if (viewport.isShowSequenceFeatures())
5351 // refresh the featureSettings to reflect UI change
5352 showFeatureSettingsUI();
5356 // close feature settings for this view.
5357 featureSettings.close();
5364 * 'focus' any colour slider that is open to the selected viewport
5366 if (viewport.getConservationSelected())
5368 SliderPanel.setConservationSlider(alignPanel,
5369 viewport.getResidueShading(), alignPanel.getViewName());
5373 SliderPanel.hideConservationSlider();
5375 if (viewport.getAbovePIDThreshold())
5377 SliderPanel.setPIDSliderSource(alignPanel,
5378 viewport.getResidueShading(), alignPanel.getViewName());
5382 SliderPanel.hidePIDSlider();
5386 * If there is a frame linked to this one in a SplitPane, switch it to the
5387 * same view tab index. No infinite recursion of calls should happen, since
5388 * tabSelectionChanged() should not get invoked on setting the selected
5389 * index to an unchanged value. Guard against setting an invalid index
5390 * before the new view peer tab has been created.
5392 final AlignViewportI peer = viewport.getCodingComplement();
5395 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
5396 .getAlignPanel().alignFrame;
5397 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5399 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5405 * On right mouse click on view tab, prompt for and set new view name.
5408 public void tabbedPane_mousePressed(MouseEvent e)
5410 if (e.isPopupTrigger())
5412 String msg = MessageManager.getString("label.enter_view_name");
5413 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
5414 String reply = JvOptionPane.showInputDialog(msg, ttl);
5418 viewport.setViewName(reply);
5419 // TODO warn if reply is in getExistingViewNames()?
5420 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5425 public AlignViewport getCurrentView()
5431 * Open the dialog for regex description parsing.
5434 protected void extractScores_actionPerformed(ActionEvent e)
5436 ParseProperties pp = new jalview.analysis.ParseProperties(
5437 viewport.getAlignment());
5438 // TODO: verify regex and introduce GUI dialog for version 2.5
5439 // if (pp.getScoresFromDescription("col", "score column ",
5440 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5442 if (pp.getScoresFromDescription("description column",
5443 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5445 buildSortByAnnotationScoresMenu();
5453 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5457 protected void showDbRefs_actionPerformed(ActionEvent e)
5459 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5465 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5469 protected void showNpFeats_actionPerformed(ActionEvent e)
5471 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5475 * find the viewport amongst the tabs in this alignment frame and close that
5480 public boolean closeView(AlignViewportI av)
5484 this.closeMenuItem_actionPerformed(false);
5487 Component[] comp = tabbedPane.getComponents();
5488 for (int i = 0; comp != null && i < comp.length; i++)
5490 if (comp[i] instanceof AlignmentPanel)
5492 if (((AlignmentPanel) comp[i]).av == av)
5495 closeView((AlignmentPanel) comp[i]);
5503 protected void build_fetchdbmenu(JMenu webService)
5505 // Temporary hack - DBRef Fetcher always top level ws entry.
5506 // TODO We probably want to store a sequence database checklist in
5507 // preferences and have checkboxes.. rather than individual sources selected
5509 final JMenu rfetch = new JMenu(
5510 MessageManager.getString("action.fetch_db_references"));
5511 rfetch.setToolTipText(MessageManager.getString(
5512 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5513 webService.add(rfetch);
5515 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5516 MessageManager.getString("option.trim_retrieved_seqs"));
5517 trimrs.setToolTipText(
5518 MessageManager.getString("label.trim_retrieved_sequences"));
5520 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5521 trimrs.addActionListener(new ActionListener()
5524 public void actionPerformed(ActionEvent e)
5526 trimrs.setSelected(trimrs.isSelected());
5527 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5528 Boolean.valueOf(trimrs.isSelected()).toString());
5532 JMenuItem fetchr = new JMenuItem(
5533 MessageManager.getString("label.standard_databases"));
5534 fetchr.setToolTipText(
5535 MessageManager.getString("label.fetch_embl_uniprot"));
5536 fetchr.addActionListener(new ActionListener()
5540 public void actionPerformed(ActionEvent e)
5542 new Thread(new Runnable()
5547 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5548 .getAlignment().isNucleotide();
5549 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5550 alignPanel.av.getSequenceSelection(),
5551 alignPanel.alignFrame, null,
5552 alignPanel.alignFrame.featureSettings, isNucleotide);
5553 dbRefFetcher.addListener(new FetchFinishedListenerI()
5556 public void finished()
5559 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5560 .getFeatureSettingsModels())
5563 alignPanel.av.mergeFeaturesStyle(srcSettings);
5565 AlignFrame.this.setMenusForViewport();
5568 dbRefFetcher.fetchDBRefs(false);
5576 new Thread(new Runnable()
5582 // final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5583 // .getSequenceFetcherSingleton();
5584 javax.swing.SwingUtilities.invokeLater(new Runnable()
5589 jalview.ws.SequenceFetcher sf = jalview.ws.SequenceFetcher
5591 String[] dbclasses = sf.getNonAlignmentSources();
5592 List<DbSourceProxy> otherdb;
5593 JMenu dfetch = new JMenu();
5594 JMenu ifetch = new JMenu();
5595 JMenuItem fetchr = null;
5596 int comp = 0, icomp = 0, mcomp = 15;
5597 String mname = null;
5599 for (String dbclass : dbclasses)
5601 otherdb = sf.getSourceProxy(dbclass);
5602 // add a single entry for this class, or submenu allowing 'fetch
5604 if (otherdb == null || otherdb.size() < 1)
5610 mname = "From " + dbclass;
5612 if (otherdb.size() == 1)
5614 DbSourceProxy src = otherdb.get(0);
5615 DbSourceProxy[] dassource = new DbSourceProxy[] { src };
5616 fetchr = new JMenuItem(src.getDbSource());
5617 fetchr.addActionListener(new ActionListener()
5621 public void actionPerformed(ActionEvent e)
5623 new Thread(new Runnable()
5629 boolean isNucleotide = alignPanel.alignFrame
5630 .getViewport().getAlignment()
5632 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5633 alignPanel.av.getSequenceSelection(),
5634 alignPanel.alignFrame, dassource,
5635 alignPanel.alignFrame.featureSettings,
5638 .addListener(new FetchFinishedListenerI()
5641 public void finished()
5643 FeatureSettingsModelI srcSettings = dassource[0]
5644 .getFeatureColourScheme();
5645 alignPanel.av.mergeFeaturesStyle(
5647 AlignFrame.this.setMenusForViewport();
5650 dbRefFetcher.fetchDBRefs(false);
5656 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5657 MessageManager.formatMessage(
5658 "label.fetch_retrieve_from", new Object[]
5659 { src.getDbName() })));
5665 final DbSourceProxy[] dassource = otherdb
5666 .toArray(new DbSourceProxy[0]);
5668 DbSourceProxy src = otherdb.get(0);
5669 fetchr = new JMenuItem(MessageManager
5670 .formatMessage("label.fetch_all_param", new Object[]
5671 { src.getDbSource() }));
5672 fetchr.addActionListener(new ActionListener()
5675 public void actionPerformed(ActionEvent e)
5677 new Thread(new Runnable()
5683 boolean isNucleotide = alignPanel.alignFrame
5684 .getViewport().getAlignment()
5686 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5687 alignPanel.av.getSequenceSelection(),
5688 alignPanel.alignFrame, dassource,
5689 alignPanel.alignFrame.featureSettings,
5692 .addListener(new FetchFinishedListenerI()
5695 public void finished()
5697 AlignFrame.this.setMenusForViewport();
5700 dbRefFetcher.fetchDBRefs(false);
5706 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5707 MessageManager.formatMessage(
5708 "label.fetch_retrieve_from_all_sources",
5710 { Integer.valueOf(otherdb.size())
5712 src.getDbSource(), src.getDbName() })));
5715 // and then build the rest of the individual menus
5716 ifetch = new JMenu(MessageManager.formatMessage(
5717 "label.source_from_db_source", new Object[]
5718 { src.getDbSource() }));
5720 String imname = null;
5722 for (DbSourceProxy sproxy : otherdb)
5724 String dbname = sproxy.getDbName();
5725 String sname = dbname.length() > 5
5726 ? dbname.substring(0, 5) + "..."
5728 String msname = dbname.length() > 10
5729 ? dbname.substring(0, 10) + "..."
5733 imname = MessageManager
5734 .formatMessage("label.from_msname", new Object[]
5737 fetchr = new JMenuItem(msname);
5738 final DbSourceProxy[] dassrc = { sproxy };
5739 fetchr.addActionListener(new ActionListener()
5743 public void actionPerformed(ActionEvent e)
5745 new Thread(new Runnable()
5751 boolean isNucleotide = alignPanel.alignFrame
5752 .getViewport().getAlignment()
5754 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5755 alignPanel.av.getSequenceSelection(),
5756 alignPanel.alignFrame, dassrc,
5757 alignPanel.alignFrame.featureSettings,
5760 .addListener(new FetchFinishedListenerI()
5763 public void finished()
5765 AlignFrame.this.setMenusForViewport();
5768 dbRefFetcher.fetchDBRefs(false);
5774 fetchr.setToolTipText(
5775 "<html>" + MessageManager.formatMessage(
5776 "label.fetch_retrieve_from", new Object[]
5780 if (++icomp >= mcomp || i == (otherdb.size()))
5782 ifetch.setText(MessageManager.formatMessage(
5783 "label.source_to_target", imname, sname));
5785 ifetch = new JMenu();
5793 if (comp >= mcomp || dbi >= (dbclasses.length))
5795 dfetch.setText(MessageManager.formatMessage(
5796 "label.source_to_target", mname, dbclass));
5798 dfetch = new JMenu();
5811 * Left justify the whole alignment.
5814 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5816 viewport.getAlignment().justify(false);
5817 viewport.notifyAlignment();
5821 * Right justify the whole alignment.
5824 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5826 viewport.getAlignment().justify(true);
5827 viewport.notifyAlignment();
5831 public void setShowSeqFeatures(boolean b)
5833 showSeqFeatures.setSelected(b);
5834 viewport.setShowSequenceFeatures(b);
5841 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5842 * awt.event.ActionEvent)
5845 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5847 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5848 alignPanel.paintAlignment(false, false);
5855 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5859 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5861 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5862 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5870 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5871 * .event.ActionEvent)
5874 protected void showGroupConservation_actionPerformed(ActionEvent e)
5876 viewport.setShowGroupConservation(showGroupConservation.getState());
5877 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5884 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5885 * .event.ActionEvent)
5888 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5890 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5891 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5898 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5899 * .event.ActionEvent)
5902 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5904 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5905 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5909 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5911 showSequenceLogo.setState(true);
5912 viewport.setShowSequenceLogo(true);
5913 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5914 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5918 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5920 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5927 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5928 * .event.ActionEvent)
5931 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5933 if (avc.makeGroupsFromSelection())
5935 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5936 alignPanel.updateAnnotation();
5937 alignPanel.paintAlignment(true,
5938 viewport.needToUpdateStructureViews());
5942 public void clearAlignmentSeqRep()
5944 // TODO refactor alignmentseqrep to controller
5945 if (viewport.getAlignment().hasSeqrep())
5947 viewport.getAlignment().setSeqrep(null);
5948 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5949 alignPanel.updateAnnotation();
5950 alignPanel.paintAlignment(true, true);
5955 protected void createGroup_actionPerformed(ActionEvent e)
5957 if (avc.createGroup())
5959 if (applyAutoAnnotationSettings.isSelected())
5961 alignPanel.updateAnnotation(true, false);
5963 alignPanel.alignmentChanged();
5968 protected void unGroup_actionPerformed(ActionEvent e)
5972 alignPanel.alignmentChanged();
5977 * make the given alignmentPanel the currently selected tab
5979 * @param alignmentPanel
5981 public void setDisplayedView(AlignmentPanel alignmentPanel)
5983 if (!viewport.getSequenceSetId()
5984 .equals(alignmentPanel.av.getSequenceSetId()))
5986 throw new Error(MessageManager.getString(
5987 "error.implementation_error_cannot_show_view_alignment_frame"));
5989 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5990 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5992 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5997 * Action on selection of menu options to Show or Hide annotations.
6000 * @param forSequences
6001 * update sequence-related annotations
6002 * @param forAlignment
6003 * update non-sequence-related annotations
6006 protected void setAnnotationsVisibility(boolean visible,
6007 boolean forSequences, boolean forAlignment)
6009 AlignmentAnnotation[] anns = alignPanel.getAlignment()
6010 .getAlignmentAnnotation();
6015 for (AlignmentAnnotation aa : anns)
6018 * don't display non-positional annotations on an alignment
6020 if (aa.annotations == null)
6024 boolean apply = (aa.sequenceRef == null && forAlignment)
6025 || (aa.sequenceRef != null && forSequences);
6028 aa.visible = visible;
6031 alignPanel.validateAnnotationDimensions(true);
6032 alignPanel.alignmentChanged();
6036 * Store selected annotation sort order for the view and repaint.
6039 protected void sortAnnotations_actionPerformed()
6041 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
6043 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
6044 alignPanel.paintAlignment(false, false);
6049 * @return alignment panels in this alignment frame
6051 public List<? extends AlignmentViewPanel> getAlignPanels()
6053 // alignPanels is never null
6054 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
6059 * Open a new alignment window, with the cDNA associated with this (protein)
6060 * alignment, aligned as is the protein.
6062 protected void viewAsCdna_actionPerformed()
6064 // TODO no longer a menu action - refactor as required
6065 final AlignmentI alignment = getViewport().getAlignment();
6066 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
6067 if (mappings == null)
6071 List<SequenceI> cdnaSeqs = new ArrayList<>();
6072 for (SequenceI aaSeq : alignment.getSequences())
6074 for (AlignedCodonFrame acf : mappings)
6076 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
6080 * There is a cDNA mapping for this protein sequence - add to new
6081 * alignment. It will share the same dataset sequence as other mapped
6082 * cDNA (no new mappings need to be created).
6084 final Sequence newSeq = new Sequence(dnaSeq);
6085 newSeq.setDatasetSequence(dnaSeq);
6086 cdnaSeqs.add(newSeq);
6090 if (cdnaSeqs.size() == 0)
6092 // show a warning dialog no mapped cDNA
6095 AlignmentI cdna = new Alignment(
6096 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
6097 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
6098 AlignFrame.DEFAULT_HEIGHT);
6099 cdna.alignAs(alignment);
6100 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
6102 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
6103 AlignFrame.DEFAULT_HEIGHT);
6107 * Set visibility of dna/protein complement view (available when shown in a
6113 protected void showComplement_actionPerformed(boolean show)
6115 SplitContainerI sf = getSplitViewContainer();
6118 sf.setComplementVisible(this, show);
6123 * Generate the reverse (optionally complemented) of the selected sequences,
6124 * and add them to the alignment
6127 protected void showReverse_actionPerformed(boolean complement)
6129 AlignmentI al = null;
6132 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
6133 al = dna.reverseCdna(complement);
6134 viewport.addAlignment(al, "");
6135 addHistoryItem(new EditCommand(
6136 MessageManager.getString("label.add_sequences"), Action.PASTE,
6137 al.getSequencesArray(), 0, al.getWidth(),
6138 viewport.getAlignment()));
6139 } catch (Exception ex)
6141 System.err.println(ex.getMessage());
6147 * Try to run a script in the Groovy console, having first ensured that this
6148 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
6149 * be targeted at this alignment.
6152 protected void runGroovy_actionPerformed()
6154 Jalview.setCurrentAlignFrame(this);
6155 groovy.ui.Console console = Desktop.getGroovyConsole();
6156 if (console != null)
6160 console.runScript();
6161 } catch (Exception ex)
6163 System.err.println((ex.toString()));
6164 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
6165 MessageManager.getString("label.couldnt_run_groovy_script"),
6166 MessageManager.getString("label.groovy_support_failed"),
6167 JvOptionPane.ERROR_MESSAGE);
6172 System.err.println("Can't run Groovy script as console not found");
6177 * Hides columns containing (or not containing) a specified feature, provided
6178 * that would not leave all columns hidden
6180 * @param featureType
6181 * @param columnsContaining
6184 public boolean hideFeatureColumns(String featureType,
6185 boolean columnsContaining)
6187 boolean notForHiding = avc.markColumnsContainingFeatures(
6188 columnsContaining, false, false, featureType);
6191 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
6192 false, featureType))
6194 getViewport().hideSelectedColumns();
6202 protected void selectHighlightedColumns_actionPerformed(
6203 ActionEvent actionEvent)
6205 // include key modifier check in case user selects from menu
6206 avc.markHighlightedColumns(
6207 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
6208 (actionEvent.getModifiers() & (ActionEvent.META_MASK
6209 | ActionEvent.CTRL_MASK)) != 0);
6213 * Rebuilds the Colour menu, including any user-defined colours which have
6214 * been loaded either on startup or during the session
6216 public void buildColourMenu()
6218 colourMenu.removeAll();
6220 colourMenu.add(applyToAllGroups);
6221 colourMenu.add(textColour);
6222 colourMenu.addSeparator();
6224 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
6225 viewport.getAlignment(), false);
6227 colourMenu.add(annotationColour);
6228 bg.add(annotationColour);
6229 colourMenu.addSeparator();
6230 colourMenu.add(conservationMenuItem);
6231 colourMenu.add(modifyConservation);
6232 colourMenu.add(abovePIDThreshold);
6233 colourMenu.add(modifyPID);
6235 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
6236 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
6240 * Open a dialog (if not already open) that allows the user to select and
6241 * calculate PCA or Tree analysis
6243 protected void openTreePcaDialog()
6245 if (alignPanel.getCalculationDialog() == null)
6247 new CalculationChooser(AlignFrame.this);
6252 * Sets the status of the HMMER menu
6254 public void updateHMMERStatus()
6256 hmmerMenu.setEnabled(HmmerCommand.isHmmerAvailable());
6259 protected void loadVcf_actionPerformed()
6261 JalviewFileChooser chooser = new JalviewFileChooser(
6262 Cache.getProperty("LAST_DIRECTORY"));
6263 chooser.setFileView(new JalviewFileView());
6264 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
6265 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
6266 final AlignFrame us = this;
6267 chooser.setResponseHandler(0, new Runnable()
6272 String choice = chooser.getSelectedFile().getPath();
6273 Cache.setProperty("LAST_DIRECTORY", choice);
6274 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
6275 new VCFLoader(choice).loadVCF(seqs, us);
6278 chooser.showOpenDialog(null);
6282 private Rectangle lastFeatureSettingsBounds = null;
6284 public void setFeatureSettingsGeometry(Rectangle bounds)
6286 lastFeatureSettingsBounds = bounds;
6290 public Rectangle getFeatureSettingsGeometry()
6292 return lastFeatureSettingsBounds;
6295 public void scrollTo(int row, int column)
6297 alignPanel.getSeqPanel().scrollTo(row, column);
6300 public void scrollToRow(int row)
6302 alignPanel.getSeqPanel().scrollToRow(row);
6305 public void scrollToColumn(int column)
6307 alignPanel.getSeqPanel().scrollToColumn(column);
6311 * BH 2019 from JalviewLite
6313 * get sequence feature groups that are hidden or shown
6320 public String[] getFeatureGroupsOfState(boolean visible)
6322 jalview.api.FeatureRenderer fr = null;
6323 if (alignPanel != null
6324 && (fr = alignPanel.getFeatureRenderer()) != null)
6326 List<String> gps = fr.getGroups(visible);
6327 String[] _gps = gps.toArray(new String[gps.size()]);
6335 * @return list of feature groups on the view
6338 public String[] getFeatureGroups()
6340 jalview.api.FeatureRenderer fr = null;
6341 if (alignPanel != null
6342 && (fr = alignPanel.getFeatureRenderer()) != null)
6344 List<String> gps = fr.getFeatureGroups();
6345 String[] _gps = gps.toArray(new String[gps.size()]);
6351 public void select(SequenceGroup sel, ColumnSelection csel,
6352 HiddenColumns hidden)
6354 alignPanel.getSeqPanel().selection(sel, csel, hidden, null);
6362 static class PrintThread extends Thread
6366 public PrintThread(AlignmentPanel ap)
6371 static PageFormat pf;
6376 PrinterJob printJob = PrinterJob.getPrinterJob();
6380 printJob.setPrintable(ap, pf);
6384 printJob.setPrintable(ap);
6387 if (printJob.printDialog())
6392 } catch (Exception PrintException)
6394 PrintException.printStackTrace();