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.awt.BorderLayout;
24 import java.awt.Color;
25 import java.awt.Component;
26 import java.awt.Rectangle;
27 import java.awt.Toolkit;
28 import java.awt.datatransfer.Clipboard;
29 import java.awt.datatransfer.DataFlavor;
30 import java.awt.datatransfer.StringSelection;
31 import java.awt.datatransfer.Transferable;
32 import java.awt.dnd.DnDConstants;
33 import java.awt.dnd.DropTargetDragEvent;
34 import java.awt.dnd.DropTargetDropEvent;
35 import java.awt.dnd.DropTargetEvent;
36 import java.awt.dnd.DropTargetListener;
37 import java.awt.event.ActionEvent;
38 import java.awt.event.ActionListener;
39 import java.awt.event.FocusAdapter;
40 import java.awt.event.FocusEvent;
41 import java.awt.event.ItemEvent;
42 import java.awt.event.ItemListener;
43 import java.awt.event.KeyAdapter;
44 import java.awt.event.KeyEvent;
45 import java.awt.event.MouseEvent;
46 import java.awt.print.PageFormat;
47 import java.awt.print.PrinterJob;
48 import java.beans.PropertyChangeListener;
50 import java.io.FileWriter;
51 import java.io.PrintWriter;
53 import java.util.ArrayList;
54 import java.util.Arrays;
55 import java.util.Collection;
56 import java.util.Deque;
57 import java.util.List;
58 import java.util.Vector;
60 import javax.swing.ButtonGroup;
61 import javax.swing.JCheckBoxMenuItem;
62 import javax.swing.JComponent;
63 import javax.swing.JEditorPane;
64 import javax.swing.JInternalFrame;
65 import javax.swing.JLabel;
66 import javax.swing.JLayeredPane;
67 import javax.swing.JMenu;
68 import javax.swing.JMenuItem;
69 import javax.swing.JPanel;
70 import javax.swing.JScrollPane;
71 import javax.swing.SwingUtilities;
72 import javax.swing.event.InternalFrameAdapter;
73 import javax.swing.event.InternalFrameEvent;
75 import jalview.analysis.AlignmentSorter;
76 import jalview.analysis.AlignmentUtils;
77 import jalview.analysis.CrossRef;
78 import jalview.analysis.Dna;
79 import jalview.analysis.GeneticCodeI;
80 import jalview.analysis.ParseProperties;
81 import jalview.analysis.SequenceIdMatcher;
82 import jalview.api.AlignExportSettingsI;
83 import jalview.api.AlignViewControllerGuiI;
84 import jalview.api.AlignViewControllerI;
85 import jalview.api.AlignViewportI;
86 import jalview.api.AlignmentViewPanel;
87 import jalview.api.FeatureSettingsControllerI;
88 import jalview.api.FeatureSettingsModelI;
89 import jalview.api.SplitContainerI;
90 import jalview.api.ViewStyleI;
91 import jalview.api.analysis.SimilarityParamsI;
92 import jalview.bin.Cache;
93 import jalview.bin.Jalview;
94 import jalview.commands.CommandI;
95 import jalview.commands.EditCommand;
96 import jalview.commands.EditCommand.Action;
97 import jalview.commands.OrderCommand;
98 import jalview.commands.RemoveGapColCommand;
99 import jalview.commands.RemoveGapsCommand;
100 import jalview.commands.SlideSequencesCommand;
101 import jalview.commands.TrimRegionCommand;
102 import jalview.datamodel.AlignExportSettingsAdapter;
103 import jalview.datamodel.AlignedCodonFrame;
104 import jalview.datamodel.Alignment;
105 import jalview.datamodel.AlignmentAnnotation;
106 import jalview.datamodel.AlignmentExportData;
107 import jalview.datamodel.AlignmentI;
108 import jalview.datamodel.AlignmentOrder;
109 import jalview.datamodel.AlignmentView;
110 import jalview.datamodel.ColumnSelection;
111 import jalview.datamodel.HiddenColumns;
112 import jalview.datamodel.PDBEntry;
113 import jalview.datamodel.SeqCigar;
114 import jalview.datamodel.Sequence;
115 import jalview.datamodel.SequenceGroup;
116 import jalview.datamodel.SequenceI;
117 import jalview.gui.ColourMenuHelper.ColourChangeListener;
118 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
119 import jalview.hmmer.HMMAlign;
120 import jalview.hmmer.HMMBuild;
121 import jalview.hmmer.HMMERParamStore;
122 import jalview.hmmer.HMMERPreset;
123 import jalview.hmmer.HMMSearch;
124 import jalview.hmmer.HmmerCommand;
125 import jalview.hmmer.JackHMMER;
126 import jalview.io.AlignmentProperties;
127 import jalview.io.AnnotationFile;
128 import jalview.io.BackupFiles;
129 import jalview.io.BioJsHTMLOutput;
130 import jalview.io.DataSourceType;
131 import jalview.io.FileFormat;
132 import jalview.io.FileFormatI;
133 import jalview.io.FileFormats;
134 import jalview.io.FileLoader;
135 import jalview.io.FileParse;
136 import jalview.io.FormatAdapter;
137 import jalview.io.HtmlSvgOutput;
138 import jalview.io.IdentifyFile;
139 import jalview.io.JPredFile;
140 import jalview.io.JalviewFileChooser;
141 import jalview.io.JalviewFileView;
142 import jalview.io.JnetAnnotationMaker;
143 import jalview.io.NewickFile;
144 import jalview.io.ScoreMatrixFile;
145 import jalview.io.TCoffeeScoreFile;
146 import jalview.io.vcf.VCFLoader;
147 import jalview.jbgui.GAlignFrame;
148 import jalview.project.Jalview2XML;
149 import jalview.schemes.ColourSchemeI;
150 import jalview.schemes.ColourSchemes;
151 import jalview.schemes.ResidueColourScheme;
152 import jalview.schemes.TCoffeeColourScheme;
153 import jalview.util.ImageMaker.TYPE;
154 import jalview.util.MessageManager;
155 import jalview.util.Platform;
156 import jalview.viewmodel.AlignmentViewport;
157 import jalview.viewmodel.ViewportRanges;
158 import jalview.ws.DBRefFetcher;
159 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
160 import jalview.ws.ServiceChangeListener;
161 import jalview.ws.WSDiscovererI;
162 import jalview.ws.api.ServiceWithParameters;
163 import jalview.ws.jws2.Jws2Discoverer;
164 import jalview.ws.jws2.PreferredServiceRegistry;
165 import jalview.ws.params.ArgumentI;
166 import jalview.ws.params.ParamDatastoreI;
167 import jalview.ws.params.WsParamSetI;
168 import jalview.ws.seqfetcher.DbSourceProxy;
169 import jalview.ws.slivkaws.SlivkaWSDiscoverer;
170 import java.io.IOException;
171 import java.util.HashSet;
172 import java.util.Set;
174 import javax.swing.JFileChooser;
175 import javax.swing.JOptionPane;
181 * @version $Revision$
183 @SuppressWarnings("serial")
184 public class AlignFrame extends GAlignFrame
185 implements DropTargetListener, IProgressIndicator,
186 AlignViewControllerGuiI, ColourChangeListener, ServiceChangeListener
188 public static final int DEFAULT_WIDTH = 700;
190 public static final int DEFAULT_HEIGHT = 500;
193 * The currently displayed panel (selected tabbed view if more than one)
195 public AlignmentPanel alignPanel;
197 AlignViewport viewport;
199 public AlignViewControllerI avc;
201 List<AlignmentPanel> alignPanels = new ArrayList<>();
204 * Last format used to load or save alignments in this window
206 FileFormatI currentFileFormat = null;
209 * Current filename for this alignment
211 String fileName = null;
214 * TODO: remove reference to 'FileObject' in AlignFrame - not correct mapping
219 * Creates a new AlignFrame object with specific width and height.
225 public AlignFrame(AlignmentI al, int width, int height)
227 this(al, null, width, height);
231 * Creates a new AlignFrame object with specific width, height and
237 * @param sequenceSetId
239 public AlignFrame(AlignmentI al, int width, int height,
240 String sequenceSetId)
242 this(al, null, width, height, sequenceSetId);
246 * Creates a new AlignFrame object with specific width, height and
252 * @param sequenceSetId
255 public AlignFrame(AlignmentI al, int width, int height,
256 String sequenceSetId, String viewId)
258 this(al, null, width, height, sequenceSetId, viewId);
262 * new alignment window with hidden columns
266 * @param hiddenColumns
267 * ColumnSelection or null
269 * Width of alignment frame
273 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
276 this(al, hiddenColumns, width, height, null);
280 * Create alignment frame for al with hiddenColumns, a specific width and
281 * height, and specific sequenceId
284 * @param hiddenColumns
287 * @param sequenceSetId
290 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
291 int height, String sequenceSetId)
293 this(al, hiddenColumns, width, height, sequenceSetId, null);
297 * Create alignment frame for al with hiddenColumns, a specific width and
298 * height, and specific sequenceId
301 * @param hiddenColumns
304 * @param sequenceSetId
309 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
310 int height, String sequenceSetId, String viewId)
312 setSize(width, height);
314 if (al.getDataset() == null)
319 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
321 alignPanel = new AlignmentPanel(this, viewport);
323 addAlignmentPanel(alignPanel, true);
327 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
328 HiddenColumns hiddenColumns, int width, int height)
330 setSize(width, height);
332 if (al.getDataset() == null)
337 viewport = new AlignViewport(al, hiddenColumns);
339 if (hiddenSeqs != null && hiddenSeqs.length > 0)
341 viewport.hideSequence(hiddenSeqs);
343 alignPanel = new AlignmentPanel(this, viewport);
344 addAlignmentPanel(alignPanel, true);
349 * Make a new AlignFrame from existing alignmentPanels
356 public AlignFrame(AlignmentPanel ap)
360 addAlignmentPanel(ap, false);
365 * initalise the alignframe from the underlying viewport data and the
370 // setBackground(Color.white); // BH 2019
372 if (!Jalview.isHeadlessMode())
374 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
377 avc = new jalview.controller.AlignViewController(this, viewport,
379 if (viewport.getAlignmentConservationAnnotation() == null)
381 // BLOSUM62Colour.setEnabled(false);
382 conservationMenuItem.setEnabled(false);
383 modifyConservation.setEnabled(false);
384 // PIDColour.setEnabled(false);
385 // abovePIDThreshold.setEnabled(false);
386 // modifyPID.setEnabled(false);
389 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
392 if (sortby.equals("Id"))
394 sortIDMenuItem_actionPerformed(null);
396 else if (sortby.equals("Pairwise Identity"))
398 sortPairwiseMenuItem_actionPerformed(null);
402 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
404 setMenusFromViewport(viewport);
405 buildSortByAnnotationScoresMenu();
406 calculateTree.addActionListener(new ActionListener()
410 public void actionPerformed(ActionEvent e)
417 if (Desktop.desktop != null)
419 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
420 if (!Platform.isJS())
422 addServiceListeners();
427 if (viewport.getWrapAlignment())
429 wrapMenuItem_actionPerformed(null);
432 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
434 this.overviewMenuItem_actionPerformed(null);
439 final List<AlignmentPanel> selviews = new ArrayList<>();
440 final List<AlignmentPanel> origview = new ArrayList<>();
441 final String menuLabel = MessageManager
442 .getString("label.copy_format_from");
443 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
444 new ViewSetProvider()
448 public AlignmentPanel[] getAllAlignmentPanels()
451 origview.add(alignPanel);
452 // make an array of all alignment panels except for this one
453 List<AlignmentPanel> aps = new ArrayList<>(
454 Arrays.asList(Desktop.getAlignmentPanels(null)));
455 aps.remove(AlignFrame.this.alignPanel);
456 return aps.toArray(new AlignmentPanel[aps.size()]);
458 }, selviews, new ItemListener()
462 public void itemStateChanged(ItemEvent e)
464 if (origview.size() > 0)
466 final AlignmentPanel ap = origview.get(0);
469 * Copy the ViewStyle of the selected panel to 'this one'.
470 * Don't change value of 'scaleProteinAsCdna' unless copying
473 ViewStyleI vs = selviews.get(0).getAlignViewport()
475 boolean fromSplitFrame = selviews.get(0)
476 .getAlignViewport().getCodingComplement() != null;
479 vs.setScaleProteinAsCdna(ap.getAlignViewport()
480 .getViewStyle().isScaleProteinAsCdna());
482 ap.getAlignViewport().setViewStyle(vs);
485 * Also rescale ViewStyle of SplitFrame complement if there is
486 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
487 * the whole ViewStyle (allow cDNA protein to have different
490 AlignViewportI complement = ap.getAlignViewport()
491 .getCodingComplement();
492 if (complement != null && vs.isScaleProteinAsCdna())
494 AlignFrame af = Desktop.getAlignFrameFor(complement);
495 ((SplitFrame) af.getSplitViewContainer())
497 af.setMenusForViewport();
501 ap.setSelected(true);
502 ap.alignFrame.setMenusForViewport();
507 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
508 .indexOf("devel") > -1
509 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
510 .indexOf("test") > -1)
512 formatMenu.add(vsel);
514 addFocusListener(new FocusAdapter()
517 public void focusGained(FocusEvent e)
519 Jalview.setCurrentAlignFrame(AlignFrame.this);
526 * Change the filename and format for the alignment, and enable the 'reload'
527 * button functionality.
534 public void setFileName(String file, FileFormatI format)
537 setFileFormat(format);
538 reload.setEnabled(true);
542 * JavaScript will have this, maybe others. More dependable than a file name
543 * and maintains a reference to the actual bytes loaded.
547 public void setFileObject(File file)
549 this.fileObject = file;
553 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
556 void addKeyListener()
558 addKeyListener(new KeyAdapter()
561 public void keyPressed(KeyEvent evt)
563 if (viewport.cursorMode
564 && ((evt.getKeyCode() >= KeyEvent.VK_0
565 && evt.getKeyCode() <= KeyEvent.VK_9)
566 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
567 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
568 && Character.isDigit(evt.getKeyChar()))
570 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
573 switch (evt.getKeyCode())
576 case 27: // escape key
577 deselectAllSequenceMenuItem_actionPerformed(null);
581 case KeyEvent.VK_DOWN:
582 if (evt.isAltDown() || !viewport.cursorMode)
584 moveSelectedSequences(false);
586 if (viewport.cursorMode)
588 alignPanel.getSeqPanel().moveCursor(0, 1);
593 if (evt.isAltDown() || !viewport.cursorMode)
595 moveSelectedSequences(true);
597 if (viewport.cursorMode)
599 alignPanel.getSeqPanel().moveCursor(0, -1);
604 case KeyEvent.VK_LEFT:
605 if (evt.isAltDown() || !viewport.cursorMode)
607 slideSequences(false,
608 alignPanel.getSeqPanel().getKeyboardNo1());
612 alignPanel.getSeqPanel().moveCursor(-1, 0);
617 case KeyEvent.VK_RIGHT:
618 if (evt.isAltDown() || !viewport.cursorMode)
620 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
624 alignPanel.getSeqPanel().moveCursor(1, 0);
628 case KeyEvent.VK_SPACE:
629 if (viewport.cursorMode)
631 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
632 || evt.isShiftDown() || evt.isAltDown());
636 // case KeyEvent.VK_A:
637 // if (viewport.cursorMode)
639 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
640 // //System.out.println("A");
644 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
645 * System.out.println("closing bracket"); } break;
647 case KeyEvent.VK_DELETE:
648 case KeyEvent.VK_BACK_SPACE:
649 if (!viewport.cursorMode)
651 cut_actionPerformed();
655 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
656 || evt.isShiftDown() || evt.isAltDown());
662 if (viewport.cursorMode)
664 alignPanel.getSeqPanel().setCursorRow();
668 if (viewport.cursorMode && !evt.isControlDown())
670 alignPanel.getSeqPanel().setCursorColumn();
674 if (viewport.cursorMode)
676 alignPanel.getSeqPanel().setCursorPosition();
680 case KeyEvent.VK_ENTER:
681 case KeyEvent.VK_COMMA:
682 if (viewport.cursorMode)
684 alignPanel.getSeqPanel().setCursorRowAndColumn();
689 if (viewport.cursorMode)
691 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
695 if (viewport.cursorMode)
697 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
702 viewport.cursorMode = !viewport.cursorMode;
703 setStatus(MessageManager
704 .formatMessage("label.keyboard_editing_mode", new String[]
705 { (viewport.cursorMode ? "on" : "off") }));
706 if (viewport.cursorMode)
708 ViewportRanges ranges = viewport.getRanges();
709 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
711 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
714 alignPanel.getSeqPanel().seqCanvas.repaint();
720 Help.showHelpWindow();
721 } catch (Exception ex)
723 ex.printStackTrace();
728 boolean toggleSeqs = !evt.isControlDown();
729 boolean toggleCols = !evt.isShiftDown();
730 toggleHiddenRegions(toggleSeqs, toggleCols);
735 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
736 boolean modifyExisting = true; // always modify, don't clear
737 // evt.isShiftDown();
738 boolean invertHighlighted = evt.isAltDown();
739 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
743 case KeyEvent.VK_PAGE_UP:
744 viewport.getRanges().pageUp();
746 case KeyEvent.VK_PAGE_DOWN:
747 viewport.getRanges().pageDown();
753 public void keyReleased(KeyEvent evt)
755 switch (evt.getKeyCode())
757 case KeyEvent.VK_LEFT:
758 if (evt.isAltDown() || !viewport.cursorMode)
760 viewport.firePropertyChange("alignment", null,
761 viewport.getAlignment().getSequences());
765 case KeyEvent.VK_RIGHT:
766 if (evt.isAltDown() || !viewport.cursorMode)
768 viewport.firePropertyChange("alignment", null,
769 viewport.getAlignment().getSequences());
777 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
779 ap.alignFrame = this;
780 avc = new jalview.controller.AlignViewController(this, viewport,
785 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
787 int aSize = alignPanels.size();
789 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
791 if (aSize == 1 && ap.av.getViewName() == null)
793 this.getContentPane().add(ap, BorderLayout.CENTER);
799 setInitialTabVisible();
802 expandViews.setEnabled(true);
803 gatherViews.setEnabled(true);
804 tabbedPane.addTab(ap.av.getViewName(), ap);
806 ap.setVisible(false);
811 if (ap.av.isPadGaps())
813 ap.av.getAlignment().padGaps();
815 ap.av.updateConservation(ap);
816 ap.av.updateConsensus(ap);
817 ap.av.updateStrucConsensus(ap);
818 ap.av.initInformationWorker(ap);
822 public void setInitialTabVisible()
824 expandViews.setEnabled(true);
825 gatherViews.setEnabled(true);
826 tabbedPane.setVisible(true);
827 AlignmentPanel first = alignPanels.get(0);
828 tabbedPane.addTab(first.av.getViewName(), first);
829 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
832 public AlignViewport getViewport()
838 public void servicesChanged(WSDiscovererI discoverer,
839 Collection<? extends ServiceWithParameters> services)
841 buildWebServicesMenu();
844 /* Set up intrinsic listeners for dynamically generated GUI bits. */
845 private void addServiceListeners()
847 if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
849 WSDiscovererI discoverer = SlivkaWSDiscoverer.getInstance();
850 discoverer.addServiceChangeListener(this);
852 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
854 WSDiscovererI discoverer = Jws2Discoverer.getDiscoverer();
855 discoverer.addServiceChangeListener(this);
857 // legacy event listener for compatibility with jws1
858 PropertyChangeListener legacyListener = (changeEvent) -> {
859 buildWebServicesMenu();
861 Desktop.instance.addJalviewPropertyChangeListener("services",legacyListener);
863 addInternalFrameListener(new InternalFrameAdapter() {
865 public void internalFrameClosed(InternalFrameEvent e) {
866 System.out.println("deregistering discoverer listener");
867 SlivkaWSDiscoverer.getInstance().removeServiceChangeListener(AlignFrame.this);
868 Jws2Discoverer.getDiscoverer().removeServiceChangeListener(AlignFrame.this);
869 Desktop.instance.removeJalviewPropertyChangeListener("services", legacyListener);
870 closeMenuItem_actionPerformed(true);
873 buildWebServicesMenu();
877 * Configure menu items that vary according to whether the alignment is
878 * nucleotide or protein
880 public void setGUINucleotide()
882 AlignmentI al = getViewport().getAlignment();
883 boolean nucleotide = al.isNucleotide();
885 loadVcf.setVisible(nucleotide);
886 showTranslation.setVisible(nucleotide);
887 showReverse.setVisible(nucleotide);
888 showReverseComplement.setVisible(nucleotide);
889 conservationMenuItem.setEnabled(!nucleotide);
891 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
892 showGroupConservation.setEnabled(!nucleotide);
894 showComplementMenuItem
895 .setText(nucleotide ? MessageManager.getString("label.protein")
896 : MessageManager.getString("label.nucleotide"));
900 * set up menus for the current viewport. This may be called after any
901 * operation that affects the data in the current view (selection changed,
902 * etc) to update the menus to reflect the new state.
905 public void setMenusForViewport()
907 setMenusFromViewport(viewport);
911 * Need to call this method when tabs are selected for multiple views, or when
912 * loading from Jalview2XML.java
917 public void setMenusFromViewport(AlignViewport av)
919 padGapsMenuitem.setSelected(av.isPadGaps());
920 colourTextMenuItem.setSelected(av.isShowColourText());
921 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
922 modifyPID.setEnabled(abovePIDThreshold.isSelected());
923 conservationMenuItem.setSelected(av.getConservationSelected());
924 modifyConservation.setEnabled(conservationMenuItem.isSelected());
925 seqLimits.setSelected(av.getShowJVSuffix());
926 idRightAlign.setSelected(av.isRightAlignIds());
927 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
928 renderGapsMenuItem.setSelected(av.isRenderGaps());
929 wrapMenuItem.setSelected(av.getWrapAlignment());
930 scaleAbove.setVisible(av.getWrapAlignment());
931 scaleLeft.setVisible(av.getWrapAlignment());
932 scaleRight.setVisible(av.getWrapAlignment());
933 annotationPanelMenuItem.setState(av.isShowAnnotation());
935 * Show/hide annotations only enabled if annotation panel is shown
937 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
938 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
939 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
940 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
941 viewBoxesMenuItem.setSelected(av.getShowBoxes());
942 viewTextMenuItem.setSelected(av.getShowText());
943 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
944 showGroupConsensus.setSelected(av.isShowGroupConsensus());
945 showGroupConservation.setSelected(av.isShowGroupConservation());
946 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
947 showSequenceLogo.setSelected(av.isShowSequenceLogo());
948 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
949 showInformationHistogram.setSelected(av.isShowInformationHistogram());
950 showHMMSequenceLogo.setSelected(av.isShowHMMSequenceLogo());
951 normaliseHMMSequenceLogo.setSelected(av.isNormaliseHMMSequenceLogo());
953 ColourMenuHelper.setColourSelected(colourMenu,
954 av.getGlobalColourScheme());
956 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
957 hiddenMarkers.setState(av.getShowHiddenMarkers());
958 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
959 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
960 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
961 autoCalculate.setSelected(av.autoCalculateConsensus);
962 sortByTree.setSelected(av.sortByTree);
963 listenToViewSelections.setSelected(av.followSelection);
965 showProducts.setEnabled(canShowProducts());
966 setGroovyEnabled(Desktop.getGroovyConsole() != null);
972 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
976 public void setGroovyEnabled(boolean b)
978 runGroovy.setEnabled(b);
981 private IProgressIndicator progressBar;
986 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
989 public void setProgressBar(String message, long id)
991 progressBar.setProgressBar(message, id);
995 public void registerHandler(final long id,
996 final IProgressIndicatorHandler handler)
998 progressBar.registerHandler(id, handler);
1003 * @return true if any progress bars are still active
1006 public boolean operationInProgress()
1008 return progressBar.operationInProgress();
1012 * Sets the text of the status bar. Note that setting a null or empty value
1013 * will cause the status bar to be hidden, with possibly undesirable flicker
1014 * of the screen layout.
1017 public void setStatus(String text)
1019 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1023 * Added so Castor Mapping file can obtain Jalview Version
1025 public String getVersion()
1027 return jalview.bin.Cache.getProperty("VERSION");
1030 public FeatureRenderer getFeatureRenderer()
1032 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1036 public void fetchSequence_actionPerformed()
1038 new SequenceFetcher(this);
1042 public void addFromFile_actionPerformed(ActionEvent e)
1044 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1048 public void hmmBuild_actionPerformed(boolean withDefaults)
1050 if (!alignmentIsSufficient(1))
1056 * get default parameters, and optionally show a dialog
1057 * to allow them to be modified
1059 ParamDatastoreI store = HMMERParamStore.forBuild(viewport);
1060 List<ArgumentI> args = store.getServiceParameters();
1064 WsParamSetI set = new HMMERPreset();
1065 WsJobParameters params = new WsJobParameters(store, set, args);
1066 if (params.showRunDialog())
1068 args = params.getJobParams();
1072 return; // user cancelled
1075 new Thread(new HMMBuild(this, args)).start();
1079 public void hmmAlign_actionPerformed(boolean withDefaults)
1081 if (!(checkForHMM() && alignmentIsSufficient(2)))
1087 * get default parameters, and optionally show a dialog
1088 * to allow them to be modified
1090 ParamDatastoreI store = HMMERParamStore.forAlign(viewport);
1091 List<ArgumentI> args = store.getServiceParameters();
1095 WsParamSetI set = new HMMERPreset();
1096 WsJobParameters params = new WsJobParameters(store, set, args);
1097 if (params.showRunDialog())
1099 args = params.getJobParams();
1103 return; // user cancelled
1106 new Thread(new HMMAlign(this, args)).start();
1110 public void hmmSearch_actionPerformed(boolean withDefaults)
1118 * get default parameters, and (if requested) show
1119 * dialog to allow modification
1121 ParamDatastoreI store = HMMERParamStore.forSearch(viewport);
1122 List<ArgumentI> args = store.getServiceParameters();
1126 WsParamSetI set = new HMMERPreset();
1127 WsJobParameters params = new WsJobParameters(store, set, args);
1128 if (params.showRunDialog())
1130 args = params.getJobParams();
1134 return; // user cancelled
1137 new Thread(new HMMSearch(this, args)).start();
1138 alignPanel.repaint();
1142 public void jackhmmer_actionPerformed(boolean withDefaults)
1146 * get default parameters, and (if requested) show
1147 * dialog to allow modification
1150 ParamDatastoreI store = HMMERParamStore.forJackhmmer(viewport);
1151 List<ArgumentI> args = store.getServiceParameters();
1155 WsParamSetI set = new HMMERPreset();
1156 WsJobParameters params = new WsJobParameters(store, set, args);
1157 if (params.showRunDialog())
1159 args = params.getJobParams();
1163 return; // user cancelled
1166 new Thread(new JackHMMER(this, args)).start();
1167 alignPanel.repaint();
1172 * Checks if the alignment has at least one hidden Markov model, if not shows
1173 * a dialog advising to run hmmbuild or load an HMM profile
1177 private boolean checkForHMM()
1179 if (viewport.getAlignment().getHmmSequences().isEmpty())
1181 JOptionPane.showMessageDialog(this,
1182 MessageManager.getString("warn.no_hmm"));
1189 protected void filterByEValue_actionPerformed()
1191 viewport.filterByEvalue(inputDouble("Enter E-Value Cutoff"));
1195 protected void filterByScore_actionPerformed()
1197 viewport.filterByScore(inputDouble("Enter Bit Score Threshold"));
1200 private double inputDouble(String message)
1204 while (d == null || d <= 0)
1206 str = JOptionPane.showInputDialog(this.alignPanel, message);
1209 d = Double.valueOf(str);
1210 } catch (NumberFormatException e)
1218 * Checks if the alignment contains the required number of sequences.
1223 public boolean alignmentIsSufficient(int required)
1225 if (getViewport().getSequenceSelection().length < required)
1227 JOptionPane.showMessageDialog(this,
1228 MessageManager.getString("label.not_enough_sequences"));
1235 * Opens a file browser and adds the selected file, if in Fasta, Stockholm or
1236 * Pfam format, to the list held under preference key "HMMSEARCH_DBS" (as a
1237 * comma-separated list)
1240 public void addDatabase_actionPerformed() throws IOException
1242 if (Cache.getProperty(Preferences.HMMSEARCH_DBS) == null)
1244 Cache.setProperty(Preferences.HMMSEARCH_DBS, "");
1247 String path = openFileChooser(false);
1248 if (path != null && new File(path).exists())
1250 IdentifyFile identifier = new IdentifyFile();
1251 FileFormatI format = identifier.identify(path, DataSourceType.FILE);
1252 if (format == FileFormat.Fasta || format == FileFormat.Stockholm
1253 || format == FileFormat.Pfam)
1255 String currentDbPaths = Cache
1256 .getProperty(Preferences.HMMSEARCH_DBS);
1257 currentDbPaths += Preferences.COMMA + path;
1258 Cache.setProperty(Preferences.HMMSEARCH_DBS, currentDbPaths);
1262 JOptionPane.showMessageDialog(this,
1263 MessageManager.getString("warn.invalid_format"));
1269 * Opens a file chooser, optionally restricted to selecting folders
1270 * (directories) only. Answers the path to the selected file or folder, or
1271 * null if none is chosen.
1276 protected String openFileChooser(boolean forFolder)
1278 // TODO duplicates GPreferences method - relocate to JalviewFileChooser?
1279 String choice = null;
1280 JFileChooser chooser = new JFileChooser();
1283 chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1285 chooser.setDialogTitle(
1286 MessageManager.getString("label.open_local_file"));
1287 chooser.setToolTipText(MessageManager.getString("action.open"));
1289 int value = chooser.showOpenDialog(this);
1291 if (value == JFileChooser.APPROVE_OPTION)
1293 choice = chooser.getSelectedFile().getPath();
1299 public void reload_actionPerformed(ActionEvent e)
1301 if (fileName != null)
1303 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1304 // originating file's format
1305 // TODO: work out how to recover feature settings for correct view(s) when
1306 // file is reloaded.
1307 if (FileFormat.Jalview.equals(currentFileFormat))
1309 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1310 for (int i = 0; i < frames.length; i++)
1312 if (frames[i] instanceof AlignFrame && frames[i] != this
1313 && ((AlignFrame) frames[i]).fileName != null
1314 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1318 frames[i].setSelected(true);
1319 Desktop.instance.closeAssociatedWindows();
1320 } catch (java.beans.PropertyVetoException ex)
1326 Desktop.instance.closeAssociatedWindows();
1328 FileLoader loader = new FileLoader();
1329 DataSourceType protocol = fileName.startsWith("http:")
1330 ? DataSourceType.URL
1331 : DataSourceType.FILE;
1332 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1336 Rectangle bounds = this.getBounds();
1338 FileLoader loader = new FileLoader();
1340 AlignFrame newframe = null;
1342 if (fileObject == null)
1345 DataSourceType protocol = (fileName.startsWith("http:")
1346 ? DataSourceType.URL
1347 : DataSourceType.FILE);
1348 newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1353 newframe = loader.LoadFileWaitTillLoaded(fileObject,
1354 DataSourceType.FILE, currentFileFormat);
1357 newframe.setBounds(bounds);
1358 if (featureSettings != null && featureSettings.isShowing())
1360 final Rectangle fspos = featureSettings.frame.getBounds();
1361 // TODO: need a 'show feature settings' function that takes bounds -
1362 // need to refactor Desktop.addFrame
1363 newframe.featureSettings_actionPerformed(null);
1364 final FeatureSettings nfs = newframe.featureSettings;
1365 SwingUtilities.invokeLater(new Runnable()
1370 nfs.frame.setBounds(fspos);
1373 this.featureSettings.close();
1374 this.featureSettings = null;
1376 this.closeMenuItem_actionPerformed(true);
1382 public void addFromText_actionPerformed(ActionEvent e)
1385 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1389 public void addFromURL_actionPerformed(ActionEvent e)
1391 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1395 public void save_actionPerformed(ActionEvent e)
1397 if (fileName == null || (currentFileFormat == null)
1398 || fileName.startsWith("http"))
1400 saveAs_actionPerformed();
1404 saveAlignment(fileName, currentFileFormat);
1409 * Saves the alignment to a file with a name chosen by the user, if necessary
1410 * warning if a file would be overwritten
1413 public void saveAs_actionPerformed()
1415 String format = currentFileFormat == null ? null
1416 : currentFileFormat.getName();
1417 JalviewFileChooser chooser = JalviewFileChooser
1418 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1420 chooser.setFileView(new JalviewFileView());
1421 chooser.setDialogTitle(
1422 MessageManager.getString("label.save_alignment_to_file"));
1423 chooser.setToolTipText(MessageManager.getString("action.save"));
1425 int value = chooser.showSaveDialog(this);
1427 if (value != JalviewFileChooser.APPROVE_OPTION)
1431 currentFileFormat = chooser.getSelectedFormat();
1432 // todo is this (2005) test now obsolete - value is never null?
1433 while (currentFileFormat == null)
1435 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1437 .getString("label.select_file_format_before_saving"),
1438 MessageManager.getString("label.file_format_not_specified"),
1439 JvOptionPane.WARNING_MESSAGE);
1440 currentFileFormat = chooser.getSelectedFormat();
1441 value = chooser.showSaveDialog(this);
1442 if (value != JalviewFileChooser.APPROVE_OPTION)
1448 fileName = chooser.getSelectedFile().getPath();
1450 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1451 Cache.setProperty("LAST_DIRECTORY", fileName);
1452 saveAlignment(fileName, currentFileFormat);
1455 boolean lastSaveSuccessful = false;
1457 FileFormatI lastFormatSaved;
1459 String lastFilenameSaved;
1462 * Raise a dialog or status message for the last call to saveAlignment.
1464 * @return true if last call to saveAlignment(file, format) was successful.
1466 public boolean isSaveAlignmentSuccessful()
1469 if (!lastSaveSuccessful)
1471 JvOptionPane.showInternalMessageDialog(this, MessageManager
1472 .formatMessage("label.couldnt_save_file", new Object[]
1473 { lastFilenameSaved }),
1474 MessageManager.getString("label.error_saving_file"),
1475 JvOptionPane.WARNING_MESSAGE);
1480 setStatus(MessageManager.formatMessage(
1481 "label.successfully_saved_to_file_in_format", new Object[]
1482 { lastFilenameSaved, lastFormatSaved }));
1485 return lastSaveSuccessful;
1489 * Saves the alignment to the specified file path, in the specified format,
1490 * which may be an alignment format, or Jalview project format. If the
1491 * alignment has hidden regions, or the format is one capable of including
1492 * non-sequence data (features, annotations, groups), then the user may be
1493 * prompted to specify what to include in the output.
1498 public void saveAlignment(String file, FileFormatI format)
1500 lastSaveSuccessful = true;
1501 lastFilenameSaved = file;
1502 lastFormatSaved = format;
1504 if (FileFormat.Jalview.equals(format))
1506 String shortName = title;
1507 if (shortName.indexOf(File.separatorChar) > -1)
1509 shortName = shortName
1510 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
1512 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file,
1515 statusBar.setText(MessageManager.formatMessage(
1516 "label.successfully_saved_to_file_in_format", new Object[]
1517 { fileName, format }));
1522 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1523 Runnable cancelAction = new Runnable()
1528 lastSaveSuccessful = false;
1531 Runnable outputAction = new Runnable()
1536 // todo defer this to inside formatSequences (or later)
1537 AlignmentExportData exportData = viewport
1538 .getAlignExportData(options);
1539 String output = new FormatAdapter(alignPanel, options)
1540 .formatSequences(format, exportData.getAlignment(),
1541 exportData.getOmitHidden(),
1542 exportData.getStartEndPostions(),
1543 viewport.getAlignment().getHiddenColumns());
1546 lastSaveSuccessful = false;
1550 // create backupfiles object and get new temp filename destination
1551 boolean doBackup = BackupFiles.getEnabled();
1552 BackupFiles backupfiles = doBackup ? new BackupFiles(file) : null;
1555 String tempFilePath = doBackup ? backupfiles.getTempFilePath()
1557 PrintWriter out = new PrintWriter(new FileWriter(tempFilePath));
1561 AlignFrame.this.setTitle(file);
1562 statusBar.setText(MessageManager.formatMessage(
1563 "label.successfully_saved_to_file_in_format",
1565 { fileName, format.getName() }));
1566 lastSaveSuccessful = true;
1567 } catch (Exception ex)
1569 lastSaveSuccessful = false;
1570 ex.printStackTrace();
1575 backupfiles.setWriteSuccess(lastSaveSuccessful);
1576 // do the backup file roll and rename the temp file to actual file
1577 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1584 * show dialog with export options if applicable; else just do it
1586 if (AlignExportOptions.isNeeded(viewport, format))
1588 AlignExportOptions choices = new AlignExportOptions(
1589 alignPanel.getAlignViewport(), format, options);
1590 choices.setResponseAction(0, outputAction);
1591 choices.setResponseAction(1, cancelAction);
1592 choices.showDialog();
1601 * Outputs the alignment to textbox in the requested format, if necessary
1602 * first prompting the user for whether to include hidden regions or
1605 * @param fileFormatName
1608 protected void outputText_actionPerformed(String fileFormatName)
1610 FileFormatI fileFormat = FileFormats.getInstance()
1611 .forName(fileFormatName);
1612 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1613 Runnable outputAction = new Runnable()
1618 // todo defer this to inside formatSequences (or later)
1619 AlignmentExportData exportData = viewport
1620 .getAlignExportData(options);
1621 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1622 cap.setForInput(null);
1625 FileFormatI format = fileFormat;
1626 cap.setText(new FormatAdapter(alignPanel, options)
1627 .formatSequences(format, exportData.getAlignment(),
1628 exportData.getOmitHidden(),
1629 exportData.getStartEndPostions(),
1630 viewport.getAlignment().getHiddenColumns()));
1631 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1632 "label.alignment_output_command", new Object[]
1633 { fileFormat.getName() }), 600, 500);
1634 } catch (OutOfMemoryError oom)
1636 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1644 * show dialog with export options if applicable; else just do it
1646 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1648 AlignExportOptions choices = new AlignExportOptions(
1649 alignPanel.getAlignViewport(), fileFormat, options);
1650 choices.setResponseAction(0, outputAction);
1651 choices.showDialog();
1666 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1668 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1669 htmlSVG.exportHTML(null);
1673 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1675 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1676 bjs.exportHTML(null);
1679 public void createImageMap(File file, String image)
1681 alignPanel.makePNGImageMap(file, image);
1685 * Creates a PNG image of the alignment and writes it to the given file. If
1686 * the file is null, the user is prompted to choose a file.
1691 public void createPNG(File f)
1693 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1697 * Creates an EPS image of the alignment and writes it to the given file. If
1698 * the file is null, the user is prompted to choose a file.
1703 public void createEPS(File f)
1705 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1709 * Creates an SVG image of the alignment and writes it to the given file. If
1710 * the file is null, the user is prompted to choose a file.
1715 public void createSVG(File f)
1717 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1721 public void pageSetup_actionPerformed(ActionEvent e)
1723 PrinterJob printJob = PrinterJob.getPrinterJob();
1724 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1734 public void printMenuItem_actionPerformed(ActionEvent e)
1736 // Putting in a thread avoids Swing painting problems
1737 PrintThread thread = new PrintThread(alignPanel);
1742 public void exportFeatures_actionPerformed(ActionEvent e)
1744 new AnnotationExporter(alignPanel).exportFeatures();
1748 public void exportAnnotations_actionPerformed(ActionEvent e)
1750 new AnnotationExporter(alignPanel).exportAnnotations();
1754 public void associatedData_actionPerformed(ActionEvent e)
1755 throws IOException, InterruptedException
1757 final JalviewFileChooser chooser = new JalviewFileChooser(
1758 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1759 chooser.setFileView(new JalviewFileView());
1760 String tooltip = MessageManager
1761 .getString("label.load_jalview_annotations");
1762 chooser.setDialogTitle(tooltip);
1763 chooser.setToolTipText(tooltip);
1764 chooser.setResponseHandler(0, new Runnable()
1769 String choice = chooser.getSelectedFile().getPath();
1770 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1771 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1775 chooser.showOpenDialog(this);
1779 * Close the current view or all views in the alignment frame. If the frame
1780 * only contains one view then the alignment will be removed from memory.
1782 * @param closeAllTabs
1785 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1787 if (alignPanels != null && alignPanels.size() < 2)
1789 closeAllTabs = true;
1794 if (alignPanels != null)
1798 if (this.isClosed())
1800 // really close all the windows - otherwise wait till
1801 // setClosed(true) is called
1802 for (int i = 0; i < alignPanels.size(); i++)
1804 AlignmentPanel ap = alignPanels.get(i);
1811 closeView(alignPanel);
1816 if (featureSettings != null && featureSettings.isOpen())
1818 featureSettings.close();
1819 featureSettings = null;
1822 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1823 * be called recursively, with the frame now in 'closed' state
1825 this.setClosed(true);
1827 } catch (Exception ex)
1829 ex.printStackTrace();
1834 * Close the specified panel and close up tabs appropriately.
1836 * @param panelToClose
1838 public void closeView(AlignmentPanel panelToClose)
1840 int index = tabbedPane.getSelectedIndex();
1841 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1842 alignPanels.remove(panelToClose);
1843 panelToClose.closePanel();
1844 panelToClose = null;
1846 tabbedPane.removeTabAt(closedindex);
1847 tabbedPane.validate();
1849 if (index > closedindex || index == tabbedPane.getTabCount())
1851 // modify currently selected tab index if necessary.
1855 this.tabSelectionChanged(index);
1861 void updateEditMenuBar()
1864 if (viewport.getHistoryList().size() > 0)
1866 undoMenuItem.setEnabled(true);
1867 CommandI command = viewport.getHistoryList().peek();
1868 undoMenuItem.setText(MessageManager
1869 .formatMessage("label.undo_command", new Object[]
1870 { command.getDescription() }));
1874 undoMenuItem.setEnabled(false);
1875 undoMenuItem.setText(MessageManager.getString("action.undo"));
1878 if (viewport.getRedoList().size() > 0)
1880 redoMenuItem.setEnabled(true);
1882 CommandI command = viewport.getRedoList().peek();
1883 redoMenuItem.setText(MessageManager
1884 .formatMessage("label.redo_command", new Object[]
1885 { command.getDescription() }));
1889 redoMenuItem.setEnabled(false);
1890 redoMenuItem.setText(MessageManager.getString("action.redo"));
1895 public void addHistoryItem(CommandI command)
1897 if (command.getSize() > 0)
1899 viewport.addToHistoryList(command);
1900 viewport.clearRedoList();
1901 updateEditMenuBar();
1902 viewport.updateHiddenColumns();
1903 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1904 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1905 // viewport.getColumnSelection()
1906 // .getHiddenColumns().size() > 0);
1912 * @return alignment objects for all views
1914 AlignmentI[] getViewAlignments()
1916 if (alignPanels != null)
1918 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1920 for (AlignmentPanel ap : alignPanels)
1922 als[i++] = ap.av.getAlignment();
1926 if (viewport != null)
1928 return new AlignmentI[] { viewport.getAlignment() };
1940 protected void undoMenuItem_actionPerformed(ActionEvent e)
1942 if (viewport.getHistoryList().isEmpty())
1946 CommandI command = viewport.getHistoryList().pop();
1947 viewport.addToRedoList(command);
1948 command.undoCommand(getViewAlignments());
1950 AlignmentViewport originalSource = getOriginatingSource(command);
1951 updateEditMenuBar();
1953 if (originalSource != null)
1955 if (originalSource != viewport)
1958 "Implementation worry: mismatch of viewport origin for undo");
1960 originalSource.updateHiddenColumns();
1961 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1963 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1964 // viewport.getColumnSelection()
1965 // .getHiddenColumns().size() > 0);
1966 originalSource.firePropertyChange("alignment", null,
1967 originalSource.getAlignment().getSequences());
1978 protected void redoMenuItem_actionPerformed(ActionEvent e)
1980 if (viewport.getRedoList().size() < 1)
1985 CommandI command = viewport.getRedoList().pop();
1986 viewport.addToHistoryList(command);
1987 command.doCommand(getViewAlignments());
1989 AlignmentViewport originalSource = getOriginatingSource(command);
1990 updateEditMenuBar();
1992 if (originalSource != null)
1995 if (originalSource != viewport)
1998 "Implementation worry: mismatch of viewport origin for redo");
2000 originalSource.updateHiddenColumns();
2001 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
2003 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2004 // viewport.getColumnSelection()
2005 // .getHiddenColumns().size() > 0);
2006 originalSource.firePropertyChange("alignment", null,
2007 originalSource.getAlignment().getSequences());
2011 AlignmentViewport getOriginatingSource(CommandI command)
2013 AlignmentViewport originalSource = null;
2014 // For sequence removal and addition, we need to fire
2015 // the property change event FROM the viewport where the
2016 // original alignment was altered
2017 AlignmentI al = null;
2018 if (command instanceof EditCommand)
2020 EditCommand editCommand = (EditCommand) command;
2021 al = editCommand.getAlignment();
2022 List<Component> comps = PaintRefresher.components
2023 .get(viewport.getSequenceSetId());
2025 for (Component comp : comps)
2027 if (comp instanceof AlignmentPanel)
2029 if (al == ((AlignmentPanel) comp).av.getAlignment())
2031 originalSource = ((AlignmentPanel) comp).av;
2038 if (originalSource == null)
2040 // The original view is closed, we must validate
2041 // the current view against the closed view first
2044 PaintRefresher.validateSequences(al, viewport.getAlignment());
2047 originalSource = viewport;
2050 return originalSource;
2059 public void moveSelectedSequences(boolean up)
2061 SequenceGroup sg = viewport.getSelectionGroup();
2067 viewport.getAlignment().moveSelectedSequencesByOne(sg,
2068 viewport.getHiddenRepSequences(), up);
2069 alignPanel.paintAlignment(true, false);
2072 synchronized void slideSequences(boolean right, int size)
2074 List<SequenceI> sg = new ArrayList<>();
2075 if (viewport.cursorMode)
2077 sg.add(viewport.getAlignment()
2078 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
2080 else if (viewport.getSelectionGroup() != null
2081 && viewport.getSelectionGroup().getSize() != viewport
2082 .getAlignment().getHeight())
2084 sg = viewport.getSelectionGroup()
2085 .getSequences(viewport.getHiddenRepSequences());
2093 List<SequenceI> invertGroup = new ArrayList<>();
2095 for (SequenceI seq : viewport.getAlignment().getSequences())
2097 if (!sg.contains(seq))
2099 invertGroup.add(seq);
2103 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
2105 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
2106 for (int i = 0; i < invertGroup.size(); i++)
2108 seqs2[i] = invertGroup.get(i);
2111 SlideSequencesCommand ssc;
2114 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
2115 viewport.getGapCharacter());
2119 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
2120 viewport.getGapCharacter());
2123 int groupAdjustment = 0;
2124 if (ssc.getGapsInsertedBegin() && right)
2126 if (viewport.cursorMode)
2128 alignPanel.getSeqPanel().moveCursor(size, 0);
2132 groupAdjustment = size;
2135 else if (!ssc.getGapsInsertedBegin() && !right)
2137 if (viewport.cursorMode)
2139 alignPanel.getSeqPanel().moveCursor(-size, 0);
2143 groupAdjustment = -size;
2147 if (groupAdjustment != 0)
2149 viewport.getSelectionGroup().setStartRes(
2150 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
2151 viewport.getSelectionGroup().setEndRes(
2152 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
2156 * just extend the last slide command if compatible; but not if in
2157 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
2159 boolean appendHistoryItem = false;
2160 Deque<CommandI> historyList = viewport.getHistoryList();
2161 boolean inSplitFrame = getSplitViewContainer() != null;
2162 if (!inSplitFrame && historyList != null && historyList.size() > 0
2163 && historyList.peek() instanceof SlideSequencesCommand)
2165 appendHistoryItem = ssc.appendSlideCommand(
2166 (SlideSequencesCommand) historyList.peek());
2169 if (!appendHistoryItem)
2171 addHistoryItem(ssc);
2184 protected void copy_actionPerformed()
2186 if (viewport.getSelectionGroup() == null)
2190 // TODO: preserve the ordering of displayed alignment annotation in any
2191 // internal paste (particularly sequence associated annotation)
2192 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2193 String[] omitHidden = null;
2195 if (viewport.hasHiddenColumns())
2197 omitHidden = viewport.getViewAsString(true);
2200 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2201 seqs, omitHidden, null);
2203 StringSelection ss = new StringSelection(output);
2207 jalview.gui.Desktop.internalCopy = true;
2208 // Its really worth setting the clipboard contents
2209 // to empty before setting the large StringSelection!!
2210 Toolkit.getDefaultToolkit().getSystemClipboard()
2211 .setContents(new StringSelection(""), null);
2213 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2215 } catch (OutOfMemoryError er)
2217 new OOMWarning("copying region", er);
2221 HiddenColumns hiddenColumns = null;
2222 if (viewport.hasHiddenColumns())
2224 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2225 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2227 // create new HiddenColumns object with copy of hidden regions
2228 // between startRes and endRes, offset by startRes
2229 hiddenColumns = new HiddenColumns(
2230 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2231 hiddenCutoff, hiddenOffset);
2234 Desktop.jalviewClipboard = new Object[] { seqs,
2235 viewport.getAlignment().getDataset(), hiddenColumns };
2236 setStatus(MessageManager.formatMessage(
2237 "label.copied_sequences_to_clipboard", new Object[]
2238 { Integer.valueOf(seqs.length).toString() }));
2246 * @throws InterruptedException
2247 * @throws IOException
2250 protected void pasteNew_actionPerformed(ActionEvent e)
2251 throws IOException, InterruptedException
2261 * @throws InterruptedException
2262 * @throws IOException
2265 protected void pasteThis_actionPerformed(ActionEvent e)
2266 throws IOException, InterruptedException
2272 * Paste contents of Jalview clipboard
2274 * @param newAlignment
2275 * true to paste to a new alignment, otherwise add to this.
2276 * @throws InterruptedException
2277 * @throws IOException
2279 void paste(boolean newAlignment) throws IOException, InterruptedException
2281 boolean externalPaste = true;
2284 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2285 Transferable contents = c.getContents(this);
2287 if (contents == null)
2296 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2297 if (str.length() < 1)
2302 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2304 } catch (OutOfMemoryError er)
2306 new OOMWarning("Out of memory pasting sequences!!", er);
2310 SequenceI[] sequences;
2311 boolean annotationAdded = false;
2312 AlignmentI alignment = null;
2314 if (Desktop.jalviewClipboard != null)
2316 // The clipboard was filled from within Jalview, we must use the
2318 // And dataset from the copied alignment
2319 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2320 // be doubly sure that we create *new* sequence objects.
2321 sequences = new SequenceI[newseq.length];
2322 for (int i = 0; i < newseq.length; i++)
2324 sequences[i] = new Sequence(newseq[i]);
2326 alignment = new Alignment(sequences);
2327 externalPaste = false;
2331 // parse the clipboard as an alignment.
2332 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2334 sequences = alignment.getSequencesArray();
2338 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2344 if (Desktop.jalviewClipboard != null)
2346 // dataset is inherited
2347 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2351 // new dataset is constructed
2352 alignment.setDataset(null);
2354 alwidth = alignment.getWidth() + 1;
2358 AlignmentI pastedal = alignment; // preserve pasted alignment object
2359 // Add pasted sequences and dataset into existing alignment.
2360 alignment = viewport.getAlignment();
2361 alwidth = alignment.getWidth() + 1;
2362 // decide if we need to import sequences from an existing dataset
2363 boolean importDs = Desktop.jalviewClipboard != null
2364 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2365 // importDs==true instructs us to copy over new dataset sequences from
2366 // an existing alignment
2367 Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2369 // minimum dataset set
2371 for (int i = 0; i < sequences.length; i++)
2375 newDs.addElement(null);
2377 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2379 if (importDs && ds != null)
2381 if (!newDs.contains(ds))
2383 newDs.setElementAt(ds, i);
2384 ds = new Sequence(ds);
2385 // update with new dataset sequence
2386 sequences[i].setDatasetSequence(ds);
2390 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2395 // copy and derive new dataset sequence
2396 sequences[i] = sequences[i].deriveSequence();
2397 alignment.getDataset()
2398 .addSequence(sequences[i].getDatasetSequence());
2399 // TODO: avoid creation of duplicate dataset sequences with a
2400 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2402 alignment.addSequence(sequences[i]); // merges dataset
2406 newDs.clear(); // tidy up
2408 if (alignment.getAlignmentAnnotation() != null)
2410 for (AlignmentAnnotation alan : alignment
2411 .getAlignmentAnnotation())
2413 if (alan.graphGroup > fgroup)
2415 fgroup = alan.graphGroup;
2419 if (pastedal.getAlignmentAnnotation() != null)
2421 // Add any annotation attached to alignment.
2422 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2423 for (int i = 0; i < alann.length; i++)
2425 annotationAdded = true;
2426 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2428 AlignmentAnnotation newann = new AlignmentAnnotation(
2430 if (newann.graphGroup > -1)
2432 if (newGraphGroups.size() <= newann.graphGroup
2433 || newGraphGroups.get(newann.graphGroup) == null)
2435 for (int q = newGraphGroups
2436 .size(); q <= newann.graphGroup; q++)
2438 newGraphGroups.add(q, null);
2440 newGraphGroups.set(newann.graphGroup,
2441 Integer.valueOf(++fgroup));
2443 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2447 newann.padAnnotation(alwidth);
2448 alignment.addAnnotation(newann);
2458 addHistoryItem(new EditCommand(
2459 MessageManager.getString("label.add_sequences"),
2460 Action.PASTE, sequences, 0, alignment.getWidth(),
2463 // Add any annotations attached to sequences
2464 for (int i = 0; i < sequences.length; i++)
2466 if (sequences[i].getAnnotation() != null)
2468 AlignmentAnnotation newann;
2469 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2471 annotationAdded = true;
2472 newann = sequences[i].getAnnotation()[a];
2473 newann.adjustForAlignment();
2474 newann.padAnnotation(alwidth);
2475 if (newann.graphGroup > -1)
2477 if (newann.graphGroup > -1)
2479 if (newGraphGroups.size() <= newann.graphGroup
2480 || newGraphGroups.get(newann.graphGroup) == null)
2482 for (int q = newGraphGroups
2483 .size(); q <= newann.graphGroup; q++)
2485 newGraphGroups.add(q, null);
2487 newGraphGroups.set(newann.graphGroup,
2488 Integer.valueOf(++fgroup));
2490 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2494 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2498 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2506 // propagate alignment changed.
2507 viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2508 if (annotationAdded)
2510 // Duplicate sequence annotation in all views.
2511 AlignmentI[] alview = this.getViewAlignments();
2512 for (int i = 0; i < sequences.length; i++)
2514 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2519 for (int avnum = 0; avnum < alview.length; avnum++)
2521 if (alview[avnum] != alignment)
2523 // duplicate in a view other than the one with input focus
2524 int avwidth = alview[avnum].getWidth() + 1;
2525 // this relies on sann being preserved after we
2526 // modify the sequence's annotation array for each duplication
2527 for (int a = 0; a < sann.length; a++)
2529 AlignmentAnnotation newann = new AlignmentAnnotation(
2531 sequences[i].addAlignmentAnnotation(newann);
2532 newann.padAnnotation(avwidth);
2533 alview[avnum].addAnnotation(newann); // annotation was
2534 // duplicated earlier
2535 // TODO JAL-1145 graphGroups are not updated for sequence
2536 // annotation added to several views. This may cause
2538 alview[avnum].setAnnotationIndex(newann, a);
2543 buildSortByAnnotationScoresMenu();
2545 viewport.firePropertyChange("alignment", null,
2546 alignment.getSequences());
2547 if (alignPanels != null)
2549 for (AlignmentPanel ap : alignPanels)
2551 ap.validateAnnotationDimensions(false);
2556 alignPanel.validateAnnotationDimensions(false);
2562 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2564 String newtitle = new String("Copied sequences");
2566 if (Desktop.jalviewClipboard != null
2567 && Desktop.jalviewClipboard[2] != null)
2569 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2570 af.viewport.setHiddenColumns(hc);
2573 // >>>This is a fix for the moment, until a better solution is
2575 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2576 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2577 .getFeatureRenderer());
2579 // TODO: maintain provenance of an alignment, rather than just make the
2580 // title a concatenation of operations.
2583 if (title.startsWith("Copied sequences"))
2589 newtitle = newtitle.concat("- from " + title);
2594 newtitle = new String("Pasted sequences");
2597 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2602 } catch (Exception ex)
2604 ex.printStackTrace();
2605 System.out.println("Exception whilst pasting: " + ex);
2606 // could be anything being pasted in here
2611 protected void expand_newalign(ActionEvent e)
2615 AlignmentI alignment = AlignmentUtils
2616 .expandContext(getViewport().getAlignment(), -1);
2617 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2619 String newtitle = new String("Flanking alignment");
2621 if (Desktop.jalviewClipboard != null
2622 && Desktop.jalviewClipboard[2] != null)
2624 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2625 af.viewport.setHiddenColumns(hc);
2628 // >>>This is a fix for the moment, until a better solution is
2630 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2631 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2632 .getFeatureRenderer());
2634 // TODO: maintain provenance of an alignment, rather than just make the
2635 // title a concatenation of operations.
2637 if (title.startsWith("Copied sequences"))
2643 newtitle = newtitle.concat("- from " + title);
2647 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2649 } catch (Exception ex)
2651 ex.printStackTrace();
2652 System.out.println("Exception whilst pasting: " + ex);
2653 // could be anything being pasted in here
2654 } catch (OutOfMemoryError oom)
2656 new OOMWarning("Viewing flanking region of alignment", oom);
2661 * Action Cut (delete and copy) the selected region
2664 protected void cut_actionPerformed()
2666 copy_actionPerformed();
2667 delete_actionPerformed();
2671 * Performs menu option to Delete the currently selected region
2674 protected void delete_actionPerformed()
2677 SequenceGroup sg = viewport.getSelectionGroup();
2683 Runnable okAction = new Runnable()
2688 SequenceI[] cut = sg.getSequences()
2689 .toArray(new SequenceI[sg.getSize()]);
2691 addHistoryItem(new EditCommand(
2692 MessageManager.getString("label.cut_sequences"), Action.CUT,
2693 cut, sg.getStartRes(),
2694 sg.getEndRes() - sg.getStartRes() + 1,
2695 viewport.getAlignment()));
2697 viewport.setSelectionGroup(null);
2698 viewport.sendSelection();
2699 viewport.getAlignment().deleteGroup(sg);
2701 viewport.firePropertyChange("alignment", null,
2702 viewport.getAlignment().getSequences());
2703 if (viewport.getAlignment().getHeight() < 1)
2707 AlignFrame.this.setClosed(true);
2708 } catch (Exception ex)
2716 * If the cut affects all sequences, prompt for confirmation
2718 boolean wholeHeight = sg.getSize() == viewport.getAlignment()
2720 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2721 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2722 if (wholeHeight && wholeWidth)
2724 JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.desktop);
2725 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2726 Object[] options = new Object[] {
2727 MessageManager.getString("action.ok"),
2728 MessageManager.getString("action.cancel") };
2729 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2730 MessageManager.getString("label.delete_all"),
2731 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2732 options, options[0]);
2747 protected void deleteGroups_actionPerformed(ActionEvent e)
2749 if (avc.deleteGroups())
2751 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2752 alignPanel.updateAnnotation();
2753 alignPanel.paintAlignment(true, true);
2764 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2766 SequenceGroup sg = new SequenceGroup(
2767 viewport.getAlignment().getSequences());
2769 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2770 viewport.setSelectionGroup(sg);
2771 viewport.isSelectionGroupChanged(true);
2772 viewport.sendSelection();
2773 // JAL-2034 - should delegate to
2774 // alignPanel to decide if overview needs
2776 alignPanel.paintAlignment(false, false);
2777 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2787 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2789 if (viewport.cursorMode)
2791 alignPanel.getSeqPanel().keyboardNo1 = null;
2792 alignPanel.getSeqPanel().keyboardNo2 = null;
2794 viewport.setSelectionGroup(null);
2795 viewport.getColumnSelection().clear();
2796 viewport.setSelectionGroup(null);
2797 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2798 // JAL-2034 - should delegate to
2799 // alignPanel to decide if overview needs
2801 alignPanel.paintAlignment(false, false);
2802 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2803 viewport.sendSelection();
2813 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2815 SequenceGroup sg = viewport.getSelectionGroup();
2819 selectAllSequenceMenuItem_actionPerformed(null);
2824 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2826 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2828 // JAL-2034 - should delegate to
2829 // alignPanel to decide if overview needs
2832 alignPanel.paintAlignment(true, false);
2833 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2834 viewport.sendSelection();
2838 public void invertColSel_actionPerformed(ActionEvent e)
2840 viewport.invertColumnSelection();
2841 alignPanel.paintAlignment(true, false);
2842 viewport.sendSelection();
2852 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2854 trimAlignment(true);
2864 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2866 trimAlignment(false);
2869 void trimAlignment(boolean trimLeft)
2871 ColumnSelection colSel = viewport.getColumnSelection();
2874 if (!colSel.isEmpty())
2878 column = colSel.getMin();
2882 column = colSel.getMax();
2886 if (viewport.getSelectionGroup() != null)
2888 seqs = viewport.getSelectionGroup()
2889 .getSequencesAsArray(viewport.getHiddenRepSequences());
2893 seqs = viewport.getAlignment().getSequencesArray();
2896 TrimRegionCommand trimRegion;
2899 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2900 column, viewport.getAlignment());
2901 viewport.getRanges().setStartRes(0);
2905 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2906 column, viewport.getAlignment());
2909 setStatus(MessageManager
2910 .formatMessage("label.removed_columns", new String[]
2911 { Integer.valueOf(trimRegion.getSize()).toString() }));
2913 addHistoryItem(trimRegion);
2915 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2917 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2918 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2920 viewport.getAlignment().deleteGroup(sg);
2924 viewport.firePropertyChange("alignment", null,
2925 viewport.getAlignment().getSequences());
2936 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2938 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2941 if (viewport.getSelectionGroup() != null)
2943 seqs = viewport.getSelectionGroup()
2944 .getSequencesAsArray(viewport.getHiddenRepSequences());
2945 start = viewport.getSelectionGroup().getStartRes();
2946 end = viewport.getSelectionGroup().getEndRes();
2950 seqs = viewport.getAlignment().getSequencesArray();
2953 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2954 "Remove Gapped Columns", seqs, start, end,
2955 viewport.getAlignment());
2957 addHistoryItem(removeGapCols);
2959 setStatus(MessageManager
2960 .formatMessage("label.removed_empty_columns", new Object[]
2961 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2963 // This is to maintain viewport position on first residue
2964 // of first sequence
2965 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2966 ViewportRanges ranges = viewport.getRanges();
2967 int startRes = seq.findPosition(ranges.getStartRes());
2968 // ShiftList shifts;
2969 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2970 // edit.alColumnChanges=shifts.getInverse();
2971 // if (viewport.hasHiddenColumns)
2972 // viewport.getColumnSelection().compensateForEdits(shifts);
2973 ranges.setStartRes(seq.findIndex(startRes) - 1);
2974 viewport.firePropertyChange("alignment", null,
2975 viewport.getAlignment().getSequences());
2986 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2988 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2991 if (viewport.getSelectionGroup() != null)
2993 seqs = viewport.getSelectionGroup()
2994 .getSequencesAsArray(viewport.getHiddenRepSequences());
2995 start = viewport.getSelectionGroup().getStartRes();
2996 end = viewport.getSelectionGroup().getEndRes();
3000 seqs = viewport.getAlignment().getSequencesArray();
3003 // This is to maintain viewport position on first residue
3004 // of first sequence
3005 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3006 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
3008 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
3009 viewport.getAlignment()));
3011 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
3013 viewport.firePropertyChange("alignment", null,
3014 viewport.getAlignment().getSequences());
3025 public void padGapsMenuitem_actionPerformed(ActionEvent e)
3027 viewport.setPadGaps(padGapsMenuitem.isSelected());
3028 viewport.firePropertyChange("alignment", null,
3029 viewport.getAlignment().getSequences());
3039 public void findMenuItem_actionPerformed(ActionEvent e)
3045 * Create a new view of the current alignment.
3048 public void newView_actionPerformed(ActionEvent e)
3050 newView(null, true);
3054 * Creates and shows a new view of the current alignment.
3057 * title of newly created view; if null, one will be generated
3058 * @param copyAnnotation
3059 * if true then duplicate all annnotation, groups and settings
3060 * @return new alignment panel, already displayed.
3062 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
3065 * Create a new AlignmentPanel (with its own, new Viewport)
3067 AlignmentPanel newap = new jalview.project.Jalview2XML()
3068 .copyAlignPanel(alignPanel);
3069 if (!copyAnnotation)
3072 * remove all groups and annotation except for the automatic stuff
3074 newap.av.getAlignment().deleteAllGroups();
3075 newap.av.getAlignment().deleteAllAnnotations(false);
3078 newap.av.setGatherViewsHere(false);
3080 if (viewport.getViewName() == null)
3082 viewport.setViewName(MessageManager
3083 .getString("label.view_name_original"));
3087 * Views share the same edits undo and redo stacks
3089 newap.av.setHistoryList(viewport.getHistoryList());
3090 newap.av.setRedoList(viewport.getRedoList());
3093 * copy any visualisation settings that are not saved in the project
3095 newap.av.setColourAppliesToAllGroups(
3096 viewport.getColourAppliesToAllGroups());
3099 * Views share the same mappings; need to deregister any new mappings
3100 * created by copyAlignPanel, and register the new reference to the shared
3103 newap.av.replaceMappings(viewport.getAlignment());
3106 * start up cDNA consensus (if applicable) now mappings are in place
3108 if (newap.av.initComplementConsensus())
3110 newap.refresh(true); // adjust layout of annotations
3113 newap.av.setViewName(getNewViewName(viewTitle));
3115 addAlignmentPanel(newap, true);
3116 newap.alignmentChanged();
3118 if (alignPanels.size() == 2)
3120 viewport.setGatherViewsHere(true);
3122 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
3127 * Make a new name for the view, ensuring it is unique within the current
3128 * sequenceSetId. (This used to be essential for Jalview Project archives, but
3129 * these now use viewId. Unique view names are still desirable for usability.)
3134 protected String getNewViewName(String viewTitle)
3136 int index = Desktop.getViewCount(viewport.getSequenceSetId());
3137 boolean addFirstIndex = false;
3138 if (viewTitle == null || viewTitle.trim().length() == 0)
3140 viewTitle = MessageManager.getString("action.view");
3141 addFirstIndex = true;
3145 index = 1;// we count from 1 if given a specific name
3147 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
3149 List<Component> comps = PaintRefresher.components
3150 .get(viewport.getSequenceSetId());
3152 List<String> existingNames = getExistingViewNames(comps);
3154 while (existingNames.contains(newViewName))
3156 newViewName = viewTitle + " " + (++index);
3162 * Returns a list of distinct view names found in the given list of
3163 * components. View names are held on the viewport of an AlignmentPanel.
3168 protected List<String> getExistingViewNames(List<Component> comps)
3170 List<String> existingNames = new ArrayList<>();
3171 for (Component comp : comps)
3173 if (comp instanceof AlignmentPanel)
3175 AlignmentPanel ap = (AlignmentPanel) comp;
3176 if (!existingNames.contains(ap.av.getViewName()))
3178 existingNames.add(ap.av.getViewName());
3182 return existingNames;
3186 * Explode tabbed views into separate windows.
3189 public void expandViews_actionPerformed(ActionEvent e)
3191 Desktop.explodeViews(this);
3195 * Gather views in separate windows back into a tabbed presentation.
3198 public void gatherViews_actionPerformed(ActionEvent e)
3200 Desktop.instance.gatherViews(this);
3210 public void font_actionPerformed(ActionEvent e)
3212 new FontChooser(alignPanel);
3222 protected void seqLimit_actionPerformed(ActionEvent e)
3224 viewport.setShowJVSuffix(seqLimits.isSelected());
3226 alignPanel.getIdPanel().getIdCanvas()
3227 .setPreferredSize(alignPanel.calculateIdWidth());
3228 alignPanel.paintAlignment(true, false);
3232 public void idRightAlign_actionPerformed(ActionEvent e)
3234 viewport.setRightAlignIds(idRightAlign.isSelected());
3235 alignPanel.paintAlignment(false, false);
3239 public void centreColumnLabels_actionPerformed(ActionEvent e)
3241 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3242 alignPanel.paintAlignment(false, false);
3248 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3251 protected void followHighlight_actionPerformed()
3254 * Set the 'follow' flag on the Viewport (and scroll to position if now
3257 final boolean state = this.followHighlightMenuItem.getState();
3258 viewport.setFollowHighlight(state);
3261 alignPanel.scrollToPosition(viewport.getSearchResults());
3272 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3274 viewport.setColourText(colourTextMenuItem.isSelected());
3275 alignPanel.paintAlignment(false, false);
3285 public void wrapMenuItem_actionPerformed(ActionEvent e)
3287 scaleAbove.setVisible(wrapMenuItem.isSelected());
3288 scaleLeft.setVisible(wrapMenuItem.isSelected());
3289 scaleRight.setVisible(wrapMenuItem.isSelected());
3290 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3291 alignPanel.updateLayout();
3295 public void showAllSeqs_actionPerformed(ActionEvent e)
3297 viewport.showAllHiddenSeqs();
3301 public void showAllColumns_actionPerformed(ActionEvent e)
3303 viewport.showAllHiddenColumns();
3304 alignPanel.paintAlignment(true, true);
3305 viewport.sendSelection();
3309 public void hideSelSequences_actionPerformed(ActionEvent e)
3311 viewport.hideAllSelectedSeqs();
3315 * called by key handler and the hide all/show all menu items
3320 protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3323 boolean hide = false;
3324 SequenceGroup sg = viewport.getSelectionGroup();
3325 if (!toggleSeqs && !toggleCols)
3327 // Hide everything by the current selection - this is a hack - we do the
3328 // invert and then hide
3329 // first check that there will be visible columns after the invert.
3330 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3331 && sg.getStartRes() <= sg.getEndRes()))
3333 // now invert the sequence set, if required - empty selection implies
3334 // that no hiding is required.
3337 invertSequenceMenuItem_actionPerformed(null);
3338 sg = viewport.getSelectionGroup();
3342 viewport.expandColSelection(sg, true);
3343 // finally invert the column selection and get the new sequence
3345 invertColSel_actionPerformed(null);
3352 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3354 hideSelSequences_actionPerformed(null);
3357 else if (!(toggleCols && viewport.hasSelectedColumns()))
3359 showAllSeqs_actionPerformed(null);
3365 if (viewport.hasSelectedColumns())
3367 hideSelColumns_actionPerformed(null);
3370 viewport.setSelectionGroup(sg);
3375 showAllColumns_actionPerformed(null);
3384 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3385 * event.ActionEvent)
3388 public void hideAllButSelection_actionPerformed(ActionEvent e)
3390 toggleHiddenRegions(false, false);
3391 viewport.sendSelection();
3398 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3402 public void hideAllSelection_actionPerformed(ActionEvent e)
3404 SequenceGroup sg = viewport.getSelectionGroup();
3405 viewport.expandColSelection(sg, false);
3406 viewport.hideAllSelectedSeqs();
3407 viewport.hideSelectedColumns();
3408 alignPanel.updateLayout();
3409 alignPanel.paintAlignment(true, true);
3410 viewport.sendSelection();
3417 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3421 public void showAllhidden_actionPerformed(ActionEvent e)
3423 viewport.showAllHiddenColumns();
3424 viewport.showAllHiddenSeqs();
3425 alignPanel.paintAlignment(true, true);
3426 viewport.sendSelection();
3430 public void hideSelColumns_actionPerformed(ActionEvent e)
3432 viewport.hideSelectedColumns();
3433 alignPanel.updateLayout();
3434 alignPanel.paintAlignment(true, true);
3435 viewport.sendSelection();
3439 public void hiddenMarkers_actionPerformed(ActionEvent e)
3441 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3452 protected void scaleAbove_actionPerformed(ActionEvent e)
3454 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3455 alignPanel.updateLayout();
3456 alignPanel.paintAlignment(true, false);
3466 protected void scaleLeft_actionPerformed(ActionEvent e)
3468 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3469 alignPanel.updateLayout();
3470 alignPanel.paintAlignment(true, false);
3480 protected void scaleRight_actionPerformed(ActionEvent e)
3482 viewport.setScaleRightWrapped(scaleRight.isSelected());
3483 alignPanel.updateLayout();
3484 alignPanel.paintAlignment(true, false);
3494 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3496 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3497 alignPanel.paintAlignment(false, false);
3507 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3509 viewport.setShowText(viewTextMenuItem.isSelected());
3510 alignPanel.paintAlignment(false, false);
3520 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3522 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3523 alignPanel.paintAlignment(false, false);
3526 public FeatureSettings featureSettings;
3529 public FeatureSettingsControllerI getFeatureSettingsUI()
3531 return featureSettings;
3535 public void featureSettings_actionPerformed(ActionEvent e)
3537 showFeatureSettingsUI();
3541 public FeatureSettingsControllerI showFeatureSettingsUI()
3543 if (featureSettings != null)
3545 featureSettings.closeOldSettings();
3546 featureSettings = null;
3548 if (!showSeqFeatures.isSelected())
3550 // make sure features are actually displayed
3551 showSeqFeatures.setSelected(true);
3552 showSeqFeatures_actionPerformed(null);
3554 featureSettings = new FeatureSettings(this);
3555 return featureSettings;
3559 * Set or clear 'Show Sequence Features'
3565 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3567 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3568 alignPanel.paintAlignment(true, true);
3572 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3573 * the annotations panel as a whole.
3575 * The options to show/hide all annotations should be enabled when the panel
3576 * is shown, and disabled when the panel is hidden.
3581 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3583 final boolean setVisible = annotationPanelMenuItem.isSelected();
3584 viewport.setShowAnnotation(setVisible);
3585 this.showAllSeqAnnotations.setEnabled(setVisible);
3586 this.hideAllSeqAnnotations.setEnabled(setVisible);
3587 this.showAllAlAnnotations.setEnabled(setVisible);
3588 this.hideAllAlAnnotations.setEnabled(setVisible);
3589 alignPanel.updateLayout();
3593 public void alignmentProperties()
3596 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3599 String content = MessageManager.formatMessage("label.html_content",
3601 { contents.toString() });
3604 if (Platform.isJS())
3606 JLabel textLabel = new JLabel();
3607 textLabel.setText(content);
3608 textLabel.setBackground(Color.WHITE);
3610 pane = new JPanel(new BorderLayout());
3611 ((JPanel) pane).setOpaque(true);
3612 pane.setBackground(Color.WHITE);
3613 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3622 JEditorPane editPane = new JEditorPane("text/html", "");
3623 editPane.setEditable(false);
3624 editPane.setText(content);
3628 JInternalFrame frame = new JInternalFrame();
3630 frame.getContentPane().add(new JScrollPane(pane));
3632 Desktop.addInternalFrame(frame, MessageManager
3633 .formatMessage("label.alignment_properties", new Object[]
3634 { getTitle() }), 500, 400);
3644 public void overviewMenuItem_actionPerformed(ActionEvent e)
3646 if (alignPanel.overviewPanel != null)
3651 JInternalFrame frame = new JInternalFrame();
3652 final OverviewPanel overview = new OverviewPanel(alignPanel);
3653 frame.setContentPane(overview);
3654 Desktop.addInternalFrame(frame, MessageManager
3655 .formatMessage("label.overview_params", new Object[]
3656 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3659 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3660 frame.addInternalFrameListener(
3661 new javax.swing.event.InternalFrameAdapter()
3664 public void internalFrameClosed(
3665 javax.swing.event.InternalFrameEvent evt)
3668 alignPanel.setOverviewPanel(null);
3671 if (getKeyListeners().length > 0)
3673 frame.addKeyListener(getKeyListeners()[0]);
3676 alignPanel.setOverviewPanel(overview);
3680 public void textColour_actionPerformed()
3682 new TextColourChooser().chooseColour(alignPanel, null);
3686 * public void covariationColour_actionPerformed() {
3688 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3692 public void annotationColour_actionPerformed()
3694 new AnnotationColourChooser(viewport, alignPanel);
3698 public void annotationColumn_actionPerformed(ActionEvent e)
3700 new AnnotationColumnChooser(viewport, alignPanel);
3704 * Action on the user checking or unchecking the option to apply the selected
3705 * colour scheme to all groups. If unchecked, groups may have their own
3706 * independent colour schemes.
3711 public void applyToAllGroups_actionPerformed(boolean selected)
3713 viewport.setColourAppliesToAllGroups(selected);
3717 * Action on user selecting a colour from the colour menu
3720 * the name (not the menu item label!) of the colour scheme
3723 public void changeColour_actionPerformed(String name)
3726 * 'User Defined' opens a panel to configure or load a
3727 * user-defined colour scheme
3729 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3731 new UserDefinedColours(alignPanel);
3736 * otherwise set the chosen colour scheme (or null for 'None')
3738 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3739 viewport, viewport.getAlignment(),
3740 viewport.getHiddenRepSequences());
3745 * Actions on setting or changing the alignment colour scheme
3750 public void changeColour(ColourSchemeI cs)
3752 // TODO: pull up to controller method
3753 ColourMenuHelper.setColourSelected(colourMenu, cs);
3755 viewport.setGlobalColourScheme(cs);
3757 alignPanel.paintAlignment(true, true);
3761 * Show the PID threshold slider panel
3764 protected void modifyPID_actionPerformed()
3766 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3767 alignPanel.getViewName());
3768 SliderPanel.showPIDSlider();
3772 * Show the Conservation slider panel
3775 protected void modifyConservation_actionPerformed()
3777 SliderPanel.setConservationSlider(alignPanel,
3778 viewport.getResidueShading(), alignPanel.getViewName());
3779 SliderPanel.showConservationSlider();
3783 * Action on selecting or deselecting (Colour) By Conservation
3786 public void conservationMenuItem_actionPerformed(boolean selected)
3788 modifyConservation.setEnabled(selected);
3789 viewport.setConservationSelected(selected);
3790 viewport.getResidueShading().setConservationApplied(selected);
3792 changeColour(viewport.getGlobalColourScheme());
3795 modifyConservation_actionPerformed();
3799 SliderPanel.hideConservationSlider();
3804 * Action on selecting or deselecting (Colour) Above PID Threshold
3807 public void abovePIDThreshold_actionPerformed(boolean selected)
3809 modifyPID.setEnabled(selected);
3810 viewport.setAbovePIDThreshold(selected);
3813 viewport.getResidueShading().setThreshold(0,
3814 viewport.isIgnoreGapsConsensus());
3817 changeColour(viewport.getGlobalColourScheme());
3820 modifyPID_actionPerformed();
3824 SliderPanel.hidePIDSlider();
3835 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3837 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3838 AlignmentSorter.sortByPID(viewport.getAlignment(),
3839 viewport.getAlignment().getSequenceAt(0));
3840 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3841 viewport.getAlignment()));
3842 alignPanel.paintAlignment(true, false);
3852 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3854 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3855 AlignmentSorter.sortByID(viewport.getAlignment());
3857 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3858 alignPanel.paintAlignment(true, false);
3868 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3870 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3871 AlignmentSorter.sortByLength(viewport.getAlignment());
3872 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3873 viewport.getAlignment()));
3874 alignPanel.paintAlignment(true, false);
3884 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3886 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3887 AlignmentSorter.sortByGroup(viewport.getAlignment());
3888 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3889 viewport.getAlignment()));
3891 alignPanel.paintAlignment(true, false);
3895 public void sortEValueMenuItem_actionPerformed(ActionEvent e)
3897 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3898 AlignmentSorter.sortByEValue(viewport.getAlignment());
3899 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3900 viewport.getAlignment()));
3901 alignPanel.paintAlignment(true, false);
3906 public void sortBitScoreMenuItem_actionPerformed(ActionEvent e)
3908 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3909 AlignmentSorter.sortByBitScore(viewport.getAlignment());
3910 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3911 viewport.getAlignment()));
3912 alignPanel.paintAlignment(true, false);
3923 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3925 new RedundancyPanel(alignPanel, this);
3935 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3937 if ((viewport.getSelectionGroup() == null)
3938 || (viewport.getSelectionGroup().getSize() < 2))
3940 JvOptionPane.showInternalMessageDialog(this,
3941 MessageManager.getString(
3942 "label.you_must_select_least_two_sequences"),
3943 MessageManager.getString("label.invalid_selection"),
3944 JvOptionPane.WARNING_MESSAGE);
3948 JInternalFrame frame = new JInternalFrame();
3949 frame.setContentPane(new PairwiseAlignPanel(viewport));
3950 Desktop.addInternalFrame(frame,
3951 MessageManager.getString("action.pairwise_alignment"), 600,
3957 public void autoCalculate_actionPerformed(ActionEvent e)
3959 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3960 if (viewport.autoCalculateConsensus)
3962 viewport.firePropertyChange("alignment", null,
3963 viewport.getAlignment().getSequences());
3968 public void sortByTreeOption_actionPerformed(ActionEvent e)
3970 viewport.sortByTree = sortByTree.isSelected();
3974 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3976 viewport.followSelection = listenToViewSelections.isSelected();
3980 * Constructs a tree panel and adds it to the desktop
3983 * tree type (NJ or AV)
3985 * name of score model used to compute the tree
3987 * parameters for the distance or similarity calculation
3989 void newTreePanel(String type, String modelName,
3990 SimilarityParamsI options)
3992 String frameTitle = "";
3995 boolean onSelection = false;
3996 if (viewport.getSelectionGroup() != null
3997 && viewport.getSelectionGroup().getSize() > 0)
3999 SequenceGroup sg = viewport.getSelectionGroup();
4001 /* Decide if the selection is a column region */
4002 for (SequenceI _s : sg.getSequences())
4004 if (_s.getLength() < sg.getEndRes())
4006 JvOptionPane.showMessageDialog(Desktop.desktop,
4007 MessageManager.getString(
4008 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
4009 MessageManager.getString(
4010 "label.sequences_selection_not_aligned"),
4011 JvOptionPane.WARNING_MESSAGE);
4020 if (viewport.getAlignment().getHeight() < 2)
4026 tp = new TreePanel(alignPanel, type, modelName, options);
4027 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
4029 frameTitle += " from ";
4031 if (viewport.getViewName() != null)
4033 frameTitle += viewport.getViewName() + " of ";
4036 frameTitle += this.title;
4038 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
4049 public void addSortByOrderMenuItem(String title,
4050 final AlignmentOrder order)
4052 final JMenuItem item = new JMenuItem(MessageManager
4053 .formatMessage("action.by_title_param", new Object[]
4056 item.addActionListener(new java.awt.event.ActionListener()
4059 public void actionPerformed(ActionEvent e)
4061 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4063 // TODO: JBPNote - have to map order entries to curent SequenceI
4065 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4067 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
4068 viewport.getAlignment()));
4070 alignPanel.paintAlignment(true, false);
4076 * Add a new sort by annotation score menu item
4079 * the menu to add the option to
4081 * the label used to retrieve scores for each sequence on the
4084 public void addSortByAnnotScoreMenuItem(JMenu sort,
4085 final String scoreLabel)
4087 final JMenuItem item = new JMenuItem(scoreLabel);
4089 item.addActionListener(new java.awt.event.ActionListener()
4092 public void actionPerformed(ActionEvent e)
4094 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4095 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4096 viewport.getAlignment());// ,viewport.getSelectionGroup());
4097 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4098 viewport.getAlignment()));
4099 alignPanel.paintAlignment(true, false);
4105 * last hash for alignment's annotation array - used to minimise cost of
4108 protected int _annotationScoreVectorHash;
4111 * search the alignment and rebuild the sort by annotation score submenu the
4112 * last alignment annotation vector hash is stored to minimize cost of
4113 * rebuilding in subsequence calls.
4117 public void buildSortByAnnotationScoresMenu()
4119 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4124 if (viewport.getAlignment().getAlignmentAnnotation()
4125 .hashCode() == _annotationScoreVectorHash)
4130 sortByAnnotScore.removeAll();
4131 Set<String> scoreSorts = new HashSet<>();
4132 for (SequenceI sqa : viewport.getAlignment().getSequences())
4134 AlignmentAnnotation[] anns = sqa.getAnnotation();
4135 for (int i = 0; anns != null && i < anns.length; i++)
4137 AlignmentAnnotation aa = anns[i];
4138 if (aa != null && aa.hasScore() && aa.sequenceRef != null)
4140 scoreSorts.add(aa.label);
4144 for (String label : scoreSorts)
4146 addSortByAnnotScoreMenuItem(sortByAnnotScore, label);
4148 sortByAnnotScore.setVisible(!scoreSorts.isEmpty());
4150 _annotationScoreVectorHash = viewport.getAlignment()
4151 .getAlignmentAnnotation().hashCode();
4155 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4156 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4157 * call. Listeners are added to remove the menu item when the treePanel is
4158 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4162 public void buildTreeSortMenu()
4164 sortByTreeMenu.removeAll();
4166 List<Component> comps = PaintRefresher.components
4167 .get(viewport.getSequenceSetId());
4168 List<TreePanel> treePanels = new ArrayList<>();
4169 for (Component comp : comps)
4171 if (comp instanceof TreePanel)
4173 treePanels.add((TreePanel) comp);
4177 if (treePanels.size() < 1)
4179 sortByTreeMenu.setVisible(false);
4183 sortByTreeMenu.setVisible(true);
4185 for (final TreePanel tp : treePanels)
4187 final JMenuItem item = new JMenuItem(tp.getTitle());
4188 item.addActionListener(new java.awt.event.ActionListener()
4191 public void actionPerformed(ActionEvent e)
4193 tp.sortByTree_actionPerformed();
4194 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4199 sortByTreeMenu.add(item);
4203 public boolean sortBy(AlignmentOrder alorder, String undoname)
4205 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4206 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4207 if (undoname != null)
4209 addHistoryItem(new OrderCommand(undoname, oldOrder,
4210 viewport.getAlignment()));
4212 alignPanel.paintAlignment(true, false);
4217 * Work out whether the whole set of sequences or just the selected set will
4218 * be submitted for multiple alignment.
4221 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4223 // Now, check we have enough sequences
4224 AlignmentView msa = null;
4226 if ((viewport.getSelectionGroup() != null)
4227 && (viewport.getSelectionGroup().getSize() > 1))
4229 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4230 // some common interface!
4232 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4233 * SequenceI[sz = seqs.getSize(false)];
4235 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4236 * seqs.getSequenceAt(i); }
4238 msa = viewport.getAlignmentView(true);
4240 else if (viewport.getSelectionGroup() != null
4241 && viewport.getSelectionGroup().getSize() == 1)
4243 int option = JvOptionPane.showConfirmDialog(this,
4244 MessageManager.getString("warn.oneseq_msainput_selection"),
4245 MessageManager.getString("label.invalid_selection"),
4246 JvOptionPane.OK_CANCEL_OPTION);
4247 if (option == JvOptionPane.OK_OPTION)
4249 msa = viewport.getAlignmentView(false);
4254 msa = viewport.getAlignmentView(false);
4260 * Decides what is submitted to a secondary structure prediction service: the
4261 * first sequence in the alignment, or in the current selection, or, if the
4262 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4263 * region or the whole alignment. (where the first sequence in the set is the
4264 * one that the prediction will be for).
4266 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4268 AlignmentView seqs = null;
4270 if ((viewport.getSelectionGroup() != null)
4271 && (viewport.getSelectionGroup().getSize() > 0))
4273 seqs = viewport.getAlignmentView(true);
4277 seqs = viewport.getAlignmentView(false);
4279 // limit sequences - JBPNote in future - could spawn multiple prediction
4281 // TODO: viewport.getAlignment().isAligned is a global state - the local
4282 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4283 if (!viewport.getAlignment().isAligned(false))
4285 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4286 // TODO: if seqs.getSequences().length>1 then should really have warned
4300 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4302 // Pick the tree file
4303 JalviewFileChooser chooser = new JalviewFileChooser(
4304 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4305 chooser.setFileView(new JalviewFileView());
4306 chooser.setDialogTitle(
4307 MessageManager.getString("label.select_newick_like_tree_file"));
4308 chooser.setToolTipText(
4309 MessageManager.getString("label.load_tree_file"));
4311 chooser.setResponseHandler(0, new Runnable()
4316 String filePath = chooser.getSelectedFile().getPath();
4317 Cache.setProperty("LAST_DIRECTORY", filePath);
4318 NewickFile fin = null;
4321 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4322 DataSourceType.FILE));
4323 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4324 } catch (Exception ex)
4326 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4328 .getString("label.problem_reading_tree_file"),
4329 JvOptionPane.WARNING_MESSAGE);
4330 ex.printStackTrace();
4332 if (fin != null && fin.hasWarningMessage())
4334 JvOptionPane.showMessageDialog(Desktop.desktop,
4335 fin.getWarningMessage(),
4336 MessageManager.getString(
4337 "label.possible_problem_with_tree_file"),
4338 JvOptionPane.WARNING_MESSAGE);
4342 chooser.showOpenDialog(this);
4345 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4347 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4350 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4351 int h, int x, int y)
4353 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4357 * Add a treeviewer for the tree extracted from a Newick file object to the
4358 * current alignment view
4365 * Associated alignment input data (or null)
4374 * @return TreePanel handle
4376 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4377 AlignmentView input, int w, int h, int x, int y)
4379 TreePanel tp = null;
4385 if (nf.getTree() != null)
4387 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4393 tp.setLocation(x, y);
4396 Desktop.addInternalFrame(tp, treeTitle, w, h);
4398 } catch (Exception ex)
4400 ex.printStackTrace();
4407 * Schedule the web services menu rebuild to the event dispatch thread.
4409 public void buildWebServicesMenu()
4411 SwingUtilities.invokeLater(() -> {
4412 webService.removeAll();
4413 if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
4415 SlivkaWSDiscoverer discoverer = SlivkaWSDiscoverer.getInstance();
4416 JMenu submenu = new JMenu("Slivka");
4417 buildWebServicesMenu(discoverer, submenu);
4418 webService.add(submenu);
4420 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4422 WSDiscovererI jws2servs = Jws2Discoverer.getDiscoverer();
4423 JMenu submenu = new JMenu("JABAWS");
4424 buildWebServicesMenu(jws2servs, submenu);
4425 webService.add(submenu);
4431 * Constructs the web services menu for the given discoverer under the
4432 * specified menu. This method must be called on the EDT
4435 * the discoverer used to build the menu
4437 * parent component which the elements will be attached to
4439 private void buildWebServicesMenu(WSDiscovererI discoverer, JMenu menu)
4441 if (discoverer.hasServices())
4443 PreferredServiceRegistry.getRegistry().populateWSMenuEntry(
4444 discoverer.getServices(), null, menu, this, null);
4446 if (discoverer.isRunning())
4448 JMenuItem item = new JMenuItem("Service discovery in progress.");
4449 item.setEnabled(false);
4452 else if (!discoverer.hasServices())
4454 JMenuItem item = new JMenuItem("No services available.");
4455 item.setEnabled(false);
4460 // private boolean buildingMenu = false;
4463 * Generates menu items and listener event actions for web service clients
4466 // public void BuildWebServiceMenu()
4468 // while (buildingMenu)
4472 // System.err.println("Waiting for building menu to finish.");
4473 // Thread.sleep(10);
4474 // } catch (Exception e)
4478 // final AlignFrame me = this;
4479 // buildingMenu = true;
4480 // new Thread(new Runnable()
4483 // public void run()
4485 // final List<JMenuItem> legacyItems = new ArrayList<>();
4488 // // System.err.println("Building ws menu again "
4489 // // + Thread.currentThread());
4490 // // TODO: add support for context dependent disabling of services based
4492 // // alignment and current selection
4493 // // TODO: add additional serviceHandle parameter to specify abstract
4495 // // class independently of AbstractName
4496 // // TODO: add in rediscovery GUI function to restart discoverer
4497 // // TODO: group services by location as well as function and/or
4499 // // object broker mechanism.
4500 // final Vector<JMenu> wsmenu = new Vector<>();
4501 // final IProgressIndicator af = me;
4504 // * do not i18n these strings - they are hard-coded in class
4505 // * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4506 // * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4508 // final JMenu msawsmenu = new JMenu("Alignment");
4509 // final JMenu secstrmenu = new JMenu(
4510 // "Secondary Structure Prediction");
4511 // final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4512 // final JMenu analymenu = new JMenu("Analysis");
4513 // final JMenu dismenu = new JMenu("Protein Disorder");
4514 // // JAL-940 - only show secondary structure prediction services from
4515 // // the legacy server
4516 // if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4518 // Discoverer.services != null && (Discoverer.services.size() > 0))
4520 // // TODO: refactor to allow list of AbstractName/Handler bindings to
4522 // // stored or retrieved from elsewhere
4523 // // No MSAWS used any more:
4524 // // Vector msaws = null; // (Vector)
4525 // // Discoverer.services.get("MsaWS");
4526 // Vector<ServiceHandle> secstrpr = Discoverer.services
4527 // .get("SecStrPred");
4528 // if (secstrpr != null)
4530 // // Add any secondary structure prediction services
4531 // for (int i = 0, j = secstrpr.size(); i < j; i++)
4533 // final ext.vamsas.ServiceHandle sh = secstrpr.get(i);
4534 // jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4535 // .getServiceClient(sh);
4536 // int p = secstrmenu.getItemCount();
4537 // impl.attachWSMenuEntry(secstrmenu, me);
4538 // int q = secstrmenu.getItemCount();
4539 // for (int litm = p; litm < q; litm++)
4541 // legacyItems.add(secstrmenu.getItem(litm));
4547 // // Add all submenus in the order they should appear on the web
4549 // wsmenu.add(msawsmenu);
4550 // wsmenu.add(secstrmenu);
4551 // wsmenu.add(dismenu);
4552 // wsmenu.add(analymenu);
4553 // // No search services yet
4554 // // wsmenu.add(seqsrchmenu);
4556 // javax.swing.SwingUtilities.invokeLater(new Runnable()
4559 // public void run()
4563 // webService.removeAll();
4564 // // first, add discovered services onto the webservices menu
4565 // if (wsmenu.size() > 0)
4567 // for (int i = 0, j = wsmenu.size(); i < j; i++)
4569 // webService.add(wsmenu.get(i));
4574 // webService.add(me.webServiceNoServices);
4576 // // TODO: move into separate menu builder class.
4577 // boolean new_sspred = false;
4579 // if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4581 // WSDiscovererI jws2servs = Jws2Discoverer.getDiscoverer();
4582 // if (jws2servs != null)
4584 // if (jws2servs.hasServices())
4586 // jws2servs.attachWSMenuEntry(webService, me);
4587 // for (ServiceWithParameters sv : jws2servs
4590 // if (sv.getName().toLowerCase().contains("jpred"))
4592 // for (JMenuItem jmi : legacyItems)
4594 // jmi.setVisible(false);
4600 // if (jws2servs.isRunning())
4602 // JMenuItem tm = new JMenuItem(
4603 // "Still discovering JABA Services");
4604 // tm.setEnabled(false);
4605 // webService.add(tm);
4610 // if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
4612 // WSDiscovererI discoverer = SlivkaWSDiscoverer
4614 // if (discoverer != null)
4616 // if (discoverer.hasServices())
4618 // discoverer.attachWSMenuEntry(webService, me);
4620 // if (discoverer.isRunning())
4622 // JMenuItem tm = new JMenuItem(
4623 // "Still discovering Slivka Services");
4624 // tm.setEnabled(false);
4625 // webService.add(tm);
4630 // build_urlServiceMenu(me.webService);
4631 // build_fetchdbmenu(webService);
4632 // for (JMenu item : wsmenu)
4634 // if (item.getItemCount() == 0)
4636 // item.setEnabled(false);
4640 // item.setEnabled(true);
4643 // } catch (Exception e)
4646 // "Exception during web service menu building process.",
4651 // } catch (Exception e)
4654 // buildingMenu = false;
4661 * construct any groupURL type service menu entries.
4665 protected void build_urlServiceMenu(JMenu webService)
4667 // TODO: remove this code when 2.7 is released
4668 // DEBUG - alignmentView
4670 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4671 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4673 * @Override public void actionPerformed(ActionEvent e) {
4674 * jalview.datamodel.AlignmentView
4675 * .testSelectionViews(af.viewport.getAlignment(),
4676 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4678 * }); webService.add(testAlView);
4680 // TODO: refactor to RestClient discoverer and merge menu entries for
4681 // rest-style services with other types of analysis/calculation service
4682 // SHmmr test client - still being implemented.
4683 // DEBUG - alignmentView
4685 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4688 client.attachWSMenuEntry(
4689 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4695 * Searches the alignment sequences for xRefs and builds the Show
4696 * Cross-References menu (formerly called Show Products), with database
4697 * sources for which cross-references are found (protein sources for a
4698 * nucleotide alignment and vice versa)
4700 * @return true if Show Cross-references menu should be enabled
4702 public boolean canShowProducts()
4704 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4705 AlignmentI dataset = viewport.getAlignment().getDataset();
4707 showProducts.removeAll();
4708 final boolean dna = viewport.getAlignment().isNucleotide();
4710 if (seqs == null || seqs.length == 0)
4712 // nothing to see here.
4716 boolean showp = false;
4719 List<String> ptypes = new CrossRef(seqs, dataset)
4720 .findXrefSourcesForSequences(dna);
4722 for (final String source : ptypes)
4725 final AlignFrame af = this;
4726 JMenuItem xtype = new JMenuItem(source);
4727 xtype.addActionListener(new ActionListener()
4730 public void actionPerformed(ActionEvent e)
4732 showProductsFor(af.viewport.getSequenceSelection(), dna,
4736 showProducts.add(xtype);
4738 showProducts.setVisible(showp);
4739 showProducts.setEnabled(showp);
4740 } catch (Exception e)
4743 "canShowProducts threw an exception - please report to help@jalview.org",
4751 * Finds and displays cross-references for the selected sequences (protein
4752 * products for nucleotide sequences, dna coding sequences for peptides).
4755 * the sequences to show cross-references for
4757 * true if from a nucleotide alignment (so showing proteins)
4759 * the database to show cross-references for
4761 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4762 final String source)
4764 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4769 * Construct and display a new frame containing the translation of this
4770 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4773 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4775 AlignmentI al = null;
4778 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4780 al = dna.translateCdna(codeTable);
4781 } catch (Exception ex)
4783 jalview.bin.Cache.log.error(
4784 "Exception during translation. Please report this !", ex);
4785 final String msg = MessageManager.getString(
4786 "label.error_when_translating_sequences_submit_bug_report");
4787 final String errorTitle = MessageManager
4788 .getString("label.implementation_error")
4789 + MessageManager.getString("label.translation_failed");
4790 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4791 JvOptionPane.ERROR_MESSAGE);
4794 if (al == null || al.getHeight() == 0)
4796 final String msg = MessageManager.getString(
4797 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4798 final String errorTitle = MessageManager
4799 .getString("label.translation_failed");
4800 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4801 JvOptionPane.WARNING_MESSAGE);
4805 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4806 af.setFileFormat(this.currentFileFormat);
4807 final String newTitle = MessageManager
4808 .formatMessage("label.translation_of_params", new Object[]
4809 { this.getTitle(), codeTable.getId() });
4810 af.setTitle(newTitle);
4811 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4813 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4814 viewport.openSplitFrame(af, new Alignment(seqs));
4818 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4825 * Set the file format
4829 public void setFileFormat(FileFormatI format)
4831 this.currentFileFormat = format;
4835 * Try to load a features file onto the alignment.
4838 * contents or path to retrieve file or a File object
4840 * access mode of file (see jalview.io.AlignFile)
4841 * @return true if features file was parsed correctly.
4843 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4846 return avc.parseFeaturesFile(file, sourceType,
4847 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4852 public void refreshFeatureUI(boolean enableIfNecessary)
4854 // note - currently this is only still here rather than in the controller
4855 // because of the featureSettings hard reference that is yet to be
4857 if (enableIfNecessary)
4859 viewport.setShowSequenceFeatures(true);
4860 showSeqFeatures.setSelected(true);
4866 public void dragEnter(DropTargetDragEvent evt)
4871 public void dragExit(DropTargetEvent evt)
4876 public void dragOver(DropTargetDragEvent evt)
4881 public void dropActionChanged(DropTargetDragEvent evt)
4886 public void drop(DropTargetDropEvent evt)
4888 // JAL-1552 - acceptDrop required before getTransferable call for
4889 // Java's Transferable for native dnd
4890 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4891 Transferable t = evt.getTransferable();
4893 final AlignFrame thisaf = this;
4894 final List<Object> files = new ArrayList<>();
4895 List<DataSourceType> protocols = new ArrayList<>();
4899 Desktop.transferFromDropTarget(files, protocols, evt, t);
4900 } catch (Exception e)
4902 e.printStackTrace();
4906 new Thread(new Runnable()
4913 // check to see if any of these files have names matching sequences
4916 SequenceIdMatcher idm = new SequenceIdMatcher(
4917 viewport.getAlignment().getSequencesArray());
4919 * Object[] { String,SequenceI}
4921 ArrayList<Object[]> filesmatched = new ArrayList<>();
4922 ArrayList<Object> filesnotmatched = new ArrayList<>();
4923 for (int i = 0; i < files.size(); i++)
4926 Object file = files.get(i);
4927 String fileName = file.toString();
4929 DataSourceType protocol = (file instanceof File
4930 ? DataSourceType.FILE
4931 : FormatAdapter.checkProtocol(fileName));
4932 if (protocol == DataSourceType.FILE)
4935 if (file instanceof File)
4938 Platform.cacheFileData(fl);
4942 fl = new File(fileName);
4944 pdbfn = fl.getName();
4946 else if (protocol == DataSourceType.URL)
4948 URL url = new URL(fileName);
4949 pdbfn = url.getFile();
4951 if (pdbfn.length() > 0)
4953 // attempt to find a match in the alignment
4954 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4955 int l = 0, c = pdbfn.indexOf(".");
4956 while (mtch == null && c != -1)
4961 } while ((c = pdbfn.indexOf(".", l)) > l);
4964 pdbfn = pdbfn.substring(0, l);
4966 mtch = idm.findAllIdMatches(pdbfn);
4973 type = new IdentifyFile().identify(file, protocol);
4974 } catch (Exception ex)
4978 if (type != null && type.isStructureFile())
4980 filesmatched.add(new Object[] { file, protocol, mtch });
4984 // File wasn't named like one of the sequences or wasn't a PDB
4986 filesnotmatched.add(file);
4990 if (filesmatched.size() > 0)
4992 boolean autoAssociate = Cache
4993 .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4996 String msg = MessageManager.formatMessage(
4997 "label.automatically_associate_structure_files_with_sequences_same_name",
4999 { Integer.valueOf(filesmatched.size())
5001 String ttl = MessageManager.getString(
5002 "label.automatically_associate_structure_files_by_name");
5003 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
5004 ttl, JvOptionPane.YES_NO_OPTION);
5005 autoAssociate = choice == JvOptionPane.YES_OPTION;
5009 for (Object[] fm : filesmatched)
5011 // try and associate
5012 // TODO: may want to set a standard ID naming formalism for
5013 // associating PDB files which have no IDs.
5014 for (SequenceI toassoc : (SequenceI[]) fm[2])
5016 PDBEntry pe = new AssociatePdbFileWithSeq()
5017 .associatePdbWithSeq(fm[0].toString(),
5018 (DataSourceType) fm[1], toassoc, false,
5022 System.err.println("Associated file : "
5023 + (fm[0].toString()) + " with "
5024 + toassoc.getDisplayId(true));
5028 // TODO: do we need to update overview ? only if features are
5030 alignPanel.paintAlignment(true, false);
5036 * add declined structures as sequences
5038 for (Object[] o : filesmatched)
5040 filesnotmatched.add(o[0]);
5044 if (filesnotmatched.size() > 0)
5046 if (assocfiles > 0 && (Cache.getDefault(
5047 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
5048 || JvOptionPane.showConfirmDialog(thisaf,
5049 "<html>" + MessageManager.formatMessage(
5050 "label.ignore_unmatched_dropped_files_info",
5053 filesnotmatched.size())
5056 MessageManager.getString(
5057 "label.ignore_unmatched_dropped_files"),
5058 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
5062 for (Object fn : filesnotmatched)
5064 loadJalviewDataFile(fn, null, null, null);
5068 } catch (Exception ex)
5070 ex.printStackTrace();
5078 * Attempt to load a "dropped" file or URL string, by testing in turn for
5080 * <li>an Annotation file</li>
5081 * <li>a JNet file</li>
5082 * <li>a features file</li>
5083 * <li>else try to interpret as an alignment file</li>
5087 * either a filename or a URL string.
5088 * @throws InterruptedException
5089 * @throws IOException
5091 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
5092 FileFormatI format, SequenceI assocSeq)
5094 // BH 2018 was String file
5097 if (sourceType == null)
5099 sourceType = FormatAdapter.checkProtocol(file);
5101 // if the file isn't identified, or not positively identified as some
5102 // other filetype (PFAM is default unidentified alignment file type) then
5103 // try to parse as annotation.
5104 boolean isAnnotation = (format == null
5105 || FileFormat.Pfam.equals(format))
5106 ? new AnnotationFile().annotateAlignmentView(viewport,
5112 // first see if its a T-COFFEE score file
5113 TCoffeeScoreFile tcf = null;
5116 tcf = new TCoffeeScoreFile(file, sourceType);
5119 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5123 new TCoffeeColourScheme(viewport.getAlignment()));
5124 isAnnotation = true;
5125 setStatus(MessageManager.getString(
5126 "label.successfully_pasted_tcoffee_scores_to_alignment"));
5130 // some problem - if no warning its probable that the ID matching
5131 // process didn't work
5132 JvOptionPane.showMessageDialog(Desktop.desktop,
5133 tcf.getWarningMessage() == null
5134 ? MessageManager.getString(
5135 "label.check_file_matches_sequence_ids_alignment")
5136 : tcf.getWarningMessage(),
5137 MessageManager.getString(
5138 "label.problem_reading_tcoffee_score_file"),
5139 JvOptionPane.WARNING_MESSAGE);
5146 } catch (Exception x)
5149 "Exception when processing data source as T-COFFEE score file",
5155 // try to see if its a JNet 'concise' style annotation file *before*
5157 // try to parse it as a features file
5160 format = new IdentifyFile().identify(file, sourceType);
5162 if (FileFormat.ScoreMatrix == format)
5164 ScoreMatrixFile sm = new ScoreMatrixFile(
5165 new FileParse(file, sourceType));
5167 // todo: i18n this message
5168 setStatus(MessageManager.formatMessage(
5169 "label.successfully_loaded_matrix",
5170 sm.getMatrixName()));
5172 else if (FileFormat.Jnet.equals(format))
5174 JPredFile predictions = new JPredFile(file, sourceType);
5175 new JnetAnnotationMaker();
5176 JnetAnnotationMaker.add_annotation(predictions,
5177 viewport.getAlignment(), 0, false);
5178 viewport.getAlignment().setupJPredAlignment();
5179 isAnnotation = true;
5181 // else if (IdentifyFile.FeaturesFile.equals(format))
5182 else if (FileFormat.Features.equals(format))
5184 if (parseFeaturesFile(file, sourceType))
5186 SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
5187 if (splitFrame != null)
5189 splitFrame.repaint();
5193 alignPanel.paintAlignment(true, true);
5199 new FileLoader().LoadFile(viewport, file, sourceType, format);
5205 alignPanel.adjustAnnotationHeight();
5206 viewport.updateSequenceIdColours();
5207 buildSortByAnnotationScoresMenu();
5208 alignPanel.paintAlignment(true, true);
5210 } catch (Exception ex)
5212 ex.printStackTrace();
5213 } catch (OutOfMemoryError oom)
5218 } catch (Exception x)
5223 + (sourceType != null
5224 ? (sourceType == DataSourceType.PASTE
5226 : "using " + sourceType + " from "
5230 ? "(parsing as '" + format + "' file)"
5232 oom, Desktop.desktop);
5237 * Method invoked by the ChangeListener on the tabbed pane, in other words
5238 * when a different tabbed pane is selected by the user or programmatically.
5241 public void tabSelectionChanged(int index)
5245 alignPanel = alignPanels.get(index);
5246 viewport = alignPanel.av;
5247 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5248 setMenusFromViewport(viewport);
5249 if (featureSettings != null && featureSettings.isOpen()
5250 && featureSettings.fr.getViewport() != viewport)
5252 if (viewport.isShowSequenceFeatures())
5254 // refresh the featureSettings to reflect UI change
5255 showFeatureSettingsUI();
5259 // close feature settings for this view.
5260 featureSettings.close();
5267 * 'focus' any colour slider that is open to the selected viewport
5269 if (viewport.getConservationSelected())
5271 SliderPanel.setConservationSlider(alignPanel,
5272 viewport.getResidueShading(), alignPanel.getViewName());
5276 SliderPanel.hideConservationSlider();
5278 if (viewport.getAbovePIDThreshold())
5280 SliderPanel.setPIDSliderSource(alignPanel,
5281 viewport.getResidueShading(), alignPanel.getViewName());
5285 SliderPanel.hidePIDSlider();
5289 * If there is a frame linked to this one in a SplitPane, switch it to the
5290 * same view tab index. No infinite recursion of calls should happen, since
5291 * tabSelectionChanged() should not get invoked on setting the selected
5292 * index to an unchanged value. Guard against setting an invalid index
5293 * before the new view peer tab has been created.
5295 final AlignViewportI peer = viewport.getCodingComplement();
5298 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
5299 .getAlignPanel().alignFrame;
5300 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5302 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5308 * On right mouse click on view tab, prompt for and set new view name.
5311 public void tabbedPane_mousePressed(MouseEvent e)
5313 if (e.isPopupTrigger())
5315 String msg = MessageManager.getString("label.enter_view_name");
5316 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
5317 String reply = JvOptionPane.showInputDialog(msg, ttl);
5321 viewport.setViewName(reply);
5322 // TODO warn if reply is in getExistingViewNames()?
5323 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5328 public AlignViewport getCurrentView()
5334 * Open the dialog for regex description parsing.
5337 protected void extractScores_actionPerformed(ActionEvent e)
5339 ParseProperties pp = new jalview.analysis.ParseProperties(
5340 viewport.getAlignment());
5341 // TODO: verify regex and introduce GUI dialog for version 2.5
5342 // if (pp.getScoresFromDescription("col", "score column ",
5343 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5345 if (pp.getScoresFromDescription("description column",
5346 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5348 buildSortByAnnotationScoresMenu();
5356 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5360 protected void showDbRefs_actionPerformed(ActionEvent e)
5362 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5368 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5372 protected void showNpFeats_actionPerformed(ActionEvent e)
5374 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5378 * find the viewport amongst the tabs in this alignment frame and close that
5383 public boolean closeView(AlignViewportI av)
5387 this.closeMenuItem_actionPerformed(false);
5390 Component[] comp = tabbedPane.getComponents();
5391 for (int i = 0; comp != null && i < comp.length; i++)
5393 if (comp[i] instanceof AlignmentPanel)
5395 if (((AlignmentPanel) comp[i]).av == av)
5398 closeView((AlignmentPanel) comp[i]);
5406 protected void build_fetchdbmenu(JMenu webService)
5408 // Temporary hack - DBRef Fetcher always top level ws entry.
5409 // TODO We probably want to store a sequence database checklist in
5410 // preferences and have checkboxes.. rather than individual sources selected
5412 final JMenu rfetch = new JMenu(
5413 MessageManager.getString("action.fetch_db_references"));
5414 rfetch.setToolTipText(MessageManager.getString(
5415 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5416 webService.add(rfetch);
5418 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5419 MessageManager.getString("option.trim_retrieved_seqs"));
5420 trimrs.setToolTipText(
5421 MessageManager.getString("label.trim_retrieved_sequences"));
5423 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5424 trimrs.addActionListener(new ActionListener()
5427 public void actionPerformed(ActionEvent e)
5429 trimrs.setSelected(trimrs.isSelected());
5430 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5431 Boolean.valueOf(trimrs.isSelected()).toString());
5435 JMenuItem fetchr = new JMenuItem(
5436 MessageManager.getString("label.standard_databases"));
5437 fetchr.setToolTipText(
5438 MessageManager.getString("label.fetch_embl_uniprot"));
5439 fetchr.addActionListener(new ActionListener()
5443 public void actionPerformed(ActionEvent e)
5445 new Thread(new Runnable()
5450 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5451 .getAlignment().isNucleotide();
5452 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5453 alignPanel.av.getSequenceSelection(),
5454 alignPanel.alignFrame, null,
5455 alignPanel.alignFrame.featureSettings, isNucleotide);
5456 dbRefFetcher.addListener(new FetchFinishedListenerI()
5459 public void finished()
5462 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5463 .getFeatureSettingsModels())
5466 alignPanel.av.mergeFeaturesStyle(srcSettings);
5468 AlignFrame.this.setMenusForViewport();
5471 dbRefFetcher.fetchDBRefs(false);
5479 new Thread(new Runnable()
5484 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5485 .getSequenceFetcherSingleton();
5486 javax.swing.SwingUtilities.invokeLater(new Runnable()
5491 String[] dbclasses = sf.getNonAlignmentSources();
5492 List<DbSourceProxy> otherdb;
5493 JMenu dfetch = new JMenu();
5494 JMenu ifetch = new JMenu();
5495 JMenuItem fetchr = null;
5496 int comp = 0, icomp = 0, mcomp = 15;
5497 String mname = null;
5499 for (String dbclass : dbclasses)
5501 otherdb = sf.getSourceProxy(dbclass);
5502 // add a single entry for this class, or submenu allowing 'fetch
5504 if (otherdb == null || otherdb.size() < 1)
5510 mname = "From " + dbclass;
5512 if (otherdb.size() == 1)
5514 final DbSourceProxy[] dassource = otherdb
5515 .toArray(new DbSourceProxy[0]);
5516 DbSourceProxy src = otherdb.get(0);
5517 fetchr = new JMenuItem(src.getDbSource());
5518 fetchr.addActionListener(new ActionListener()
5522 public void actionPerformed(ActionEvent e)
5524 new Thread(new Runnable()
5530 boolean isNucleotide = alignPanel.alignFrame
5531 .getViewport().getAlignment()
5533 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5534 alignPanel.av.getSequenceSelection(),
5535 alignPanel.alignFrame, dassource,
5536 alignPanel.alignFrame.featureSettings,
5539 .addListener(new FetchFinishedListenerI()
5542 public void finished()
5544 FeatureSettingsModelI srcSettings = dassource[0]
5545 .getFeatureColourScheme();
5546 alignPanel.av.mergeFeaturesStyle(
5548 AlignFrame.this.setMenusForViewport();
5551 dbRefFetcher.fetchDBRefs(false);
5557 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5558 MessageManager.formatMessage(
5559 "label.fetch_retrieve_from", new Object[]
5560 { src.getDbName() })));
5566 final DbSourceProxy[] dassource = otherdb
5567 .toArray(new DbSourceProxy[0]);
5569 DbSourceProxy src = otherdb.get(0);
5570 fetchr = new JMenuItem(MessageManager
5571 .formatMessage("label.fetch_all_param", new Object[]
5572 { src.getDbSource() }));
5573 fetchr.addActionListener(new ActionListener()
5576 public void actionPerformed(ActionEvent e)
5578 new Thread(new Runnable()
5584 boolean isNucleotide = alignPanel.alignFrame
5585 .getViewport().getAlignment()
5587 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5588 alignPanel.av.getSequenceSelection(),
5589 alignPanel.alignFrame, dassource,
5590 alignPanel.alignFrame.featureSettings,
5593 .addListener(new FetchFinishedListenerI()
5596 public void finished()
5598 AlignFrame.this.setMenusForViewport();
5601 dbRefFetcher.fetchDBRefs(false);
5607 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5608 MessageManager.formatMessage(
5609 "label.fetch_retrieve_from_all_sources",
5611 { Integer.valueOf(otherdb.size())
5613 src.getDbSource(), src.getDbName() })));
5616 // and then build the rest of the individual menus
5617 ifetch = new JMenu(MessageManager.formatMessage(
5618 "label.source_from_db_source", new Object[]
5619 { src.getDbSource() }));
5621 String imname = null;
5623 for (DbSourceProxy sproxy : otherdb)
5625 String dbname = sproxy.getDbName();
5626 String sname = dbname.length() > 5
5627 ? dbname.substring(0, 5) + "..."
5629 String msname = dbname.length() > 10
5630 ? dbname.substring(0, 10) + "..."
5634 imname = MessageManager
5635 .formatMessage("label.from_msname", new Object[]
5638 fetchr = new JMenuItem(msname);
5639 final DbSourceProxy[] dassrc = { sproxy };
5640 fetchr.addActionListener(new ActionListener()
5644 public void actionPerformed(ActionEvent e)
5646 new Thread(new Runnable()
5652 boolean isNucleotide = alignPanel.alignFrame
5653 .getViewport().getAlignment()
5655 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5656 alignPanel.av.getSequenceSelection(),
5657 alignPanel.alignFrame, dassrc,
5658 alignPanel.alignFrame.featureSettings,
5661 .addListener(new FetchFinishedListenerI()
5664 public void finished()
5666 AlignFrame.this.setMenusForViewport();
5669 dbRefFetcher.fetchDBRefs(false);
5675 fetchr.setToolTipText(
5676 "<html>" + MessageManager.formatMessage(
5677 "label.fetch_retrieve_from", new Object[]
5681 if (++icomp >= mcomp || i == (otherdb.size()))
5683 ifetch.setText(MessageManager.formatMessage(
5684 "label.source_to_target", imname, sname));
5686 ifetch = new JMenu();
5694 if (comp >= mcomp || dbi >= (dbclasses.length))
5696 dfetch.setText(MessageManager.formatMessage(
5697 "label.source_to_target", mname, dbclass));
5699 dfetch = new JMenu();
5712 * Left justify the whole alignment.
5715 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5717 AlignmentI al = viewport.getAlignment();
5719 viewport.firePropertyChange("alignment", null, al);
5723 * Right justify the whole alignment.
5726 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5728 AlignmentI al = viewport.getAlignment();
5730 viewport.firePropertyChange("alignment", null, al);
5734 public void setShowSeqFeatures(boolean b)
5736 showSeqFeatures.setSelected(b);
5737 viewport.setShowSequenceFeatures(b);
5744 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5745 * awt.event.ActionEvent)
5748 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5750 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5751 alignPanel.paintAlignment(false, false);
5758 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5762 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5764 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5765 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5773 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5774 * .event.ActionEvent)
5777 protected void showGroupConservation_actionPerformed(ActionEvent e)
5779 viewport.setShowGroupConservation(showGroupConservation.getState());
5780 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5787 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5788 * .event.ActionEvent)
5791 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5793 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5794 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5801 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5802 * .event.ActionEvent)
5805 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5807 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5808 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5812 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5814 showSequenceLogo.setState(true);
5815 viewport.setShowSequenceLogo(true);
5816 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5817 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5821 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5823 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5830 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5831 * .event.ActionEvent)
5834 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5836 if (avc.makeGroupsFromSelection())
5838 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5839 alignPanel.updateAnnotation();
5840 alignPanel.paintAlignment(true,
5841 viewport.needToUpdateStructureViews());
5845 public void clearAlignmentSeqRep()
5847 // TODO refactor alignmentseqrep to controller
5848 if (viewport.getAlignment().hasSeqrep())
5850 viewport.getAlignment().setSeqrep(null);
5851 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5852 alignPanel.updateAnnotation();
5853 alignPanel.paintAlignment(true, true);
5858 protected void createGroup_actionPerformed(ActionEvent e)
5860 if (avc.createGroup())
5862 if (applyAutoAnnotationSettings.isSelected())
5864 alignPanel.updateAnnotation(true, false);
5866 alignPanel.alignmentChanged();
5871 protected void unGroup_actionPerformed(ActionEvent e)
5875 alignPanel.alignmentChanged();
5880 * make the given alignmentPanel the currently selected tab
5882 * @param alignmentPanel
5884 public void setDisplayedView(AlignmentPanel alignmentPanel)
5886 if (!viewport.getSequenceSetId()
5887 .equals(alignmentPanel.av.getSequenceSetId()))
5889 throw new Error(MessageManager.getString(
5890 "error.implementation_error_cannot_show_view_alignment_frame"));
5892 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5893 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5895 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5900 * Action on selection of menu options to Show or Hide annotations.
5903 * @param forSequences
5904 * update sequence-related annotations
5905 * @param forAlignment
5906 * update non-sequence-related annotations
5909 protected void setAnnotationsVisibility(boolean visible,
5910 boolean forSequences, boolean forAlignment)
5912 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5913 .getAlignmentAnnotation();
5918 for (AlignmentAnnotation aa : anns)
5921 * don't display non-positional annotations on an alignment
5923 if (aa.annotations == null)
5927 boolean apply = (aa.sequenceRef == null && forAlignment)
5928 || (aa.sequenceRef != null && forSequences);
5931 aa.visible = visible;
5934 alignPanel.validateAnnotationDimensions(true);
5935 alignPanel.alignmentChanged();
5939 * Store selected annotation sort order for the view and repaint.
5942 protected void sortAnnotations_actionPerformed()
5944 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5946 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5947 alignPanel.paintAlignment(false, false);
5952 * @return alignment panels in this alignment frame
5954 public List<? extends AlignmentViewPanel> getAlignPanels()
5956 // alignPanels is never null
5957 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5962 * Open a new alignment window, with the cDNA associated with this (protein)
5963 * alignment, aligned as is the protein.
5965 protected void viewAsCdna_actionPerformed()
5967 // TODO no longer a menu action - refactor as required
5968 final AlignmentI alignment = getViewport().getAlignment();
5969 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5970 if (mappings == null)
5974 List<SequenceI> cdnaSeqs = new ArrayList<>();
5975 for (SequenceI aaSeq : alignment.getSequences())
5977 for (AlignedCodonFrame acf : mappings)
5979 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5983 * There is a cDNA mapping for this protein sequence - add to new
5984 * alignment. It will share the same dataset sequence as other mapped
5985 * cDNA (no new mappings need to be created).
5987 final Sequence newSeq = new Sequence(dnaSeq);
5988 newSeq.setDatasetSequence(dnaSeq);
5989 cdnaSeqs.add(newSeq);
5993 if (cdnaSeqs.size() == 0)
5995 // show a warning dialog no mapped cDNA
5998 AlignmentI cdna = new Alignment(
5999 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
6000 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
6001 AlignFrame.DEFAULT_HEIGHT);
6002 cdna.alignAs(alignment);
6003 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
6005 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
6006 AlignFrame.DEFAULT_HEIGHT);
6010 * Set visibility of dna/protein complement view (available when shown in a
6016 protected void showComplement_actionPerformed(boolean show)
6018 SplitContainerI sf = getSplitViewContainer();
6021 sf.setComplementVisible(this, show);
6026 * Generate the reverse (optionally complemented) of the selected sequences,
6027 * and add them to the alignment
6030 protected void showReverse_actionPerformed(boolean complement)
6032 AlignmentI al = null;
6035 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
6036 al = dna.reverseCdna(complement);
6037 viewport.addAlignment(al, "");
6038 addHistoryItem(new EditCommand(
6039 MessageManager.getString("label.add_sequences"), Action.PASTE,
6040 al.getSequencesArray(), 0, al.getWidth(),
6041 viewport.getAlignment()));
6042 } catch (Exception ex)
6044 System.err.println(ex.getMessage());
6050 * Try to run a script in the Groovy console, having first ensured that this
6051 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
6052 * be targeted at this alignment.
6055 protected void runGroovy_actionPerformed()
6057 Jalview.setCurrentAlignFrame(this);
6058 groovy.ui.Console console = Desktop.getGroovyConsole();
6059 if (console != null)
6063 console.runScript();
6064 } catch (Exception ex)
6066 System.err.println((ex.toString()));
6067 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
6068 MessageManager.getString("label.couldnt_run_groovy_script"),
6069 MessageManager.getString("label.groovy_support_failed"),
6070 JvOptionPane.ERROR_MESSAGE);
6075 System.err.println("Can't run Groovy script as console not found");
6080 * Hides columns containing (or not containing) a specified feature, provided
6081 * that would not leave all columns hidden
6083 * @param featureType
6084 * @param columnsContaining
6087 public boolean hideFeatureColumns(String featureType,
6088 boolean columnsContaining)
6090 boolean notForHiding = avc.markColumnsContainingFeatures(
6091 columnsContaining, false, false, featureType);
6094 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
6095 false, featureType))
6097 getViewport().hideSelectedColumns();
6105 protected void selectHighlightedColumns_actionPerformed(
6106 ActionEvent actionEvent)
6108 // include key modifier check in case user selects from menu
6109 avc.markHighlightedColumns(
6110 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
6111 (actionEvent.getModifiers() & (ActionEvent.META_MASK
6112 | ActionEvent.CTRL_MASK)) != 0);
6116 * Rebuilds the Colour menu, including any user-defined colours which have
6117 * been loaded either on startup or during the session
6119 public void buildColourMenu()
6121 colourMenu.removeAll();
6123 colourMenu.add(applyToAllGroups);
6124 colourMenu.add(textColour);
6125 colourMenu.addSeparator();
6127 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
6128 viewport.getAlignment(), false);
6130 colourMenu.add(annotationColour);
6131 bg.add(annotationColour);
6132 colourMenu.addSeparator();
6133 colourMenu.add(conservationMenuItem);
6134 colourMenu.add(modifyConservation);
6135 colourMenu.add(abovePIDThreshold);
6136 colourMenu.add(modifyPID);
6138 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
6139 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
6143 * Open a dialog (if not already open) that allows the user to select and
6144 * calculate PCA or Tree analysis
6146 protected void openTreePcaDialog()
6148 if (alignPanel.getCalculationDialog() == null)
6150 new CalculationChooser(AlignFrame.this);
6155 * Sets the status of the HMMER menu
6157 public void updateHMMERStatus()
6159 hmmerMenu.setEnabled(HmmerCommand.isHmmerAvailable());
6163 protected void loadVcf_actionPerformed()
6165 JalviewFileChooser chooser = new JalviewFileChooser(
6166 Cache.getProperty("LAST_DIRECTORY"));
6167 chooser.setFileView(new JalviewFileView());
6168 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
6169 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
6170 final AlignFrame us = this;
6171 chooser.setResponseHandler(0, new Runnable()
6176 String choice = chooser.getSelectedFile().getPath();
6177 Cache.setProperty("LAST_DIRECTORY", choice);
6178 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
6179 new VCFLoader(choice).loadVCF(seqs, us);
6182 chooser.showOpenDialog(null);
6186 private Rectangle lastFeatureSettingsBounds = null;
6189 public void setFeatureSettingsGeometry(Rectangle bounds)
6191 lastFeatureSettingsBounds = bounds;
6195 public Rectangle getFeatureSettingsGeometry()
6197 return lastFeatureSettingsBounds;
6201 class PrintThread extends Thread
6205 public PrintThread(AlignmentPanel ap)
6210 static PageFormat pf;
6215 PrinterJob printJob = PrinterJob.getPrinterJob();
6219 printJob.setPrintable(ap, pf);
6223 printJob.setPrintable(ap);
6226 if (printJob.printDialog())
6231 } catch (Exception PrintException)
6233 PrintException.printStackTrace();