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 jalview.analysis.AlignmentSorter;
24 import jalview.analysis.AlignmentUtils;
25 import jalview.analysis.CrossRef;
26 import jalview.analysis.Dna;
27 import jalview.analysis.ParseProperties;
28 import jalview.analysis.SequenceIdMatcher;
29 import jalview.api.AlignExportSettingI;
30 import jalview.api.AlignViewControllerGuiI;
31 import jalview.api.AlignViewControllerI;
32 import jalview.api.AlignViewportI;
33 import jalview.api.AlignmentViewPanel;
34 import jalview.api.FeatureSettingsControllerI;
35 import jalview.api.SplitContainerI;
36 import jalview.api.ViewStyleI;
37 import jalview.api.analysis.SimilarityParamsI;
38 import jalview.bin.Cache;
39 import jalview.bin.Jalview;
40 import jalview.commands.CommandI;
41 import jalview.commands.EditCommand;
42 import jalview.commands.EditCommand.Action;
43 import jalview.commands.OrderCommand;
44 import jalview.commands.RemoveGapColCommand;
45 import jalview.commands.RemoveGapsCommand;
46 import jalview.commands.SlideSequencesCommand;
47 import jalview.commands.TrimRegionCommand;
48 import jalview.datamodel.AlignedCodonFrame;
49 import jalview.datamodel.Alignment;
50 import jalview.datamodel.AlignmentAnnotation;
51 import jalview.datamodel.AlignmentExportData;
52 import jalview.datamodel.AlignmentI;
53 import jalview.datamodel.AlignmentOrder;
54 import jalview.datamodel.AlignmentView;
55 import jalview.datamodel.ColumnSelection;
56 import jalview.datamodel.HiddenColumns;
57 import jalview.datamodel.HiddenMarkovModel;
58 import jalview.datamodel.HiddenSequences;
59 import jalview.datamodel.PDBEntry;
60 import jalview.datamodel.SeqCigar;
61 import jalview.datamodel.Sequence;
62 import jalview.datamodel.SequenceGroup;
63 import jalview.datamodel.SequenceI;
64 import jalview.gui.ColourMenuHelper.ColourChangeListener;
65 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
66 import jalview.hmmer.HMMAlignThread;
67 import jalview.hmmer.HMMBuildThread;
68 import jalview.hmmer.HMMERParamStore;
69 import jalview.hmmer.HMMERPreset;
70 import jalview.hmmer.HMMSearchThread;
71 import jalview.hmmer.HmmerCommand;
72 import jalview.io.AlignmentProperties;
73 import jalview.io.AnnotationFile;
74 import jalview.io.BioJsHTMLOutput;
75 import jalview.io.DataSourceType;
76 import jalview.io.FileFormat;
77 import jalview.io.FileFormatI;
78 import jalview.io.FileFormats;
79 import jalview.io.FileLoader;
80 import jalview.io.FileParse;
81 import jalview.io.FormatAdapter;
82 import jalview.io.HtmlSvgOutput;
83 import jalview.io.IdentifyFile;
84 import jalview.io.JPredFile;
85 import jalview.io.JalviewFileChooser;
86 import jalview.io.JalviewFileView;
87 import jalview.io.JnetAnnotationMaker;
88 import jalview.io.NewickFile;
89 import jalview.io.ScoreMatrixFile;
90 import jalview.io.TCoffeeScoreFile;
91 import jalview.jbgui.GAlignFrame;
92 import jalview.schemes.ColourSchemeI;
93 import jalview.schemes.ColourSchemes;
94 import jalview.schemes.ResidueColourScheme;
95 import jalview.schemes.TCoffeeColourScheme;
96 import jalview.util.MessageManager;
97 import jalview.util.StringUtils;
98 import jalview.viewmodel.AlignmentViewport;
99 import jalview.viewmodel.ViewportRanges;
100 import jalview.ws.DBRefFetcher;
101 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
102 import jalview.ws.jws1.Discoverer;
103 import jalview.ws.jws2.Jws2Discoverer;
104 import jalview.ws.jws2.jabaws2.Jws2Instance;
105 import jalview.ws.params.ArgumentI;
106 import jalview.ws.params.ParamDatastoreI;
107 import jalview.ws.params.WsParamSetI;
108 import jalview.ws.seqfetcher.DbSourceProxy;
110 import java.awt.BorderLayout;
111 import java.awt.Component;
112 import java.awt.Rectangle;
113 import java.awt.Toolkit;
114 import java.awt.datatransfer.Clipboard;
115 import java.awt.datatransfer.DataFlavor;
116 import java.awt.datatransfer.StringSelection;
117 import java.awt.datatransfer.Transferable;
118 import java.awt.dnd.DnDConstants;
119 import java.awt.dnd.DropTargetDragEvent;
120 import java.awt.dnd.DropTargetDropEvent;
121 import java.awt.dnd.DropTargetEvent;
122 import java.awt.dnd.DropTargetListener;
123 import java.awt.event.ActionEvent;
124 import java.awt.event.ActionListener;
125 import java.awt.event.FocusAdapter;
126 import java.awt.event.FocusEvent;
127 import java.awt.event.ItemEvent;
128 import java.awt.event.ItemListener;
129 import java.awt.event.KeyAdapter;
130 import java.awt.event.KeyEvent;
131 import java.awt.event.MouseEvent;
132 import java.awt.print.PageFormat;
133 import java.awt.print.PrinterJob;
134 import java.beans.PropertyChangeEvent;
136 import java.io.FileWriter;
137 import java.io.IOException;
138 import java.io.PrintWriter;
140 import java.util.ArrayList;
141 import java.util.Arrays;
142 import java.util.Deque;
143 import java.util.Enumeration;
144 import java.util.HashMap;
145 import java.util.Hashtable;
146 import java.util.List;
147 import java.util.Map;
148 import java.util.Scanner;
149 import java.util.Vector;
151 import javax.swing.JCheckBoxMenuItem;
152 import javax.swing.JEditorPane;
153 import javax.swing.JFileChooser;
154 import javax.swing.JFrame;
155 import javax.swing.JInternalFrame;
156 import javax.swing.JLayeredPane;
157 import javax.swing.JMenu;
158 import javax.swing.JMenuItem;
159 import javax.swing.JOptionPane;
160 import javax.swing.JScrollPane;
161 import javax.swing.SwingUtilities;
167 * @version $Revision$
169 public class AlignFrame extends GAlignFrame implements DropTargetListener,
170 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
173 Map<String, Float> distribution = new HashMap<>(); // temporary
175 public static final int DEFAULT_WIDTH = 700;
177 public static final int DEFAULT_HEIGHT = 500;
180 * The currently displayed panel (selected tabbed view if more than one)
182 public AlignmentPanel alignPanel;
184 AlignViewport viewport;
186 ViewportRanges vpRanges;
188 public AlignViewControllerI avc;
190 * The selected HMM for this align frame
192 SequenceI selectedHMMSequence;
194 List<AlignmentPanel> alignPanels = new ArrayList<>();
197 * Last format used to load or save alignments in this window
199 FileFormatI currentFileFormat = null;
202 * Current filename for this alignment
204 String fileName = null;
208 * Creates a new AlignFrame object with specific width and height.
214 public AlignFrame(AlignmentI al, int width, int height)
216 this(al, null, width, height);
220 * Creates a new AlignFrame object with specific width, height and
226 * @param sequenceSetId
228 public AlignFrame(AlignmentI al, int width, int height,
229 String sequenceSetId)
231 this(al, null, width, height, sequenceSetId);
235 * Creates a new AlignFrame object with specific width, height and
241 * @param sequenceSetId
244 public AlignFrame(AlignmentI al, int width, int height,
245 String sequenceSetId, String viewId)
247 this(al, null, width, height, sequenceSetId, viewId);
251 * new alignment window with hidden columns
255 * @param hiddenColumns
256 * ColumnSelection or null
258 * Width of alignment frame
262 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
265 this(al, hiddenColumns, width, height, null);
269 * Create alignment frame for al with hiddenColumns, a specific width and
270 * height, and specific sequenceId
273 * @param hiddenColumns
276 * @param sequenceSetId
279 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
280 int height, String sequenceSetId)
282 this(al, hiddenColumns, width, height, sequenceSetId, null);
286 * Create alignment frame for al with hiddenColumns, a specific width and
287 * height, and specific sequenceId
290 * @param hiddenColumns
293 * @param sequenceSetId
298 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
299 int height, String sequenceSetId, String viewId)
301 setSize(width, height);
303 if (al.getDataset() == null)
308 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
310 alignPanel = new AlignmentPanel(this, viewport);
312 addAlignmentPanel(alignPanel, true);
316 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
317 HiddenColumns hiddenColumns, int width, int height)
319 setSize(width, height);
321 if (al.getDataset() == null)
326 viewport = new AlignViewport(al, hiddenColumns);
328 if (hiddenSeqs != null && hiddenSeqs.length > 0)
330 viewport.hideSequence(hiddenSeqs);
332 alignPanel = new AlignmentPanel(this, viewport);
333 addAlignmentPanel(alignPanel, true);
338 * Make a new AlignFrame from existing alignmentPanels
345 public AlignFrame(AlignmentPanel ap)
349 addAlignmentPanel(ap, false);
354 * initalise the alignframe from the underlying viewport data and the
359 if (!Jalview.isHeadlessMode())
361 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
364 vpRanges = viewport.getRanges();
365 avc = new jalview.controller.AlignViewController(this, viewport,
367 if (viewport.getAlignmentConservationAnnotation() == null)
369 // BLOSUM62Colour.setEnabled(false);
370 conservationMenuItem.setEnabled(false);
371 modifyConservation.setEnabled(false);
372 // PIDColour.setEnabled(false);
373 // abovePIDThreshold.setEnabled(false);
374 // modifyPID.setEnabled(false);
377 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
380 if (sortby.equals("Id"))
382 sortIDMenuItem_actionPerformed(null);
384 else if (sortby.equals("Pairwise Identity"))
386 sortPairwiseMenuItem_actionPerformed(null);
390 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
392 setMenusFromViewport(viewport);
393 buildSortByAnnotationScoresMenu();
394 calculateTree.addActionListener(new ActionListener()
398 public void actionPerformed(ActionEvent e)
405 if (Desktop.desktop != null)
407 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
408 addServiceListeners();
412 if (viewport.getWrapAlignment())
414 wrapMenuItem_actionPerformed(null);
417 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
419 this.overviewMenuItem_actionPerformed(null);
424 final List<AlignmentPanel> selviews = new ArrayList<>();
425 final List<AlignmentPanel> origview = new ArrayList<>();
426 final String menuLabel = MessageManager
427 .getString("label.copy_format_from");
428 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
429 new ViewSetProvider()
433 public AlignmentPanel[] getAllAlignmentPanels()
436 origview.add(alignPanel);
437 // make an array of all alignment panels except for this one
438 List<AlignmentPanel> aps = new ArrayList<>(
439 Arrays.asList(Desktop.getAlignmentPanels(null)));
440 aps.remove(AlignFrame.this.alignPanel);
441 return aps.toArray(new AlignmentPanel[aps.size()]);
443 }, selviews, new ItemListener()
447 public void itemStateChanged(ItemEvent e)
449 if (origview.size() > 0)
451 final AlignmentPanel ap = origview.get(0);
454 * Copy the ViewStyle of the selected panel to 'this one'.
455 * Don't change value of 'scaleProteinAsCdna' unless copying
458 ViewStyleI vs = selviews.get(0).getAlignViewport()
460 boolean fromSplitFrame = selviews.get(0)
461 .getAlignViewport().getCodingComplement() != null;
464 vs.setScaleProteinAsCdna(ap.getAlignViewport()
465 .getViewStyle().isScaleProteinAsCdna());
467 ap.getAlignViewport().setViewStyle(vs);
470 * Also rescale ViewStyle of SplitFrame complement if there is
471 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
472 * the whole ViewStyle (allow cDNA protein to have different
475 AlignViewportI complement = ap.getAlignViewport()
476 .getCodingComplement();
477 if (complement != null && vs.isScaleProteinAsCdna())
479 AlignFrame af = Desktop.getAlignFrameFor(complement);
480 ((SplitFrame) af.getSplitViewContainer())
482 af.setMenusForViewport();
486 ap.setSelected(true);
487 ap.alignFrame.setMenusForViewport();
492 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
493 .indexOf("devel") > -1
494 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
495 .indexOf("test") > -1)
497 formatMenu.add(vsel);
499 addFocusListener(new FocusAdapter()
502 public void focusGained(FocusEvent e)
504 Jalview.setCurrentAlignFrame(AlignFrame.this);
511 * Change the filename and format for the alignment, and enable the 'reload'
512 * button functionality.
519 public void setFileName(String file, FileFormatI format)
522 setFileFormat(format);
523 reload.setEnabled(true);
527 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
530 void addKeyListener()
532 addKeyListener(new KeyAdapter()
535 public void keyPressed(KeyEvent evt)
537 if (viewport.cursorMode
538 && ((evt.getKeyCode() >= KeyEvent.VK_0
539 && evt.getKeyCode() <= KeyEvent.VK_9)
540 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
541 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
542 && Character.isDigit(evt.getKeyChar()))
544 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
547 switch (evt.getKeyCode())
550 case 27: // escape key
551 deselectAllSequenceMenuItem_actionPerformed(null);
555 case KeyEvent.VK_DOWN:
556 if (evt.isAltDown() || !viewport.cursorMode)
558 moveSelectedSequences(false);
560 if (viewport.cursorMode)
562 alignPanel.getSeqPanel().moveCursor(0, 1);
567 if (evt.isAltDown() || !viewport.cursorMode)
569 moveSelectedSequences(true);
571 if (viewport.cursorMode)
573 alignPanel.getSeqPanel().moveCursor(0, -1);
578 case KeyEvent.VK_LEFT:
579 if (evt.isAltDown() || !viewport.cursorMode)
581 slideSequences(false,
582 alignPanel.getSeqPanel().getKeyboardNo1());
586 alignPanel.getSeqPanel().moveCursor(-1, 0);
591 case KeyEvent.VK_RIGHT:
592 if (evt.isAltDown() || !viewport.cursorMode)
594 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
598 alignPanel.getSeqPanel().moveCursor(1, 0);
602 case KeyEvent.VK_SPACE:
603 if (viewport.cursorMode)
605 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
606 || evt.isShiftDown() || evt.isAltDown());
610 // case KeyEvent.VK_A:
611 // if (viewport.cursorMode)
613 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
614 // //System.out.println("A");
618 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
619 * System.out.println("closing bracket"); } break;
621 case KeyEvent.VK_DELETE:
622 case KeyEvent.VK_BACK_SPACE:
623 if (!viewport.cursorMode)
625 cut_actionPerformed(null);
629 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
630 || evt.isShiftDown() || evt.isAltDown());
636 if (viewport.cursorMode)
638 alignPanel.getSeqPanel().setCursorRow();
642 if (viewport.cursorMode && !evt.isControlDown())
644 alignPanel.getSeqPanel().setCursorColumn();
648 if (viewport.cursorMode)
650 alignPanel.getSeqPanel().setCursorPosition();
654 case KeyEvent.VK_ENTER:
655 case KeyEvent.VK_COMMA:
656 if (viewport.cursorMode)
658 alignPanel.getSeqPanel().setCursorRowAndColumn();
663 if (viewport.cursorMode)
665 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
669 if (viewport.cursorMode)
671 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
676 viewport.cursorMode = !viewport.cursorMode;
677 statusBar.setText(MessageManager
678 .formatMessage("label.keyboard_editing_mode", new String[]
679 { (viewport.cursorMode ? "on" : "off") }));
680 if (viewport.cursorMode)
682 alignPanel.getSeqPanel().seqCanvas.cursorX = vpRanges
684 alignPanel.getSeqPanel().seqCanvas.cursorY = vpRanges
687 alignPanel.getSeqPanel().seqCanvas.repaint();
693 Help.showHelpWindow();
694 } catch (Exception ex)
696 ex.printStackTrace();
701 boolean toggleSeqs = !evt.isControlDown();
702 boolean toggleCols = !evt.isShiftDown();
703 toggleHiddenRegions(toggleSeqs, toggleCols);
708 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
709 boolean modifyExisting = true; // always modify, don't clear
710 // evt.isShiftDown();
711 boolean invertHighlighted = evt.isAltDown();
712 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
716 case KeyEvent.VK_PAGE_UP:
719 case KeyEvent.VK_PAGE_DOWN:
726 public void keyReleased(KeyEvent evt)
728 switch (evt.getKeyCode())
730 case KeyEvent.VK_LEFT:
731 if (evt.isAltDown() || !viewport.cursorMode)
733 viewport.firePropertyChange("alignment", null,
734 viewport.getAlignment().getSequences());
738 case KeyEvent.VK_RIGHT:
739 if (evt.isAltDown() || !viewport.cursorMode)
741 viewport.firePropertyChange("alignment", null,
742 viewport.getAlignment().getSequences());
750 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
752 ap.alignFrame = this;
753 avc = new jalview.controller.AlignViewController(this, viewport,
758 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
760 int aSize = alignPanels.size();
762 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
764 if (aSize == 1 && ap.av.viewName == null)
766 this.getContentPane().add(ap, BorderLayout.CENTER);
772 setInitialTabVisible();
775 expandViews.setEnabled(true);
776 gatherViews.setEnabled(true);
777 tabbedPane.addTab(ap.av.viewName, ap);
779 ap.setVisible(false);
784 if (ap.av.isPadGaps())
786 ap.av.getAlignment().padGaps();
788 ap.av.updateConservation(ap);
789 ap.av.updateConsensus(ap);
790 ap.av.updateStrucConsensus(ap);
791 ap.av.updateInformation(ap);
795 public void setInitialTabVisible()
797 expandViews.setEnabled(true);
798 gatherViews.setEnabled(true);
799 tabbedPane.setVisible(true);
800 AlignmentPanel first = alignPanels.get(0);
801 tabbedPane.addTab(first.av.viewName, first);
802 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
805 public AlignViewport getViewport()
810 /* Set up intrinsic listeners for dynamically generated GUI bits. */
811 private void addServiceListeners()
813 final java.beans.PropertyChangeListener thisListener;
814 Desktop.instance.addJalviewPropertyChangeListener("services",
815 thisListener = new java.beans.PropertyChangeListener()
818 public void propertyChange(PropertyChangeEvent evt)
820 // // System.out.println("Discoverer property change.");
821 // if (evt.getPropertyName().equals("services"))
823 SwingUtilities.invokeLater(new Runnable()
830 "Rebuild WS Menu for service change");
831 BuildWebServiceMenu();
838 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
841 public void internalFrameClosed(
842 javax.swing.event.InternalFrameEvent evt)
844 // System.out.println("deregistering discoverer listener");
845 Desktop.instance.removeJalviewPropertyChangeListener("services",
847 closeMenuItem_actionPerformed(true);
850 // Finally, build the menu once to get current service state
851 new Thread(new Runnable()
856 BuildWebServiceMenu();
862 * Configure menu items that vary according to whether the alignment is
863 * nucleotide or protein
865 public void setGUINucleotide()
867 AlignmentI al = getViewport().getAlignment();
868 boolean nucleotide = al.isNucleotide();
870 showTranslation.setVisible(nucleotide);
871 showReverse.setVisible(nucleotide);
872 showReverseComplement.setVisible(nucleotide);
873 conservationMenuItem.setEnabled(!nucleotide);
875 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
876 showGroupConservation.setEnabled(!nucleotide);
878 showComplementMenuItem
879 .setText(nucleotide ? MessageManager.getString("label.protein")
880 : MessageManager.getString("label.nucleotide"));
884 * set up menus for the current viewport. This may be called after any
885 * operation that affects the data in the current view (selection changed,
886 * etc) to update the menus to reflect the new state.
889 public void setMenusForViewport()
891 setMenusFromViewport(viewport);
895 * Need to call this method when tabs are selected for multiple views, or when
896 * loading from Jalview2XML.java
901 void setMenusFromViewport(AlignViewport av)
903 padGapsMenuitem.setSelected(av.isPadGaps());
904 colourTextMenuItem.setSelected(av.isShowColourText());
905 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
906 modifyPID.setEnabled(abovePIDThreshold.isSelected());
907 conservationMenuItem.setSelected(av.getConservationSelected());
908 modifyConservation.setEnabled(conservationMenuItem.isSelected());
909 seqLimits.setSelected(av.getShowJVSuffix());
910 idRightAlign.setSelected(av.isRightAlignIds());
911 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
912 renderGapsMenuItem.setSelected(av.isRenderGaps());
913 wrapMenuItem.setSelected(av.getWrapAlignment());
914 scaleAbove.setVisible(av.getWrapAlignment());
915 scaleLeft.setVisible(av.getWrapAlignment());
916 scaleRight.setVisible(av.getWrapAlignment());
917 annotationPanelMenuItem.setState(av.isShowAnnotation());
919 * Show/hide annotations only enabled if annotation panel is shown
921 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
922 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
923 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
924 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
925 viewBoxesMenuItem.setSelected(av.getShowBoxes());
926 viewTextMenuItem.setSelected(av.getShowText());
927 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
928 showGroupConsensus.setSelected(av.isShowGroupConsensus());
929 showGroupConservation.setSelected(av.isShowGroupConservation());
930 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
931 showSequenceLogo.setSelected(av.isShowSequenceLogo());
932 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
933 showInformationHistogram.setSelected(av.isShowInformationHistogram());
934 showHMMSequenceLogo.setSelected(av.isShowHMMSequenceLogo());
935 normaliseHMMSequenceLogo.setSelected(av.isNormaliseHMMSequenceLogo());
937 ColourMenuHelper.setColourSelected(colourMenu,
938 av.getGlobalColourScheme());
940 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
941 hiddenMarkers.setState(av.getShowHiddenMarkers());
942 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
943 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
944 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
945 autoCalculate.setSelected(av.autoCalculateConsensus);
946 sortByTree.setSelected(av.sortByTree);
947 listenToViewSelections.setSelected(av.followSelection);
949 showProducts.setEnabled(canShowProducts());
950 setGroovyEnabled(Desktop.getGroovyConsole() != null);
956 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
960 public void setGroovyEnabled(boolean b)
962 runGroovy.setEnabled(b);
965 private IProgressIndicator progressBar;
970 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
973 public void setProgressBar(String message, long id)
975 progressBar.setProgressBar(message, id);
979 public void registerHandler(final long id,
980 final IProgressIndicatorHandler handler)
982 progressBar.registerHandler(id, handler);
987 * @return true if any progress bars are still active
990 public boolean operationInProgress()
992 return progressBar.operationInProgress();
996 public void setStatus(String text)
998 statusBar.setText(text);
1002 * Added so Castor Mapping file can obtain Jalview Version
1004 public String getVersion()
1006 return jalview.bin.Cache.getProperty("VERSION");
1009 public FeatureRenderer getFeatureRenderer()
1011 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1015 public void fetchSequence_actionPerformed(ActionEvent e)
1017 new jalview.gui.SequenceFetcher(this);
1021 public void addFromFile_actionPerformed(ActionEvent e)
1023 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1027 public void hmmBuildSettings_actionPerformed()
1029 if (!(alignmentIsSufficient(1)))
1033 WsParamSetI set = new HMMERPreset();
1034 List<ArgumentI> args = new ArrayList<>();
1035 ParamDatastoreI store = new HMMERParamStore("hmmbuild");
1036 WsJobParameters params = new WsJobParameters(new JFrame(), store, set,
1038 if (params.showRunDialog())
1040 new Thread(new HMMBuildThread(this, params.getJobParams())).start();
1042 alignPanel.repaint();
1047 public void hmmAlignSettings_actionPerformed()
1049 if (!(checkForHMM() && alignmentIsSufficient(2)))
1053 WsParamSetI set = new HMMERPreset();
1054 List<ArgumentI> args = new ArrayList<>();
1055 ParamDatastoreI store = new HMMERParamStore("hmmalign");
1056 WsJobParameters params = new WsJobParameters(new JFrame(), store, set,
1058 if (params.showRunDialog())
1060 new Thread(new HMMAlignThread(this, true, params.getJobParams()))
1063 alignPanel.repaint();
1067 public void hmmSearchSettings_actionPerformed()
1073 WsParamSetI set = new HMMERPreset();
1074 List<ArgumentI> args = new ArrayList<>();
1075 ParamDatastoreI store = new HMMERParamStore("hmmsearch");
1076 WsJobParameters params = new WsJobParameters(new JFrame(), store, set,
1078 if (params.showRunDialog())
1080 new Thread(new HMMSearchThread(this, true, params.getJobParams()))
1083 alignPanel.repaint();
1087 public void hmmBuildRun_actionPerformed()
1089 if (!alignmentIsSufficient(1))
1093 new Thread(new HMMBuildThread(this, null))
1098 public void hmmAlignRun_actionPerformed()
1100 if (!(checkForHMM() && alignmentIsSufficient(2)))
1104 new Thread(new HMMAlignThread(this, true, null))
1109 public void hmmSearchRun_actionPerformed()
1115 new Thread(new HMMSearchThread(this, true, null))
1120 * Checks if the frame has a selected hidden Markov model
1124 private boolean checkForHMM()
1126 if (getSelectedHMM() == null)
1128 JOptionPane.showMessageDialog(this,
1129 MessageManager.getString("warn.no_selected_hmm"));
1136 * Checks if the alignment contains the required number of sequences.
1141 public boolean alignmentIsSufficient(int required)
1143 if (getViewport().getAlignment().getSequences().size() < required)
1145 JOptionPane.showMessageDialog(this,
1146 MessageManager.getString("warn.not_enough_sequences"));
1153 public void addDatabase_actionPerformed() throws IOException
1155 if (Cache.getProperty(Preferences.HMMSEARCH_DB_PATHS) == null)
1157 Cache.setProperty(Preferences.HMMSEARCH_DBS, "");
1158 Cache.setProperty(Preferences.HMMSEARCH_DB_PATHS, "");
1161 String path = openFileChooser(false);
1162 if (new File(path).exists())
1164 IdentifyFile identifier = new IdentifyFile();
1165 FileFormatI format = identifier.identify(path, DataSourceType.FILE);
1166 if (format == FileFormat.Fasta || format == FileFormat.Stockholm
1167 || format == FileFormat.Pfam)
1169 String currentDbs = Cache.getProperty(Preferences.HMMSEARCH_DBS);
1170 String currentDbPaths = Cache
1171 .getProperty(Preferences.HMMSEARCH_DB_PATHS);
1172 currentDbPaths += " " + path;
1174 String fileName = StringUtils.getLastToken(path, File.separator);
1175 Scanner scanner = new Scanner(fileName).useDelimiter(".");
1176 String name = scanner.next();
1178 currentDbs += " " + path; // TODO remove path from file name
1181 Cache.setProperty(Preferences.HMMSEARCH_DB_PATHS, currentDbPaths);
1182 Cache.setProperty(Preferences.HMMSEARCH_DBS, currentDbPaths);
1186 JOptionPane.showMessageDialog(this,
1187 MessageManager.getString("warn.invalid_format"));
1192 JOptionPane.showMessageDialog(this,
1193 MessageManager.getString("warn.not_enough_sequences"));
1198 * Opens a file chooser
1203 protected String openFileChooser(boolean forFolder)
1205 String choice = null;
1206 JFileChooser chooser = new JFileChooser();
1209 chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1211 chooser.setDialogTitle(
1212 MessageManager.getString("label.open_local_file"));
1213 chooser.setToolTipText(MessageManager.getString("action.open"));
1215 int value = chooser.showOpenDialog(this);
1217 if (value == JFileChooser.APPROVE_OPTION)
1219 choice = chooser.getSelectedFile().getPath();
1225 public void reload_actionPerformed(ActionEvent e)
1227 if (fileName != null)
1229 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1230 // originating file's format
1231 // TODO: work out how to recover feature settings for correct view(s) when
1232 // file is reloaded.
1233 if (FileFormat.Jalview.equals(currentFileFormat))
1235 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1236 for (int i = 0; i < frames.length; i++)
1238 if (frames[i] instanceof AlignFrame && frames[i] != this
1239 && ((AlignFrame) frames[i]).fileName != null
1240 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1244 frames[i].setSelected(true);
1245 Desktop.instance.closeAssociatedWindows();
1246 } catch (java.beans.PropertyVetoException ex)
1252 Desktop.instance.closeAssociatedWindows();
1254 FileLoader loader = new FileLoader();
1255 DataSourceType protocol = fileName.startsWith("http:")
1256 ? DataSourceType.URL
1257 : DataSourceType.FILE;
1258 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1262 Rectangle bounds = this.getBounds();
1264 FileLoader loader = new FileLoader();
1265 DataSourceType protocol = fileName.startsWith("http:")
1266 ? DataSourceType.URL
1267 : DataSourceType.FILE;
1268 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1269 protocol, currentFileFormat);
1271 newframe.setBounds(bounds);
1272 if (featureSettings != null && featureSettings.isShowing())
1274 final Rectangle fspos = featureSettings.frame.getBounds();
1275 // TODO: need a 'show feature settings' function that takes bounds -
1276 // need to refactor Desktop.addFrame
1277 newframe.featureSettings_actionPerformed(null);
1278 final FeatureSettings nfs = newframe.featureSettings;
1279 SwingUtilities.invokeLater(new Runnable()
1284 nfs.frame.setBounds(fspos);
1287 this.featureSettings.close();
1288 this.featureSettings = null;
1290 this.closeMenuItem_actionPerformed(true);
1296 public void addFromText_actionPerformed(ActionEvent e)
1299 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1303 public void addFromURL_actionPerformed(ActionEvent e)
1305 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1309 public void save_actionPerformed(ActionEvent e)
1311 if (fileName == null || (currentFileFormat == null)
1312 || fileName.startsWith("http"))
1314 saveAs_actionPerformed(null);
1318 saveAlignment(fileName, currentFileFormat);
1329 public void saveAs_actionPerformed(ActionEvent e)
1331 String format = currentFileFormat == null ? null
1332 : currentFileFormat.getName();
1333 JalviewFileChooser chooser = JalviewFileChooser
1334 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1336 chooser.setFileView(new JalviewFileView());
1337 chooser.setDialogTitle(
1338 MessageManager.getString("label.save_alignment_to_file"));
1339 chooser.setToolTipText(MessageManager.getString("action.save"));
1341 int value = chooser.showSaveDialog(this);
1343 if (value == JalviewFileChooser.APPROVE_OPTION)
1345 currentFileFormat = chooser.getSelectedFormat();
1346 while (currentFileFormat == null)
1348 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1349 MessageManager.getString(
1350 "label.select_file_format_before_saving"),
1351 MessageManager.getString("label.file_format_not_specified"),
1352 JvOptionPane.WARNING_MESSAGE);
1353 currentFileFormat = chooser.getSelectedFormat();
1354 value = chooser.showSaveDialog(this);
1355 if (value != JalviewFileChooser.APPROVE_OPTION)
1361 fileName = chooser.getSelectedFile().getPath();
1363 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1365 Cache.setProperty("LAST_DIRECTORY", fileName);
1366 saveAlignment(fileName, currentFileFormat);
1370 public boolean saveAlignment(String file, FileFormatI format)
1372 boolean success = true;
1374 if (FileFormat.Jalview.equals(format))
1376 String shortName = title;
1378 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1380 shortName = shortName.substring(
1381 shortName.lastIndexOf(java.io.File.separatorChar) + 1);
1384 success = new Jalview2XML().saveAlignment(this, file, shortName);
1386 statusBar.setText(MessageManager.formatMessage(
1387 "label.successfully_saved_to_file_in_format", new Object[]
1388 { fileName, format }));
1393 AlignmentExportData exportData = getAlignmentForExport(format,
1395 if (exportData.getSettings().isCancelled())
1399 FormatAdapter f = new FormatAdapter(alignPanel,
1400 exportData.getSettings());
1401 String output = f.formatSequences(format, exportData.getAlignment(), // class
1405 // occur in the distant future
1406 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1407 f.getCacheSuffixDefault(format),
1408 viewport.getAlignment().getHiddenColumns());
1418 PrintWriter out = new PrintWriter(new FileWriter(file));
1422 this.setTitle(file);
1423 statusBar.setText(MessageManager.formatMessage(
1424 "label.successfully_saved_to_file_in_format", new Object[]
1425 { fileName, format.getName() }));
1426 } catch (Exception ex)
1429 ex.printStackTrace();
1436 JvOptionPane.showInternalMessageDialog(this, MessageManager
1437 .formatMessage("label.couldnt_save_file", new Object[]
1439 MessageManager.getString("label.error_saving_file"),
1440 JvOptionPane.WARNING_MESSAGE);
1446 private void warningMessage(String warning, String title)
1448 if (new jalview.util.Platform().isHeadless())
1450 System.err.println("Warning: " + title + "\nWarning: " + warning);
1455 JvOptionPane.showInternalMessageDialog(this, warning, title,
1456 JvOptionPane.WARNING_MESSAGE);
1468 protected void outputText_actionPerformed(ActionEvent e)
1470 FileFormatI fileFormat = FileFormats.getInstance()
1471 .forName(e.getActionCommand());
1472 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1474 if (exportData.getSettings().isCancelled())
1478 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1479 cap.setForInput(null);
1482 FileFormatI format = fileFormat;
1483 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1484 .formatSequences(format, exportData.getAlignment(),
1485 exportData.getOmitHidden(),
1486 exportData.getStartEndPostions(),
1487 viewport.getAlignment().getHiddenColumns()));
1488 Desktop.addInternalFrame(cap, MessageManager
1489 .formatMessage("label.alignment_output_command", new Object[]
1490 { e.getActionCommand() }), 600, 500);
1491 } catch (OutOfMemoryError oom)
1493 new OOMWarning("Outputting alignment as " + e.getActionCommand(),
1500 public static AlignmentExportData getAlignmentForExport(
1501 FileFormatI format, AlignViewportI viewport,
1502 AlignExportSettingI exportSettings)
1504 AlignmentI alignmentToExport = null;
1505 AlignExportSettingI settings = exportSettings;
1506 String[] omitHidden = null;
1508 HiddenSequences hiddenSeqs = viewport.getAlignment()
1509 .getHiddenSequences();
1511 alignmentToExport = viewport.getAlignment();
1513 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1514 if (settings == null)
1516 settings = new AlignExportSettings(hasHiddenSeqs,
1517 viewport.hasHiddenColumns(), format);
1519 // settings.isExportAnnotations();
1521 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1523 omitHidden = viewport.getViewAsString(false,
1524 settings.isExportHiddenSequences());
1527 int[] alignmentStartEnd = new int[2];
1528 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1530 alignmentToExport = hiddenSeqs.getFullAlignment();
1534 alignmentToExport = viewport.getAlignment();
1536 alignmentStartEnd = viewport.getAlignment().getHiddenColumns()
1537 .getVisibleStartAndEndIndex(alignmentToExport.getWidth());
1538 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1539 omitHidden, alignmentStartEnd, settings);
1550 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1552 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1553 htmlSVG.exportHTML(null);
1557 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1559 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1560 bjs.exportHTML(null);
1563 public void createImageMap(File file, String image)
1565 alignPanel.makePNGImageMap(file, image);
1575 public void createPNG(File f)
1577 alignPanel.makePNG(f);
1587 public void createEPS(File f)
1589 alignPanel.makeEPS(f);
1593 public void createSVG(File f)
1595 alignPanel.makeSVG(f);
1599 public void pageSetup_actionPerformed(ActionEvent e)
1601 PrinterJob printJob = PrinterJob.getPrinterJob();
1602 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1612 public void printMenuItem_actionPerformed(ActionEvent e)
1614 // Putting in a thread avoids Swing painting problems
1615 PrintThread thread = new PrintThread(alignPanel);
1620 public void exportFeatures_actionPerformed(ActionEvent e)
1622 new AnnotationExporter().exportFeatures(alignPanel);
1626 public void exportAnnotations_actionPerformed(ActionEvent e)
1628 new AnnotationExporter().exportAnnotations(alignPanel);
1632 public void associatedData_actionPerformed(ActionEvent e)
1633 throws IOException, InterruptedException
1635 // Pick the tree file
1636 JalviewFileChooser chooser = new JalviewFileChooser(
1637 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1638 chooser.setFileView(new JalviewFileView());
1639 chooser.setDialogTitle(
1640 MessageManager.getString("label.load_jalview_annotations"));
1641 chooser.setToolTipText(
1642 MessageManager.getString("label.load_jalview_annotations"));
1644 int value = chooser.showOpenDialog(null);
1646 if (value == JalviewFileChooser.APPROVE_OPTION)
1648 String choice = chooser.getSelectedFile().getPath();
1649 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1650 loadJalviewDataFile(choice, null, null, null);
1656 * Close the current view or all views in the alignment frame. If the frame
1657 * only contains one view then the alignment will be removed from memory.
1659 * @param closeAllTabs
1662 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1664 if (alignPanels != null && alignPanels.size() < 2)
1666 closeAllTabs = true;
1671 if (alignPanels != null)
1675 if (this.isClosed())
1677 // really close all the windows - otherwise wait till
1678 // setClosed(true) is called
1679 for (int i = 0; i < alignPanels.size(); i++)
1681 AlignmentPanel ap = alignPanels.get(i);
1688 closeView(alignPanel);
1695 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1696 * be called recursively, with the frame now in 'closed' state
1698 this.setClosed(true);
1700 } catch (Exception ex)
1702 ex.printStackTrace();
1707 * Close the specified panel and close up tabs appropriately.
1709 * @param panelToClose
1711 public void closeView(AlignmentPanel panelToClose)
1713 int index = tabbedPane.getSelectedIndex();
1714 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1715 alignPanels.remove(panelToClose);
1716 panelToClose.closePanel();
1717 panelToClose = null;
1719 tabbedPane.removeTabAt(closedindex);
1720 tabbedPane.validate();
1722 if (index > closedindex || index == tabbedPane.getTabCount())
1724 // modify currently selected tab index if necessary.
1728 this.tabSelectionChanged(index);
1734 void updateEditMenuBar()
1737 if (viewport.getHistoryList().size() > 0)
1739 undoMenuItem.setEnabled(true);
1740 CommandI command = viewport.getHistoryList().peek();
1741 undoMenuItem.setText(MessageManager
1742 .formatMessage("label.undo_command", new Object[]
1743 { command.getDescription() }));
1747 undoMenuItem.setEnabled(false);
1748 undoMenuItem.setText(MessageManager.getString("action.undo"));
1751 if (viewport.getRedoList().size() > 0)
1753 redoMenuItem.setEnabled(true);
1755 CommandI command = viewport.getRedoList().peek();
1756 redoMenuItem.setText(MessageManager
1757 .formatMessage("label.redo_command", new Object[]
1758 { command.getDescription() }));
1762 redoMenuItem.setEnabled(false);
1763 redoMenuItem.setText(MessageManager.getString("action.redo"));
1768 public void addHistoryItem(CommandI command)
1770 if (command.getSize() > 0)
1772 viewport.addToHistoryList(command);
1773 viewport.clearRedoList();
1774 updateEditMenuBar();
1775 viewport.updateHiddenColumns();
1776 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1777 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1778 // viewport.getColumnSelection()
1779 // .getHiddenColumns().size() > 0);
1785 * @return alignment objects for all views
1787 AlignmentI[] getViewAlignments()
1789 if (alignPanels != null)
1791 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1793 for (AlignmentPanel ap : alignPanels)
1795 als[i++] = ap.av.getAlignment();
1799 if (viewport != null)
1801 return new AlignmentI[] { viewport.getAlignment() };
1813 protected void undoMenuItem_actionPerformed(ActionEvent e)
1815 if (viewport.getHistoryList().isEmpty())
1819 CommandI command = viewport.getHistoryList().pop();
1820 viewport.addToRedoList(command);
1821 command.undoCommand(getViewAlignments());
1823 AlignmentViewport originalSource = getOriginatingSource(command);
1824 updateEditMenuBar();
1826 if (originalSource != null)
1828 if (originalSource != viewport)
1831 "Implementation worry: mismatch of viewport origin for undo");
1833 originalSource.updateHiddenColumns();
1834 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1836 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1837 // viewport.getColumnSelection()
1838 // .getHiddenColumns().size() > 0);
1839 originalSource.firePropertyChange("alignment", null,
1840 originalSource.getAlignment().getSequences());
1851 protected void redoMenuItem_actionPerformed(ActionEvent e)
1853 if (viewport.getRedoList().size() < 1)
1858 CommandI command = viewport.getRedoList().pop();
1859 viewport.addToHistoryList(command);
1860 command.doCommand(getViewAlignments());
1862 AlignmentViewport originalSource = getOriginatingSource(command);
1863 updateEditMenuBar();
1865 if (originalSource != null)
1868 if (originalSource != viewport)
1871 "Implementation worry: mismatch of viewport origin for redo");
1873 originalSource.updateHiddenColumns();
1874 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1876 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1877 // viewport.getColumnSelection()
1878 // .getHiddenColumns().size() > 0);
1879 originalSource.firePropertyChange("alignment", null,
1880 originalSource.getAlignment().getSequences());
1884 AlignmentViewport getOriginatingSource(CommandI command)
1886 AlignmentViewport originalSource = null;
1887 // For sequence removal and addition, we need to fire
1888 // the property change event FROM the viewport where the
1889 // original alignment was altered
1890 AlignmentI al = null;
1891 if (command instanceof EditCommand)
1893 EditCommand editCommand = (EditCommand) command;
1894 al = editCommand.getAlignment();
1895 List<Component> comps = PaintRefresher.components
1896 .get(viewport.getSequenceSetId());
1898 for (Component comp : comps)
1900 if (comp instanceof AlignmentPanel)
1902 if (al == ((AlignmentPanel) comp).av.getAlignment())
1904 originalSource = ((AlignmentPanel) comp).av;
1911 if (originalSource == null)
1913 // The original view is closed, we must validate
1914 // the current view against the closed view first
1917 PaintRefresher.validateSequences(al, viewport.getAlignment());
1920 originalSource = viewport;
1923 return originalSource;
1932 public void moveSelectedSequences(boolean up)
1934 SequenceGroup sg = viewport.getSelectionGroup();
1940 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1941 viewport.getHiddenRepSequences(), up);
1942 alignPanel.paintAlignment(true);
1945 synchronized void slideSequences(boolean right, int size)
1947 List<SequenceI> sg = new ArrayList<>();
1948 if (viewport.cursorMode)
1950 sg.add(viewport.getAlignment()
1951 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1953 else if (viewport.getSelectionGroup() != null
1954 && viewport.getSelectionGroup().getSize() != viewport
1955 .getAlignment().getHeight())
1957 sg = viewport.getSelectionGroup()
1958 .getSequences(viewport.getHiddenRepSequences());
1966 List<SequenceI> invertGroup = new ArrayList<>();
1968 for (SequenceI seq : viewport.getAlignment().getSequences())
1970 if (!sg.contains(seq))
1972 invertGroup.add(seq);
1976 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1978 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1979 for (int i = 0; i < invertGroup.size(); i++)
1981 seqs2[i] = invertGroup.get(i);
1984 SlideSequencesCommand ssc;
1987 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1988 viewport.getGapCharacter());
1992 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1993 viewport.getGapCharacter());
1996 int groupAdjustment = 0;
1997 if (ssc.getGapsInsertedBegin() && right)
1999 if (viewport.cursorMode)
2001 alignPanel.getSeqPanel().moveCursor(size, 0);
2005 groupAdjustment = size;
2008 else if (!ssc.getGapsInsertedBegin() && !right)
2010 if (viewport.cursorMode)
2012 alignPanel.getSeqPanel().moveCursor(-size, 0);
2016 groupAdjustment = -size;
2020 if (groupAdjustment != 0)
2022 viewport.getSelectionGroup().setStartRes(
2023 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
2024 viewport.getSelectionGroup().setEndRes(
2025 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
2029 * just extend the last slide command if compatible; but not if in
2030 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
2032 boolean appendHistoryItem = false;
2033 Deque<CommandI> historyList = viewport.getHistoryList();
2034 boolean inSplitFrame = getSplitViewContainer() != null;
2035 if (!inSplitFrame && historyList != null && historyList.size() > 0
2036 && historyList.peek() instanceof SlideSequencesCommand)
2038 appendHistoryItem = ssc.appendSlideCommand(
2039 (SlideSequencesCommand) historyList.peek());
2042 if (!appendHistoryItem)
2044 addHistoryItem(ssc);
2057 protected void copy_actionPerformed(ActionEvent e)
2060 if (viewport.getSelectionGroup() == null)
2064 // TODO: preserve the ordering of displayed alignment annotation in any
2065 // internal paste (particularly sequence associated annotation)
2066 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2067 String[] omitHidden = null;
2069 if (viewport.hasHiddenColumns())
2071 omitHidden = viewport.getViewAsString(true);
2074 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2075 seqs, omitHidden, null);
2077 StringSelection ss = new StringSelection(output);
2081 jalview.gui.Desktop.internalCopy = true;
2082 // Its really worth setting the clipboard contents
2083 // to empty before setting the large StringSelection!!
2084 Toolkit.getDefaultToolkit().getSystemClipboard()
2085 .setContents(new StringSelection(""), null);
2087 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2089 } catch (OutOfMemoryError er)
2091 new OOMWarning("copying region", er);
2095 ArrayList<int[]> hiddenColumns = null;
2096 if (viewport.hasHiddenColumns())
2098 hiddenColumns = new ArrayList<>();
2100 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2101 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2102 ArrayList<int[]> hiddenRegions = viewport.getAlignment()
2103 .getHiddenColumns().getHiddenColumnsCopy();
2104 for (int[] region : hiddenRegions)
2107 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
2111 { region[0] - hiddenOffset, region[1] - hiddenOffset });
2116 Desktop.jalviewClipboard = new Object[] { seqs,
2117 viewport.getAlignment().getDataset(), hiddenColumns };
2118 statusBar.setText(MessageManager.formatMessage(
2119 "label.copied_sequences_to_clipboard", new Object[]
2120 { Integer.valueOf(seqs.length).toString() }));
2128 * @throws InterruptedException
2129 * @throws IOException
2132 protected void pasteNew_actionPerformed(ActionEvent e)
2133 throws IOException, InterruptedException
2143 * @throws InterruptedException
2144 * @throws IOException
2147 protected void pasteThis_actionPerformed(ActionEvent e)
2148 throws IOException, InterruptedException
2154 * Paste contents of Jalview clipboard
2156 * @param newAlignment
2157 * true to paste to a new alignment, otherwise add to this.
2158 * @throws InterruptedException
2159 * @throws IOException
2161 void paste(boolean newAlignment) throws IOException, InterruptedException
2163 boolean externalPaste = true;
2166 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2167 Transferable contents = c.getContents(this);
2169 if (contents == null)
2178 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2179 if (str.length() < 1)
2184 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2186 } catch (OutOfMemoryError er)
2188 new OOMWarning("Out of memory pasting sequences!!", er);
2192 SequenceI[] sequences;
2193 boolean annotationAdded = false;
2194 AlignmentI alignment = null;
2196 if (Desktop.jalviewClipboard != null)
2198 // The clipboard was filled from within Jalview, we must use the
2200 // And dataset from the copied alignment
2201 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2202 // be doubly sure that we create *new* sequence objects.
2203 sequences = new SequenceI[newseq.length];
2204 for (int i = 0; i < newseq.length; i++)
2206 sequences[i] = new Sequence(newseq[i]);
2208 alignment = new Alignment(sequences);
2209 externalPaste = false;
2213 // parse the clipboard as an alignment.
2214 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2216 sequences = alignment.getSequencesArray();
2220 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2226 if (Desktop.jalviewClipboard != null)
2228 // dataset is inherited
2229 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2233 // new dataset is constructed
2234 alignment.setDataset(null);
2236 alwidth = alignment.getWidth() + 1;
2240 AlignmentI pastedal = alignment; // preserve pasted alignment object
2241 // Add pasted sequences and dataset into existing alignment.
2242 alignment = viewport.getAlignment();
2243 alwidth = alignment.getWidth() + 1;
2244 // decide if we need to import sequences from an existing dataset
2245 boolean importDs = Desktop.jalviewClipboard != null
2246 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2247 // importDs==true instructs us to copy over new dataset sequences from
2248 // an existing alignment
2249 Vector newDs = (importDs) ? new Vector() : null; // used to create
2250 // minimum dataset set
2252 for (int i = 0; i < sequences.length; i++)
2256 newDs.addElement(null);
2258 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2260 if (importDs && ds != null)
2262 if (!newDs.contains(ds))
2264 newDs.setElementAt(ds, i);
2265 ds = new Sequence(ds);
2266 // update with new dataset sequence
2267 sequences[i].setDatasetSequence(ds);
2271 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2276 // copy and derive new dataset sequence
2277 sequences[i] = sequences[i].deriveSequence();
2278 alignment.getDataset()
2279 .addSequence(sequences[i].getDatasetSequence());
2280 // TODO: avoid creation of duplicate dataset sequences with a
2281 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2283 alignment.addSequence(sequences[i]); // merges dataset
2287 newDs.clear(); // tidy up
2289 if (alignment.getAlignmentAnnotation() != null)
2291 for (AlignmentAnnotation alan : alignment
2292 .getAlignmentAnnotation())
2294 if (alan.graphGroup > fgroup)
2296 fgroup = alan.graphGroup;
2300 if (pastedal.getAlignmentAnnotation() != null)
2302 // Add any annotation attached to alignment.
2303 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2304 for (int i = 0; i < alann.length; i++)
2306 annotationAdded = true;
2307 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2309 AlignmentAnnotation newann = new AlignmentAnnotation(
2311 if (newann.graphGroup > -1)
2313 if (newGraphGroups.size() <= newann.graphGroup
2314 || newGraphGroups.get(newann.graphGroup) == null)
2316 for (int q = newGraphGroups
2317 .size(); q <= newann.graphGroup; q++)
2319 newGraphGroups.add(q, null);
2321 newGraphGroups.set(newann.graphGroup,
2322 new Integer(++fgroup));
2324 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2328 newann.padAnnotation(alwidth);
2329 alignment.addAnnotation(newann);
2339 addHistoryItem(new EditCommand(
2340 MessageManager.getString("label.add_sequences"),
2341 Action.PASTE, sequences, 0, alignment.getWidth(),
2344 // Add any annotations attached to sequences
2345 for (int i = 0; i < sequences.length; i++)
2347 if (sequences[i].getAnnotation() != null)
2349 AlignmentAnnotation newann;
2350 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2352 annotationAdded = true;
2353 newann = sequences[i].getAnnotation()[a];
2354 newann.adjustForAlignment();
2355 newann.padAnnotation(alwidth);
2356 if (newann.graphGroup > -1)
2358 if (newann.graphGroup > -1)
2360 if (newGraphGroups.size() <= newann.graphGroup
2361 || newGraphGroups.get(newann.graphGroup) == null)
2363 for (int q = newGraphGroups
2364 .size(); q <= newann.graphGroup; q++)
2366 newGraphGroups.add(q, null);
2368 newGraphGroups.set(newann.graphGroup,
2369 new Integer(++fgroup));
2371 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2375 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2379 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2387 // propagate alignment changed.
2388 vpRanges.setEndSeq(alignment.getHeight());
2389 if (annotationAdded)
2391 // Duplicate sequence annotation in all views.
2392 AlignmentI[] alview = this.getViewAlignments();
2393 for (int i = 0; i < sequences.length; i++)
2395 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2400 for (int avnum = 0; avnum < alview.length; avnum++)
2402 if (alview[avnum] != alignment)
2404 // duplicate in a view other than the one with input focus
2405 int avwidth = alview[avnum].getWidth() + 1;
2406 // this relies on sann being preserved after we
2407 // modify the sequence's annotation array for each duplication
2408 for (int a = 0; a < sann.length; a++)
2410 AlignmentAnnotation newann = new AlignmentAnnotation(
2412 sequences[i].addAlignmentAnnotation(newann);
2413 newann.padAnnotation(avwidth);
2414 alview[avnum].addAnnotation(newann); // annotation was
2415 // duplicated earlier
2416 // TODO JAL-1145 graphGroups are not updated for sequence
2417 // annotation added to several views. This may cause
2419 alview[avnum].setAnnotationIndex(newann, a);
2424 buildSortByAnnotationScoresMenu();
2426 viewport.firePropertyChange("alignment", null,
2427 alignment.getSequences());
2428 if (alignPanels != null)
2430 for (AlignmentPanel ap : alignPanels)
2432 ap.validateAnnotationDimensions(false);
2437 alignPanel.validateAnnotationDimensions(false);
2443 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2445 String newtitle = new String("Copied sequences");
2447 if (Desktop.jalviewClipboard != null
2448 && Desktop.jalviewClipboard[2] != null)
2450 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2451 for (int[] region : hc)
2453 af.viewport.hideColumns(region[0], region[1]);
2457 // >>>This is a fix for the moment, until a better solution is
2459 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2460 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2461 .getFeatureRenderer());
2463 // TODO: maintain provenance of an alignment, rather than just make the
2464 // title a concatenation of operations.
2467 if (title.startsWith("Copied sequences"))
2473 newtitle = newtitle.concat("- from " + title);
2478 newtitle = new String("Pasted sequences");
2481 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2486 } catch (Exception ex)
2488 ex.printStackTrace();
2489 System.out.println("Exception whilst pasting: " + ex);
2490 // could be anything being pasted in here
2495 protected void expand_newalign(ActionEvent e)
2499 AlignmentI alignment = AlignmentUtils
2500 .expandContext(getViewport().getAlignment(), -1);
2501 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2503 String newtitle = new String("Flanking alignment");
2505 if (Desktop.jalviewClipboard != null
2506 && Desktop.jalviewClipboard[2] != null)
2508 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2509 for (int region[] : hc)
2511 af.viewport.hideColumns(region[0], region[1]);
2515 // >>>This is a fix for the moment, until a better solution is
2517 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2518 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2519 .getFeatureRenderer());
2521 // TODO: maintain provenance of an alignment, rather than just make the
2522 // title a concatenation of operations.
2524 if (title.startsWith("Copied sequences"))
2530 newtitle = newtitle.concat("- from " + title);
2534 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2536 } catch (Exception ex)
2538 ex.printStackTrace();
2539 System.out.println("Exception whilst pasting: " + ex);
2540 // could be anything being pasted in here
2541 } catch (OutOfMemoryError oom)
2543 new OOMWarning("Viewing flanking region of alignment", oom);
2554 protected void cut_actionPerformed(ActionEvent e)
2556 copy_actionPerformed(null);
2557 delete_actionPerformed(null);
2567 protected void delete_actionPerformed(ActionEvent evt)
2570 SequenceGroup sg = viewport.getSelectionGroup();
2577 * If the cut affects all sequences, warn, remove highlighted columns
2579 if (sg.getSize() == viewport.getAlignment().getHeight())
2581 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2582 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2583 if (isEntireAlignWidth)
2585 int confirm = JvOptionPane.showConfirmDialog(this,
2586 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2587 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2588 JvOptionPane.OK_CANCEL_OPTION);
2590 if (confirm == JvOptionPane.CANCEL_OPTION
2591 || confirm == JvOptionPane.CLOSED_OPTION)
2596 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2597 sg.getEndRes() + 1);
2599 SequenceI[] cut = sg.getSequences()
2600 .toArray(new SequenceI[sg.getSize()]);
2602 addHistoryItem(new EditCommand(
2603 MessageManager.getString("label.cut_sequences"), Action.CUT,
2604 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2605 viewport.getAlignment()));
2607 viewport.setSelectionGroup(null);
2608 viewport.sendSelection();
2609 viewport.getAlignment().deleteGroup(sg);
2611 viewport.firePropertyChange("alignment", null,
2612 viewport.getAlignment().getSequences());
2613 if (viewport.getAlignment().getHeight() < 1)
2617 this.setClosed(true);
2618 } catch (Exception ex)
2631 protected void deleteGroups_actionPerformed(ActionEvent e)
2633 if (avc.deleteGroups())
2635 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2636 alignPanel.updateAnnotation();
2637 alignPanel.paintAlignment(true);
2648 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2650 SequenceGroup sg = new SequenceGroup();
2652 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2654 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2657 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2658 viewport.setSelectionGroup(sg);
2659 viewport.sendSelection();
2660 // JAL-2034 - should delegate to
2661 // alignPanel to decide if overview needs
2663 alignPanel.paintAlignment(false);
2664 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2674 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2676 if (viewport.cursorMode)
2678 alignPanel.getSeqPanel().keyboardNo1 = null;
2679 alignPanel.getSeqPanel().keyboardNo2 = null;
2681 viewport.setSelectionGroup(null);
2682 viewport.getColumnSelection().clear();
2683 viewport.setSelectionGroup(null);
2684 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2685 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2686 // JAL-2034 - should delegate to
2687 // alignPanel to decide if overview needs
2689 alignPanel.paintAlignment(false);
2690 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2691 viewport.sendSelection();
2701 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2703 SequenceGroup sg = viewport.getSelectionGroup();
2707 selectAllSequenceMenuItem_actionPerformed(null);
2712 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2714 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2716 // JAL-2034 - should delegate to
2717 // alignPanel to decide if overview needs
2720 alignPanel.paintAlignment(true);
2721 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2722 viewport.sendSelection();
2726 public void invertColSel_actionPerformed(ActionEvent e)
2728 viewport.invertColumnSelection();
2729 alignPanel.paintAlignment(true);
2730 viewport.sendSelection();
2740 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2742 trimAlignment(true);
2752 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2754 trimAlignment(false);
2757 void trimAlignment(boolean trimLeft)
2759 ColumnSelection colSel = viewport.getColumnSelection();
2762 if (!colSel.isEmpty())
2766 column = colSel.getMin();
2770 column = colSel.getMax();
2774 if (viewport.getSelectionGroup() != null)
2776 seqs = viewport.getSelectionGroup()
2777 .getSequencesAsArray(viewport.getHiddenRepSequences());
2781 seqs = viewport.getAlignment().getSequencesArray();
2784 TrimRegionCommand trimRegion;
2787 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2788 column, viewport.getAlignment());
2789 vpRanges.setStartRes(0);
2793 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2794 column, viewport.getAlignment());
2797 statusBar.setText(MessageManager
2798 .formatMessage("label.removed_columns", new String[]
2799 { Integer.valueOf(trimRegion.getSize()).toString() }));
2801 addHistoryItem(trimRegion);
2803 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2805 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2806 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2808 viewport.getAlignment().deleteGroup(sg);
2812 viewport.firePropertyChange("alignment", null,
2813 viewport.getAlignment().getSequences());
2824 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2826 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2829 if (viewport.getSelectionGroup() != null)
2831 seqs = viewport.getSelectionGroup()
2832 .getSequencesAsArray(viewport.getHiddenRepSequences());
2833 start = viewport.getSelectionGroup().getStartRes();
2834 end = viewport.getSelectionGroup().getEndRes();
2838 seqs = viewport.getAlignment().getSequencesArray();
2841 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2842 "Remove Gapped Columns", seqs, start, end,
2843 viewport.getAlignment());
2845 addHistoryItem(removeGapCols);
2847 statusBar.setText(MessageManager
2848 .formatMessage("label.removed_empty_columns", new Object[]
2849 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2851 // This is to maintain viewport position on first residue
2852 // of first sequence
2853 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2854 int startRes = seq.findPosition(vpRanges.getStartRes());
2855 // ShiftList shifts;
2856 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2857 // edit.alColumnChanges=shifts.getInverse();
2858 // if (viewport.hasHiddenColumns)
2859 // viewport.getColumnSelection().compensateForEdits(shifts);
2860 vpRanges.setStartRes(seq.findIndex(startRes) - 1);
2861 viewport.firePropertyChange("alignment", null,
2862 viewport.getAlignment().getSequences());
2873 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2875 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2878 if (viewport.getSelectionGroup() != null)
2880 seqs = viewport.getSelectionGroup()
2881 .getSequencesAsArray(viewport.getHiddenRepSequences());
2882 start = viewport.getSelectionGroup().getStartRes();
2883 end = viewport.getSelectionGroup().getEndRes();
2887 seqs = viewport.getAlignment().getSequencesArray();
2890 // This is to maintain viewport position on first residue
2891 // of first sequence
2892 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2893 int startRes = seq.findPosition(vpRanges.getStartRes());
2895 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2896 viewport.getAlignment()));
2898 vpRanges.setStartRes(seq.findIndex(startRes) - 1);
2900 viewport.firePropertyChange("alignment", null,
2901 viewport.getAlignment().getSequences());
2912 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2914 viewport.setPadGaps(padGapsMenuitem.isSelected());
2915 viewport.firePropertyChange("alignment", null,
2916 viewport.getAlignment().getSequences());
2926 public void findMenuItem_actionPerformed(ActionEvent e)
2932 * Create a new view of the current alignment.
2935 public void newView_actionPerformed(ActionEvent e)
2937 newView(null, true);
2941 * Creates and shows a new view of the current alignment.
2944 * title of newly created view; if null, one will be generated
2945 * @param copyAnnotation
2946 * if true then duplicate all annnotation, groups and settings
2947 * @return new alignment panel, already displayed.
2949 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2952 * Create a new AlignmentPanel (with its own, new Viewport)
2954 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2956 if (!copyAnnotation)
2959 * remove all groups and annotation except for the automatic stuff
2961 newap.av.getAlignment().deleteAllGroups();
2962 newap.av.getAlignment().deleteAllAnnotations(false);
2965 newap.av.setGatherViewsHere(false);
2967 if (viewport.viewName == null)
2969 viewport.viewName = MessageManager
2970 .getString("label.view_name_original");
2974 * Views share the same edits undo and redo stacks
2976 newap.av.setHistoryList(viewport.getHistoryList());
2977 newap.av.setRedoList(viewport.getRedoList());
2980 * Views share the same mappings; need to deregister any new mappings
2981 * created by copyAlignPanel, and register the new reference to the shared
2984 newap.av.replaceMappings(viewport.getAlignment());
2987 * start up cDNA consensus (if applicable) now mappings are in place
2989 if (newap.av.initComplementConsensus())
2991 newap.refresh(true); // adjust layout of annotations
2994 newap.av.viewName = getNewViewName(viewTitle);
2996 addAlignmentPanel(newap, true);
2997 newap.alignmentChanged();
2999 if (alignPanels.size() == 2)
3001 viewport.setGatherViewsHere(true);
3003 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
3008 * Make a new name for the view, ensuring it is unique within the current
3009 * sequenceSetId. (This used to be essential for Jalview Project archives, but
3010 * these now use viewId. Unique view names are still desirable for usability.)
3015 protected String getNewViewName(String viewTitle)
3017 int index = Desktop.getViewCount(viewport.getSequenceSetId());
3018 boolean addFirstIndex = false;
3019 if (viewTitle == null || viewTitle.trim().length() == 0)
3021 viewTitle = MessageManager.getString("action.view");
3022 addFirstIndex = true;
3026 index = 1;// we count from 1 if given a specific name
3028 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
3030 List<Component> comps = PaintRefresher.components
3031 .get(viewport.getSequenceSetId());
3033 List<String> existingNames = getExistingViewNames(comps);
3035 while (existingNames.contains(newViewName))
3037 newViewName = viewTitle + " " + (++index);
3043 * Returns a list of distinct view names found in the given list of
3044 * components. View names are held on the viewport of an AlignmentPanel.
3049 protected List<String> getExistingViewNames(List<Component> comps)
3051 List<String> existingNames = new ArrayList<>();
3052 for (Component comp : comps)
3054 if (comp instanceof AlignmentPanel)
3056 AlignmentPanel ap = (AlignmentPanel) comp;
3057 if (!existingNames.contains(ap.av.viewName))
3059 existingNames.add(ap.av.viewName);
3063 return existingNames;
3067 * Explode tabbed views into separate windows.
3070 public void expandViews_actionPerformed(ActionEvent e)
3072 Desktop.explodeViews(this);
3076 * Gather views in separate windows back into a tabbed presentation.
3079 public void gatherViews_actionPerformed(ActionEvent e)
3081 Desktop.instance.gatherViews(this);
3091 public void font_actionPerformed(ActionEvent e)
3093 new FontChooser(alignPanel);
3103 protected void seqLimit_actionPerformed(ActionEvent e)
3105 viewport.setShowJVSuffix(seqLimits.isSelected());
3107 alignPanel.getIdPanel().getIdCanvas()
3108 .setPreferredSize(alignPanel.calculateIdWidth());
3109 alignPanel.paintAlignment(true);
3113 public void idRightAlign_actionPerformed(ActionEvent e)
3115 viewport.setRightAlignIds(idRightAlign.isSelected());
3116 alignPanel.paintAlignment(true);
3120 public void centreColumnLabels_actionPerformed(ActionEvent e)
3122 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3123 alignPanel.paintAlignment(true);
3129 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3132 protected void followHighlight_actionPerformed()
3135 * Set the 'follow' flag on the Viewport (and scroll to position if now
3138 final boolean state = this.followHighlightMenuItem.getState();
3139 viewport.setFollowHighlight(state);
3142 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
3153 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3155 viewport.setColourText(colourTextMenuItem.isSelected());
3156 alignPanel.paintAlignment(true);
3166 public void wrapMenuItem_actionPerformed(ActionEvent e)
3168 scaleAbove.setVisible(wrapMenuItem.isSelected());
3169 scaleLeft.setVisible(wrapMenuItem.isSelected());
3170 scaleRight.setVisible(wrapMenuItem.isSelected());
3171 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3172 alignPanel.updateLayout();
3176 public void showAllSeqs_actionPerformed(ActionEvent e)
3178 viewport.showAllHiddenSeqs();
3182 public void showAllColumns_actionPerformed(ActionEvent e)
3184 viewport.showAllHiddenColumns();
3185 alignPanel.paintAlignment(true);
3186 viewport.sendSelection();
3190 public void hideSelSequences_actionPerformed(ActionEvent e)
3192 viewport.hideAllSelectedSeqs();
3196 * called by key handler and the hide all/show all menu items
3201 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3204 boolean hide = false;
3205 SequenceGroup sg = viewport.getSelectionGroup();
3206 if (!toggleSeqs && !toggleCols)
3208 // Hide everything by the current selection - this is a hack - we do the
3209 // invert and then hide
3210 // first check that there will be visible columns after the invert.
3211 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3212 && sg.getStartRes() <= sg.getEndRes()))
3214 // now invert the sequence set, if required - empty selection implies
3215 // that no hiding is required.
3218 invertSequenceMenuItem_actionPerformed(null);
3219 sg = viewport.getSelectionGroup();
3223 viewport.expandColSelection(sg, true);
3224 // finally invert the column selection and get the new sequence
3226 invertColSel_actionPerformed(null);
3233 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3235 hideSelSequences_actionPerformed(null);
3238 else if (!(toggleCols && viewport.hasSelectedColumns()))
3240 showAllSeqs_actionPerformed(null);
3246 if (viewport.hasSelectedColumns())
3248 hideSelColumns_actionPerformed(null);
3251 viewport.setSelectionGroup(sg);
3256 showAllColumns_actionPerformed(null);
3265 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3266 * event.ActionEvent)
3269 public void hideAllButSelection_actionPerformed(ActionEvent e)
3271 toggleHiddenRegions(false, false);
3272 viewport.sendSelection();
3279 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3283 public void hideAllSelection_actionPerformed(ActionEvent e)
3285 SequenceGroup sg = viewport.getSelectionGroup();
3286 viewport.expandColSelection(sg, false);
3287 viewport.hideAllSelectedSeqs();
3288 viewport.hideSelectedColumns();
3289 alignPanel.paintAlignment(true);
3290 viewport.sendSelection();
3297 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3301 public void showAllhidden_actionPerformed(ActionEvent e)
3303 viewport.showAllHiddenColumns();
3304 viewport.showAllHiddenSeqs();
3305 alignPanel.paintAlignment(true);
3306 viewport.sendSelection();
3310 public void hideSelColumns_actionPerformed(ActionEvent e)
3312 viewport.hideSelectedColumns();
3313 alignPanel.paintAlignment(true);
3314 viewport.sendSelection();
3318 public void hiddenMarkers_actionPerformed(ActionEvent e)
3320 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3331 protected void scaleAbove_actionPerformed(ActionEvent e)
3333 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3334 alignPanel.paintAlignment(true);
3344 protected void scaleLeft_actionPerformed(ActionEvent e)
3346 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3347 alignPanel.paintAlignment(true);
3357 protected void scaleRight_actionPerformed(ActionEvent e)
3359 viewport.setScaleRightWrapped(scaleRight.isSelected());
3360 alignPanel.paintAlignment(true);
3370 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3372 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3373 alignPanel.paintAlignment(true);
3383 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3385 viewport.setShowText(viewTextMenuItem.isSelected());
3386 alignPanel.paintAlignment(true);
3396 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3398 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3399 alignPanel.paintAlignment(true);
3402 public FeatureSettings featureSettings;
3405 public FeatureSettingsControllerI getFeatureSettingsUI()
3407 return featureSettings;
3411 public void featureSettings_actionPerformed(ActionEvent e)
3413 if (featureSettings != null)
3415 featureSettings.close();
3416 featureSettings = null;
3418 if (!showSeqFeatures.isSelected())
3420 // make sure features are actually displayed
3421 showSeqFeatures.setSelected(true);
3422 showSeqFeatures_actionPerformed(null);
3424 featureSettings = new FeatureSettings(this);
3428 * Set or clear 'Show Sequence Features'
3434 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3436 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3437 alignPanel.paintAlignment(true);
3441 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3442 * the annotations panel as a whole.
3444 * The options to show/hide all annotations should be enabled when the panel
3445 * is shown, and disabled when the panel is hidden.
3450 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3452 final boolean setVisible = annotationPanelMenuItem.isSelected();
3453 viewport.setShowAnnotation(setVisible);
3454 this.showAllSeqAnnotations.setEnabled(setVisible);
3455 this.hideAllSeqAnnotations.setEnabled(setVisible);
3456 this.showAllAlAnnotations.setEnabled(setVisible);
3457 this.hideAllAlAnnotations.setEnabled(setVisible);
3458 alignPanel.updateLayout();
3462 public void alignmentProperties()
3464 JEditorPane editPane = new JEditorPane("text/html", "");
3465 editPane.setEditable(false);
3466 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3469 MessageManager.formatMessage("label.html_content", new Object[]
3470 { contents.toString() }));
3471 JInternalFrame frame = new JInternalFrame();
3472 frame.getContentPane().add(new JScrollPane(editPane));
3474 Desktop.addInternalFrame(frame, MessageManager
3475 .formatMessage("label.alignment_properties", new Object[]
3476 { getTitle() }), 500, 400);
3486 public void overviewMenuItem_actionPerformed(ActionEvent e)
3488 if (alignPanel.overviewPanel != null)
3493 JInternalFrame frame = new JInternalFrame();
3494 final OverviewPanel overview = new OverviewPanel(alignPanel);
3495 frame.setContentPane(overview);
3496 Desktop.addInternalFrame(frame, MessageManager
3497 .formatMessage("label.overview_params", new Object[]
3498 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3501 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3502 frame.addInternalFrameListener(
3503 new javax.swing.event.InternalFrameAdapter()
3506 public void internalFrameClosed(
3507 javax.swing.event.InternalFrameEvent evt)
3510 alignPanel.setOverviewPanel(null);
3514 alignPanel.setOverviewPanel(overview);
3518 public void textColour_actionPerformed()
3520 new TextColourChooser().chooseColour(alignPanel, null);
3524 * public void covariationColour_actionPerformed() {
3526 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3530 public void annotationColour_actionPerformed()
3532 new AnnotationColourChooser(viewport, alignPanel);
3536 public void annotationColumn_actionPerformed(ActionEvent e)
3538 new AnnotationColumnChooser(viewport, alignPanel);
3542 * Action on the user checking or unchecking the option to apply the selected
3543 * colour scheme to all groups. If unchecked, groups may have their own
3544 * independent colour schemes.
3549 public void applyToAllGroups_actionPerformed(boolean selected)
3551 viewport.setColourAppliesToAllGroups(selected);
3555 * Action on user selecting a colour from the colour menu
3558 * the name (not the menu item label!) of the colour scheme
3561 public void changeColour_actionPerformed(String name)
3564 * 'User Defined' opens a panel to configure or load a
3565 * user-defined colour scheme
3567 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3569 new UserDefinedColours(alignPanel);
3574 * otherwise set the chosen colour scheme (or null for 'None')
3576 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3577 viewport.getAlignment(), viewport.getHiddenRepSequences());
3582 * Actions on setting or changing the alignment colour scheme
3587 public void changeColour(ColourSchemeI cs)
3589 // TODO: pull up to controller method
3590 ColourMenuHelper.setColourSelected(colourMenu, cs);
3592 viewport.setGlobalColourScheme(cs);
3594 alignPanel.paintAlignment(true);
3598 * Show the PID threshold slider panel
3601 protected void modifyPID_actionPerformed()
3603 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3604 alignPanel.getViewName());
3605 SliderPanel.showPIDSlider();
3609 * Show the Conservation slider panel
3612 protected void modifyConservation_actionPerformed()
3614 SliderPanel.setConservationSlider(alignPanel,
3615 viewport.getResidueShading(), alignPanel.getViewName());
3616 SliderPanel.showConservationSlider();
3620 * Action on selecting or deselecting (Colour) By Conservation
3623 public void conservationMenuItem_actionPerformed(boolean selected)
3625 modifyConservation.setEnabled(selected);
3626 viewport.setConservationSelected(selected);
3627 viewport.getResidueShading().setConservationApplied(selected);
3629 changeColour(viewport.getGlobalColourScheme());
3632 modifyConservation_actionPerformed();
3636 SliderPanel.hideConservationSlider();
3641 * Action on selecting or deselecting (Colour) Above PID Threshold
3644 public void abovePIDThreshold_actionPerformed(boolean selected)
3646 modifyPID.setEnabled(selected);
3647 viewport.setAbovePIDThreshold(selected);
3650 viewport.getResidueShading().setThreshold(0,
3651 viewport.isIgnoreGapsConsensus());
3654 changeColour(viewport.getGlobalColourScheme());
3657 modifyPID_actionPerformed();
3661 SliderPanel.hidePIDSlider();
3672 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3674 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3675 AlignmentSorter.sortByPID(viewport.getAlignment(),
3676 viewport.getAlignment().getSequenceAt(0));
3677 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3678 viewport.getAlignment()));
3679 alignPanel.paintAlignment(true);
3689 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3691 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3692 AlignmentSorter.sortByID(viewport.getAlignment());
3694 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3695 alignPanel.paintAlignment(true);
3705 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3707 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3708 AlignmentSorter.sortByLength(viewport.getAlignment());
3709 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3710 viewport.getAlignment()));
3711 alignPanel.paintAlignment(true);
3721 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3723 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3724 AlignmentSorter.sortByGroup(viewport.getAlignment());
3725 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3726 viewport.getAlignment()));
3728 alignPanel.paintAlignment(true);
3738 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3740 new RedundancyPanel(alignPanel, this);
3750 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3752 if ((viewport.getSelectionGroup() == null)
3753 || (viewport.getSelectionGroup().getSize() < 2))
3755 JvOptionPane.showInternalMessageDialog(this,
3756 MessageManager.getString(
3757 "label.you_must_select_least_two_sequences"),
3758 MessageManager.getString("label.invalid_selection"),
3759 JvOptionPane.WARNING_MESSAGE);
3763 JInternalFrame frame = new JInternalFrame();
3764 frame.setContentPane(new PairwiseAlignPanel(viewport));
3765 Desktop.addInternalFrame(frame,
3766 MessageManager.getString("action.pairwise_alignment"), 600,
3772 public void autoCalculate_actionPerformed(ActionEvent e)
3774 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3775 if (viewport.autoCalculateConsensus)
3777 viewport.firePropertyChange("alignment", null,
3778 viewport.getAlignment().getSequences());
3783 public void sortByTreeOption_actionPerformed(ActionEvent e)
3785 viewport.sortByTree = sortByTree.isSelected();
3789 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3791 viewport.followSelection = listenToViewSelections.isSelected();
3795 * Constructs a tree panel and adds it to the desktop
3798 * tree type (NJ or AV)
3800 * name of score model used to compute the tree
3802 * parameters for the distance or similarity calculation
3804 void newTreePanel(String type, String modelName,
3805 SimilarityParamsI options)
3807 String frameTitle = "";
3810 boolean onSelection = false;
3811 if (viewport.getSelectionGroup() != null
3812 && viewport.getSelectionGroup().getSize() > 0)
3814 SequenceGroup sg = viewport.getSelectionGroup();
3816 /* Decide if the selection is a column region */
3817 for (SequenceI _s : sg.getSequences())
3819 if (_s.getLength() < sg.getEndRes())
3821 JvOptionPane.showMessageDialog(Desktop.desktop,
3822 MessageManager.getString(
3823 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3824 MessageManager.getString(
3825 "label.sequences_selection_not_aligned"),
3826 JvOptionPane.WARNING_MESSAGE);
3835 if (viewport.getAlignment().getHeight() < 2)
3841 tp = new TreePanel(alignPanel, type, modelName, options);
3842 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3844 frameTitle += " from ";
3846 if (viewport.viewName != null)
3848 frameTitle += viewport.viewName + " of ";
3851 frameTitle += this.title;
3853 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3864 public void addSortByOrderMenuItem(String title,
3865 final AlignmentOrder order)
3867 final JMenuItem item = new JMenuItem(MessageManager
3868 .formatMessage("action.by_title_param", new Object[]
3871 item.addActionListener(new java.awt.event.ActionListener()
3874 public void actionPerformed(ActionEvent e)
3876 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3878 // TODO: JBPNote - have to map order entries to curent SequenceI
3880 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3882 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3883 viewport.getAlignment()));
3885 alignPanel.paintAlignment(true);
3891 * Add a new sort by annotation score menu item
3894 * the menu to add the option to
3896 * the label used to retrieve scores for each sequence on the
3899 public void addSortByAnnotScoreMenuItem(JMenu sort,
3900 final String scoreLabel)
3902 final JMenuItem item = new JMenuItem(scoreLabel);
3904 item.addActionListener(new java.awt.event.ActionListener()
3907 public void actionPerformed(ActionEvent e)
3909 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3910 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3911 viewport.getAlignment());// ,viewport.getSelectionGroup());
3912 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3913 viewport.getAlignment()));
3914 alignPanel.paintAlignment(true);
3920 * last hash for alignment's annotation array - used to minimise cost of
3923 protected int _annotationScoreVectorHash;
3926 * search the alignment and rebuild the sort by annotation score submenu the
3927 * last alignment annotation vector hash is stored to minimize cost of
3928 * rebuilding in subsequence calls.
3932 public void buildSortByAnnotationScoresMenu()
3934 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3939 if (viewport.getAlignment().getAlignmentAnnotation()
3940 .hashCode() != _annotationScoreVectorHash)
3942 sortByAnnotScore.removeAll();
3943 // almost certainly a quicker way to do this - but we keep it simple
3944 Hashtable scoreSorts = new Hashtable();
3945 AlignmentAnnotation aann[];
3946 for (SequenceI sqa : viewport.getAlignment().getSequences())
3948 aann = sqa.getAnnotation();
3949 for (int i = 0; aann != null && i < aann.length; i++)
3951 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3953 scoreSorts.put(aann[i].label, aann[i].label);
3957 Enumeration labels = scoreSorts.keys();
3958 while (labels.hasMoreElements())
3960 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3961 (String) labels.nextElement());
3963 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3966 _annotationScoreVectorHash = viewport.getAlignment()
3967 .getAlignmentAnnotation().hashCode();
3972 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3973 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3974 * call. Listeners are added to remove the menu item when the treePanel is
3975 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3979 public void buildTreeSortMenu()
3981 sortByTreeMenu.removeAll();
3983 List<Component> comps = PaintRefresher.components
3984 .get(viewport.getSequenceSetId());
3985 List<TreePanel> treePanels = new ArrayList<>();
3986 for (Component comp : comps)
3988 if (comp instanceof TreePanel)
3990 treePanels.add((TreePanel) comp);
3994 if (treePanels.size() < 1)
3996 sortByTreeMenu.setVisible(false);
4000 sortByTreeMenu.setVisible(true);
4002 for (final TreePanel tp : treePanels)
4004 final JMenuItem item = new JMenuItem(tp.getTitle());
4005 item.addActionListener(new java.awt.event.ActionListener()
4008 public void actionPerformed(ActionEvent e)
4010 tp.sortByTree_actionPerformed();
4011 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4016 sortByTreeMenu.add(item);
4020 public boolean sortBy(AlignmentOrder alorder, String undoname)
4022 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4023 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4024 if (undoname != null)
4026 addHistoryItem(new OrderCommand(undoname, oldOrder,
4027 viewport.getAlignment()));
4029 alignPanel.paintAlignment(true);
4034 * Work out whether the whole set of sequences or just the selected set will
4035 * be submitted for multiple alignment.
4038 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4040 // Now, check we have enough sequences
4041 AlignmentView msa = null;
4043 if ((viewport.getSelectionGroup() != null)
4044 && (viewport.getSelectionGroup().getSize() > 1))
4046 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4047 // some common interface!
4049 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4050 * SequenceI[sz = seqs.getSize(false)];
4052 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4053 * seqs.getSequenceAt(i); }
4055 msa = viewport.getAlignmentView(true);
4057 else if (viewport.getSelectionGroup() != null
4058 && viewport.getSelectionGroup().getSize() == 1)
4060 int option = JvOptionPane.showConfirmDialog(this,
4061 MessageManager.getString("warn.oneseq_msainput_selection"),
4062 MessageManager.getString("label.invalid_selection"),
4063 JvOptionPane.OK_CANCEL_OPTION);
4064 if (option == JvOptionPane.OK_OPTION)
4066 msa = viewport.getAlignmentView(false);
4071 msa = viewport.getAlignmentView(false);
4077 * Decides what is submitted to a secondary structure prediction service: the
4078 * first sequence in the alignment, or in the current selection, or, if the
4079 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4080 * region or the whole alignment. (where the first sequence in the set is the
4081 * one that the prediction will be for).
4083 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4085 AlignmentView seqs = null;
4087 if ((viewport.getSelectionGroup() != null)
4088 && (viewport.getSelectionGroup().getSize() > 0))
4090 seqs = viewport.getAlignmentView(true);
4094 seqs = viewport.getAlignmentView(false);
4096 // limit sequences - JBPNote in future - could spawn multiple prediction
4098 // TODO: viewport.getAlignment().isAligned is a global state - the local
4099 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4100 if (!viewport.getAlignment().isAligned(false))
4102 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4103 // TODO: if seqs.getSequences().length>1 then should really have warned
4117 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4119 // Pick the tree file
4120 JalviewFileChooser chooser = new JalviewFileChooser(
4121 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4122 chooser.setFileView(new JalviewFileView());
4123 chooser.setDialogTitle(
4124 MessageManager.getString("label.select_newick_like_tree_file"));
4125 chooser.setToolTipText(
4126 MessageManager.getString("label.load_tree_file"));
4128 int value = chooser.showOpenDialog(null);
4130 if (value == JalviewFileChooser.APPROVE_OPTION)
4132 String filePath = chooser.getSelectedFile().getPath();
4133 Cache.setProperty("LAST_DIRECTORY", filePath);
4134 NewickFile fin = null;
4137 fin = new NewickFile(filePath, DataSourceType.FILE);
4138 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4139 } catch (Exception ex)
4141 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4142 MessageManager.getString("label.problem_reading_tree_file"),
4143 JvOptionPane.WARNING_MESSAGE);
4144 ex.printStackTrace();
4146 if (fin != null && fin.hasWarningMessage())
4148 JvOptionPane.showMessageDialog(Desktop.desktop,
4149 fin.getWarningMessage(),
4151 .getString("label.possible_problem_with_tree_file"),
4152 JvOptionPane.WARNING_MESSAGE);
4157 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4159 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4162 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4163 int h, int x, int y)
4165 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4169 * Add a treeviewer for the tree extracted from a Newick file object to the
4170 * current alignment view
4177 * Associated alignment input data (or null)
4186 * @return TreePanel handle
4188 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4189 AlignmentView input, int w, int h, int x, int y)
4191 TreePanel tp = null;
4197 if (nf.getTree() != null)
4199 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4205 tp.setLocation(x, y);
4208 Desktop.addInternalFrame(tp, treeTitle, w, h);
4210 } catch (Exception ex)
4212 ex.printStackTrace();
4218 private boolean buildingMenu = false;
4221 * Generates menu items and listener event actions for web service clients
4224 public void BuildWebServiceMenu()
4226 while (buildingMenu)
4230 System.err.println("Waiting for building menu to finish.");
4232 } catch (Exception e)
4236 final AlignFrame me = this;
4237 buildingMenu = true;
4238 new Thread(new Runnable()
4243 final List<JMenuItem> legacyItems = new ArrayList<>();
4246 // System.err.println("Building ws menu again "
4247 // + Thread.currentThread());
4248 // TODO: add support for context dependent disabling of services based
4250 // alignment and current selection
4251 // TODO: add additional serviceHandle parameter to specify abstract
4253 // class independently of AbstractName
4254 // TODO: add in rediscovery GUI function to restart discoverer
4255 // TODO: group services by location as well as function and/or
4257 // object broker mechanism.
4258 final Vector<JMenu> wsmenu = new Vector<>();
4259 final IProgressIndicator af = me;
4262 * do not i18n these strings - they are hard-coded in class
4263 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4264 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4266 final JMenu msawsmenu = new JMenu("Alignment");
4267 final JMenu secstrmenu = new JMenu(
4268 "Secondary Structure Prediction");
4269 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4270 final JMenu analymenu = new JMenu("Analysis");
4271 final JMenu dismenu = new JMenu("Protein Disorder");
4272 // JAL-940 - only show secondary structure prediction services from
4273 // the legacy server
4274 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4276 Discoverer.services != null && (Discoverer.services.size() > 0))
4278 // TODO: refactor to allow list of AbstractName/Handler bindings to
4280 // stored or retrieved from elsewhere
4281 // No MSAWS used any more:
4282 // Vector msaws = null; // (Vector)
4283 // Discoverer.services.get("MsaWS");
4284 Vector secstrpr = (Vector) Discoverer.services
4286 if (secstrpr != null)
4288 // Add any secondary structure prediction services
4289 for (int i = 0, j = secstrpr.size(); i < j; i++)
4291 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4293 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4294 .getServiceClient(sh);
4295 int p = secstrmenu.getItemCount();
4296 impl.attachWSMenuEntry(secstrmenu, me);
4297 int q = secstrmenu.getItemCount();
4298 for (int litm = p; litm < q; litm++)
4300 legacyItems.add(secstrmenu.getItem(litm));
4306 // Add all submenus in the order they should appear on the web
4308 wsmenu.add(msawsmenu);
4309 wsmenu.add(secstrmenu);
4310 wsmenu.add(dismenu);
4311 wsmenu.add(analymenu);
4312 // No search services yet
4313 // wsmenu.add(seqsrchmenu);
4315 javax.swing.SwingUtilities.invokeLater(new Runnable()
4322 webService.removeAll();
4323 // first, add discovered services onto the webservices menu
4324 if (wsmenu.size() > 0)
4326 for (int i = 0, j = wsmenu.size(); i < j; i++)
4328 webService.add(wsmenu.get(i));
4333 webService.add(me.webServiceNoServices);
4335 // TODO: move into separate menu builder class.
4336 boolean new_sspred = false;
4337 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4339 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4340 if (jws2servs != null)
4342 if (jws2servs.hasServices())
4344 jws2servs.attachWSMenuEntry(webService, me);
4345 for (Jws2Instance sv : jws2servs.getServices())
4347 if (sv.description.toLowerCase().contains("jpred"))
4349 for (JMenuItem jmi : legacyItems)
4351 jmi.setVisible(false);
4357 if (jws2servs.isRunning())
4359 JMenuItem tm = new JMenuItem(
4360 "Still discovering JABA Services");
4361 tm.setEnabled(false);
4366 build_urlServiceMenu(me.webService);
4367 build_fetchdbmenu(webService);
4368 for (JMenu item : wsmenu)
4370 if (item.getItemCount() == 0)
4372 item.setEnabled(false);
4376 item.setEnabled(true);
4379 } catch (Exception e)
4382 "Exception during web service menu building process.",
4387 } catch (Exception e)
4390 buildingMenu = false;
4397 * construct any groupURL type service menu entries.
4401 private void build_urlServiceMenu(JMenu webService)
4403 // TODO: remove this code when 2.7 is released
4404 // DEBUG - alignmentView
4406 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4407 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4409 * @Override public void actionPerformed(ActionEvent e) {
4410 * jalview.datamodel.AlignmentView
4411 * .testSelectionViews(af.viewport.getAlignment(),
4412 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4414 * }); webService.add(testAlView);
4416 // TODO: refactor to RestClient discoverer and merge menu entries for
4417 // rest-style services with other types of analysis/calculation service
4418 // SHmmr test client - still being implemented.
4419 // DEBUG - alignmentView
4421 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4424 client.attachWSMenuEntry(
4425 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4431 * Searches the alignment sequences for xRefs and builds the Show
4432 * Cross-References menu (formerly called Show Products), with database
4433 * sources for which cross-references are found (protein sources for a
4434 * nucleotide alignment and vice versa)
4436 * @return true if Show Cross-references menu should be enabled
4438 public boolean canShowProducts()
4440 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4441 AlignmentI dataset = viewport.getAlignment().getDataset();
4443 showProducts.removeAll();
4444 final boolean dna = viewport.getAlignment().isNucleotide();
4446 if (seqs == null || seqs.length == 0)
4448 // nothing to see here.
4452 boolean showp = false;
4455 List<String> ptypes = new CrossRef(seqs, dataset)
4456 .findXrefSourcesForSequences(dna);
4458 for (final String source : ptypes)
4461 final AlignFrame af = this;
4462 JMenuItem xtype = new JMenuItem(source);
4463 xtype.addActionListener(new ActionListener()
4466 public void actionPerformed(ActionEvent e)
4468 showProductsFor(af.viewport.getSequenceSelection(), dna,
4472 showProducts.add(xtype);
4474 showProducts.setVisible(showp);
4475 showProducts.setEnabled(showp);
4476 } catch (Exception e)
4479 "canShowProducts threw an exception - please report to help@jalview.org",
4487 * Finds and displays cross-references for the selected sequences (protein
4488 * products for nucleotide sequences, dna coding sequences for peptides).
4491 * the sequences to show cross-references for
4493 * true if from a nucleotide alignment (so showing proteins)
4495 * the database to show cross-references for
4497 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4498 final String source)
4500 new Thread(CrossRefAction.showProductsFor(sel, _odna, source, this))
4505 * Construct and display a new frame containing the translation of this
4506 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4509 public void showTranslation_actionPerformed(ActionEvent e)
4511 AlignmentI al = null;
4514 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4516 al = dna.translateCdna();
4517 } catch (Exception ex)
4519 jalview.bin.Cache.log.error(
4520 "Exception during translation. Please report this !", ex);
4521 final String msg = MessageManager.getString(
4522 "label.error_when_translating_sequences_submit_bug_report");
4523 final String errorTitle = MessageManager
4524 .getString("label.implementation_error")
4525 + MessageManager.getString("label.translation_failed");
4526 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4527 JvOptionPane.ERROR_MESSAGE);
4530 if (al == null || al.getHeight() == 0)
4532 final String msg = MessageManager.getString(
4533 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4534 final String errorTitle = MessageManager
4535 .getString("label.translation_failed");
4536 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4537 JvOptionPane.WARNING_MESSAGE);
4541 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4542 af.setFileFormat(this.currentFileFormat);
4543 final String newTitle = MessageManager
4544 .formatMessage("label.translation_of_params", new Object[]
4545 { this.getTitle() });
4546 af.setTitle(newTitle);
4547 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4549 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4550 viewport.openSplitFrame(af, new Alignment(seqs));
4554 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4561 * Set the file format
4565 public void setFileFormat(FileFormatI format)
4567 this.currentFileFormat = format;
4571 * Try to load a features file onto the alignment.
4574 * contents or path to retrieve file
4576 * access mode of file (see jalview.io.AlignFile)
4577 * @return true if features file was parsed correctly.
4579 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4581 return avc.parseFeaturesFile(file, sourceType,
4582 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4587 public void refreshFeatureUI(boolean enableIfNecessary)
4589 // note - currently this is only still here rather than in the controller
4590 // because of the featureSettings hard reference that is yet to be
4592 if (enableIfNecessary)
4594 viewport.setShowSequenceFeatures(true);
4595 showSeqFeatures.setSelected(true);
4601 public void dragEnter(DropTargetDragEvent evt)
4606 public void dragExit(DropTargetEvent evt)
4611 public void dragOver(DropTargetDragEvent evt)
4616 public void dropActionChanged(DropTargetDragEvent evt)
4621 public void drop(DropTargetDropEvent evt)
4623 // JAL-1552 - acceptDrop required before getTransferable call for
4624 // Java's Transferable for native dnd
4625 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4626 Transferable t = evt.getTransferable();
4627 List<String> files = new ArrayList<>();
4628 List<DataSourceType> protocols = new ArrayList<>();
4632 Desktop.transferFromDropTarget(files, protocols, evt, t);
4633 } catch (Exception e)
4635 e.printStackTrace();
4641 // check to see if any of these files have names matching sequences in
4643 SequenceIdMatcher idm = new SequenceIdMatcher(
4644 viewport.getAlignment().getSequencesArray());
4646 * Object[] { String,SequenceI}
4648 ArrayList<Object[]> filesmatched = new ArrayList<>();
4649 ArrayList<String> filesnotmatched = new ArrayList<>();
4650 for (int i = 0; i < files.size(); i++)
4652 String file = files.get(i).toString();
4654 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4655 if (protocol == DataSourceType.FILE)
4657 File fl = new File(file);
4658 pdbfn = fl.getName();
4660 else if (protocol == DataSourceType.URL)
4662 URL url = new URL(file);
4663 pdbfn = url.getFile();
4665 if (pdbfn.length() > 0)
4667 // attempt to find a match in the alignment
4668 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4669 int l = 0, c = pdbfn.indexOf(".");
4670 while (mtch == null && c != -1)
4675 } while ((c = pdbfn.indexOf(".", l)) > l);
4678 pdbfn = pdbfn.substring(0, l);
4680 mtch = idm.findAllIdMatches(pdbfn);
4684 FileFormatI type = null;
4687 type = new IdentifyFile().identify(file, protocol);
4688 } catch (Exception ex)
4692 if (type != null && type.isStructureFile())
4694 filesmatched.add(new Object[] { file, protocol, mtch });
4698 // File wasn't named like one of the sequences or wasn't a PDB file.
4699 filesnotmatched.add(file);
4703 if (filesmatched.size() > 0)
4705 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4706 || JvOptionPane.showConfirmDialog(this,
4707 MessageManager.formatMessage(
4708 "label.automatically_associate_structure_files_with_sequences_same_name",
4710 { Integer.valueOf(filesmatched.size())
4712 MessageManager.getString(
4713 "label.automatically_associate_structure_files_by_name"),
4714 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION)
4717 for (Object[] fm : filesmatched)
4719 // try and associate
4720 // TODO: may want to set a standard ID naming formalism for
4721 // associating PDB files which have no IDs.
4722 for (SequenceI toassoc : (SequenceI[]) fm[2])
4724 PDBEntry pe = new AssociatePdbFileWithSeq()
4725 .associatePdbWithSeq((String) fm[0],
4726 (DataSourceType) fm[1], toassoc, false,
4730 System.err.println("Associated file : " + ((String) fm[0])
4731 + " with " + toassoc.getDisplayId(true));
4735 alignPanel.paintAlignment(true);
4739 if (filesnotmatched.size() > 0)
4741 if (assocfiles > 0 && (Cache.getDefault(
4742 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4743 || JvOptionPane.showConfirmDialog(this,
4744 "<html>" + MessageManager.formatMessage(
4745 "label.ignore_unmatched_dropped_files_info",
4747 { Integer.valueOf(filesnotmatched.size())
4750 MessageManager.getString(
4751 "label.ignore_unmatched_dropped_files"),
4752 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4756 for (String fn : filesnotmatched)
4758 loadJalviewDataFile(fn, null, null, null);
4762 } catch (Exception ex)
4764 ex.printStackTrace();
4770 * Attempt to load a "dropped" file or URL string, by testing in turn for
4772 * <li>an Annotation file</li>
4773 * <li>a JNet file</li>
4774 * <li>a features file</li>
4775 * <li>else try to interpret as an alignment file</li>
4779 * either a filename or a URL string.
4780 * @throws InterruptedException
4781 * @throws IOException
4783 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4784 FileFormatI format, SequenceI assocSeq)
4788 if (sourceType == null)
4790 sourceType = FormatAdapter.checkProtocol(file);
4792 // if the file isn't identified, or not positively identified as some
4793 // other filetype (PFAM is default unidentified alignment file type) then
4794 // try to parse as annotation.
4795 boolean isAnnotation = (format == null
4796 || FileFormat.Pfam.equals(format))
4797 ? new AnnotationFile().annotateAlignmentView(viewport,
4803 // first see if its a T-COFFEE score file
4804 TCoffeeScoreFile tcf = null;
4807 tcf = new TCoffeeScoreFile(file, sourceType);
4810 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4814 new TCoffeeColourScheme(viewport.getAlignment()));
4815 isAnnotation = true;
4816 statusBar.setText(MessageManager.getString(
4817 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4821 // some problem - if no warning its probable that the ID matching
4822 // process didn't work
4823 JvOptionPane.showMessageDialog(Desktop.desktop,
4824 tcf.getWarningMessage() == null
4825 ? MessageManager.getString(
4826 "label.check_file_matches_sequence_ids_alignment")
4827 : tcf.getWarningMessage(),
4828 MessageManager.getString(
4829 "label.problem_reading_tcoffee_score_file"),
4830 JvOptionPane.WARNING_MESSAGE);
4837 } catch (Exception x)
4840 "Exception when processing data source as T-COFFEE score file",
4846 // try to see if its a JNet 'concise' style annotation file *before*
4848 // try to parse it as a features file
4851 format = new IdentifyFile().identify(file, sourceType);
4853 if (FileFormat.ScoreMatrix == format)
4855 ScoreMatrixFile sm = new ScoreMatrixFile(
4856 new FileParse(file, sourceType));
4858 // todo: i18n this message
4859 statusBar.setText(MessageManager.formatMessage(
4860 "label.successfully_loaded_matrix",
4861 sm.getMatrixName()));
4863 else if (FileFormat.Jnet.equals(format))
4865 JPredFile predictions = new JPredFile(file, sourceType);
4866 new JnetAnnotationMaker();
4867 JnetAnnotationMaker.add_annotation(predictions,
4868 viewport.getAlignment(), 0, false);
4869 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
4870 viewport.getAlignment().setSeqrep(repseq);
4871 HiddenColumns cs = new HiddenColumns();
4872 cs.hideInsertionsFor(repseq);
4873 viewport.getAlignment().setHiddenColumns(cs);
4874 isAnnotation = true;
4876 // else if (IdentifyFile.FeaturesFile.equals(format))
4877 else if (FileFormat.Features.equals(format))
4879 if (parseFeaturesFile(file, sourceType))
4881 alignPanel.paintAlignment(true);
4886 new FileLoader().LoadFile(viewport, file, sourceType, format);
4892 alignPanel.adjustAnnotationHeight();
4893 viewport.updateSequenceIdColours();
4894 buildSortByAnnotationScoresMenu();
4895 alignPanel.paintAlignment(true);
4897 } catch (Exception ex)
4899 ex.printStackTrace();
4900 } catch (OutOfMemoryError oom)
4905 } catch (Exception x)
4910 + (sourceType != null
4911 ? (sourceType == DataSourceType.PASTE
4913 : "using " + sourceType + " from "
4917 ? "(parsing as '" + format + "' file)"
4919 oom, Desktop.desktop);
4924 * Method invoked by the ChangeListener on the tabbed pane, in other words
4925 * when a different tabbed pane is selected by the user or programmatically.
4928 public void tabSelectionChanged(int index)
4932 alignPanel = alignPanels.get(index);
4933 viewport = alignPanel.av;
4934 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4935 setMenusFromViewport(viewport);
4939 * 'focus' any colour slider that is open to the selected viewport
4941 if (viewport.getConservationSelected())
4943 SliderPanel.setConservationSlider(alignPanel,
4944 viewport.getResidueShading(), alignPanel.getViewName());
4948 SliderPanel.hideConservationSlider();
4950 if (viewport.getAbovePIDThreshold())
4952 SliderPanel.setPIDSliderSource(alignPanel,
4953 viewport.getResidueShading(), alignPanel.getViewName());
4957 SliderPanel.hidePIDSlider();
4961 * If there is a frame linked to this one in a SplitPane, switch it to the
4962 * same view tab index. No infinite recursion of calls should happen, since
4963 * tabSelectionChanged() should not get invoked on setting the selected
4964 * index to an unchanged value. Guard against setting an invalid index
4965 * before the new view peer tab has been created.
4967 final AlignViewportI peer = viewport.getCodingComplement();
4970 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4971 .getAlignPanel().alignFrame;
4972 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4974 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4980 * On right mouse click on view tab, prompt for and set new view name.
4983 public void tabbedPane_mousePressed(MouseEvent e)
4985 if (e.isPopupTrigger())
4987 String msg = MessageManager.getString("label.enter_view_name");
4988 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4989 JvOptionPane.QUESTION_MESSAGE);
4993 viewport.viewName = reply;
4994 // TODO warn if reply is in getExistingViewNames()?
4995 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5000 public AlignViewport getCurrentView()
5006 * Open the dialog for regex description parsing.
5009 protected void extractScores_actionPerformed(ActionEvent e)
5011 ParseProperties pp = new jalview.analysis.ParseProperties(
5012 viewport.getAlignment());
5013 // TODO: verify regex and introduce GUI dialog for version 2.5
5014 // if (pp.getScoresFromDescription("col", "score column ",
5015 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5017 if (pp.getScoresFromDescription("description column",
5018 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5020 buildSortByAnnotationScoresMenu();
5028 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5032 protected void showDbRefs_actionPerformed(ActionEvent e)
5034 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5040 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5044 protected void showNpFeats_actionPerformed(ActionEvent e)
5046 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5050 * find the viewport amongst the tabs in this alignment frame and close that
5055 public boolean closeView(AlignViewportI av)
5059 this.closeMenuItem_actionPerformed(false);
5062 Component[] comp = tabbedPane.getComponents();
5063 for (int i = 0; comp != null && i < comp.length; i++)
5065 if (comp[i] instanceof AlignmentPanel)
5067 if (((AlignmentPanel) comp[i]).av == av)
5070 closeView((AlignmentPanel) comp[i]);
5078 protected void build_fetchdbmenu(JMenu webService)
5080 // Temporary hack - DBRef Fetcher always top level ws entry.
5081 // TODO We probably want to store a sequence database checklist in
5082 // preferences and have checkboxes.. rather than individual sources selected
5084 final JMenu rfetch = new JMenu(
5085 MessageManager.getString("action.fetch_db_references"));
5086 rfetch.setToolTipText(MessageManager.getString(
5087 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5088 webService.add(rfetch);
5090 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5091 MessageManager.getString("option.trim_retrieved_seqs"));
5092 trimrs.setToolTipText(
5093 MessageManager.getString("label.trim_retrieved_sequences"));
5094 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5095 trimrs.addActionListener(new ActionListener()
5098 public void actionPerformed(ActionEvent e)
5100 trimrs.setSelected(trimrs.isSelected());
5101 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5102 Boolean.valueOf(trimrs.isSelected()).toString());
5106 JMenuItem fetchr = new JMenuItem(
5107 MessageManager.getString("label.standard_databases"));
5108 fetchr.setToolTipText(
5109 MessageManager.getString("label.fetch_embl_uniprot"));
5110 fetchr.addActionListener(new ActionListener()
5114 public void actionPerformed(ActionEvent e)
5116 new Thread(new Runnable()
5121 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5122 .getAlignment().isNucleotide();
5123 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5124 alignPanel.av.getSequenceSelection(),
5125 alignPanel.alignFrame, null,
5126 alignPanel.alignFrame.featureSettings, isNucleotide);
5127 dbRefFetcher.addListener(new FetchFinishedListenerI()
5130 public void finished()
5132 AlignFrame.this.setMenusForViewport();
5135 dbRefFetcher.fetchDBRefs(false);
5143 final AlignFrame me = this;
5144 new Thread(new Runnable()
5149 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5150 .getSequenceFetcherSingleton(me);
5151 javax.swing.SwingUtilities.invokeLater(new Runnable()
5156 String[] dbclasses = sf.getOrderedSupportedSources();
5157 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5158 // jalview.util.QuickSort.sort(otherdb, otherdb);
5159 List<DbSourceProxy> otherdb;
5160 JMenu dfetch = new JMenu();
5161 JMenu ifetch = new JMenu();
5162 JMenuItem fetchr = null;
5163 int comp = 0, icomp = 0, mcomp = 15;
5164 String mname = null;
5166 for (String dbclass : dbclasses)
5168 otherdb = sf.getSourceProxy(dbclass);
5169 // add a single entry for this class, or submenu allowing 'fetch
5171 if (otherdb == null || otherdb.size() < 1)
5175 // List<DbSourceProxy> dbs=otherdb;
5176 // otherdb=new ArrayList<DbSourceProxy>();
5177 // for (DbSourceProxy db:dbs)
5179 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5183 mname = "From " + dbclass;
5185 if (otherdb.size() == 1)
5187 final DbSourceProxy[] dassource = otherdb
5188 .toArray(new DbSourceProxy[0]);
5189 DbSourceProxy src = otherdb.get(0);
5190 fetchr = new JMenuItem(src.getDbSource());
5191 fetchr.addActionListener(new ActionListener()
5195 public void actionPerformed(ActionEvent e)
5197 new Thread(new Runnable()
5203 boolean isNucleotide = alignPanel.alignFrame
5204 .getViewport().getAlignment()
5206 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5207 alignPanel.av.getSequenceSelection(),
5208 alignPanel.alignFrame, dassource,
5209 alignPanel.alignFrame.featureSettings,
5212 .addListener(new FetchFinishedListenerI()
5215 public void finished()
5217 AlignFrame.this.setMenusForViewport();
5220 dbRefFetcher.fetchDBRefs(false);
5226 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5227 MessageManager.formatMessage(
5228 "label.fetch_retrieve_from", new Object[]
5229 { src.getDbName() })));
5235 final DbSourceProxy[] dassource = otherdb
5236 .toArray(new DbSourceProxy[0]);
5238 DbSourceProxy src = otherdb.get(0);
5239 fetchr = new JMenuItem(MessageManager
5240 .formatMessage("label.fetch_all_param", new Object[]
5241 { src.getDbSource() }));
5242 fetchr.addActionListener(new ActionListener()
5245 public void actionPerformed(ActionEvent e)
5247 new Thread(new Runnable()
5253 boolean isNucleotide = alignPanel.alignFrame
5254 .getViewport().getAlignment()
5256 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5257 alignPanel.av.getSequenceSelection(),
5258 alignPanel.alignFrame, dassource,
5259 alignPanel.alignFrame.featureSettings,
5262 .addListener(new FetchFinishedListenerI()
5265 public void finished()
5267 AlignFrame.this.setMenusForViewport();
5270 dbRefFetcher.fetchDBRefs(false);
5276 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5277 MessageManager.formatMessage(
5278 "label.fetch_retrieve_from_all_sources",
5280 { Integer.valueOf(otherdb.size())
5282 src.getDbSource(), src.getDbName() })));
5285 // and then build the rest of the individual menus
5286 ifetch = new JMenu(MessageManager.formatMessage(
5287 "label.source_from_db_source", new Object[]
5288 { src.getDbSource() }));
5290 String imname = null;
5292 for (DbSourceProxy sproxy : otherdb)
5294 String dbname = sproxy.getDbName();
5295 String sname = dbname.length() > 5
5296 ? dbname.substring(0, 5) + "..."
5298 String msname = dbname.length() > 10
5299 ? dbname.substring(0, 10) + "..."
5303 imname = MessageManager
5304 .formatMessage("label.from_msname", new Object[]
5307 fetchr = new JMenuItem(msname);
5308 final DbSourceProxy[] dassrc = { sproxy };
5309 fetchr.addActionListener(new ActionListener()
5313 public void actionPerformed(ActionEvent e)
5315 new Thread(new Runnable()
5321 boolean isNucleotide = alignPanel.alignFrame
5322 .getViewport().getAlignment()
5324 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5325 alignPanel.av.getSequenceSelection(),
5326 alignPanel.alignFrame, dassrc,
5327 alignPanel.alignFrame.featureSettings,
5330 .addListener(new FetchFinishedListenerI()
5333 public void finished()
5335 AlignFrame.this.setMenusForViewport();
5338 dbRefFetcher.fetchDBRefs(false);
5344 fetchr.setToolTipText(
5345 "<html>" + MessageManager.formatMessage(
5346 "label.fetch_retrieve_from", new Object[]
5350 if (++icomp >= mcomp || i == (otherdb.size()))
5352 ifetch.setText(MessageManager.formatMessage(
5353 "label.source_to_target", imname, sname));
5355 ifetch = new JMenu();
5363 if (comp >= mcomp || dbi >= (dbclasses.length))
5365 dfetch.setText(MessageManager.formatMessage(
5366 "label.source_to_target", mname, dbclass));
5368 dfetch = new JMenu();
5381 * Left justify the whole alignment.
5384 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5386 AlignmentI al = viewport.getAlignment();
5388 viewport.firePropertyChange("alignment", null, al);
5392 * Right justify the whole alignment.
5395 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5397 AlignmentI al = viewport.getAlignment();
5399 viewport.firePropertyChange("alignment", null, al);
5403 public void setShowSeqFeatures(boolean b)
5405 showSeqFeatures.setSelected(b);
5406 viewport.setShowSequenceFeatures(b);
5413 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5414 * awt.event.ActionEvent)
5417 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5419 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5420 alignPanel.paintAlignment(true);
5427 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5431 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5433 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5434 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5442 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5443 * .event.ActionEvent)
5446 protected void showGroupConservation_actionPerformed(ActionEvent e)
5448 viewport.setShowGroupConservation(showGroupConservation.getState());
5449 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5456 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5457 * .event.ActionEvent)
5460 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5462 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5463 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5470 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5471 * .event.ActionEvent)
5474 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5476 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5477 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5481 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5483 showSequenceLogo.setState(true);
5484 viewport.setShowSequenceLogo(true);
5485 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5486 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5490 protected void showInformationHistogram_actionPerformed(ActionEvent e)
5492 viewport.setShowInformationHistogram(
5493 showInformationHistogram.getState());
5494 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5498 protected void showHMMSequenceLogo_actionPerformed(ActionEvent e)
5500 viewport.setShowHMMSequenceLogo(showHMMSequenceLogo.getState());
5501 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5505 protected void normaliseHMMSequenceLogo_actionPerformed(ActionEvent e)
5507 showHMMSequenceLogo.setState(true);
5508 viewport.setShowHMMSequenceLogo(true);
5509 viewport.setNormaliseHMMSequenceLogo(normaliseSequenceLogo.getState());
5510 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5514 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5516 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5523 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5524 * .event.ActionEvent)
5527 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5529 if (avc.makeGroupsFromSelection())
5531 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5532 alignPanel.updateAnnotation();
5533 alignPanel.paintAlignment(true);
5537 public void clearAlignmentSeqRep()
5539 // TODO refactor alignmentseqrep to controller
5540 if (viewport.getAlignment().hasSeqrep())
5542 viewport.getAlignment().setSeqrep(null);
5543 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5544 alignPanel.updateAnnotation();
5545 alignPanel.paintAlignment(true);
5550 protected void createGroup_actionPerformed(ActionEvent e)
5552 if (avc.createGroup())
5554 alignPanel.alignmentChanged();
5559 protected void unGroup_actionPerformed(ActionEvent e)
5563 alignPanel.alignmentChanged();
5568 * make the given alignmentPanel the currently selected tab
5570 * @param alignmentPanel
5572 public void setDisplayedView(AlignmentPanel alignmentPanel)
5574 if (!viewport.getSequenceSetId()
5575 .equals(alignmentPanel.av.getSequenceSetId()))
5577 throw new Error(MessageManager.getString(
5578 "error.implementation_error_cannot_show_view_alignment_frame"));
5580 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5581 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5583 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5588 * Action on selection of menu options to Show or Hide annotations.
5591 * @param forSequences
5592 * update sequence-related annotations
5593 * @param forAlignment
5594 * update non-sequence-related annotations
5597 protected void setAnnotationsVisibility(boolean visible,
5598 boolean forSequences, boolean forAlignment)
5600 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5601 .getAlignmentAnnotation();
5606 for (AlignmentAnnotation aa : anns)
5609 * don't display non-positional annotations on an alignment
5611 if (aa.annotations == null)
5615 boolean apply = (aa.sequenceRef == null && forAlignment)
5616 || (aa.sequenceRef != null && forSequences);
5619 aa.visible = visible;
5622 alignPanel.validateAnnotationDimensions(true);
5623 alignPanel.alignmentChanged();
5627 * Store selected annotation sort order for the view and repaint.
5630 protected void sortAnnotations_actionPerformed()
5632 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5634 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5635 alignPanel.paintAlignment(true);
5640 * @return alignment panels in this alignment frame
5642 public List<? extends AlignmentViewPanel> getAlignPanels()
5644 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5648 * Open a new alignment window, with the cDNA associated with this (protein)
5649 * alignment, aligned as is the protein.
5651 protected void viewAsCdna_actionPerformed()
5653 // TODO no longer a menu action - refactor as required
5654 final AlignmentI alignment = getViewport().getAlignment();
5655 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5656 if (mappings == null)
5660 List<SequenceI> cdnaSeqs = new ArrayList<>();
5661 for (SequenceI aaSeq : alignment.getSequences())
5663 for (AlignedCodonFrame acf : mappings)
5665 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5669 * There is a cDNA mapping for this protein sequence - add to new
5670 * alignment. It will share the same dataset sequence as other mapped
5671 * cDNA (no new mappings need to be created).
5673 final Sequence newSeq = new Sequence(dnaSeq);
5674 newSeq.setDatasetSequence(dnaSeq);
5675 cdnaSeqs.add(newSeq);
5679 if (cdnaSeqs.size() == 0)
5681 // show a warning dialog no mapped cDNA
5684 AlignmentI cdna = new Alignment(
5685 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5686 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5687 AlignFrame.DEFAULT_HEIGHT);
5688 cdna.alignAs(alignment);
5689 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5691 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5692 AlignFrame.DEFAULT_HEIGHT);
5696 * Set visibility of dna/protein complement view (available when shown in a
5702 protected void showComplement_actionPerformed(boolean show)
5704 SplitContainerI sf = getSplitViewContainer();
5707 sf.setComplementVisible(this, show);
5712 * Generate the reverse (optionally complemented) of the selected sequences,
5713 * and add them to the alignment
5716 protected void showReverse_actionPerformed(boolean complement)
5718 AlignmentI al = null;
5721 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5722 al = dna.reverseCdna(complement);
5723 viewport.addAlignment(al, "");
5724 addHistoryItem(new EditCommand(
5725 MessageManager.getString("label.add_sequences"), Action.PASTE,
5726 al.getSequencesArray(), 0, al.getWidth(),
5727 viewport.getAlignment()));
5728 } catch (Exception ex)
5730 System.err.println(ex.getMessage());
5736 * Try to run a script in the Groovy console, having first ensured that this
5737 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5738 * be targeted at this alignment.
5741 protected void runGroovy_actionPerformed()
5743 Jalview.setCurrentAlignFrame(this);
5744 groovy.ui.Console console = Desktop.getGroovyConsole();
5745 if (console != null)
5749 console.runScript();
5750 } catch (Exception ex)
5752 System.err.println((ex.toString()));
5753 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5754 MessageManager.getString("label.couldnt_run_groovy_script"),
5755 MessageManager.getString("label.groovy_support_failed"),
5756 JvOptionPane.ERROR_MESSAGE);
5761 System.err.println("Can't run Groovy script as console not found");
5766 * Hides columns containing (or not containing) a specified feature, provided
5767 * that would not leave all columns hidden
5769 * @param featureType
5770 * @param columnsContaining
5773 public boolean hideFeatureColumns(String featureType,
5774 boolean columnsContaining)
5776 boolean notForHiding = avc.markColumnsContainingFeatures(
5777 columnsContaining, false, false, featureType);
5780 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5781 false, featureType))
5783 getViewport().hideSelectedColumns();
5791 protected void selectHighlightedColumns_actionPerformed(
5792 ActionEvent actionEvent)
5794 // include key modifier check in case user selects from menu
5795 avc.markHighlightedColumns(
5796 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5797 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5798 | ActionEvent.CTRL_MASK)) != 0);
5802 * Rebuilds the Colour menu, including any user-defined colours which have
5803 * been loaded either on startup or during the session
5805 public void buildColourMenu()
5807 colourMenu.removeAll();
5809 colourMenu.add(applyToAllGroups);
5810 colourMenu.add(textColour);
5811 colourMenu.addSeparator();
5813 ColourMenuHelper.addMenuItems(colourMenu, this, viewport.getAlignment(),
5816 colourMenu.addSeparator();
5817 colourMenu.add(conservationMenuItem);
5818 colourMenu.add(modifyConservation);
5819 colourMenu.add(abovePIDThreshold);
5820 colourMenu.add(modifyPID);
5821 colourMenu.add(annotationColour);
5823 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5824 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5828 * Open a dialog (if not already open) that allows the user to select and
5829 * calculate PCA or Tree analysis
5831 protected void openTreePcaDialog()
5833 if (alignPanel.getCalculationDialog() == null)
5835 new CalculationChooser(AlignFrame.this);
5840 * Sets the status of the HMMER menu
5842 public void updateHMMERStatus()
5844 hmmerMenu.setEnabled(HmmerCommand.isHmmerAvailable());
5848 * Returns the selected hidden Markov model.
5852 public HiddenMarkovModel getSelectedHMM()
5854 if (selectedHMMSequence == null)
5858 return selectedHMMSequence.getHMM();
5862 * Returns the selected hidden Markov model.
5866 public SequenceI getSelectedHMMSequence()
5868 return selectedHMMSequence;
5872 * Sets the selected hidden Markov model
5874 * @param selectedHMM
5876 public void setSelectedHMMSequence(SequenceI selectedHMM)
5878 this.selectedHMMSequence = selectedHMM;
5879 hmmAlign.setText(MessageManager.getString("label.hmmalign") + " to "
5880 + selectedHMM.getHMM().getName());
5881 hmmSearch.setText(MessageManager.getString("label.hmmsearch") + " with "
5882 + selectedHMM.getHMM().getName());
5886 public void hmmerMenu_actionPerformed(ActionEvent e)
5888 SequenceGroup grp = getViewport().getSelectionGroup();
5891 hmmBuild.setText(MessageManager.getString("label.hmmbuild") + " from "
5896 hmmBuild.setText(MessageManager.getString("label.hmmbuild")
5897 + " from Alignment");
5903 class PrintThread extends Thread
5907 public PrintThread(AlignmentPanel ap)
5912 static PageFormat pf;
5917 PrinterJob printJob = PrinterJob.getPrinterJob();
5921 printJob.setPrintable(ap, pf);
5925 printJob.setPrintable(ap);
5928 if (printJob.printDialog())
5933 } catch (Exception PrintException)
5935 PrintException.printStackTrace();