2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import java.util.Locale;
25 import java.io.IOException;
26 import java.util.HashSet;
29 import javax.swing.JFileChooser;
30 import javax.swing.JOptionPane;
31 import java.awt.BorderLayout;
32 import java.awt.Color;
33 import java.awt.Component;
34 import java.awt.Dimension;
35 import java.awt.Rectangle;
36 import java.awt.Toolkit;
37 import java.awt.datatransfer.Clipboard;
38 import java.awt.datatransfer.DataFlavor;
39 import java.awt.datatransfer.StringSelection;
40 import java.awt.datatransfer.Transferable;
41 import java.awt.dnd.DnDConstants;
42 import java.awt.dnd.DropTargetDragEvent;
43 import java.awt.dnd.DropTargetDropEvent;
44 import java.awt.dnd.DropTargetEvent;
45 import java.awt.dnd.DropTargetListener;
46 import java.awt.event.ActionEvent;
47 import java.awt.event.ActionListener;
48 import java.awt.event.FocusAdapter;
49 import java.awt.event.FocusEvent;
50 import java.awt.event.ItemEvent;
51 import java.awt.event.ItemListener;
52 import java.awt.event.KeyAdapter;
53 import java.awt.event.KeyEvent;
54 import java.awt.event.MouseEvent;
55 import java.awt.print.PageFormat;
56 import java.awt.print.PrinterJob;
57 import java.beans.PropertyChangeEvent;
58 import java.beans.PropertyChangeListener;
60 import java.io.FileWriter;
61 import java.io.PrintWriter;
63 import java.util.ArrayList;
64 import java.util.Arrays;
65 import java.util.Collection;
66 import java.util.Deque;
67 import java.util.Enumeration;
68 import java.util.Hashtable;
69 import java.util.List;
70 import java.util.Vector;
72 import javax.swing.ButtonGroup;
73 import javax.swing.JCheckBoxMenuItem;
74 import javax.swing.JComponent;
75 import javax.swing.JEditorPane;
76 import javax.swing.JInternalFrame;
77 import javax.swing.JLabel;
78 import javax.swing.JLayeredPane;
79 import javax.swing.JMenu;
80 import javax.swing.JMenuItem;
81 import javax.swing.JPanel;
82 import javax.swing.JScrollPane;
83 import javax.swing.SwingUtilities;
84 import javax.swing.event.InternalFrameAdapter;
85 import javax.swing.event.InternalFrameEvent;
87 import ext.vamsas.ServiceHandle;
88 import jalview.analysis.AlignmentSorter;
89 import jalview.analysis.AlignmentUtils;
90 import jalview.analysis.CrossRef;
91 import jalview.analysis.Dna;
92 import jalview.analysis.GeneticCodeI;
93 import jalview.analysis.ParseProperties;
94 import jalview.analysis.SequenceIdMatcher;
95 import jalview.api.AlignExportSettingsI;
96 import jalview.api.AlignViewControllerGuiI;
97 import jalview.api.AlignViewControllerI;
98 import jalview.api.AlignViewportI;
99 import jalview.api.AlignmentViewPanel;
100 import jalview.api.FeatureSettingsControllerI;
101 import jalview.api.FeatureSettingsModelI;
102 import jalview.api.SplitContainerI;
103 import jalview.api.ViewStyleI;
104 import jalview.api.analysis.SimilarityParamsI;
105 import jalview.bin.Cache;
106 import jalview.bin.Console;
107 import jalview.bin.Jalview;
108 import jalview.commands.CommandI;
109 import jalview.commands.EditCommand;
110 import jalview.commands.EditCommand.Action;
111 import jalview.commands.OrderCommand;
112 import jalview.commands.RemoveGapColCommand;
113 import jalview.commands.RemoveGapsCommand;
114 import jalview.commands.SlideSequencesCommand;
115 import jalview.commands.TrimRegionCommand;
116 import jalview.datamodel.AlignExportSettingsAdapter;
117 import jalview.datamodel.AlignedCodonFrame;
118 import jalview.datamodel.Alignment;
119 import jalview.datamodel.AlignmentAnnotation;
120 import jalview.datamodel.AlignmentExportData;
121 import jalview.datamodel.AlignmentI;
122 import jalview.datamodel.AlignmentOrder;
123 import jalview.datamodel.AlignmentView;
124 import jalview.datamodel.ColumnSelection;
125 import jalview.datamodel.HiddenColumns;
126 import jalview.datamodel.PDBEntry;
127 import jalview.datamodel.SeqCigar;
128 import jalview.datamodel.Sequence;
129 import jalview.datamodel.SequenceGroup;
130 import jalview.datamodel.SequenceI;
131 import jalview.gui.ColourMenuHelper.ColourChangeListener;
132 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
133 import jalview.hmmer.HMMAlign;
134 import jalview.hmmer.HMMBuild;
135 import jalview.hmmer.HMMERParamStore;
136 import jalview.hmmer.HMMERPreset;
137 import jalview.hmmer.HMMSearch;
138 import jalview.hmmer.HmmerCommand;
139 import jalview.hmmer.JackHMMER;
140 import jalview.io.AlignmentProperties;
141 import jalview.io.AnnotationFile;
142 import jalview.io.BackupFiles;
143 import jalview.io.BioJsHTMLOutput;
144 import jalview.io.DataSourceType;
145 import jalview.io.FileFormat;
146 import jalview.io.FileFormatI;
147 import jalview.io.FileFormats;
148 import jalview.io.FileLoader;
149 import jalview.io.FileParse;
150 import jalview.io.FormatAdapter;
151 import jalview.io.HtmlSvgOutput;
152 import jalview.io.IdentifyFile;
153 import jalview.io.JPredFile;
154 import jalview.io.JalviewFileChooser;
155 import jalview.io.JalviewFileView;
156 import jalview.io.JnetAnnotationMaker;
157 import jalview.io.NewickFile;
158 import jalview.io.ScoreMatrixFile;
159 import jalview.io.TCoffeeScoreFile;
160 import jalview.io.vcf.VCFLoader;
161 import jalview.jbgui.GAlignFrame;
162 import jalview.project.Jalview2XML;
163 import jalview.schemes.ColourSchemeI;
164 import jalview.schemes.ColourSchemes;
165 import jalview.schemes.ResidueColourScheme;
166 import jalview.schemes.TCoffeeColourScheme;
167 import jalview.util.HttpUtils;
168 import jalview.util.ImageMaker.TYPE;
169 import jalview.util.MessageManager;
170 import jalview.util.Platform;
171 import jalview.viewmodel.AlignmentViewport;
172 import jalview.viewmodel.ViewportRanges;
173 import jalview.ws.DBRefFetcher;
174 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
175 import jalview.ws.ServiceChangeListener;
176 import jalview.ws.WSDiscovererI;
177 import jalview.ws.api.ServiceWithParameters;
178 import jalview.ws.jws1.Discoverer;
179 import jalview.ws.jws2.Jws2Discoverer;
180 import jalview.ws.jws2.PreferredServiceRegistry;
181 import jalview.ws.params.ArgumentI;
182 import jalview.ws.params.ParamDatastoreI;
183 import jalview.ws.params.WsParamSetI;
184 import jalview.ws.seqfetcher.DbSourceProxy;
185 import jalview.ws2.client.api.WebServiceDiscovererI;
186 import jalview.ws2.client.slivka.SlivkaWSDiscoverer;
187 import jalview.ws2.gui.WebServicesMenuManager;
188 import java.io.IOException;
189 import java.util.HashSet;
190 import java.util.Set;
192 import javax.swing.JFileChooser;
193 import javax.swing.JOptionPane;
195 import java.awt.BorderLayout;
196 import java.awt.Color;
197 import java.awt.Component;
198 import java.awt.Dimension;
199 import java.awt.Rectangle;
200 import java.awt.Toolkit;
201 import java.awt.datatransfer.Clipboard;
202 import java.awt.datatransfer.DataFlavor;
203 import java.awt.datatransfer.StringSelection;
204 import java.awt.datatransfer.Transferable;
205 import java.awt.dnd.DnDConstants;
206 import java.awt.dnd.DropTargetDragEvent;
207 import java.awt.dnd.DropTargetDropEvent;
208 import java.awt.dnd.DropTargetEvent;
209 import java.awt.dnd.DropTargetListener;
210 import java.awt.event.ActionEvent;
211 import java.awt.event.ActionListener;
212 import java.awt.event.FocusAdapter;
213 import java.awt.event.FocusEvent;
214 import java.awt.event.ItemEvent;
215 import java.awt.event.ItemListener;
216 import java.awt.event.KeyAdapter;
217 import java.awt.event.KeyEvent;
218 import java.awt.event.MouseEvent;
219 import java.awt.print.PageFormat;
220 import java.awt.print.PrinterJob;
221 import java.beans.PropertyChangeEvent;
222 import java.beans.PropertyChangeListener;
224 import java.io.FileWriter;
225 import java.io.PrintWriter;
227 import java.util.ArrayList;
228 import java.util.Arrays;
229 import java.util.Collection;
230 import java.util.Deque;
231 import java.util.Enumeration;
232 import java.util.Hashtable;
233 import java.util.List;
234 import java.util.Vector;
236 import javax.swing.ButtonGroup;
237 import javax.swing.JCheckBoxMenuItem;
238 import javax.swing.JComponent;
239 import javax.swing.JEditorPane;
240 import javax.swing.JInternalFrame;
241 import javax.swing.JLabel;
242 import javax.swing.JLayeredPane;
243 import javax.swing.JMenu;
244 import javax.swing.JMenuItem;
245 import javax.swing.JPanel;
246 import javax.swing.JScrollPane;
247 import javax.swing.SwingUtilities;
248 import javax.swing.event.InternalFrameAdapter;
249 import javax.swing.event.InternalFrameEvent;
251 import ext.vamsas.ServiceHandle;
257 * @version $Revision$
259 @SuppressWarnings("serial")
260 public class AlignFrame extends GAlignFrame
261 implements DropTargetListener, IProgressIndicator,
262 AlignViewControllerGuiI, ColourChangeListener, ServiceChangeListener
265 public static int frameCount;
267 public static final int DEFAULT_WIDTH = 700;
269 public static final int DEFAULT_HEIGHT = 500;
272 * The currently displayed panel (selected tabbed view if more than one)
274 public AlignmentPanel alignPanel;
276 AlignViewport viewport;
278 public AlignViewControllerI avc;
280 List<AlignmentPanel> alignPanels = new ArrayList<>();
283 * Last format used to load or save alignments in this window
285 FileFormatI currentFileFormat = null;
288 * Current filename for this alignment
290 String fileName = null;
293 * TODO: remove reference to 'FileObject' in AlignFrame - not correct mapping
299 private DataSourceType protocol ;
302 * Creates a new AlignFrame object with specific width and height.
308 public AlignFrame(AlignmentI al, int width, int height)
310 this(al, null, width, height);
314 * Creates a new AlignFrame object with specific width, height and
320 * @param sequenceSetId
322 public AlignFrame(AlignmentI al, int width, int height,
323 String sequenceSetId)
325 this(al, null, width, height, sequenceSetId);
329 * Creates a new AlignFrame object with specific width, height and
335 * @param sequenceSetId
338 public AlignFrame(AlignmentI al, int width, int height,
339 String sequenceSetId, String viewId)
341 this(al, null, width, height, sequenceSetId, viewId);
345 * new alignment window with hidden columns
349 * @param hiddenColumns
350 * ColumnSelection or null
352 * Width of alignment frame
356 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
359 this(al, hiddenColumns, width, height, null);
363 * Create alignment frame for al with hiddenColumns, a specific width and
364 * height, and specific sequenceId
367 * @param hiddenColumns
370 * @param sequenceSetId
373 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
374 int height, String sequenceSetId)
376 this(al, hiddenColumns, width, height, sequenceSetId, null);
380 * Create alignment frame for al with hiddenColumns, a specific width and
381 * height, and specific sequenceId
384 * @param hiddenColumns
387 * @param sequenceSetId
392 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
393 int height, String sequenceSetId, String viewId)
398 setSize(width, height);
400 if (al.getDataset() == null)
405 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
407 // JalviewJS needs to distinguish a new panel from an old one in init()
408 // alignPanel = new AlignmentPanel(this, viewport);
409 // addAlignmentPanel(alignPanel, true);
413 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
414 HiddenColumns hiddenColumns, int width, int height)
416 setSize(width, height);
418 if (al.getDataset() == null)
423 viewport = new AlignViewport(al, hiddenColumns);
425 if (hiddenSeqs != null && hiddenSeqs.length > 0)
427 viewport.hideSequence(hiddenSeqs);
429 // alignPanel = new AlignmentPanel(this, viewport);
430 // addAlignmentPanel(alignPanel, true);
435 * Make a new AlignFrame from existing alignmentPanels
442 public AlignFrame(AlignmentPanel ap)
446 // addAlignmentPanel(ap, false);
451 * initalise the alignframe from the underlying viewport data and the
457 boolean newPanel = (alignPanel == null);
458 viewport.setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
463 // need to set this up front if NOANNOTATION is
464 // used in conjunction with SHOWOVERVIEW.
466 // I have not determined if this is appropriate for
467 // Jalview/Java, as it means we are setting this flag
468 // for all subsequent AlignFrames. For now, at least,
469 // I am setting it to be JalviewJS-only.
471 boolean showAnnotation = Jalview.getInstance().getShowAnnotation();
472 viewport.setShowAnnotation(showAnnotation);
474 alignPanel = new AlignmentPanel(this, viewport);
476 addAlignmentPanel(alignPanel, newPanel);
478 // setBackground(Color.white); // BH 2019
480 if (!Jalview.isHeadlessMode())
482 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
484 statusPanel.setVisible(Jalview.getInstance().getShowStatus());
485 alignFrameMenuBar.setVisible(Jalview.getInstance().getAllowMenuBar());
488 avc = new jalview.controller.AlignViewController(this, viewport,
490 if (viewport.getAlignmentConservationAnnotation() == null)
492 // BLOSUM62Colour.setEnabled(false);
493 conservationMenuItem.setEnabled(false);
494 modifyConservation.setEnabled(false);
495 // PIDColour.setEnabled(false);
496 // abovePIDThreshold.setEnabled(false);
497 // modifyPID.setEnabled(false);
500 String sortby = Cache.getDefault(Preferences.SORT_ALIGNMENT,
503 if (sortby.equals("Id"))
505 sortIDMenuItem_actionPerformed(null);
507 else if (sortby.equals("Pairwise Identity"))
509 sortPairwiseMenuItem_actionPerformed(null);
514 // this.alignPanel.av
515 // .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
517 setMenusFromViewport(viewport);
518 buildSortByAnnotationScoresMenu();
519 calculateTree.addActionListener(new ActionListener()
523 public void actionPerformed(ActionEvent e)
530 if (Desktop.getDesktopPane() != null)
532 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
533 addServiceListeners();
534 if (!Platform.isJS())
540 if (viewport.getWrapAlignment())
542 wrapMenuItem_actionPerformed(null);
545 if (Cache.getDefault(Preferences.SHOW_OVERVIEW, false))
547 this.overviewMenuItem_actionPerformed(null);
552 final List<AlignmentViewPanel> selviews = new ArrayList<>();
553 final List<AlignmentPanel> origview = new ArrayList<>();
554 final String menuLabel = MessageManager
555 .getString("label.copy_format_from");
556 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
557 new ViewSetProvider()
561 public AlignmentPanel[] getAllAlignmentPanels()
564 origview.add(alignPanel);
565 // make an array of all alignment panels except for this one
566 List<AlignmentPanel> aps = new ArrayList<>(
567 Arrays.asList(Desktop.getAlignmentPanels(null)));
568 aps.remove(AlignFrame.this.alignPanel);
569 return aps.toArray(new AlignmentPanel[aps.size()]);
571 }, selviews, new ItemListener()
575 public void itemStateChanged(ItemEvent e)
577 if (origview.size() > 0)
579 final AlignmentPanel ap = origview.get(0);
582 * Copy the ViewStyle of the selected panel to 'this one'.
583 * Don't change value of 'scaleProteinAsCdna' unless copying
586 ViewStyleI vs = selviews.get(0).getAlignViewport()
588 boolean fromSplitFrame = selviews.get(0)
589 .getAlignViewport().getCodingComplement() != null;
592 vs.setScaleProteinAsCdna(ap.getAlignViewport()
593 .getViewStyle().isScaleProteinAsCdna());
595 ap.getAlignViewport().setViewStyle(vs);
598 * Also rescale ViewStyle of SplitFrame complement if there is
599 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
600 * the whole ViewStyle (allow cDNA protein to have different
603 AlignViewportI complement = ap.getAlignViewport()
604 .getCodingComplement();
605 if (complement != null && vs.isScaleProteinAsCdna())
607 AlignFrame af = Desktop.getAlignFrameFor(complement);
608 ((SplitFrame) af.getSplitViewContainer())
610 af.setMenusForViewport();
614 ap.setSelected(true);
615 ap.alignFrame.setMenusForViewport();
620 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase(Locale.ROOT)
621 .indexOf("devel") > -1
622 || Cache.getDefault("VERSION", "DEVELOPMENT")
623 .toLowerCase(Locale.ROOT).indexOf("test") > -1)
625 formatMenu.add(vsel);
627 addFocusListener(new FocusAdapter()
631 public void focusGained(FocusEvent e)
633 Jalview.setCurrentAlignFrame(AlignFrame.this);
640 * Change the filename and format for the alignment, and enable the 'reload'
641 * button functionality.
650 public void setFileName(String file, FileFormatI format)
653 setFileFormat(format);
654 reload.setEnabled(true);
660 * @param file from SwingJS; may contain bytes -- for reload
661 * @param protocol from SwingJS; may be RELATIVE_URL
664 public void setFile(String fileName, File file, DataSourceType protocol, FileFormatI format)
666 this.fileName = fileName;
667 this.fileObject = file;
668 this.protocol = protocol;
669 setFileFormat(format);
670 reload.setEnabled(true);
674 * JavaScript will have this, maybe others. More dependable than a file name
675 * and maintains a reference to the actual bytes loaded.
680 public void setFileObject(File file)
682 this.fileObject = file;
686 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
690 void addKeyListener()
692 addKeyListener(new KeyAdapter()
696 public void keyPressed(KeyEvent evt)
698 if (viewport.cursorMode
699 && ((evt.getKeyCode() >= KeyEvent.VK_0
700 && evt.getKeyCode() <= KeyEvent.VK_9)
701 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
702 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
703 && Character.isDigit(evt.getKeyChar()))
705 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
708 switch (evt.getKeyCode())
711 case KeyEvent.VK_ESCAPE: // escape key
712 // alignPanel.deselectAllSequences();
713 alignPanel.deselectAllSequences();
717 case KeyEvent.VK_DOWN:
718 if (evt.isAltDown() || !viewport.cursorMode)
720 moveSelectedSequences(false);
722 if (viewport.cursorMode)
724 alignPanel.getSeqPanel().moveCursor(0, 1, evt.isShiftDown());
729 if (evt.isAltDown() || !viewport.cursorMode)
731 moveSelectedSequences(true);
733 if (viewport.cursorMode)
735 alignPanel.getSeqPanel().moveCursor(0, -1, evt.isShiftDown());
740 case KeyEvent.VK_LEFT:
741 if (evt.isAltDown() || !viewport.cursorMode)
743 slideSequences(false,
744 alignPanel.getSeqPanel().getKeyboardNo1());
748 alignPanel.getSeqPanel().moveCursor(-1, 0, evt.isShiftDown());
753 case KeyEvent.VK_RIGHT:
754 if (evt.isAltDown() || !viewport.cursorMode)
756 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
760 alignPanel.getSeqPanel().moveCursor(1, 0, evt.isShiftDown());
764 case KeyEvent.VK_SPACE:
765 if (viewport.cursorMode)
767 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
768 || evt.isShiftDown() || evt.isAltDown());
772 // case KeyEvent.VK_A:
773 // if (viewport.cursorMode)
775 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
776 // //System.out.println("A");
780 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
781 * System.out.println("closing bracket"); } break;
783 case KeyEvent.VK_DELETE:
784 case KeyEvent.VK_BACK_SPACE:
785 if (!viewport.cursorMode)
787 cut_actionPerformed();
791 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
792 || evt.isShiftDown() || evt.isAltDown());
798 if (viewport.cursorMode)
800 alignPanel.getSeqPanel().setCursorRow();
804 if (viewport.cursorMode && !evt.isControlDown())
806 alignPanel.getSeqPanel().setCursorColumn();
810 if (viewport.cursorMode)
812 alignPanel.getSeqPanel().setCursorPosition();
816 case KeyEvent.VK_ENTER:
817 case KeyEvent.VK_COMMA:
818 if (viewport.cursorMode)
820 alignPanel.getSeqPanel().setCursorRowAndColumn();
825 if (viewport.cursorMode)
827 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
831 if (viewport.cursorMode)
833 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
838 viewport.cursorMode = !viewport.cursorMode;
839 setStatus(MessageManager
840 .formatMessage("label.keyboard_editing_mode", new String[]
841 { (viewport.cursorMode ? "on" : "off") }));
842 if (viewport.cursorMode)
844 ViewportRanges ranges = viewport.getRanges();
845 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
847 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
850 alignPanel.getSeqPanel().seqCanvas.repaint();
856 Help.showHelpWindow();
857 } catch (Exception ex)
859 ex.printStackTrace();
864 boolean toggleSeqs = !evt.isControlDown();
865 boolean toggleCols = !evt.isShiftDown();
866 toggleHiddenRegions(toggleSeqs, toggleCols);
871 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
872 boolean modifyExisting = true; // always modify, don't clear
873 // evt.isShiftDown();
874 boolean invertHighlighted = evt.isAltDown();
875 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
879 case KeyEvent.VK_PAGE_UP:
880 viewport.getRanges().pageUp();
882 case KeyEvent.VK_PAGE_DOWN:
883 viewport.getRanges().pageDown();
889 public void keyReleased(KeyEvent evt)
891 switch (evt.getKeyCode())
893 case KeyEvent.VK_LEFT:
894 if (evt.isAltDown() || !viewport.cursorMode)
896 viewport.notifyAlignment();
900 case KeyEvent.VK_RIGHT:
901 if (evt.isAltDown() || !viewport.cursorMode)
903 viewport.notifyAlignment();
911 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
913 ap.alignFrame = this;
914 avc = new jalview.controller.AlignViewController(this, viewport,
919 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
921 int aSize = alignPanels.size();
923 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
925 if (aSize == 1 && ap.av.getViewName() == null)
927 this.getContentPane().add(ap, BorderLayout.CENTER);
933 setInitialTabVisible();
936 expandViews.setEnabled(true);
937 gatherViews.setEnabled(true);
938 tabbedPane.addTab(ap.av.getViewName(), ap);
940 ap.setVisible(false);
945 if (ap.av.isPadGaps())
947 ap.av.getAlignment().padGaps();
949 if (Jalview.getInstance().getStartCalculations())
951 ap.av.updateConservation(ap);
952 ap.av.updateConsensus(ap);
953 ap.av.updateStrucConsensus(ap);
954 ap.av.initInformationWorker(ap);
959 public void setInitialTabVisible()
961 expandViews.setEnabled(true);
962 gatherViews.setEnabled(true);
963 tabbedPane.setVisible(true);
964 AlignmentPanel first = alignPanels.get(0);
965 tabbedPane.addTab(first.av.getViewName(), first);
966 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
969 public AlignViewport getViewport()
975 public void servicesChanged(WSDiscovererI discoverer,
976 Collection<? extends ServiceWithParameters> services)
978 buildWebServicesMenu();
981 /* Set up intrinsic listeners for dynamically generated GUI bits. */
982 private void addServiceListeners()
984 if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
986 WSDiscovererI discoverer = SlivkaWSDiscoverer.getInstance();
987 discoverer.addServiceChangeListener(this);
989 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
991 WSDiscovererI discoverer = Jws2Discoverer.getInstance();
992 discoverer.addServiceChangeListener(this);
994 // legacy event listener for compatibility with jws1
995 PropertyChangeListener legacyListener = (changeEvent) -> {
996 buildWebServicesMenu();
998 Desktop.getInstance().addJalviewPropertyChangeListener("services",legacyListener);
1000 addInternalFrameListener(new InternalFrameAdapter() {
1002 public void internalFrameClosed(InternalFrameEvent e) {
1003 System.out.println("deregistering discoverer listener");
1004 SlivkaWSDiscoverer.getInstance().removeServiceChangeListener(AlignFrame.this);
1005 Jws2Discoverer.getInstance().removeServiceChangeListener(AlignFrame.this);
1006 Desktop.getInstance().removeJalviewPropertyChangeListener("services", legacyListener);
1007 closeMenuItem_actionPerformed(true);
1010 buildWebServicesMenu();
1014 * Configure menu items that vary according to whether the alignment is
1015 * nucleotide or protein
1018 public void setGUINucleotide()
1020 AlignmentI al = getViewport().getAlignment();
1021 boolean nucleotide = al.isNucleotide();
1023 loadVcf.setVisible(nucleotide);
1024 showTranslation.setVisible(nucleotide);
1025 showReverse.setVisible(nucleotide);
1026 showReverseComplement.setVisible(nucleotide);
1027 conservationMenuItem.setEnabled(!nucleotide);
1029 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
1030 showGroupConservation.setEnabled(!nucleotide);
1032 showComplementMenuItem
1033 .setText(nucleotide ? MessageManager.getString("label.protein")
1034 : MessageManager.getString("label.nucleotide"));
1038 * set up menus for the current viewport. This may be called after any
1039 * operation that affects the data in the current view (selection changed,
1040 * etc) to update the menus to reflect the new state.
1044 public void setMenusForViewport()
1046 setMenusFromViewport(viewport);
1050 * Need to call this method when tabs are selected for multiple views, or when
1051 * loading from Jalview2XML.java
1057 public void setMenusFromViewport(AlignViewport av)
1059 padGapsMenuitem.setSelected(av.isPadGaps());
1060 colourTextMenuItem.setSelected(av.isShowColourText());
1061 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
1062 modifyPID.setEnabled(abovePIDThreshold.isSelected());
1063 conservationMenuItem.setSelected(av.getConservationSelected());
1064 modifyConservation.setEnabled(conservationMenuItem.isSelected());
1065 seqLimits.setSelected(av.getShowJVSuffix());
1066 idRightAlign.setSelected(av.isRightAlignIds());
1067 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
1068 renderGapsMenuItem.setSelected(av.isRenderGaps());
1069 wrapMenuItem.setSelected(av.getWrapAlignment());
1070 scaleAbove.setVisible(av.getWrapAlignment());
1071 scaleLeft.setVisible(av.getWrapAlignment());
1072 scaleRight.setVisible(av.getWrapAlignment());
1073 annotationPanelMenuItem.setState(av.isShowAnnotation());
1074 // Show/hide annotations only enabled if annotation panel is shown
1075 syncAnnotationMenuItems(av.isShowAnnotation());
1076 viewBoxesMenuItem.setSelected(av.getShowBoxes());
1077 viewTextMenuItem.setSelected(av.getShowText());
1078 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
1079 showGroupConsensus.setSelected(av.isShowGroupConsensus());
1080 showGroupConservation.setSelected(av.isShowGroupConservation());
1081 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
1082 showSequenceLogo.setSelected(av.isShowSequenceLogo());
1083 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
1084 showInformationHistogram.setSelected(av.isShowInformationHistogram());
1085 showHMMSequenceLogo.setSelected(av.isShowHMMSequenceLogo());
1086 normaliseHMMSequenceLogo.setSelected(av.isNormaliseHMMSequenceLogo());
1088 ColourMenuHelper.setColourSelected(colourMenu,
1089 av.getGlobalColourScheme());
1091 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
1092 hiddenMarkers.setState(av.getShowHiddenMarkers());
1093 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
1094 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
1095 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
1097 .setSelected(av.getAutoCalculateConsensusAndConservation());
1098 sortByTree.setSelected(av.sortByTree);
1099 listenToViewSelections.setSelected(av.followSelection);
1101 showProducts.setEnabled(canShowProducts());
1102 setGroovyEnabled(Desktop.getGroovyConsole() != null);
1104 updateEditMenuBar();
1108 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
1113 public void setGroovyEnabled(boolean b)
1115 runGroovy.setEnabled(b);
1118 private IProgressIndicator progressBar;
1123 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
1127 public void setProgressBar(String message, long id)
1129 progressBar.setProgressBar(message, id);
1133 public void removeProgressBar(long id)
1135 progressBar.removeProgressBar(id);
1139 public void registerHandler(final long id,
1140 final IProgressIndicatorHandler handler)
1142 progressBar.registerHandler(id, handler);
1147 * @return true if any progress bars are still active
1151 public boolean operationInProgress()
1153 return progressBar.operationInProgress();
1157 * Sets the text of the status bar. Note that setting a null or empty value
1158 * will cause the status bar to be hidden, with possibly undesirable flicker
1159 * of the screen layout.
1163 public void setStatus(String text)
1165 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1169 * Added so Castor Mapping file can obtain Jalview Version
1172 public String getVersion()
1174 return Cache.getProperty("VERSION");
1177 public FeatureRenderer getFeatureRenderer()
1179 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1183 public void fetchSequence_actionPerformed()
1185 new SequenceFetcher(this);
1189 public void addFromFile_actionPerformed(ActionEvent e)
1191 Desktop.getInstance().inputLocalFileMenuItem_actionPerformed(viewport);
1195 public void hmmBuild_actionPerformed(boolean withDefaults)
1197 if (!alignmentIsSufficient(1))
1203 * get default parameters, and optionally show a dialog
1204 * to allow them to be modified
1206 ParamDatastoreI store = HMMERParamStore.forBuild(viewport);
1207 List<ArgumentI> args = store.getServiceParameters();
1211 WsParamSetI set = new HMMERPreset();
1212 WsJobParameters params = new WsJobParameters(store, set, args);
1213 params.showRunDialog().thenAccept((startJob) -> {
1216 var args2 = params.getJobParams();
1217 new Thread(new HMMBuild(this, args2)).start();
1223 new Thread(new HMMBuild(this, args)).start();
1228 public void hmmAlign_actionPerformed(boolean withDefaults)
1230 if (!(checkForHMM() && alignmentIsSufficient(2)))
1236 * get default parameters, and optionally show a dialog
1237 * to allow them to be modified
1239 ParamDatastoreI store = HMMERParamStore.forAlign(viewport);
1240 List<ArgumentI> args = store.getServiceParameters();
1244 WsParamSetI set = new HMMERPreset();
1245 WsJobParameters params = new WsJobParameters(store, set, args);
1246 params.showRunDialog().thenAccept((startJob) -> {
1249 var args2 = params.getJobParams();
1250 new Thread(new HMMAlign(this, args2)).start();
1256 new Thread(new HMMAlign(this, args)).start();
1261 public void hmmSearch_actionPerformed(boolean withDefaults)
1269 * get default parameters, and (if requested) show
1270 * dialog to allow modification
1272 ParamDatastoreI store = HMMERParamStore.forSearch(viewport);
1273 List<ArgumentI> args = store.getServiceParameters();
1277 WsParamSetI set = new HMMERPreset();
1278 WsJobParameters params = new WsJobParameters(store, set, args);
1279 params.showRunDialog().thenAccept((startJob) -> {
1282 var args2 = params.getJobParams();
1283 new Thread(new HMMSearch(this, args2)).start();
1284 alignPanel.repaint();
1290 new Thread(new HMMSearch(this, args)).start();
1291 alignPanel.repaint();
1296 public void jackhmmer_actionPerformed(boolean withDefaults)
1300 * get default parameters, and (if requested) show
1301 * dialog to allow modification
1304 ParamDatastoreI store = HMMERParamStore.forJackhmmer(viewport);
1305 List<ArgumentI> args = store.getServiceParameters();
1309 WsParamSetI set = new HMMERPreset();
1310 WsJobParameters params = new WsJobParameters(store, set, args);
1311 params.showRunDialog().thenAccept((startJob) -> {
1314 var args2 = params.getJobParams();
1315 new Thread(new JackHMMER(this, args2)).start();
1316 alignPanel.repaint();
1322 new Thread(new JackHMMER(this, args)).start();
1323 alignPanel.repaint();
1328 * Checks if the alignment has at least one hidden Markov model, if not shows
1329 * a dialog advising to run hmmbuild or load an HMM profile
1333 private boolean checkForHMM()
1335 if (viewport.getAlignment().getHmmSequences().isEmpty())
1337 JOptionPane.showMessageDialog(this,
1338 MessageManager.getString("warn.no_hmm"));
1345 protected void filterByEValue_actionPerformed()
1347 viewport.filterByEvalue(inputDouble("Enter E-Value Cutoff"));
1351 protected void filterByScore_actionPerformed()
1353 viewport.filterByScore(inputDouble("Enter Bit Score Threshold"));
1356 private double inputDouble(String message)
1360 while (d == null || d <= 0)
1362 str = JOptionPane.showInputDialog(this.alignPanel, message);
1365 d = Double.valueOf(str);
1366 } catch (NumberFormatException e)
1374 * Checks if the alignment contains the required number of sequences.
1379 public boolean alignmentIsSufficient(int required)
1381 if (getViewport().getSequenceSelection().length < required)
1383 JOptionPane.showMessageDialog(this,
1384 MessageManager.getString("label.not_enough_sequences"));
1391 * Opens a file browser and adds the selected file, if in Fasta, Stockholm or
1392 * Pfam format, to the list held under preference key "HMMSEARCH_DBS" (as a
1393 * comma-separated list)
1396 public void addDatabase_actionPerformed() throws IOException
1398 if (Cache.getProperty(Preferences.HMMSEARCH_DBS) == null)
1400 Cache.setProperty(Preferences.HMMSEARCH_DBS, "");
1403 String path = openFileChooser(false);
1404 if (path != null && new File(path).exists())
1406 IdentifyFile identifier = new IdentifyFile();
1407 FileFormatI format = identifier.identify(path, DataSourceType.FILE);
1408 if (format == FileFormat.Fasta || format == FileFormat.Stockholm
1409 || format == FileFormat.Pfam)
1411 String currentDbPaths = Cache
1412 .getProperty(Preferences.HMMSEARCH_DBS);
1413 currentDbPaths += Preferences.COMMA + path;
1414 Cache.setProperty(Preferences.HMMSEARCH_DBS, currentDbPaths);
1418 JOptionPane.showMessageDialog(this,
1419 MessageManager.getString("warn.invalid_format"));
1425 * Opens a file chooser, optionally restricted to selecting folders
1426 * (directories) only. Answers the path to the selected file or folder, or
1427 * null if none is chosen.
1432 protected String openFileChooser(boolean forFolder)
1434 // TODO duplicates GPreferences method - relocate to JalviewFileChooser?
1435 String choice = null;
1436 JFileChooser chooser = new JFileChooser();
1439 chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1441 chooser.setDialogTitle(
1442 MessageManager.getString("label.open_local_file"));
1443 chooser.setToolTipText(MessageManager.getString("action.open"));
1445 int value = chooser.showOpenDialog(this);
1447 if (value == JFileChooser.APPROVE_OPTION)
1449 choice = chooser.getSelectedFile().getPath();
1455 public void reload_actionPerformed(ActionEvent e)
1457 if (fileName == null && fileObject == null)
1461 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1462 // originating file's format
1463 // TODO: work out how to recover feature settings for correct view(s) when
1464 // file is reloaded.
1465 if (FileFormat.Jalview.equals(currentFileFormat))
1467 JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
1468 for (int i = 0; i < frames.length; i++)
1470 if (frames[i] instanceof AlignFrame && frames[i] != this
1471 && ((AlignFrame) frames[i]).fileName != null
1472 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1476 frames[i].setSelected(true);
1477 Desktop.getInstance().closeAssociatedWindows();
1478 } catch (java.beans.PropertyVetoException ex)
1484 Desktop.getInstance().closeAssociatedWindows();
1486 FileLoader loader = new FileLoader();
1487 loader.LoadFile(viewport, (fileObject == null ? fileName : fileObject), protocol, currentFileFormat);
1491 Rectangle bounds = this.getBounds();
1493 FileLoader loader = new FileLoader();
1495 AlignFrame newframe = null;
1497 if (fileObject == null)
1499 newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1504 newframe = loader.LoadFileWaitTillLoaded(fileObject,
1505 DataSourceType.FILE, currentFileFormat);
1508 newframe.setBounds(bounds);
1509 if (featureSettings != null && featureSettings.isShowing())
1511 final Rectangle fspos = featureSettings.frame.getBounds();
1512 // TODO: need a 'show feature settings' function that takes bounds -
1513 // need to refactor Desktop.addFrame
1514 newframe.featureSettings_actionPerformed(null);
1515 final FeatureSettings nfs = newframe.featureSettings;
1516 SwingUtilities.invokeLater(new Runnable()
1522 nfs.frame.setBounds(fspos);
1525 this.featureSettings.close();
1526 this.featureSettings = null;
1528 this.closeMenuItem_actionPerformed(true);
1534 public void addFromText_actionPerformed(ActionEvent e)
1536 Desktop.getInstance()
1537 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1541 public void addFromURL_actionPerformed(ActionEvent e)
1543 Desktop.getInstance().inputURLMenuItem_actionPerformed(viewport);
1547 public void save_actionPerformed(ActionEvent e)
1549 if (fileName == null || (currentFileFormat == null)
1550 || HttpUtils.startsWithHttpOrHttps(fileName))
1552 saveAs_actionPerformed();
1556 saveAlignment(fileName, currentFileFormat);
1561 * Saves the alignment to a file with a name chosen by the user, if necessary
1562 * warning if a file would be overwritten
1566 public void saveAs_actionPerformed()
1568 String format = currentFileFormat == null ? null
1569 : currentFileFormat.getName();
1570 JalviewFileChooser chooser = JalviewFileChooser
1571 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1573 chooser.setFileView(new JalviewFileView());
1574 chooser.setDialogTitle(
1575 MessageManager.getString("label.save_alignment_to_file"));
1576 chooser.setToolTipText(MessageManager.getString("action.save"));
1578 int value = chooser.showSaveDialog(this);
1580 if (value != JalviewFileChooser.APPROVE_OPTION)
1584 currentFileFormat = chooser.getSelectedFormat();
1585 // todo is this (2005) test now obsolete - value is never null?
1586 while (currentFileFormat == null)
1588 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
1590 .getString("label.select_file_format_before_saving"),
1591 MessageManager.getString("label.file_format_not_specified"),
1592 JvOptionPane.WARNING_MESSAGE);
1593 currentFileFormat = chooser.getSelectedFormat();
1594 value = chooser.showSaveDialog(this);
1595 if (value != JalviewFileChooser.APPROVE_OPTION)
1601 fileName = chooser.getSelectedFile().getPath();
1603 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1604 Cache.setProperty("LAST_DIRECTORY", fileName);
1605 saveAlignment(fileName, currentFileFormat);
1608 boolean lastSaveSuccessful = false;
1610 FileFormatI lastFormatSaved;
1612 String lastFilenameSaved;
1615 * Raise a dialog or status message for the last call to saveAlignment.
1617 * @return true if last call to saveAlignment(file, format) was successful.
1620 public boolean isSaveAlignmentSuccessful()
1623 if (!lastSaveSuccessful)
1625 if (!Platform.isHeadless())
1627 JvOptionPane.showInternalMessageDialog(this, MessageManager
1628 .formatMessage("label.couldnt_save_file", new Object[]
1629 { lastFilenameSaved }),
1630 MessageManager.getString("label.error_saving_file"),
1631 JvOptionPane.WARNING_MESSAGE);
1635 Console.error(MessageManager
1636 .formatMessage("label.couldnt_save_file", new Object[]
1637 { lastFilenameSaved }));
1643 setStatus(MessageManager.formatMessage(
1644 "label.successfully_saved_to_file_in_format", new Object[]
1645 { lastFilenameSaved, lastFormatSaved }));
1648 return lastSaveSuccessful;
1652 * Saves the alignment to the specified file path, in the specified format,
1653 * which may be an alignment format, or Jalview project format. If the
1654 * alignment has hidden regions, or the format is one capable of including
1655 * non-sequence data (features, annotations, groups), then the user may be
1656 * prompted to specify what to include in the output.
1662 public void saveAlignment(String file, FileFormatI format)
1664 lastSaveSuccessful = true;
1665 lastFilenameSaved = file;
1666 lastFormatSaved = format;
1668 if (FileFormat.Jalview.equals(format))
1670 String shortName = title;
1671 if (shortName.indexOf(File.separatorChar) > -1)
1673 shortName = shortName
1674 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
1676 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file,
1679 statusBar.setText(MessageManager.formatMessage(
1680 "label.successfully_saved_to_file_in_format", new Object[]
1681 { fileName, format }));
1686 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1687 Runnable cancelAction = new Runnable()
1693 lastSaveSuccessful = false;
1696 Runnable outputAction = new Runnable()
1702 // todo defer this to inside formatSequences (or later)
1703 AlignmentExportData exportData = viewport
1704 .getAlignExportData(options);
1705 String output = new FormatAdapter(alignPanel, options)
1706 .formatSequences(format, exportData.getAlignment(),
1707 exportData.getOmitHidden(),
1708 exportData.getStartEndPostions(),
1709 viewport.getAlignment().getHiddenColumns());
1712 lastSaveSuccessful = false;
1716 // create backupfiles object and get new temp filename destination
1717 boolean doBackup = BackupFiles.getEnabled();
1718 BackupFiles backupfiles = null;
1722 "ALIGNFRAME making backupfiles object for " + file);
1723 backupfiles = new BackupFiles(file);
1727 String tempFilePath = doBackup ? backupfiles.getTempFilePath()
1729 Console.trace("ALIGNFRAME setting PrintWriter");
1730 PrintWriter out = new PrintWriter(new FileWriter(tempFilePath));
1732 if (backupfiles != null)
1734 Console.trace("ALIGNFRAME about to write to temp file "
1735 + backupfiles.getTempFilePath());
1738 Console.trace("ALIGNFRAME about to close file");
1740 Console.trace("ALIGNFRAME closed file");
1741 AlignFrame.this.setTitle(file);
1742 statusBar.setText(MessageManager.formatMessage(
1743 "label.successfully_saved_to_file_in_format",
1745 { fileName, format.getName() }));
1746 lastSaveSuccessful = true;
1747 } catch (IOException e)
1749 lastSaveSuccessful = false;
1751 "ALIGNFRAME Something happened writing the temp file");
1752 Console.error(e.getMessage());
1753 Console.debug(Cache.getStackTraceString(e));
1754 } catch (Exception ex)
1756 lastSaveSuccessful = false;
1758 "ALIGNFRAME Something unexpected happened writing the temp file");
1759 Console.error(ex.getMessage());
1760 Console.debug(Cache.getStackTraceString(ex));
1765 backupfiles.setWriteSuccess(lastSaveSuccessful);
1766 Console.debug("ALIGNFRAME writing temp file was "
1767 + (lastSaveSuccessful ? "" : "NOT ") + "successful");
1768 // do the backup file roll and rename the temp file to actual file
1770 "ALIGNFRAME about to rollBackupsAndRenameTempFile");
1771 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1773 "ALIGNFRAME performed rollBackupsAndRenameTempFile "
1774 + (lastSaveSuccessful ? "" : "un")
1782 * show dialog with export options if applicable; else just do it
1784 if (AlignExportOptions.isNeeded(viewport, format))
1786 AlignExportOptions choices = new AlignExportOptions(
1787 alignPanel.getAlignViewport(), format, options);
1788 choices.setResponseAction(0, outputAction);
1789 choices.setResponseAction(1, cancelAction);
1790 choices.showDialog();
1799 * Outputs the alignment to textbox in the requested format, if necessary
1800 * first prompting the user for whether to include hidden regions or
1803 * @param fileFormatName
1807 protected void outputText_actionPerformed(String fileFormatName)
1809 FileFormatI fileFormat = FileFormats.getInstance()
1810 .forName(fileFormatName);
1811 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1812 Runnable outputAction = new Runnable()
1818 // todo defer this to inside formatSequences (or later)
1819 AlignmentExportData exportData = viewport
1820 .getAlignExportData(options);
1821 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1822 cap.setForInput(null);
1825 FileFormatI format = fileFormat;
1826 cap.setText(new FormatAdapter(alignPanel, options)
1827 .formatSequences(format, exportData.getAlignment(),
1828 exportData.getOmitHidden(),
1829 exportData.getStartEndPostions(),
1830 viewport.getAlignment().getHiddenColumns()));
1831 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1832 "label.alignment_output_command", new Object[]
1833 { fileFormat.getName() }), 600, 500);
1834 } catch (OutOfMemoryError oom)
1836 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1844 * show dialog with export options if applicable; else just do it
1846 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1848 AlignExportOptions choices = new AlignExportOptions(
1849 alignPanel.getAlignViewport(), fileFormat, options);
1850 choices.setResponseAction(0, outputAction);
1851 choices.showDialog();
1867 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1869 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1870 htmlSVG.exportHTML(null);
1874 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1876 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1877 bjs.exportHTML(null);
1882 public void createImageMap(File file, String image)
1884 alignPanel.makePNGImageMap(file, image);
1888 * Creates a PNG image of the alignment and writes it to the given file. If
1889 * the file is null, the user is prompted to choose a file.
1895 public void createPNG(File f)
1897 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1901 * Creates an EPS image of the alignment and writes it to the given file. If
1902 * the file is null, the user is prompted to choose a file.
1908 public void createEPS(File f)
1910 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1914 * Creates an SVG image of the alignment and writes it to the given file. If
1915 * the file is null, the user is prompted to choose a file.
1921 public void createSVG(File f)
1923 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1927 public void pageSetup_actionPerformed(ActionEvent e)
1929 PrinterJob printJob = PrinterJob.getPrinterJob();
1930 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1941 public void printMenuItem_actionPerformed(ActionEvent e)
1943 // Putting in a thread avoids Swing painting problems
1944 PrintThread thread = new PrintThread(alignPanel);
1949 public void exportFeatures_actionPerformed(ActionEvent e)
1951 new AnnotationExporter(alignPanel).exportFeatures();
1955 public void exportAnnotations_actionPerformed(ActionEvent e)
1957 new AnnotationExporter(alignPanel).exportAnnotations();
1961 public void associatedData_actionPerformed(ActionEvent e)
1962 throws IOException, InterruptedException
1964 final JalviewFileChooser chooser = new JalviewFileChooser(
1965 Cache.getProperty("LAST_DIRECTORY"));
1966 chooser.setFileView(new JalviewFileView());
1967 String tooltip = MessageManager
1968 .getString("label.load_jalview_annotations");
1969 chooser.setDialogTitle(tooltip);
1970 chooser.setToolTipText(tooltip);
1971 chooser.setResponseHandler(0, new Runnable()
1977 String choice = chooser.getSelectedFile().getPath();
1978 Cache.setProperty("LAST_DIRECTORY", choice);
1979 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1983 chooser.showOpenDialog(this);
1987 * Close the current view or all views in the alignment frame. If the frame
1988 * only contains one view then the alignment will be removed from memory.
1990 * @param closeAllTabs
1994 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1996 if (alignPanels != null && alignPanels.size() < 2)
1998 closeAllTabs = true;
2003 if (alignPanels != null)
2007 if (this.isClosed())
2009 // really close all the windows - otherwise wait till
2010 // setClosed(true) is called
2011 for (int i = 0; i < alignPanels.size(); i++)
2013 AlignmentPanel ap = alignPanels.get(i);
2020 closeView(alignPanel);
2025 if (featureSettings != null && featureSettings.isOpen())
2027 featureSettings.close();
2028 featureSettings = null;
2031 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
2032 * be called recursively, with the frame now in 'closed' state
2034 this.setClosed(true);
2036 } catch (Exception ex)
2038 ex.printStackTrace();
2043 * Close the specified panel and close up tabs appropriately.
2045 * @param panelToClose
2048 public void closeView(AlignmentPanel panelToClose)
2050 int index = tabbedPane.getSelectedIndex();
2051 int closedindex = tabbedPane.indexOfComponent(panelToClose);
2052 alignPanels.remove(panelToClose);
2053 panelToClose.closePanel();
2054 panelToClose = null;
2056 tabbedPane.removeTabAt(closedindex);
2057 tabbedPane.validate();
2059 if (index > closedindex || index == tabbedPane.getTabCount())
2061 // modify currently selected tab index if necessary.
2065 this.tabSelectionChanged(index);
2072 void updateEditMenuBar()
2075 if (viewport.getHistoryList().size() > 0)
2077 undoMenuItem.setEnabled(true);
2078 CommandI command = viewport.getHistoryList().peek();
2079 undoMenuItem.setText(MessageManager
2080 .formatMessage("label.undo_command", new Object[]
2081 { command.getDescription() }));
2085 undoMenuItem.setEnabled(false);
2086 undoMenuItem.setText(MessageManager.getString("action.undo"));
2089 if (viewport.getRedoList().size() > 0)
2091 redoMenuItem.setEnabled(true);
2093 CommandI command = viewport.getRedoList().peek();
2094 redoMenuItem.setText(MessageManager
2095 .formatMessage("label.redo_command", new Object[]
2096 { command.getDescription() }));
2100 redoMenuItem.setEnabled(false);
2101 redoMenuItem.setText(MessageManager.getString("action.redo"));
2106 public void addHistoryItem(CommandI command)
2108 if (command.getSize() > 0)
2110 viewport.addToHistoryList(command);
2111 viewport.clearRedoList();
2112 updateEditMenuBar();
2113 viewport.updateHiddenColumns();
2114 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
2115 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2116 // viewport.getColumnSelection()
2117 // .getHiddenColumns().size() > 0);
2123 * @return alignment objects for all views
2126 AlignmentI[] getViewAlignments()
2128 if (alignPanels != null)
2130 AlignmentI[] als = new AlignmentI[alignPanels.size()];
2132 for (AlignmentPanel ap : alignPanels)
2134 als[i++] = ap.av.getAlignment();
2138 if (viewport != null)
2140 return new AlignmentI[] { viewport.getAlignment() };
2153 protected void undoMenuItem_actionPerformed(ActionEvent e)
2155 if (viewport.getHistoryList().isEmpty())
2159 CommandI command = viewport.getHistoryList().pop();
2160 viewport.addToRedoList(command);
2161 command.undoCommand(getViewAlignments());
2163 AlignmentViewport originalSource = getOriginatingSource(command);
2164 updateEditMenuBar();
2166 if (originalSource != null)
2168 if (originalSource != viewport)
2171 "Implementation worry: mismatch of viewport origin for undo");
2173 originalSource.updateHiddenColumns();
2174 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
2176 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2177 // viewport.getColumnSelection()
2178 // .getHiddenColumns().size() > 0);
2179 originalSource.notifyAlignment();
2192 protected void redoMenuItem_actionPerformed(ActionEvent e)
2194 if (viewport.getRedoList().size() < 1)
2199 CommandI command = viewport.getRedoList().pop();
2200 viewport.addToHistoryList(command);
2201 command.doCommand(getViewAlignments());
2203 AlignmentViewport originalSource = getOriginatingSource(command);
2204 updateEditMenuBar();
2206 if (originalSource != null)
2209 if (originalSource != viewport)
2212 "Implementation worry: mismatch of viewport origin for redo");
2214 originalSource.updateHiddenColumns();
2215 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
2217 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2218 // viewport.getColumnSelection()
2219 // .getHiddenColumns().size() > 0);
2220 originalSource.notifyAlignment();
2225 AlignmentViewport getOriginatingSource(CommandI command)
2227 AlignmentViewport originalSource = null;
2228 // For sequence removal and addition, we need to fire
2229 // the property change event FROM the viewport where the
2230 // original alignment was altered
2231 AlignmentI al = null;
2232 if (command instanceof EditCommand)
2234 EditCommand editCommand = (EditCommand) command;
2235 al = editCommand.getAlignment();
2236 List<Component> comps = PaintRefresher.components
2237 .get(viewport.getSequenceSetId());
2239 for (Component comp : comps)
2241 if (comp instanceof AlignmentPanel)
2243 if (al == ((AlignmentPanel) comp).av.getAlignment())
2245 originalSource = ((AlignmentPanel) comp).av;
2252 if (originalSource == null)
2254 // The original view is closed, we must validate
2255 // the current view against the closed view first
2258 PaintRefresher.validateSequences(al, viewport.getAlignment());
2261 originalSource = viewport;
2264 return originalSource;
2268 * Calls AlignmentI.moveSelectedSequencesByOne with current sequence selection
2269 * or the sequence under cursor in keyboard mode
2275 public void moveSelectedSequences(boolean up)
2277 SequenceGroup sg = viewport.getSelectionGroup();
2281 if (viewport.cursorMode)
2283 sg = new SequenceGroup();
2284 sg.addSequence(viewport.getAlignment().getSequenceAt(
2285 alignPanel.getSeqPanel().seqCanvas.cursorY), false);
2293 if (sg.getSize() < 1)
2297 // TODO: JAL-3733 - add an event to the undo buffer for this !
2298 viewport.getAlignment().moveSelectedSequencesByOne(sg,
2299 viewport.getHiddenRepSequences(), up);
2300 alignPanel.paintAlignment(true, false);
2303 synchronized void slideSequences(boolean right, int size)
2305 List<SequenceI> sg = new ArrayList<>();
2306 if (viewport.cursorMode)
2308 sg.add(viewport.getAlignment()
2309 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
2311 else if (viewport.getSelectionGroup() != null
2312 && viewport.getSelectionGroup().getSize() != viewport
2313 .getAlignment().getHeight())
2315 sg = viewport.getSelectionGroup()
2316 .getSequences(viewport.getHiddenRepSequences());
2324 List<SequenceI> invertGroup = new ArrayList<>();
2326 for (SequenceI seq : viewport.getAlignment().getSequences())
2328 if (!sg.contains(seq))
2330 invertGroup.add(seq);
2334 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
2336 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
2337 for (int i = 0; i < invertGroup.size(); i++)
2339 seqs2[i] = invertGroup.get(i);
2342 SlideSequencesCommand ssc;
2345 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
2346 viewport.getGapCharacter());
2350 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
2351 viewport.getGapCharacter());
2354 int groupAdjustment = 0;
2355 if (ssc.getGapsInsertedBegin() && right)
2357 if (viewport.cursorMode)
2359 alignPanel.getSeqPanel().moveCursor(size, 0);
2363 groupAdjustment = size;
2366 else if (!ssc.getGapsInsertedBegin() && !right)
2368 if (viewport.cursorMode)
2370 alignPanel.getSeqPanel().moveCursor(-size, 0);
2374 groupAdjustment = -size;
2378 if (groupAdjustment != 0)
2380 viewport.getSelectionGroup().setStartRes(
2381 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
2382 viewport.getSelectionGroup().setEndRes(
2383 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
2387 * just extend the last slide command if compatible; but not if in
2388 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
2390 boolean appendHistoryItem = false;
2391 Deque<CommandI> historyList = viewport.getHistoryList();
2392 boolean inSplitFrame = getSplitViewContainer() != null;
2393 if (!inSplitFrame && historyList != null && historyList.size() > 0
2394 && historyList.peek() instanceof SlideSequencesCommand)
2396 appendHistoryItem = ssc.appendSlideCommand(
2397 (SlideSequencesCommand) historyList.peek());
2400 if (!appendHistoryItem)
2402 addHistoryItem(ssc);
2416 protected void copy_actionPerformed()
2418 if (viewport.getSelectionGroup() == null)
2422 // TODO: preserve the ordering of displayed alignment annotation in any
2423 // internal paste (particularly sequence associated annotation)
2424 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2425 String[] omitHidden = null;
2427 if (viewport.hasHiddenColumns())
2429 omitHidden = viewport.getViewAsString(true);
2432 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2433 seqs, omitHidden, null);
2435 StringSelection ss = new StringSelection(output);
2437 Desktop d = Desktop.getInstance();
2440 d.internalCopy = true;
2441 // Its really worth setting the clipboard contents
2442 // to empty before setting the large StringSelection!!
2443 Toolkit.getDefaultToolkit().getSystemClipboard()
2444 .setContents(new StringSelection(""), null);
2446 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2448 } catch (OutOfMemoryError er)
2450 new OOMWarning("copying region", er);
2454 HiddenColumns hiddenColumns = null;
2455 if (viewport.hasHiddenColumns())
2457 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2458 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2460 // create new HiddenColumns object with copy of hidden regions
2461 // between startRes and endRes, offset by startRes
2462 hiddenColumns = new HiddenColumns(
2463 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2464 hiddenCutoff, hiddenOffset);
2467 d.jalviewClipboard = new Object[] { seqs,
2468 viewport.getAlignment().getDataset(), hiddenColumns };
2469 setStatus(MessageManager.formatMessage(
2470 "label.copied_sequences_to_clipboard", new Object[]
2471 { Integer.valueOf(seqs.length).toString() }));
2479 * @throws InterruptedException
2480 * @throws IOException
2484 protected void pasteNew_actionPerformed(ActionEvent e)
2485 throws IOException, InterruptedException
2495 * @throws InterruptedException
2496 * @throws IOException
2500 protected void pasteThis_actionPerformed(ActionEvent e)
2501 throws IOException, InterruptedException
2507 * Paste contents of Jalview clipboard
2509 * @param newAlignment
2510 * true to paste to a new alignment, otherwise add to this.
2511 * @throws InterruptedException
2512 * @throws IOException
2514 void paste(boolean newAlignment) throws IOException, InterruptedException
2516 boolean externalPaste = true;
2519 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2520 Transferable contents = c.getContents(this);
2522 if (contents == null)
2531 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2532 if (str.length() < 1)
2537 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2539 } catch (OutOfMemoryError er)
2541 new OOMWarning("Out of memory pasting sequences!!", er);
2545 SequenceI[] sequences;
2546 boolean annotationAdded = false;
2547 AlignmentI alignment = null;
2549 Desktop d = Desktop.getInstance();
2551 if (d.jalviewClipboard != null)
2553 // The clipboard was filled from within Jalview, we must use the
2555 // And dataset from the copied alignment
2556 SequenceI[] newseq = (SequenceI[]) d.jalviewClipboard[0];
2557 // be doubly sure that we create *new* sequence objects.
2558 sequences = new SequenceI[newseq.length];
2559 for (int i = 0; i < newseq.length; i++)
2561 sequences[i] = new Sequence(newseq[i]);
2563 alignment = new Alignment(sequences);
2564 externalPaste = false;
2568 // parse the clipboard as an alignment.
2569 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2571 sequences = alignment.getSequencesArray();
2575 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2581 if (d.jalviewClipboard != null)
2583 // dataset is inherited
2584 alignment.setDataset((Alignment) d.jalviewClipboard[1]);
2588 // new dataset is constructed
2589 alignment.setDataset(null);
2591 alwidth = alignment.getWidth() + 1;
2595 AlignmentI pastedal = alignment; // preserve pasted alignment object
2596 // Add pasted sequences and dataset into existing alignment.
2597 alignment = viewport.getAlignment();
2598 alwidth = alignment.getWidth() + 1;
2599 // decide if we need to import sequences from an existing dataset
2600 boolean importDs = d.jalviewClipboard != null
2601 && d.jalviewClipboard[1] != alignment.getDataset();
2602 // importDs==true instructs us to copy over new dataset sequences from
2603 // an existing alignment
2604 Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2606 // minimum dataset set
2608 for (int i = 0; i < sequences.length; i++)
2612 newDs.addElement(null);
2614 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2616 if (importDs && ds != null)
2618 if (!newDs.contains(ds))
2620 newDs.setElementAt(ds, i);
2621 ds = new Sequence(ds);
2622 // update with new dataset sequence
2623 sequences[i].setDatasetSequence(ds);
2627 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2632 // copy and derive new dataset sequence
2633 sequences[i] = sequences[i].deriveSequence();
2634 alignment.getDataset()
2635 .addSequence(sequences[i].getDatasetSequence());
2636 // TODO: avoid creation of duplicate dataset sequences with a
2637 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2639 alignment.addSequence(sequences[i]); // merges dataset
2643 newDs.clear(); // tidy up
2645 if (alignment.getAlignmentAnnotation() != null)
2647 for (AlignmentAnnotation alan : alignment
2648 .getAlignmentAnnotation())
2650 if (alan.graphGroup > fgroup)
2652 fgroup = alan.graphGroup;
2656 if (pastedal.getAlignmentAnnotation() != null)
2658 // Add any annotation attached to alignment.
2659 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2660 for (int i = 0; i < alann.length; i++)
2662 annotationAdded = true;
2663 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2665 AlignmentAnnotation newann = new AlignmentAnnotation(
2667 if (newann.graphGroup > -1)
2669 if (newGraphGroups.size() <= newann.graphGroup
2670 || newGraphGroups.get(newann.graphGroup) == null)
2672 for (int q = newGraphGroups
2673 .size(); q <= newann.graphGroup; q++)
2675 newGraphGroups.add(q, null);
2677 newGraphGroups.set(newann.graphGroup,
2678 Integer.valueOf(++fgroup));
2680 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2684 newann.padAnnotation(alwidth);
2685 alignment.addAnnotation(newann);
2695 addHistoryItem(new EditCommand(
2696 MessageManager.getString("label.add_sequences"),
2697 Action.PASTE, sequences, 0, alignment.getWidth(),
2700 // Add any annotations attached to sequences
2701 for (int i = 0; i < sequences.length; i++)
2703 if (sequences[i].getAnnotation() != null)
2705 AlignmentAnnotation newann;
2706 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2708 annotationAdded = true;
2709 newann = sequences[i].getAnnotation()[a];
2710 newann.adjustForAlignment();
2711 newann.padAnnotation(alwidth);
2712 if (newann.graphGroup > -1)
2714 if (newann.graphGroup > -1)
2716 if (newGraphGroups.size() <= newann.graphGroup
2717 || newGraphGroups.get(newann.graphGroup) == null)
2719 for (int q = newGraphGroups
2720 .size(); q <= newann.graphGroup; q++)
2722 newGraphGroups.add(q, null);
2724 newGraphGroups.set(newann.graphGroup,
2725 Integer.valueOf(++fgroup));
2727 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2731 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2735 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2743 // propagate alignment changed.
2744 viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2745 if (annotationAdded)
2747 // Duplicate sequence annotation in all views.
2748 AlignmentI[] alview = this.getViewAlignments();
2749 for (int i = 0; i < sequences.length; i++)
2751 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2756 for (int avnum = 0; avnum < alview.length; avnum++)
2758 if (alview[avnum] != alignment)
2760 // duplicate in a view other than the one with input focus
2761 int avwidth = alview[avnum].getWidth() + 1;
2762 // this relies on sann being preserved after we
2763 // modify the sequence's annotation array for each duplication
2764 for (int a = 0; a < sann.length; a++)
2766 AlignmentAnnotation newann = new AlignmentAnnotation(
2768 sequences[i].addAlignmentAnnotation(newann);
2769 newann.padAnnotation(avwidth);
2770 alview[avnum].addAnnotation(newann); // annotation was
2771 // duplicated earlier
2772 // TODO JAL-1145 graphGroups are not updated for sequence
2773 // annotation added to several views. This may cause
2775 alview[avnum].setAnnotationIndex(newann, a);
2780 buildSortByAnnotationScoresMenu();
2782 viewport.notifyAlignment();
2783 if (alignPanels != null)
2785 for (AlignmentPanel ap : alignPanels)
2787 ap.validateAnnotationDimensions(false);
2792 alignPanel.validateAnnotationDimensions(false);
2798 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2800 String newtitle = new String("Copied sequences");
2802 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2804 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2805 af.viewport.setHiddenColumns(hc);
2808 // >>>This is a fix for the moment, until a better solution is
2810 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2811 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2812 .getFeatureRenderer());
2814 // TODO: maintain provenance of an alignment, rather than just make the
2815 // title a concatenation of operations.
2818 if (title.startsWith("Copied sequences"))
2824 newtitle = newtitle.concat("- from " + title);
2829 newtitle = new String("Pasted sequences");
2832 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2837 } catch (Exception ex)
2839 ex.printStackTrace();
2840 System.out.println("Exception whilst pasting: " + ex);
2841 // could be anything being pasted in here
2846 protected void expand_newalign(ActionEvent e)
2850 AlignmentI alignment = AlignmentUtils
2851 .expandContext(getViewport().getAlignment(), -1);
2852 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2854 String newtitle = new String("Flanking alignment");
2855 Desktop d = Desktop.getInstance();
2856 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2858 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2859 af.viewport.setHiddenColumns(hc);
2862 // >>>This is a fix for the moment, until a better solution is
2864 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2865 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2866 .getFeatureRenderer());
2868 // TODO: maintain provenance of an alignment, rather than just make the
2869 // title a concatenation of operations.
2871 if (title.startsWith("Copied sequences"))
2877 newtitle = newtitle.concat("- from " + title);
2881 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2883 } catch (Exception ex)
2885 ex.printStackTrace();
2886 System.out.println("Exception whilst pasting: " + ex);
2887 // could be anything being pasted in here
2888 } catch (OutOfMemoryError oom)
2890 new OOMWarning("Viewing flanking region of alignment", oom);
2895 * Action Cut (delete and copy) the selected region
2899 protected void cut_actionPerformed()
2901 copy_actionPerformed();
2902 delete_actionPerformed();
2906 * Performs menu option to Delete the currently selected region
2910 protected void delete_actionPerformed()
2913 SequenceGroup sg = viewport.getSelectionGroup();
2919 Runnable okAction = new Runnable()
2925 SequenceI[] cut = sg.getSequences()
2926 .toArray(new SequenceI[sg.getSize()]);
2928 addHistoryItem(new EditCommand(
2929 MessageManager.getString("label.cut_sequences"), Action.CUT,
2930 cut, sg.getStartRes(),
2931 sg.getEndRes() - sg.getStartRes() + 1,
2932 viewport.getAlignment()));
2934 viewport.setSelectionGroup(null);
2935 viewport.sendSelection();
2936 viewport.getAlignment().deleteGroup(sg);
2938 viewport.notifyAlignment();
2940 if (viewport.getAlignment().getHeight() < 1)
2944 AlignFrame.this.setClosed(true);
2945 } catch (Exception ex)
2955 * If the cut affects all sequences, prompt for confirmation
2957 boolean wholeHeight = sg.getSize() == viewport.getAlignment()
2959 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2960 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2961 if (wholeHeight && wholeWidth)
2963 JvOptionPane dialog = JvOptionPane
2964 .newOptionDialog(Desktop.getDesktopPane());
2965 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2966 Object[] options = new Object[] {
2967 MessageManager.getString("action.ok"),
2968 MessageManager.getString("action.cancel") };
2969 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2970 MessageManager.getString("label.delete_all"),
2971 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2972 options, options[0]);
2988 protected void deleteGroups_actionPerformed(ActionEvent e)
2990 if (avc.deleteGroups())
2992 updateAll(viewport.getSequenceSetId());
2996 private void updateAll(String id)
3000 // this will force a non-fast repaint of both the IdPanel and SeqPanel
3001 alignPanel.getIdPanel().getIdCanvas().setNoFastPaint();
3002 alignPanel.getSeqPanel().seqCanvas.setNoFastPaint();
3003 alignPanel.repaint();
3008 PaintRefresher.Refresh(this, id);
3009 alignPanel.paintAlignment(true, true);
3011 alignPanel.updateAnnotation();
3022 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
3024 alignPanel.selectAllSequences();
3035 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
3037 alignPanel.deselectAllSequences();
3048 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
3050 SequenceGroup sg = viewport.getSelectionGroup();
3054 alignPanel.selectAllSequences();
3059 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
3061 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
3063 // JAL-2034 - should delegate to
3064 // alignPanel to decide if overview needs
3067 alignPanel.paintAlignment(true, false);
3068 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
3069 viewport.sendSelection();
3073 public void invertColSel_actionPerformed(ActionEvent e)
3075 viewport.invertColumnSelection();
3076 alignPanel.paintAlignment(true, false);
3077 viewport.sendSelection();
3088 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
3090 trimAlignment(true);
3101 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
3103 trimAlignment(false);
3106 void trimAlignment(boolean trimLeft)
3108 ColumnSelection colSel = viewport.getColumnSelection();
3111 if (!colSel.isEmpty())
3115 column = colSel.getMin();
3119 column = colSel.getMax();
3123 if (viewport.getSelectionGroup() != null)
3125 seqs = viewport.getSelectionGroup()
3126 .getSequencesAsArray(viewport.getHiddenRepSequences());
3130 seqs = viewport.getAlignment().getSequencesArray();
3133 TrimRegionCommand trimRegion;
3136 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
3137 column, viewport.getAlignment());
3138 viewport.getRanges().setStartRes(0);
3142 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
3143 column, viewport.getAlignment());
3146 setStatus(MessageManager.formatMessage("label.removed_columns",
3148 { Integer.valueOf(trimRegion.getSize()).toString() }));
3150 addHistoryItem(trimRegion);
3152 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3154 if ((trimLeft && !sg.adjustForRemoveLeft(column))
3155 || (!trimLeft && !sg.adjustForRemoveRight(column)))
3157 viewport.getAlignment().deleteGroup(sg);
3161 viewport.notifyAlignment();
3174 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
3176 int start = 0, end = viewport.getAlignment().getWidth() - 1;
3179 if (viewport.getSelectionGroup() != null)
3181 seqs = viewport.getSelectionGroup()
3182 .getSequencesAsArray(viewport.getHiddenRepSequences());
3183 start = viewport.getSelectionGroup().getStartRes();
3184 end = viewport.getSelectionGroup().getEndRes();
3188 seqs = viewport.getAlignment().getSequencesArray();
3191 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
3192 "Remove Gapped Columns", seqs, start, end,
3193 viewport.getAlignment());
3195 addHistoryItem(removeGapCols);
3197 setStatus(MessageManager.formatMessage("label.removed_empty_columns",
3199 { Integer.valueOf(removeGapCols.getSize()).toString() }));
3201 // This is to maintain viewport position on first residue
3202 // of first sequence
3203 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3204 ViewportRanges ranges = viewport.getRanges();
3205 int startRes = seq.findPosition(ranges.getStartRes());
3206 // ShiftList shifts;
3207 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
3208 // edit.alColumnChanges=shifts.getInverse();
3209 // if (viewport.hasHiddenColumns)
3210 // viewport.getColumnSelection().compensateForEdits(shifts);
3211 ranges.setStartRes(seq.findIndex(startRes) - 1);
3212 viewport.notifyAlignment();
3225 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
3227 int start = 0, end = viewport.getAlignment().getWidth() - 1;
3230 if (viewport.getSelectionGroup() != null)
3232 seqs = viewport.getSelectionGroup()
3233 .getSequencesAsArray(viewport.getHiddenRepSequences());
3234 start = viewport.getSelectionGroup().getStartRes();
3235 end = viewport.getSelectionGroup().getEndRes();
3239 seqs = viewport.getAlignment().getSequencesArray();
3242 // This is to maintain viewport position on first residue
3243 // of first sequence
3244 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3245 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
3247 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
3248 viewport.getAlignment()));
3250 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
3251 viewport.notifyAlignment();
3263 public void padGapsMenuitem_actionPerformed(ActionEvent e)
3265 viewport.setPadGaps(padGapsMenuitem.isSelected());
3266 viewport.notifyAlignment();
3271 * Opens a Finder dialog
3277 public void findMenuItem_actionPerformed(ActionEvent e)
3279 new Finder(alignPanel, false, null);
3283 * Create a new view of the current alignment.
3287 public void newView_actionPerformed(ActionEvent e)
3289 newView(null, true);
3293 * Creates and shows a new view of the current alignment.
3296 * title of newly created view; if null, one will be generated
3297 * @param copyAnnotation
3298 * if true then duplicate all annnotation, groups and settings
3299 * @return new alignment panel, already displayed.
3302 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
3305 * Create a new AlignmentPanel (with its own, new Viewport)
3307 AlignmentPanel newap = new jalview.project.Jalview2XML()
3308 .copyAlignPanel(alignPanel);
3309 if (!copyAnnotation)
3312 * remove all groups and annotation except for the automatic stuff
3314 newap.av.getAlignment().deleteAllGroups();
3315 newap.av.getAlignment().deleteAllAnnotations(false);
3318 newap.av.setGatherViewsHere(false);
3320 if (viewport.getViewName() == null)
3322 viewport.setViewName(
3323 MessageManager.getString("label.view_name_original"));
3327 * Views share the same edits undo and redo stacks
3329 newap.av.setHistoryList(viewport.getHistoryList());
3330 newap.av.setRedoList(viewport.getRedoList());
3333 * copy any visualisation settings that are not saved in the project
3335 newap.av.setColourAppliesToAllGroups(
3336 viewport.getColourAppliesToAllGroups());
3339 * Views share the same mappings; need to deregister any new mappings
3340 * created by copyAlignPanel, and register the new reference to the shared
3343 newap.av.replaceMappings(viewport.getAlignment());
3346 * start up cDNA consensus (if applicable) now mappings are in place
3348 if (newap.av.initComplementConsensus())
3350 newap.refresh(true); // adjust layout of annotations
3353 newap.av.setViewName(getNewViewName(viewTitle));
3355 addAlignmentPanel(newap, true);
3356 newap.alignmentChanged();
3358 if (alignPanels.size() == 2)
3360 viewport.setGatherViewsHere(true);
3362 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
3367 * Make a new name for the view, ensuring it is unique within the current
3368 * sequenceSetId. (This used to be essential for Jalview Project archives, but
3369 * these now use viewId. Unique view names are still desirable for usability.)
3375 protected String getNewViewName(String viewTitle)
3377 int index = Desktop.getViewCount(viewport.getSequenceSetId());
3378 boolean addFirstIndex = false;
3379 if (viewTitle == null || viewTitle.trim().length() == 0)
3381 viewTitle = MessageManager.getString("action.view");
3382 addFirstIndex = true;
3386 index = 1;// we count from 1 if given a specific name
3388 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
3390 List<Component> comps = PaintRefresher.components
3391 .get(viewport.getSequenceSetId());
3393 List<String> existingNames = getExistingViewNames(comps);
3395 while (existingNames.contains(newViewName))
3397 newViewName = viewTitle + " " + (++index);
3403 * Returns a list of distinct view names found in the given list of
3404 * components. View names are held on the viewport of an AlignmentPanel.
3410 protected List<String> getExistingViewNames(List<Component> comps)
3412 List<String> existingNames = new ArrayList<>();
3413 for (Component comp : comps)
3415 if (comp instanceof AlignmentPanel)
3417 AlignmentPanel ap = (AlignmentPanel) comp;
3418 if (!existingNames.contains(ap.av.getViewName()))
3420 existingNames.add(ap.av.getViewName());
3424 return existingNames;
3428 * Explode tabbed views into separate windows.
3432 public void expandViews_actionPerformed(ActionEvent e)
3434 Desktop.explodeViews(this);
3438 * Gather views in separate windows back into a tabbed presentation.
3442 public void gatherViews_actionPerformed(ActionEvent e)
3444 Desktop.getInstance().gatherViews(this);
3455 public void font_actionPerformed(ActionEvent e)
3457 new FontChooser(alignPanel);
3468 protected void seqLimit_actionPerformed(ActionEvent e)
3470 viewport.setShowJVSuffix(seqLimits.isSelected());
3472 alignPanel.getIdPanel().getIdCanvas()
3473 .setPreferredSize(alignPanel.calculateIdWidth());
3474 alignPanel.paintAlignment(true, false);
3478 public void idRightAlign_actionPerformed(ActionEvent e)
3480 viewport.setRightAlignIds(idRightAlign.isSelected());
3481 alignPanel.paintAlignment(false, false);
3485 public void centreColumnLabels_actionPerformed(ActionEvent e)
3487 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3488 alignPanel.paintAlignment(false, false);
3494 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3498 protected void followHighlight_actionPerformed()
3501 * Set the 'follow' flag on the Viewport (and scroll to position if now
3504 final boolean state = this.followHighlightMenuItem.getState();
3505 viewport.setFollowHighlight(state);
3508 alignPanel.scrollToPosition(viewport.getSearchResults());
3520 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3522 viewport.setColourText(colourTextMenuItem.isSelected());
3523 alignPanel.paintAlignment(false, false);
3534 public void wrapMenuItem_actionPerformed(ActionEvent e)
3536 scaleAbove.setVisible(wrapMenuItem.isSelected());
3537 scaleLeft.setVisible(wrapMenuItem.isSelected());
3538 scaleRight.setVisible(wrapMenuItem.isSelected());
3539 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3540 alignPanel.updateLayout();
3544 public void showAllSeqs_actionPerformed(ActionEvent e)
3546 viewport.showAllHiddenSeqs();
3550 public void showAllColumns_actionPerformed(ActionEvent e)
3552 viewport.showAllHiddenColumns();
3553 alignPanel.paintAlignment(true, true);
3554 viewport.sendSelection();
3558 public void hideSelSequences_actionPerformed(ActionEvent e)
3560 viewport.hideAllSelectedSeqs();
3564 * called by key handler and the hide all/show all menu items
3570 protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3573 boolean hide = false;
3574 SequenceGroup sg = viewport.getSelectionGroup();
3575 if (!toggleSeqs && !toggleCols)
3577 // Hide everything by the current selection - this is a hack - we do the
3578 // invert and then hide
3579 // first check that there will be visible columns after the invert.
3580 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3581 && sg.getStartRes() <= sg.getEndRes()))
3583 // now invert the sequence set, if required - empty selection implies
3584 // that no hiding is required.
3587 invertSequenceMenuItem_actionPerformed(null);
3588 sg = viewport.getSelectionGroup();
3592 viewport.expandColSelection(sg, true);
3593 // finally invert the column selection and get the new sequence
3595 invertColSel_actionPerformed(null);
3602 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3604 hideSelSequences_actionPerformed(null);
3607 else if (!(toggleCols && viewport.hasSelectedColumns()))
3609 showAllSeqs_actionPerformed(null);
3615 if (viewport.hasSelectedColumns())
3617 hideSelColumns_actionPerformed(null);
3620 viewport.setSelectionGroup(sg);
3625 showAllColumns_actionPerformed(null);
3634 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3635 * event.ActionEvent)
3639 public void hideAllButSelection_actionPerformed(ActionEvent e)
3641 toggleHiddenRegions(false, false);
3642 viewport.sendSelection();
3649 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3654 public void hideAllSelection_actionPerformed(ActionEvent e)
3656 SequenceGroup sg = viewport.getSelectionGroup();
3657 viewport.expandColSelection(sg, false);
3658 viewport.hideAllSelectedSeqs();
3659 viewport.hideSelectedColumns();
3660 alignPanel.updateLayout();
3661 alignPanel.paintAlignment(true, true);
3662 viewport.sendSelection();
3669 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3674 public void showAllhidden_actionPerformed(ActionEvent e)
3676 viewport.showAllHiddenColumns();
3677 viewport.showAllHiddenSeqs();
3678 alignPanel.paintAlignment(true, true);
3679 viewport.sendSelection();
3683 public void hideSelColumns_actionPerformed(ActionEvent e)
3685 viewport.hideSelectedColumns();
3686 alignPanel.updateLayout();
3687 alignPanel.paintAlignment(true, true);
3688 viewport.sendSelection();
3692 public void hiddenMarkers_actionPerformed(ActionEvent e)
3694 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3706 protected void scaleAbove_actionPerformed(ActionEvent e)
3708 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3709 alignPanel.updateLayout();
3710 alignPanel.paintAlignment(true, false);
3721 protected void scaleLeft_actionPerformed(ActionEvent e)
3723 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3724 alignPanel.updateLayout();
3725 alignPanel.paintAlignment(true, false);
3736 protected void scaleRight_actionPerformed(ActionEvent e)
3738 viewport.setScaleRightWrapped(scaleRight.isSelected());
3739 alignPanel.updateLayout();
3740 alignPanel.paintAlignment(true, false);
3751 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3753 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3754 alignPanel.paintAlignment(false, false);
3765 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3767 viewport.setShowText(viewTextMenuItem.isSelected());
3768 alignPanel.paintAlignment(false, false);
3779 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3781 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3782 alignPanel.paintAlignment(false, false);
3785 public FeatureSettings featureSettings;
3788 public FeatureSettingsControllerI getFeatureSettingsUI()
3790 return featureSettings;
3794 public void featureSettings_actionPerformed(ActionEvent e)
3796 showFeatureSettingsUI();
3800 public FeatureSettingsControllerI showFeatureSettingsUI()
3802 if (featureSettings != null)
3804 featureSettings.closeOldSettings();
3805 featureSettings = null;
3807 if (!showSeqFeatures.isSelected())
3809 // make sure features are actually displayed
3810 showSeqFeatures.setSelected(true);
3811 showSeqFeatures_actionPerformed(null);
3813 featureSettings = new FeatureSettings(this);
3814 return featureSettings;
3818 * Set or clear 'Show Sequence Features'
3825 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3827 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3828 alignPanel.paintAlignment(true, true);
3832 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3833 * the annotations panel as a whole.
3835 * The options to show/hide all annotations should be enabled when the panel
3836 * is shown, and disabled when the panel is hidden.
3842 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3844 final boolean setVisible = annotationPanelMenuItem.isSelected();
3845 viewport.setShowAnnotation(setVisible);
3846 syncAnnotationMenuItems(setVisible);
3847 alignPanel.updateLayout();
3849 SwingUtilities.invokeLater(new Runnable() {
3854 alignPanel.updateScrollBarsFromRanges();
3860 private void syncAnnotationMenuItems(boolean setVisible)
3862 showAllSeqAnnotations.setEnabled(setVisible);
3863 hideAllSeqAnnotations.setEnabled(setVisible);
3864 showAllAlAnnotations.setEnabled(setVisible);
3865 hideAllAlAnnotations.setEnabled(setVisible);
3869 public void alignmentProperties()
3872 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3875 String content = MessageManager.formatMessage("label.html_content",
3877 { contents.toString() });
3880 if (Platform.isJS())
3882 JLabel textLabel = new JLabel();
3883 textLabel.setText(content);
3884 textLabel.setBackground(Color.WHITE);
3886 pane = new JPanel(new BorderLayout());
3887 ((JPanel) pane).setOpaque(true);
3888 pane.setBackground(Color.WHITE);
3889 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3898 JEditorPane editPane = new JEditorPane("text/html", "");
3899 editPane.setEditable(false);
3900 editPane.setText(content);
3904 JInternalFrame frame = new JInternalFrame();
3906 frame.getContentPane().add(new JScrollPane(pane));
3908 Desktop.addInternalFrame(frame, MessageManager
3909 .formatMessage("label.alignment_properties", new Object[]
3910 { getTitle() }), 500, 400);
3921 public void overviewMenuItem_actionPerformed(ActionEvent e)
3923 if (alignPanel.overviewPanel != null)
3928 JInternalFrame frame = new JInternalFrame();
3930 // BH 2019.07.26 we allow for an embedded
3931 // undecorated overview with defined size
3932 frame.setName(Platform.getAppID("overview"));
3934 Dimension dim = Platform.getDimIfEmbedded(frame, -1, -1);
3935 if (dim != null && dim.width == 0)
3937 dim = null; // hidden, not embedded
3939 OverviewPanel overview = new OverviewPanel(alignPanel, dim);
3941 frame.setContentPane(overview);
3944 dim = new Dimension();
3945 // was frame.getSize(), but that is 0,0 at this point;
3949 // we are imbedding, and so we have an undecorated frame
3950 // and we can set the the frame dimensions accordingly.
3952 // allowing for unresizable option using, style="resize:none"
3953 boolean resizable = (Platform.getEmbeddedAttribute(frame,
3954 "resize") != "none");
3955 Desktop.addInternalFrame(frame, MessageManager
3956 .formatMessage("label.overview_params", new Object[]
3957 { this.getTitle() }), Desktop.FRAME_MAKE_VISIBLE, dim.width,
3958 dim.height, resizable, Desktop.FRAME_ALLOW_ANY_SIZE);
3960 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3961 frame.addInternalFrameListener(
3962 new javax.swing.event.InternalFrameAdapter()
3966 public void internalFrameClosed(
3967 javax.swing.event.InternalFrameEvent evt)
3970 alignPanel.setOverviewPanel(null);
3973 if (getKeyListeners().length > 0)
3975 frame.addKeyListener(getKeyListeners()[0]);
3978 alignPanel.setOverviewPanel(overview);
3982 public void textColour_actionPerformed()
3984 new TextColourChooser().chooseColour(alignPanel, null);
3988 * public void covariationColour_actionPerformed() {
3990 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3995 public void annotationColour_actionPerformed()
3997 new AnnotationColourChooser(viewport, alignPanel);
4001 public void annotationColumn_actionPerformed(ActionEvent e)
4003 new AnnotationColumnChooser(viewport, alignPanel);
4007 * Action on the user checking or unchecking the option to apply the selected
4008 * colour scheme to all groups. If unchecked, groups may have their own
4009 * independent colour schemes.
4015 public void applyToAllGroups_actionPerformed(boolean selected)
4017 viewport.setColourAppliesToAllGroups(selected);
4021 * Action on user selecting a colour from the colour menu
4024 * the name (not the menu item label!) of the colour scheme
4028 public void changeColour_actionPerformed(String name)
4031 * 'User Defined' opens a panel to configure or load a
4032 * user-defined colour scheme
4034 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
4036 new UserDefinedColours(alignPanel);
4041 * otherwise set the chosen colour scheme (or null for 'None')
4043 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
4044 viewport, viewport.getAlignment(),
4045 viewport.getHiddenRepSequences());
4050 * Actions on setting or changing the alignment colour scheme
4056 public void changeColour(ColourSchemeI cs)
4058 // TODO: pull up to controller method
4059 ColourMenuHelper.setColourSelected(colourMenu, cs);
4061 viewport.setGlobalColourScheme(cs);
4063 alignPanel.paintAlignment(true, true);
4067 * Show the PID threshold slider panel
4071 protected void modifyPID_actionPerformed()
4073 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
4074 alignPanel.getViewName());
4075 SliderPanel.showPIDSlider();
4079 * Show the Conservation slider panel
4083 protected void modifyConservation_actionPerformed()
4085 SliderPanel.setConservationSlider(alignPanel,
4086 viewport.getResidueShading(), alignPanel.getViewName());
4087 SliderPanel.showConservationSlider();
4091 * Action on selecting or deselecting (Colour) By Conservation
4095 public void conservationMenuItem_actionPerformed(boolean selected)
4097 modifyConservation.setEnabled(selected);
4098 viewport.setConservationSelected(selected);
4099 viewport.getResidueShading().setConservationApplied(selected);
4101 changeColour(viewport.getGlobalColourScheme());
4104 modifyConservation_actionPerformed();
4108 SliderPanel.hideConservationSlider();
4113 * Action on selecting or deselecting (Colour) Above PID Threshold
4117 public void abovePIDThreshold_actionPerformed(boolean selected)
4119 modifyPID.setEnabled(selected);
4120 viewport.setAbovePIDThreshold(selected);
4123 viewport.getResidueShading().setThreshold(0,
4124 viewport.isIgnoreGapsConsensus());
4127 changeColour(viewport.getGlobalColourScheme());
4130 modifyPID_actionPerformed();
4134 SliderPanel.hidePIDSlider();
4146 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
4148 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4149 AlignmentSorter.sortByPID(viewport.getAlignment(),
4150 viewport.getAlignment().getSequenceAt(0));
4151 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
4152 viewport.getAlignment()));
4153 alignPanel.paintAlignment(true, false);
4164 public void sortIDMenuItem_actionPerformed(ActionEvent e)
4166 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4167 AlignmentSorter.sortByID(viewport.getAlignment());
4169 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
4170 alignPanel.paintAlignment(true, false);
4181 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
4183 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4184 AlignmentSorter.sortByLength(viewport.getAlignment());
4185 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
4186 viewport.getAlignment()));
4187 alignPanel.paintAlignment(true, false);
4198 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
4200 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4201 AlignmentSorter.sortByGroup(viewport.getAlignment());
4202 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4203 viewport.getAlignment()));
4205 alignPanel.paintAlignment(true, false);
4209 public void sortEValueMenuItem_actionPerformed(ActionEvent e)
4211 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4212 AlignmentSorter.sortByEValue(viewport.getAlignment());
4213 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4214 viewport.getAlignment()));
4215 alignPanel.paintAlignment(true, false);
4220 public void sortBitScoreMenuItem_actionPerformed(ActionEvent e)
4222 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4223 AlignmentSorter.sortByBitScore(viewport.getAlignment());
4224 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4225 viewport.getAlignment()));
4226 alignPanel.paintAlignment(true, false);
4238 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
4240 new RedundancyPanel(alignPanel, this);
4251 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
4253 if ((viewport.getSelectionGroup() == null)
4254 || (viewport.getSelectionGroup().getSize() < 2))
4256 JvOptionPane.showInternalMessageDialog(this,
4257 MessageManager.getString(
4258 "label.you_must_select_least_two_sequences"),
4259 MessageManager.getString("label.invalid_selection"),
4260 JvOptionPane.WARNING_MESSAGE);
4264 JInternalFrame frame = new JInternalFrame();
4265 frame.setContentPane(new PairwiseAlignPanel(viewport));
4266 Desktop.addInternalFrame(frame,
4267 MessageManager.getString("action.pairwise_alignment"), 600,
4273 public void autoCalculate_actionPerformed(ActionEvent e)
4275 viewport.setAutoCalculateConsensusAndConservation(
4276 autoCalculate.isSelected());
4277 if (viewport.getAutoCalculateConsensusAndConservation())
4279 viewport.notifyAlignment();
4284 public void sortByTreeOption_actionPerformed(ActionEvent e)
4286 viewport.sortByTree = sortByTree.isSelected();
4290 protected void listenToViewSelections_actionPerformed(ActionEvent e)
4292 viewport.followSelection = listenToViewSelections.isSelected();
4296 * Constructs a tree panel and adds it to the desktop
4299 * tree type (NJ or AV)
4301 * name of score model used to compute the tree
4303 * parameters for the distance or similarity calculation
4306 void newTreePanel(String type, String modelName,
4307 SimilarityParamsI options)
4309 String frameTitle = "";
4312 boolean onSelection = false;
4313 if (viewport.getSelectionGroup() != null
4314 && viewport.getSelectionGroup().getSize() > 0)
4316 SequenceGroup sg = viewport.getSelectionGroup();
4318 /* Decide if the selection is a column region */
4319 for (SequenceI _s : sg.getSequences())
4321 if (_s.getLength() < sg.getEndRes())
4323 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4324 MessageManager.getString(
4325 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
4326 MessageManager.getString(
4327 "label.sequences_selection_not_aligned"),
4328 JvOptionPane.WARNING_MESSAGE);
4337 if (viewport.getAlignment().getHeight() < 2)
4343 tp = new TreePanel(alignPanel, type, modelName, options);
4344 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
4346 frameTitle += " from ";
4348 if (viewport.getViewName() != null)
4350 frameTitle += viewport.getViewName() + " of ";
4353 frameTitle += this.title;
4355 Dimension dim = Platform.getDimIfEmbedded(tp, 600, 500);
4356 Desktop.addInternalFrame(tp, frameTitle, dim.width, dim.height);
4368 public void addSortByOrderMenuItem(String title,
4369 final AlignmentOrder order)
4371 final JMenuItem item = new JMenuItem(MessageManager
4372 .formatMessage("action.by_title_param", new Object[]
4375 item.addActionListener(new java.awt.event.ActionListener()
4379 public void actionPerformed(ActionEvent e)
4381 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4383 // TODO: JBPNote - have to map order entries to curent SequenceI
4385 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4387 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
4388 viewport.getAlignment()));
4390 alignPanel.paintAlignment(true, false);
4396 * Add a new sort by annotation score menu item
4399 * the menu to add the option to
4401 * the label used to retrieve scores for each sequence on the
4405 public void addSortByAnnotScoreMenuItem(JMenu sort,
4406 final String scoreLabel)
4408 final JMenuItem item = new JMenuItem(scoreLabel);
4410 item.addActionListener(new java.awt.event.ActionListener()
4414 public void actionPerformed(ActionEvent e)
4416 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4417 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4418 viewport.getAlignment());// ,viewport.getSelectionGroup());
4419 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4420 viewport.getAlignment()));
4421 alignPanel.paintAlignment(true, false);
4427 * last hash for alignment's annotation array - used to minimise cost of
4430 protected int _annotationScoreVectorHash;
4433 * search the alignment and rebuild the sort by annotation score submenu the
4434 * last alignment annotation vector hash is stored to minimize cost of
4435 * rebuilding in subsequence calls.
4440 public void buildSortByAnnotationScoresMenu()
4442 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4447 if (viewport.getAlignment().getAlignmentAnnotation()
4448 .hashCode() == _annotationScoreVectorHash)
4453 sortByAnnotScore.removeAll();
4454 Set<String> scoreSorts = new HashSet<>();
4455 for (SequenceI sqa : viewport.getAlignment().getSequences())
4457 AlignmentAnnotation[] anns = sqa.getAnnotation();
4458 for (int i = 0; anns != null && i < anns.length; i++)
4460 AlignmentAnnotation aa = anns[i];
4461 if (aa != null && aa.hasScore() && aa.sequenceRef != null)
4463 scoreSorts.add(aa.label);
4467 for (String label : scoreSorts)
4469 addSortByAnnotScoreMenuItem(sortByAnnotScore, label);
4471 sortByAnnotScore.setVisible(!scoreSorts.isEmpty());
4473 _annotationScoreVectorHash = viewport.getAlignment()
4474 .getAlignmentAnnotation().hashCode();
4478 * Enable (or, if desired, make visible) the By Tree
4479 * submenu only if it has at least one element (or will have).
4483 protected void enableSortMenuOptions()
4485 List<TreePanel> treePanels = getTreePanels();
4486 sortByTreeMenu.setEnabled(!treePanels.isEmpty());
4490 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4491 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4492 * call. Listeners are added to remove the menu item when the treePanel is
4493 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4498 public void buildTreeSortMenu()
4500 sortByTreeMenu.removeAll();
4502 List<TreePanel> treePanels = getTreePanels();
4504 for (final TreePanel tp : treePanels)
4506 final JMenuItem item = new JMenuItem(tp.getTitle());
4507 item.addActionListener(new java.awt.event.ActionListener()
4511 public void actionPerformed(ActionEvent e)
4513 tp.sortByTree_actionPerformed();
4514 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4519 sortByTreeMenu.add(item);
4523 private List<TreePanel> getTreePanels()
4525 List<Component> comps = PaintRefresher.components
4526 .get(viewport.getSequenceSetId());
4527 List<TreePanel> treePanels = new ArrayList<>();
4528 for (Component comp : comps)
4530 if (comp instanceof TreePanel)
4532 treePanels.add((TreePanel) comp);
4538 public boolean sortBy(AlignmentOrder alorder, String undoname)
4540 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4541 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4542 if (undoname != null)
4544 addHistoryItem(new OrderCommand(undoname, oldOrder,
4545 viewport.getAlignment()));
4547 alignPanel.paintAlignment(true, false);
4552 * Work out whether the whole set of sequences or just the selected set will
4553 * be submitted for multiple alignment.
4557 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4559 // Now, check we have enough sequences
4560 AlignmentView msa = null;
4562 if ((viewport.getSelectionGroup() != null)
4563 && (viewport.getSelectionGroup().getSize() > 1))
4565 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4566 // some common interface!
4568 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4569 * SequenceI[sz = seqs.getSize(false)];
4571 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4572 * seqs.getSequenceAt(i); }
4574 msa = viewport.getAlignmentView(true);
4576 else if (viewport.getSelectionGroup() != null
4577 && viewport.getSelectionGroup().getSize() == 1)
4579 int option = JvOptionPane.showConfirmDialog(this,
4580 MessageManager.getString("warn.oneseq_msainput_selection"),
4581 MessageManager.getString("label.invalid_selection"),
4582 JvOptionPane.OK_CANCEL_OPTION);
4583 if (option == JvOptionPane.OK_OPTION)
4585 msa = viewport.getAlignmentView(false);
4590 msa = viewport.getAlignmentView(false);
4596 * Decides what is submitted to a secondary structure prediction service: the
4597 * first sequence in the alignment, or in the current selection, or, if the
4598 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4599 * region or the whole alignment. (where the first sequence in the set is the
4600 * one that the prediction will be for).
4603 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4605 AlignmentView seqs = null;
4607 if ((viewport.getSelectionGroup() != null)
4608 && (viewport.getSelectionGroup().getSize() > 0))
4610 seqs = viewport.getAlignmentView(true);
4614 seqs = viewport.getAlignmentView(false);
4616 // limit sequences - JBPNote in future - could spawn multiple prediction
4618 // TODO: viewport.getAlignment().isAligned is a global state - the local
4619 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4620 if (!viewport.getAlignment().isAligned(false))
4622 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4623 // TODO: if seqs.getSequences().length>1 then should really have warned
4638 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4640 // Pick the tree file
4641 JalviewFileChooser chooser = new JalviewFileChooser(
4642 Cache.getProperty("LAST_DIRECTORY"));
4643 chooser.setFileView(new JalviewFileView());
4644 chooser.setDialogTitle(
4645 MessageManager.getString("label.select_newick_like_tree_file"));
4646 chooser.setToolTipText(
4647 MessageManager.getString("label.load_tree_file"));
4649 chooser.setResponseHandler(0, new Runnable()
4655 String filePath = chooser.getSelectedFile().getPath();
4656 Cache.setProperty("LAST_DIRECTORY", filePath);
4657 NewickFile fin = null;
4660 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4661 DataSourceType.FILE));
4662 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4663 } catch (Exception ex)
4665 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4668 .getString("label.problem_reading_tree_file"),
4669 JvOptionPane.WARNING_MESSAGE);
4670 ex.printStackTrace();
4672 if (fin != null && fin.hasWarningMessage())
4674 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4675 fin.getWarningMessage(),
4676 MessageManager.getString(
4677 "label.possible_problem_with_tree_file"),
4678 JvOptionPane.WARNING_MESSAGE);
4682 chooser.showOpenDialog(this);
4685 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4687 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4690 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4691 int h, int x, int y)
4693 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4697 * Add a treeviewer for the tree extracted from a Newick file object to the
4698 * current alignment view
4705 * Associated alignment input data (or null)
4714 * @return TreePanel handle
4717 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4718 AlignmentView input, int w, int h, int x, int y)
4720 TreePanel tp = null;
4726 if (nf.getTree() != null)
4728 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4729 Dimension dim = Platform.getDimIfEmbedded(tp, -1, -1);
4732 dim = new Dimension(w, h);
4736 // no offset, either
4739 tp.setSize(dim.width, dim.height);
4743 tp.setLocation(x, y);
4746 Desktop.addInternalFrame(tp, treeTitle, dim.width, dim.height);
4748 } catch (Exception ex)
4750 ex.printStackTrace();
4756 private WebServicesMenuManager slivkaMenu = new WebServicesMenuManager("slivka", this);
4758 * Schedule the web services menu rebuild to the event dispatch thread.
4760 public void buildWebServicesMenu()
4762 SwingUtilities.invokeLater(() -> {
4763 Console.info("Rebuiling WS menu");
4764 webService.removeAll();
4765 if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
4767 Console.info("Building web service menu for slivka");
4768 SlivkaWSDiscoverer discoverer = SlivkaWSDiscoverer.getInstance();
4769 slivkaMenu.setServices(discoverer);
4770 slivkaMenu.setInProgress(discoverer.isRunning());
4771 slivkaMenu.setNoServices(discoverer.isDone() && !discoverer.hasServices());
4772 webService.add(slivkaMenu.getMenu());
4774 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4776 WSDiscovererI jws2servs = Jws2Discoverer.getInstance();
4777 JMenu submenu = new JMenu("JABAWS");
4778 buildLegacyWebServicesMenu(submenu);
4779 buildWebServicesMenu(jws2servs, submenu);
4780 webService.add(submenu);
4782 build_urlServiceMenu(webService);
4783 build_fetchdbmenu(webService);
4787 private void buildLegacyWebServicesMenu(JMenu menu)
4789 JMenu secstrmenu = new JMenu("Secondary Structure Prediction");
4790 if (Discoverer.getServices() != null && Discoverer.getServices().size() > 0)
4792 var secstrpred = Discoverer.getServices().get("SecStrPred");
4793 if (secstrpred != null)
4795 for (ext.vamsas.ServiceHandle sh : secstrpred)
4797 var menuProvider = Discoverer.getServiceClient(sh);
4798 menuProvider.attachWSMenuEntry(secstrmenu, this);
4802 menu.add(secstrmenu);
4806 * Constructs the web services menu for the given discoverer under the
4807 * specified menu. This method must be called on the EDT
4810 * the discoverer used to build the menu
4812 * parent component which the elements will be attached to
4814 private void buildWebServicesMenu(WSDiscovererI discoverer, JMenu menu)
4816 if (discoverer.hasServices())
4818 PreferredServiceRegistry.getRegistry().populateWSMenuEntry(
4819 discoverer.getServices(), sv -> buildWebServicesMenu(), menu,
4822 if (discoverer.isRunning())
4824 JMenuItem item = new JMenuItem("Service discovery in progress.");
4825 item.setEnabled(false);
4828 else if (!discoverer.hasServices())
4830 JMenuItem item = new JMenuItem("No services available.");
4831 item.setEnabled(false);
4837 * construct any groupURL type service menu entries.
4842 protected void build_urlServiceMenu(JMenu webService)
4844 // TODO: remove this code when 2.7 is released
4845 // DEBUG - alignmentView
4847 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4848 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4850 * public void actionPerformed(ActionEvent e) {
4851 * jalview.datamodel.AlignmentView
4852 * .testSelectionViews(af.viewport.getAlignment(),
4853 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4855 * }); webService.add(testAlView);
4857 // TODO: refactor to RestClient discoverer and merge menu entries for
4858 // rest-style services with other types of analysis/calculation service
4859 // SHmmr test client - still being implemented.
4860 // DEBUG - alignmentView
4862 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4865 client.attachWSMenuEntry(
4866 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4872 * Searches the alignment sequences for xRefs and builds the Show
4873 * Cross-References menu (formerly called Show Products), with database
4874 * sources for which cross-references are found (protein sources for a
4875 * nucleotide alignment and vice versa)
4877 * @return true if Show Cross-references menu should be enabled
4880 public boolean canShowProducts()
4882 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4883 AlignmentI dataset = viewport.getAlignment().getDataset();
4885 showProducts.removeAll();
4886 final boolean dna = viewport.getAlignment().isNucleotide();
4888 if (seqs == null || seqs.length == 0)
4890 // nothing to see here.
4894 boolean showp = false;
4897 List<String> ptypes = new CrossRef(seqs, dataset)
4898 .findXrefSourcesForSequences(dna);
4900 for (final String source : ptypes)
4903 final AlignFrame af = this;
4904 JMenuItem xtype = new JMenuItem(source);
4905 xtype.addActionListener(new ActionListener()
4909 public void actionPerformed(ActionEvent e)
4911 showProductsFor(af.viewport.getSequenceSelection(), dna,
4915 showProducts.add(xtype);
4917 showProducts.setVisible(showp);
4918 showProducts.setEnabled(showp);
4919 } catch (Exception e)
4922 "canShowProducts threw an exception - please report to help@jalview.org",
4930 * Finds and displays cross-references for the selected sequences (protein
4931 * products for nucleotide sequences, dna coding sequences for peptides).
4934 * the sequences to show cross-references for
4936 * true if from a nucleotide alignment (so showing proteins)
4938 * the database to show cross-references for
4941 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4942 final String source)
4944 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4949 * Construct and display a new frame containing the translation of this
4950 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4954 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4956 AlignmentI al = null;
4959 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4961 al = dna.translateCdna(codeTable);
4962 } catch (Exception ex)
4964 Console.error("Exception during translation. Please report this !",
4966 final String msg = MessageManager.getString(
4967 "label.error_when_translating_sequences_submit_bug_report");
4968 final String errorTitle = MessageManager
4969 .getString("label.implementation_error")
4970 + MessageManager.getString("label.translation_failed");
4971 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4972 errorTitle, JvOptionPane.ERROR_MESSAGE);
4975 if (al == null || al.getHeight() == 0)
4977 final String msg = MessageManager.getString(
4978 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4979 final String errorTitle = MessageManager
4980 .getString("label.translation_failed");
4981 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4982 errorTitle, JvOptionPane.WARNING_MESSAGE);
4986 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4987 af.setFileFormat(this.currentFileFormat);
4988 final String newTitle = MessageManager
4989 .formatMessage("label.translation_of_params", new Object[]
4990 { this.getTitle(), codeTable.getId() });
4991 af.setTitle(newTitle);
4992 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4994 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4995 AlignViewport.openSplitFrame(this, af, new Alignment(seqs));
4999 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
5006 * Set the file format
5011 public void setFileFormat(FileFormatI format)
5013 this.currentFileFormat = format;
5017 * Try to load a features file onto the alignment.
5020 * contents or path to retrieve file or a File object
5022 * access mode of file (see jalview.io.AlignFile)
5023 * @return true if features file was parsed correctly.
5026 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
5029 return avc.parseFeaturesFile(file, sourceType,
5030 Cache.getDefault(Preferences.RELAXEDSEQIDMATCHING, false));
5035 public void refreshFeatureUI(boolean enableIfNecessary)
5037 // note - currently this is only still here rather than in the controller
5038 // because of the featureSettings hard reference that is yet to be
5040 if (enableIfNecessary)
5042 viewport.setShowSequenceFeatures(true);
5043 showSeqFeatures.setSelected(true);
5049 public void dragEnter(DropTargetDragEvent evt)
5054 public void dragExit(DropTargetEvent evt)
5059 public void dragOver(DropTargetDragEvent evt)
5064 public void dropActionChanged(DropTargetDragEvent evt)
5069 public void drop(DropTargetDropEvent evt)
5071 // JAL-1552 - acceptDrop required before getTransferable call for
5072 // Java's Transferable for native dnd
5073 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
5074 Transferable t = evt.getTransferable();
5076 final List<Object> files = new ArrayList<>();
5077 List<DataSourceType> protocols = new ArrayList<>();
5081 Desktop.transferFromDropTarget(files, protocols, evt, t);
5082 if (files.size() > 0)
5084 new Thread(new Runnable()
5090 loadDroppedFiles(files, protocols, evt, t);
5094 } catch (Exception e)
5096 e.printStackTrace();
5100 protected void loadDroppedFiles(List<Object> files,
5101 List<DataSourceType> protocols, DropTargetDropEvent evt,
5106 // check to see if any of these files have names matching sequences
5109 SequenceIdMatcher idm = new SequenceIdMatcher(
5110 viewport.getAlignment().getSequencesArray());
5112 * Object[] { String,SequenceI}
5114 ArrayList<Object[]> filesmatched = new ArrayList<>();
5115 ArrayList<Object> filesnotmatched = new ArrayList<>();
5116 for (int i = 0; i < files.size(); i++)
5119 Object fileObj = files.get(i);
5120 String fileName = fileObj.toString();
5122 DataSourceType protocol = (fileObj instanceof File
5123 ? DataSourceType.FILE
5124 : FormatAdapter.checkProtocol(fileName));
5125 if (protocol == DataSourceType.FILE)
5128 if (fileObj instanceof File)
5130 file = (File) fileObj;
5131 Platform.cacheFileData(file);
5135 file = new File(fileName);
5137 pdbfn = file.getName();
5139 else if (protocol == DataSourceType.URL)
5141 URL url = new URL(fileName);
5142 pdbfn = url.getFile();
5144 if (pdbfn.length() > 0)
5146 // attempt to find a match in the alignment
5147 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5148 int l = 0, c = pdbfn.indexOf(".");
5149 while (mtch == null && c != -1)
5154 } while ((c = pdbfn.indexOf(".", l)) > l);
5157 pdbfn = pdbfn.substring(0, l);
5159 mtch = idm.findAllIdMatches(pdbfn);
5166 type = new IdentifyFile().identify(fileObj, protocol);
5167 } catch (Exception ex)
5171 if (type != null && type.isStructureFile())
5173 filesmatched.add(new Object[] { fileObj, protocol, mtch });
5177 // File wasn't named like one of the sequences or wasn't a PDB
5179 filesnotmatched.add(fileObj);
5183 if (filesmatched.size() > 0)
5185 boolean autoAssociate = Cache
5186 .getDefault(Preferences.AUTOASSOCIATE_PDBANDSEQS, false);
5189 String msg = MessageManager.formatMessage(
5190 "label.automatically_associate_structure_files_with_sequences_same_name",
5192 { Integer.valueOf(filesmatched.size()).toString() });
5193 String ttl = MessageManager.getString(
5194 "label.automatically_associate_structure_files_by_name");
5195 int choice = JvOptionPane.showConfirmDialog(this, msg, ttl,
5196 JvOptionPane.YES_NO_OPTION);
5197 autoAssociate = choice == JvOptionPane.YES_OPTION;
5201 for (Object[] fm : filesmatched)
5203 // try and associate
5204 // TODO: may want to set a standard ID naming formalism for
5205 // associating PDB files which have no IDs.
5206 for (SequenceI toassoc : (SequenceI[]) fm[2])
5208 PDBEntry pe = AssociatePdbFileWithSeq.associatePdbWithSeq(
5209 fm[0].toString(), (DataSourceType) fm[1], toassoc,
5213 System.err.println("Associated file : " + (fm[0].toString())
5214 + " with " + toassoc.getDisplayId(true));
5218 // TODO: do we need to update overview ? only if features are
5220 alignPanel.paintAlignment(true, false);
5226 * add declined structures as sequences
5228 for (Object[] o : filesmatched)
5230 filesnotmatched.add(o[0]);
5234 if (filesnotmatched.size() > 0)
5236 if (assocfiles > 0 && (Cache
5237 .getDefault("AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
5238 || JvOptionPane.showConfirmDialog(this,
5239 "<html>" + MessageManager.formatMessage(
5240 "label.ignore_unmatched_dropped_files_info",
5242 { Integer.valueOf(filesnotmatched.size())
5245 MessageManager.getString(
5246 "label.ignore_unmatched_dropped_files"),
5247 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
5251 for (Object fn : filesnotmatched)
5253 loadJalviewDataFile(fn, null, null, null);
5257 } catch (Exception ex)
5259 ex.printStackTrace();
5264 * Attempt to load a "dropped" file or URL string, by testing in turn for
5266 * <li>an Annotation file</li>
5267 * <li>a JNet file</li>
5268 * <li>a features file</li>
5269 * <li>else try to interpret as an alignment file</li>
5273 * either a filename or a URL string.
5274 * @throws InterruptedException
5275 * @throws IOException
5278 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
5279 FileFormatI format, SequenceI assocSeq)
5281 // BH 2018 was String file
5284 if (sourceType == null)
5286 sourceType = FormatAdapter.checkProtocol(file);
5288 // if the file isn't identified, or not positively identified as some
5289 // other filetype (PFAM is default unidentified alignment file type) then
5290 // try to parse as annotation.
5291 boolean isAnnotation = (format == null
5292 || FileFormat.Pfam.equals(format))
5293 ? new AnnotationFile().annotateAlignmentView(viewport,
5299 // first see if its a T-COFFEE score file
5300 TCoffeeScoreFile tcf = null;
5303 tcf = new TCoffeeScoreFile(file, sourceType);
5306 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5310 new TCoffeeColourScheme(viewport.getAlignment()));
5311 isAnnotation = true;
5312 setStatus(MessageManager.getString(
5313 "label.successfully_pasted_tcoffee_scores_to_alignment"));
5317 // some problem - if no warning its probable that the ID matching
5318 // process didn't work
5319 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
5320 tcf.getWarningMessage() == null
5321 ? MessageManager.getString(
5322 "label.check_file_matches_sequence_ids_alignment")
5323 : tcf.getWarningMessage(),
5324 MessageManager.getString(
5325 "label.problem_reading_tcoffee_score_file"),
5326 JvOptionPane.WARNING_MESSAGE);
5333 } catch (Exception x)
5336 "Exception when processing data source as T-COFFEE score file",
5342 // try to see if its a JNet 'concise' style annotation file *before*
5344 // try to parse it as a features file
5347 format = new IdentifyFile().identify(file, sourceType);
5349 if (FileFormat.ScoreMatrix == format)
5351 ScoreMatrixFile sm = new ScoreMatrixFile(
5352 new FileParse(file, sourceType));
5354 // todo: i18n this message
5355 setStatus(MessageManager.formatMessage(
5356 "label.successfully_loaded_matrix",
5357 sm.getMatrixName()));
5359 else if (FileFormat.Jnet.equals(format))
5361 JPredFile predictions = new JPredFile(file, sourceType);
5362 new JnetAnnotationMaker();
5363 JnetAnnotationMaker.add_annotation(predictions,
5364 viewport.getAlignment(), 0, false);
5365 viewport.getAlignment().setupJPredAlignment();
5366 isAnnotation = true;
5368 // else if (IdentifyFile.FeaturesFile.equals(format))
5369 else if (FileFormat.Features.equals(format))
5371 if (parseFeaturesFile(file, sourceType))
5373 SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
5374 if (splitFrame != null)
5376 splitFrame.repaint();
5380 alignPanel.paintAlignment(true, true);
5386 new FileLoader().LoadFile(viewport, file, sourceType, format);
5392 updateForAnnotations();
5394 } catch (Exception ex)
5396 ex.printStackTrace();
5397 } catch (OutOfMemoryError oom)
5402 } catch (Exception x)
5407 + (sourceType != null
5408 ? (sourceType == DataSourceType.PASTE
5410 : "using " + sourceType + " from "
5414 ? "(parsing as '" + format + "' file)"
5416 oom, Desktop.getDesktopPane());
5421 * Do all updates necessary after an annotation file such as jnet. Also called
5422 * from Jalview.loadAppletParams for "annotations", "jnetFile"
5425 public void updateForAnnotations()
5427 alignPanel.adjustAnnotationHeight();
5428 viewport.updateSequenceIdColours();
5429 buildSortByAnnotationScoresMenu();
5430 alignPanel.paintAlignment(true, true);
5434 * Change the display state for the given feature groups -- Added by BH from
5438 * list of group strings
5440 * visible or invisible
5443 public void setFeatureGroupState(String[] groups, boolean state)
5445 jalview.api.FeatureRenderer fr = null;
5446 viewport.setShowSequenceFeatures(true);
5447 if (alignPanel != null
5448 && (fr = alignPanel.getFeatureRenderer()) != null)
5451 fr.setGroupVisibility(Arrays.asList(groups), state);
5452 alignPanel.getSeqPanel().seqCanvas.repaint();
5453 if (alignPanel.overviewPanel != null)
5455 alignPanel.overviewPanel.updateOverviewImage();
5461 * Method invoked by the ChangeListener on the tabbed pane, in other words
5462 * when a different tabbed pane is selected by the user or programmatically.
5466 public void tabSelectionChanged(int index)
5470 alignPanel = alignPanels.get(index);
5471 viewport = alignPanel.av;
5472 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5473 setMenusFromViewport(viewport);
5474 if (featureSettings != null && featureSettings.isOpen()
5475 && featureSettings.fr.getViewport() != viewport)
5477 if (viewport.isShowSequenceFeatures())
5479 // refresh the featureSettings to reflect UI change
5480 showFeatureSettingsUI();
5484 // close feature settings for this view.
5485 featureSettings.close();
5492 * 'focus' any colour slider that is open to the selected viewport
5494 if (viewport.getConservationSelected())
5496 SliderPanel.setConservationSlider(alignPanel,
5497 viewport.getResidueShading(), alignPanel.getViewName());
5501 SliderPanel.hideConservationSlider();
5503 if (viewport.getAbovePIDThreshold())
5505 SliderPanel.setPIDSliderSource(alignPanel,
5506 viewport.getResidueShading(), alignPanel.getViewName());
5510 SliderPanel.hidePIDSlider();
5514 * If there is a frame linked to this one in a SplitPane, switch it to the
5515 * same view tab index. No infinite recursion of calls should happen, since
5516 * tabSelectionChanged() should not get invoked on setting the selected
5517 * index to an unchanged value. Guard against setting an invalid index
5518 * before the new view peer tab has been created.
5520 final AlignViewportI peer = viewport.getCodingComplement();
5523 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
5524 .getAlignPanel().alignFrame;
5525 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5527 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5533 * On right mouse click on view tab, prompt for and set new view name.
5537 public void tabbedPane_mousePressed(MouseEvent e)
5539 if (e.isPopupTrigger())
5541 String msg = MessageManager.getString("label.enter_view_name");
5542 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
5543 String reply = JvOptionPane.showInputDialog(msg, ttl);
5547 viewport.setViewName(reply);
5548 // TODO warn if reply is in getExistingViewNames()?
5549 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5554 public AlignViewport getCurrentView()
5560 * Open the dialog for regex description parsing.
5564 protected void extractScores_actionPerformed(ActionEvent e)
5566 ParseProperties pp = new jalview.analysis.ParseProperties(
5567 viewport.getAlignment());
5568 // TODO: verify regex and introduce GUI dialog for version 2.5
5569 // if (pp.getScoresFromDescription("col", "score column ",
5570 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5572 if (pp.getScoresFromDescription("description column",
5573 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5575 buildSortByAnnotationScoresMenu();
5583 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5588 protected void showDbRefs_actionPerformed(ActionEvent e)
5590 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5596 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5601 protected void showNpFeats_actionPerformed(ActionEvent e)
5603 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5607 * find the viewport amongst the tabs in this alignment frame and close that
5613 public boolean closeView(AlignViewportI av)
5617 this.closeMenuItem_actionPerformed(false);
5620 Component[] comp = tabbedPane.getComponents();
5621 for (int i = 0; comp != null && i < comp.length; i++)
5623 if (comp[i] instanceof AlignmentPanel)
5625 if (((AlignmentPanel) comp[i]).av == av)
5628 closeView((AlignmentPanel) comp[i]);
5636 protected void build_fetchdbmenu(JMenu webService)
5638 // Temporary hack - DBRef Fetcher always top level ws entry.
5639 // TODO We probably want to store a sequence database checklist in
5640 // preferences and have checkboxes.. rather than individual sources selected
5642 final JMenu rfetch = new JMenu(
5643 MessageManager.getString("action.fetch_db_references"));
5644 rfetch.setToolTipText(MessageManager.getString(
5645 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5646 webService.add(rfetch);
5648 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5649 MessageManager.getString("option.trim_retrieved_seqs"));
5650 trimrs.setToolTipText(
5651 MessageManager.getString("label.trim_retrieved_sequences"));
5653 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5654 trimrs.addActionListener(new ActionListener()
5658 public void actionPerformed(ActionEvent e)
5660 trimrs.setSelected(trimrs.isSelected());
5661 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5662 Boolean.valueOf(trimrs.isSelected()).toString());
5666 JMenuItem fetchr = new JMenuItem(
5667 MessageManager.getString("label.standard_databases"));
5668 fetchr.setToolTipText(
5669 MessageManager.getString("label.fetch_embl_uniprot"));
5670 fetchr.addActionListener(new ActionListener()
5674 public void actionPerformed(ActionEvent e)
5676 new Thread(new Runnable()
5682 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5683 .getAlignment().isNucleotide();
5684 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5685 alignPanel.av.getSequenceSelection(),
5686 alignPanel.alignFrame, null,
5687 alignPanel.alignFrame.featureSettings, isNucleotide);
5688 dbRefFetcher.addListener(new FetchFinishedListenerI()
5692 public void finished()
5695 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5696 .getFeatureSettingsModels())
5699 alignPanel.av.mergeFeaturesStyle(srcSettings);
5701 AlignFrame.this.setMenusForViewport();
5704 dbRefFetcher.fetchDBRefs(false);
5712 new Thread(new Runnable()
5719 // final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5720 // .getSequenceFetcherSingleton();
5721 javax.swing.SwingUtilities.invokeLater(new Runnable()
5727 jalview.ws.SequenceFetcher sf = jalview.ws.SequenceFetcher
5729 String[] dbclasses = sf.getNonAlignmentSources();
5730 List<DbSourceProxy> otherdb;
5731 JMenu dfetch = new JMenu();
5732 JMenu ifetch = new JMenu();
5733 JMenuItem fetchr = null;
5734 int comp = 0, icomp = 0, mcomp = 15;
5735 String mname = null;
5737 for (String dbclass : dbclasses)
5739 otherdb = sf.getSourceProxy(dbclass);
5740 // add a single entry for this class, or submenu allowing 'fetch
5742 if (otherdb == null || otherdb.size() < 1)
5748 mname = "From " + dbclass;
5750 if (otherdb.size() == 1)
5752 DbSourceProxy src = otherdb.get(0);
5753 DbSourceProxy[] dassource = new DbSourceProxy[] { src };
5754 fetchr = new JMenuItem(src.getDbSource());
5755 fetchr.addActionListener(new ActionListener()
5759 public void actionPerformed(ActionEvent e)
5761 new Thread(new Runnable()
5767 boolean isNucleotide = alignPanel.alignFrame
5768 .getViewport().getAlignment()
5770 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5771 alignPanel.av.getSequenceSelection(),
5772 alignPanel.alignFrame, dassource,
5773 alignPanel.alignFrame.featureSettings,
5776 .addListener(new FetchFinishedListenerI()
5780 public void finished()
5782 FeatureSettingsModelI srcSettings = dassource[0]
5783 .getFeatureColourScheme();
5784 alignPanel.av.mergeFeaturesStyle(
5786 AlignFrame.this.setMenusForViewport();
5789 dbRefFetcher.fetchDBRefs(false);
5795 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5796 MessageManager.formatMessage(
5797 "label.fetch_retrieve_from", new Object[]
5798 { src.getDbName() })));
5804 final DbSourceProxy[] dassource = otherdb
5805 .toArray(new DbSourceProxy[0]);
5807 DbSourceProxy src = otherdb.get(0);
5808 fetchr = new JMenuItem(MessageManager
5809 .formatMessage("label.fetch_all_param", new Object[]
5810 { src.getDbSource() }));
5811 fetchr.addActionListener(new ActionListener()
5815 public void actionPerformed(ActionEvent e)
5817 new Thread(new Runnable()
5823 boolean isNucleotide = alignPanel.alignFrame
5824 .getViewport().getAlignment()
5826 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5827 alignPanel.av.getSequenceSelection(),
5828 alignPanel.alignFrame, dassource,
5829 alignPanel.alignFrame.featureSettings,
5832 .addListener(new FetchFinishedListenerI()
5836 public void finished()
5838 AlignFrame.this.setMenusForViewport();
5841 dbRefFetcher.fetchDBRefs(false);
5847 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5848 MessageManager.formatMessage(
5849 "label.fetch_retrieve_from_all_sources",
5851 { Integer.valueOf(otherdb.size())
5853 src.getDbSource(), src.getDbName() })));
5856 // and then build the rest of the individual menus
5857 ifetch = new JMenu(MessageManager.formatMessage(
5858 "label.source_from_db_source", new Object[]
5859 { src.getDbSource() }));
5861 String imname = null;
5863 for (DbSourceProxy sproxy : otherdb)
5865 String dbname = sproxy.getDbName();
5866 String sname = dbname.length() > 5
5867 ? dbname.substring(0, 5) + "..."
5869 String msname = dbname.length() > 10
5870 ? dbname.substring(0, 10) + "..."
5874 imname = MessageManager
5875 .formatMessage("label.from_msname", new Object[]
5878 fetchr = new JMenuItem(msname);
5879 final DbSourceProxy[] dassrc = { sproxy };
5880 fetchr.addActionListener(new ActionListener()
5884 public void actionPerformed(ActionEvent e)
5886 new Thread(new Runnable()
5892 boolean isNucleotide = alignPanel.alignFrame
5893 .getViewport().getAlignment()
5895 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5896 alignPanel.av.getSequenceSelection(),
5897 alignPanel.alignFrame, dassrc,
5898 alignPanel.alignFrame.featureSettings,
5901 .addListener(new FetchFinishedListenerI()
5905 public void finished()
5907 AlignFrame.this.setMenusForViewport();
5910 dbRefFetcher.fetchDBRefs(false);
5916 fetchr.setToolTipText(
5917 "<html>" + MessageManager.formatMessage(
5918 "label.fetch_retrieve_from", new Object[]
5922 if (++icomp >= mcomp || i == (otherdb.size()))
5924 ifetch.setText(MessageManager.formatMessage(
5925 "label.source_to_target", imname, sname));
5927 ifetch = new JMenu();
5935 if (comp >= mcomp || dbi >= (dbclasses.length))
5937 dfetch.setText(MessageManager.formatMessage(
5938 "label.source_to_target", mname, dbclass));
5940 dfetch = new JMenu();
5953 * Left justify the whole alignment.
5957 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5959 viewport.getAlignment().justify(false);
5960 viewport.notifyAlignment();
5964 * Right justify the whole alignment.
5968 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5970 viewport.getAlignment().justify(true);
5971 viewport.notifyAlignment();
5975 public void setShowSeqFeatures(boolean b)
5977 showSeqFeatures.setSelected(b);
5978 viewport.setShowSequenceFeatures(b);
5985 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5986 * awt.event.ActionEvent)
5990 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5992 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5993 alignPanel.paintAlignment(false, false);
6000 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
6005 protected void showGroupConsensus_actionPerformed(ActionEvent e)
6007 viewport.setShowGroupConsensus(showGroupConsensus.getState());
6008 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
6016 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
6017 * .event.ActionEvent)
6021 protected void showGroupConservation_actionPerformed(ActionEvent e)
6023 viewport.setShowGroupConservation(showGroupConservation.getState());
6024 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
6031 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
6032 * .event.ActionEvent)
6036 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
6038 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
6039 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
6046 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
6047 * .event.ActionEvent)
6051 protected void showSequenceLogo_actionPerformed(ActionEvent e)
6053 viewport.setShowSequenceLogo(showSequenceLogo.getState());
6054 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
6058 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
6060 showSequenceLogo.setState(true);
6061 viewport.setShowSequenceLogo(true);
6062 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
6063 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
6067 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
6069 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
6076 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
6077 * .event.ActionEvent)
6081 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
6083 if (avc.makeGroupsFromSelection())
6085 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
6086 alignPanel.updateAnnotation();
6087 alignPanel.paintAlignment(true,
6088 viewport.needToUpdateStructureViews());
6092 public void clearAlignmentSeqRep()
6094 // TODO refactor alignmentseqrep to controller
6095 if (viewport.getAlignment().hasSeqrep())
6097 viewport.getAlignment().setSeqrep(null);
6098 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
6099 alignPanel.updateAnnotation();
6100 alignPanel.paintAlignment(true, true);
6105 protected void createGroup_actionPerformed(ActionEvent e)
6107 if (avc.createGroup())
6109 if (applyAutoAnnotationSettings.isSelected())
6111 alignPanel.updateAnnotation(true, false);
6113 alignPanel.alignmentChanged();
6118 protected void unGroup_actionPerformed(ActionEvent e)
6122 alignPanel.alignmentChanged();
6127 * make the given alignmentPanel the currently selected tab
6129 * @param alignmentPanel
6132 public void setDisplayedView(AlignmentPanel alignmentPanel)
6134 if (!viewport.getSequenceSetId()
6135 .equals(alignmentPanel.av.getSequenceSetId()))
6137 throw new Error(MessageManager.getString(
6138 "error.implementation_error_cannot_show_view_alignment_frame"));
6140 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
6141 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
6143 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
6148 * Action on selection of menu options to Show or Hide annotations.
6151 * @param forSequences
6152 * update sequence-related annotations
6153 * @param forAlignment
6154 * update non-sequence-related annotations
6158 protected void setAnnotationsVisibility(boolean visible,
6159 boolean forSequences, boolean forAlignment)
6161 AlignmentAnnotation[] anns = alignPanel.getAlignment()
6162 .getAlignmentAnnotation();
6167 for (AlignmentAnnotation aa : anns)
6170 * don't display non-positional annotations on an alignment
6172 if (aa.annotations == null)
6176 boolean apply = (aa.sequenceRef == null && forAlignment)
6177 || (aa.sequenceRef != null && forSequences);
6180 aa.visible = visible;
6183 alignPanel.validateAnnotationDimensions(true);
6184 alignPanel.alignmentChanged();
6188 * Store selected annotation sort order for the view and repaint.
6192 protected void sortAnnotations_actionPerformed()
6194 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
6196 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
6197 alignPanel.paintAlignment(false, false);
6202 * @return alignment panels in this alignment frame
6205 public List<? extends AlignmentViewPanel> getAlignPanels()
6207 // alignPanels is never null
6208 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
6213 * Open a new alignment window, with the cDNA associated with this (protein)
6214 * alignment, aligned as is the protein.
6217 protected void viewAsCdna_actionPerformed()
6219 // TODO no longer a menu action - refactor as required
6220 final AlignmentI alignment = getViewport().getAlignment();
6221 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
6222 if (mappings == null)
6226 List<SequenceI> cdnaSeqs = new ArrayList<>();
6227 for (SequenceI aaSeq : alignment.getSequences())
6229 for (AlignedCodonFrame acf : mappings)
6231 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
6235 * There is a cDNA mapping for this protein sequence - add to new
6236 * alignment. It will share the same dataset sequence as other mapped
6237 * cDNA (no new mappings need to be created).
6239 final Sequence newSeq = new Sequence(dnaSeq);
6240 newSeq.setDatasetSequence(dnaSeq);
6241 cdnaSeqs.add(newSeq);
6245 if (cdnaSeqs.size() == 0)
6247 // show a warning dialog no mapped cDNA
6250 AlignmentI cdna = new Alignment(
6251 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
6252 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
6253 AlignFrame.DEFAULT_HEIGHT);
6254 cdna.alignAs(alignment);
6255 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
6257 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
6258 AlignFrame.DEFAULT_HEIGHT);
6262 * Set visibility of dna/protein complement view (available when shown in a
6269 protected void showComplement_actionPerformed(boolean show)
6271 SplitContainerI sf = getSplitViewContainer();
6274 sf.setComplementVisible(this, show);
6279 * Generate the reverse (optionally complemented) of the selected sequences,
6280 * and add them to the alignment
6284 protected void showReverse_actionPerformed(boolean complement)
6286 AlignmentI al = null;
6289 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
6290 al = dna.reverseCdna(complement);
6291 viewport.addAlignment(al, "");
6292 addHistoryItem(new EditCommand(
6293 MessageManager.getString("label.add_sequences"), Action.PASTE,
6294 al.getSequencesArray(), 0, al.getWidth(),
6295 viewport.getAlignment()));
6296 } catch (Exception ex)
6298 System.err.println(ex.getMessage());
6304 * Try to run a script in the Groovy console, having first ensured that this
6305 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
6306 * be targeted at this alignment.
6310 protected void runGroovy_actionPerformed()
6312 Jalview.setCurrentAlignFrame(this);
6313 groovy.ui.Console console = Desktop.getGroovyConsole();
6314 if (console != null)
6318 console.runScript();
6319 } catch (Exception ex)
6321 System.err.println((ex.toString()));
6322 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
6323 MessageManager.getString("label.couldnt_run_groovy_script"),
6324 MessageManager.getString("label.groovy_support_failed"),
6325 JvOptionPane.ERROR_MESSAGE);
6330 System.err.println("Can't run Groovy script as console not found");
6335 * Hides columns containing (or not containing) a specified feature, provided
6336 * that would not leave all columns hidden
6338 * @param featureType
6339 * @param columnsContaining
6343 public boolean hideFeatureColumns(String featureType,
6344 boolean columnsContaining)
6346 boolean notForHiding = avc.markColumnsContainingFeatures(
6347 columnsContaining, false, false, featureType);
6350 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
6351 false, featureType))
6353 getViewport().hideSelectedColumns();
6361 protected void selectHighlightedColumns_actionPerformed(
6362 ActionEvent actionEvent)
6364 // include key modifier check in case user selects from menu
6365 avc.markHighlightedColumns(
6366 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
6367 (actionEvent.getModifiers() & (ActionEvent.META_MASK
6368 | ActionEvent.CTRL_MASK)) != 0);
6372 * Rebuilds the Colour menu, including any user-defined colours which have
6373 * been loaded either on startup or during the session
6376 public void buildColourMenu()
6378 colourMenu.removeAll();
6380 colourMenu.add(applyToAllGroups);
6381 colourMenu.add(textColour);
6382 colourMenu.addSeparator();
6384 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
6385 viewport.getAlignment(), false);
6387 colourMenu.add(annotationColour);
6388 bg.add(annotationColour);
6389 colourMenu.addSeparator();
6390 colourMenu.add(conservationMenuItem);
6391 colourMenu.add(modifyConservation);
6392 colourMenu.add(abovePIDThreshold);
6393 colourMenu.add(modifyPID);
6395 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
6396 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
6400 * Open a dialog (if not already open) that allows the user to select and
6401 * calculate PCA or Tree analysis
6404 protected void openTreePcaDialog()
6406 if (alignPanel.getCalculationDialog() == null)
6408 new CalculationChooser(AlignFrame.this);
6413 * Sets the status of the HMMER menu
6415 public void updateHMMERStatus()
6417 hmmerMenu.setEnabled(HmmerCommand.isHmmerAvailable());
6421 protected void loadVcf_actionPerformed()
6423 JalviewFileChooser chooser = new JalviewFileChooser(
6424 Cache.getProperty("LAST_DIRECTORY"));
6425 chooser.setFileView(new JalviewFileView());
6426 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
6427 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
6428 final AlignFrame us = this;
6429 chooser.setResponseHandler(0, new Runnable()
6435 String choice = chooser.getSelectedFile().getPath();
6436 Cache.setProperty("LAST_DIRECTORY", choice);
6437 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
6438 new VCFLoader(choice).loadVCF(seqs, us);
6441 chooser.showOpenDialog(null);
6445 private Rectangle lastFeatureSettingsBounds = null;
6448 public void setFeatureSettingsGeometry(Rectangle bounds)
6450 lastFeatureSettingsBounds = bounds;
6454 public Rectangle getFeatureSettingsGeometry()
6456 return lastFeatureSettingsBounds;
6459 public void scrollTo(int row, int column)
6461 alignPanel.getSeqPanel().scrollTo(row, column);
6464 public void scrollToRow(int row)
6466 alignPanel.getSeqPanel().scrollToRow(row);
6469 public void scrollToColumn(int column)
6471 alignPanel.getSeqPanel().scrollToColumn(column);
6475 * BH 2019 from JalviewLite
6477 * get sequence feature groups that are hidden or shown
6484 public String[] getFeatureGroupsOfState(boolean visible)
6486 jalview.api.FeatureRenderer fr = null;
6487 if (alignPanel != null
6488 && (fr = alignPanel.getFeatureRenderer()) != null)
6490 List<String> gps = fr.getGroups(visible);
6491 String[] _gps = gps.toArray(new String[gps.size()]);
6499 * @return list of feature groups on the view
6502 public String[] getFeatureGroups()
6504 jalview.api.FeatureRenderer fr = null;
6505 if (alignPanel != null
6506 && (fr = alignPanel.getFeatureRenderer()) != null)
6508 List<String> gps = fr.getFeatureGroups();
6509 String[] _gps = gps.toArray(new String[gps.size()]);
6515 public void select(SequenceGroup sel, ColumnSelection csel,
6516 HiddenColumns hidden)
6518 alignPanel.getSeqPanel().selection(sel, csel, hidden, null);
6526 static class PrintThread extends Thread
6530 public PrintThread(AlignmentPanel ap)
6535 static PageFormat pf;
6540 PrinterJob printJob = PrinterJob.getPrinterJob();
6544 printJob.setPrintable(ap, pf);
6548 printJob.setPrintable(ap);
6551 if (printJob.printDialog())
6556 } catch (Exception PrintException)
6558 PrintException.printStackTrace();