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.HMMAlign;
67 import jalview.hmmer.HMMBuild;
68 import jalview.hmmer.HMMERParamStore;
69 import jalview.hmmer.HMMERPreset;
70 import jalview.hmmer.HMMSearch;
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.io.vcf.VCFLoader;
92 import jalview.jbgui.GAlignFrame;
93 import jalview.schemes.ColourSchemeI;
94 import jalview.schemes.ColourSchemes;
95 import jalview.schemes.ResidueColourScheme;
96 import jalview.schemes.TCoffeeColourScheme;
97 import jalview.util.MessageManager;
98 import jalview.util.StringUtils;
99 import jalview.viewmodel.AlignmentViewport;
100 import jalview.viewmodel.ViewportRanges;
101 import jalview.ws.DBRefFetcher;
102 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
103 import jalview.ws.jws1.Discoverer;
104 import jalview.ws.jws2.Jws2Discoverer;
105 import jalview.ws.jws2.jabaws2.Jws2Instance;
106 import jalview.ws.params.ArgumentI;
107 import jalview.ws.params.ParamDatastoreI;
108 import jalview.ws.params.WsParamSetI;
109 import jalview.ws.params.simple.Option;
110 import jalview.ws.seqfetcher.DbSourceProxy;
112 import java.awt.BorderLayout;
113 import java.awt.Component;
114 import java.awt.Rectangle;
115 import java.awt.Toolkit;
116 import java.awt.datatransfer.Clipboard;
117 import java.awt.datatransfer.DataFlavor;
118 import java.awt.datatransfer.StringSelection;
119 import java.awt.datatransfer.Transferable;
120 import java.awt.dnd.DnDConstants;
121 import java.awt.dnd.DropTargetDragEvent;
122 import java.awt.dnd.DropTargetDropEvent;
123 import java.awt.dnd.DropTargetEvent;
124 import java.awt.dnd.DropTargetListener;
125 import java.awt.event.ActionEvent;
126 import java.awt.event.ActionListener;
127 import java.awt.event.FocusAdapter;
128 import java.awt.event.FocusEvent;
129 import java.awt.event.ItemEvent;
130 import java.awt.event.ItemListener;
131 import java.awt.event.KeyAdapter;
132 import java.awt.event.KeyEvent;
133 import java.awt.event.MouseEvent;
134 import java.awt.print.PageFormat;
135 import java.awt.print.PrinterJob;
136 import java.beans.PropertyChangeEvent;
138 import java.io.FileWriter;
139 import java.io.IOException;
140 import java.io.PrintWriter;
142 import java.util.ArrayList;
143 import java.util.Arrays;
144 import java.util.Deque;
145 import java.util.Enumeration;
146 import java.util.HashMap;
147 import java.util.Hashtable;
148 import java.util.List;
149 import java.util.Map;
150 import java.util.Scanner;
151 import java.util.Vector;
153 import javax.swing.JCheckBoxMenuItem;
154 import javax.swing.JEditorPane;
155 import javax.swing.JFileChooser;
156 import javax.swing.JInternalFrame;
157 import javax.swing.JLayeredPane;
158 import javax.swing.JMenu;
159 import javax.swing.JMenuItem;
160 import javax.swing.JOptionPane;
161 import javax.swing.JScrollPane;
162 import javax.swing.SwingUtilities;
168 * @version $Revision$
170 public class AlignFrame extends GAlignFrame implements DropTargetListener,
171 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
174 Map<String, Float> distribution = new HashMap<>(); // temporary
176 public static final int DEFAULT_WIDTH = 700;
178 public static final int DEFAULT_HEIGHT = 500;
181 * The currently displayed panel (selected tabbed view if more than one)
183 public AlignmentPanel alignPanel;
185 AlignViewport viewport;
187 public AlignViewControllerI avc;
189 * The selected HMM for this align frame
191 SequenceI selectedHMMSequence;
193 List<AlignmentPanel> alignPanels = new ArrayList<>();
196 * Last format used to load or save alignments in this window
198 FileFormatI currentFileFormat = null;
201 * Current filename for this alignment
203 String fileName = null;
207 * Creates a new AlignFrame object with specific width and height.
213 public AlignFrame(AlignmentI al, int width, int height)
215 this(al, null, width, height);
219 * Creates a new AlignFrame object with specific width, height and
225 * @param sequenceSetId
227 public AlignFrame(AlignmentI al, int width, int height,
228 String sequenceSetId)
230 this(al, null, width, height, sequenceSetId);
234 * Creates a new AlignFrame object with specific width, height and
240 * @param sequenceSetId
243 public AlignFrame(AlignmentI al, int width, int height,
244 String sequenceSetId, String viewId)
246 this(al, null, width, height, sequenceSetId, viewId);
250 * new alignment window with hidden columns
254 * @param hiddenColumns
255 * ColumnSelection or null
257 * Width of alignment frame
261 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
264 this(al, hiddenColumns, width, height, null);
268 * Create alignment frame for al with hiddenColumns, a specific width and
269 * height, and specific sequenceId
272 * @param hiddenColumns
275 * @param sequenceSetId
278 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
279 int height, String sequenceSetId)
281 this(al, hiddenColumns, width, height, sequenceSetId, null);
285 * Create alignment frame for al with hiddenColumns, a specific width and
286 * height, and specific sequenceId
289 * @param hiddenColumns
292 * @param sequenceSetId
297 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
298 int height, String sequenceSetId, String viewId)
300 setSize(width, height);
302 if (al.getDataset() == null)
307 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
309 alignPanel = new AlignmentPanel(this, viewport);
311 addAlignmentPanel(alignPanel, true);
315 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
316 HiddenColumns hiddenColumns, int width, int height)
318 setSize(width, height);
320 if (al.getDataset() == null)
325 viewport = new AlignViewport(al, hiddenColumns);
327 if (hiddenSeqs != null && hiddenSeqs.length > 0)
329 viewport.hideSequence(hiddenSeqs);
331 alignPanel = new AlignmentPanel(this, viewport);
332 addAlignmentPanel(alignPanel, true);
337 * Make a new AlignFrame from existing alignmentPanels
344 public AlignFrame(AlignmentPanel ap)
348 addAlignmentPanel(ap, false);
353 * initalise the alignframe from the underlying viewport data and the
358 if (!Jalview.isHeadlessMode())
360 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
363 avc = new jalview.controller.AlignViewController(this, viewport,
365 if (viewport.getAlignmentConservationAnnotation() == null)
367 // BLOSUM62Colour.setEnabled(false);
368 conservationMenuItem.setEnabled(false);
369 modifyConservation.setEnabled(false);
370 // PIDColour.setEnabled(false);
371 // abovePIDThreshold.setEnabled(false);
372 // modifyPID.setEnabled(false);
375 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
378 if (sortby.equals("Id"))
380 sortIDMenuItem_actionPerformed(null);
382 else if (sortby.equals("Pairwise Identity"))
384 sortPairwiseMenuItem_actionPerformed(null);
388 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
390 setMenusFromViewport(viewport);
391 buildSortByAnnotationScoresMenu();
392 calculateTree.addActionListener(new ActionListener()
396 public void actionPerformed(ActionEvent e)
403 if (Desktop.desktop != null)
405 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
406 addServiceListeners();
410 if (viewport.getWrapAlignment())
412 wrapMenuItem_actionPerformed(null);
415 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
417 this.overviewMenuItem_actionPerformed(null);
422 final List<AlignmentPanel> selviews = new ArrayList<>();
423 final List<AlignmentPanel> origview = new ArrayList<>();
424 final String menuLabel = MessageManager
425 .getString("label.copy_format_from");
426 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
427 new ViewSetProvider()
431 public AlignmentPanel[] getAllAlignmentPanels()
434 origview.add(alignPanel);
435 // make an array of all alignment panels except for this one
436 List<AlignmentPanel> aps = new ArrayList<>(
437 Arrays.asList(Desktop.getAlignmentPanels(null)));
438 aps.remove(AlignFrame.this.alignPanel);
439 return aps.toArray(new AlignmentPanel[aps.size()]);
441 }, selviews, new ItemListener()
445 public void itemStateChanged(ItemEvent e)
447 if (origview.size() > 0)
449 final AlignmentPanel ap = origview.get(0);
452 * Copy the ViewStyle of the selected panel to 'this one'.
453 * Don't change value of 'scaleProteinAsCdna' unless copying
456 ViewStyleI vs = selviews.get(0).getAlignViewport()
458 boolean fromSplitFrame = selviews.get(0)
459 .getAlignViewport().getCodingComplement() != null;
462 vs.setScaleProteinAsCdna(ap.getAlignViewport()
463 .getViewStyle().isScaleProteinAsCdna());
465 ap.getAlignViewport().setViewStyle(vs);
468 * Also rescale ViewStyle of SplitFrame complement if there is
469 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
470 * the whole ViewStyle (allow cDNA protein to have different
473 AlignViewportI complement = ap.getAlignViewport()
474 .getCodingComplement();
475 if (complement != null && vs.isScaleProteinAsCdna())
477 AlignFrame af = Desktop.getAlignFrameFor(complement);
478 ((SplitFrame) af.getSplitViewContainer())
480 af.setMenusForViewport();
484 ap.setSelected(true);
485 ap.alignFrame.setMenusForViewport();
490 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
491 .indexOf("devel") > -1
492 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
493 .indexOf("test") > -1)
495 formatMenu.add(vsel);
497 addFocusListener(new FocusAdapter()
500 public void focusGained(FocusEvent e)
502 Jalview.setCurrentAlignFrame(AlignFrame.this);
509 * Change the filename and format for the alignment, and enable the 'reload'
510 * button functionality.
517 public void setFileName(String file, FileFormatI format)
520 setFileFormat(format);
521 reload.setEnabled(true);
525 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
528 void addKeyListener()
530 addKeyListener(new KeyAdapter()
533 public void keyPressed(KeyEvent evt)
535 if (viewport.cursorMode
536 && ((evt.getKeyCode() >= KeyEvent.VK_0
537 && evt.getKeyCode() <= KeyEvent.VK_9)
538 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
539 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
540 && Character.isDigit(evt.getKeyChar()))
542 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
545 switch (evt.getKeyCode())
548 case 27: // escape key
549 deselectAllSequenceMenuItem_actionPerformed(null);
553 case KeyEvent.VK_DOWN:
554 if (evt.isAltDown() || !viewport.cursorMode)
556 moveSelectedSequences(false);
558 if (viewport.cursorMode)
560 alignPanel.getSeqPanel().moveCursor(0, 1);
565 if (evt.isAltDown() || !viewport.cursorMode)
567 moveSelectedSequences(true);
569 if (viewport.cursorMode)
571 alignPanel.getSeqPanel().moveCursor(0, -1);
576 case KeyEvent.VK_LEFT:
577 if (evt.isAltDown() || !viewport.cursorMode)
579 slideSequences(false,
580 alignPanel.getSeqPanel().getKeyboardNo1());
584 alignPanel.getSeqPanel().moveCursor(-1, 0);
589 case KeyEvent.VK_RIGHT:
590 if (evt.isAltDown() || !viewport.cursorMode)
592 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
596 alignPanel.getSeqPanel().moveCursor(1, 0);
600 case KeyEvent.VK_SPACE:
601 if (viewport.cursorMode)
603 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
604 || evt.isShiftDown() || evt.isAltDown());
608 // case KeyEvent.VK_A:
609 // if (viewport.cursorMode)
611 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
612 // //System.out.println("A");
616 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
617 * System.out.println("closing bracket"); } break;
619 case KeyEvent.VK_DELETE:
620 case KeyEvent.VK_BACK_SPACE:
621 if (!viewport.cursorMode)
623 cut_actionPerformed(null);
627 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
628 || evt.isShiftDown() || evt.isAltDown());
634 if (viewport.cursorMode)
636 alignPanel.getSeqPanel().setCursorRow();
640 if (viewport.cursorMode && !evt.isControlDown())
642 alignPanel.getSeqPanel().setCursorColumn();
646 if (viewport.cursorMode)
648 alignPanel.getSeqPanel().setCursorPosition();
652 case KeyEvent.VK_ENTER:
653 case KeyEvent.VK_COMMA:
654 if (viewport.cursorMode)
656 alignPanel.getSeqPanel().setCursorRowAndColumn();
661 if (viewport.cursorMode)
663 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
667 if (viewport.cursorMode)
669 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
674 viewport.cursorMode = !viewport.cursorMode;
675 statusBar.setText(MessageManager
676 .formatMessage("label.keyboard_editing_mode", new String[]
677 { (viewport.cursorMode ? "on" : "off") }));
678 if (viewport.cursorMode)
680 ViewportRanges ranges = viewport.getRanges();
681 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
683 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
686 alignPanel.getSeqPanel().seqCanvas.repaint();
692 Help.showHelpWindow();
693 } catch (Exception ex)
695 ex.printStackTrace();
700 boolean toggleSeqs = !evt.isControlDown();
701 boolean toggleCols = !evt.isShiftDown();
702 toggleHiddenRegions(toggleSeqs, toggleCols);
707 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
708 boolean modifyExisting = true; // always modify, don't clear
709 // evt.isShiftDown();
710 boolean invertHighlighted = evt.isAltDown();
711 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
715 case KeyEvent.VK_PAGE_UP:
716 viewport.getRanges().pageUp();
718 case KeyEvent.VK_PAGE_DOWN:
719 viewport.getRanges().pageDown();
725 public void keyReleased(KeyEvent evt)
727 switch (evt.getKeyCode())
729 case KeyEvent.VK_LEFT:
730 if (evt.isAltDown() || !viewport.cursorMode)
732 viewport.firePropertyChange("alignment", null,
733 viewport.getAlignment().getSequences());
737 case KeyEvent.VK_RIGHT:
738 if (evt.isAltDown() || !viewport.cursorMode)
740 viewport.firePropertyChange("alignment", null,
741 viewport.getAlignment().getSequences());
749 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
751 ap.alignFrame = this;
752 avc = new jalview.controller.AlignViewController(this, viewport,
757 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
759 int aSize = alignPanels.size();
761 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
763 if (aSize == 1 && ap.av.viewName == null)
765 this.getContentPane().add(ap, BorderLayout.CENTER);
771 setInitialTabVisible();
774 expandViews.setEnabled(true);
775 gatherViews.setEnabled(true);
776 tabbedPane.addTab(ap.av.viewName, ap);
778 ap.setVisible(false);
783 if (ap.av.isPadGaps())
785 ap.av.getAlignment().padGaps();
787 ap.av.updateConservation(ap);
788 ap.av.updateConsensus(ap);
789 ap.av.updateStrucConsensus(ap);
790 ap.av.initInformationWorker(ap);
794 public void setInitialTabVisible()
796 expandViews.setEnabled(true);
797 gatherViews.setEnabled(true);
798 tabbedPane.setVisible(true);
799 AlignmentPanel first = alignPanels.get(0);
800 tabbedPane.addTab(first.av.viewName, first);
801 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
804 public AlignViewport getViewport()
809 /* Set up intrinsic listeners for dynamically generated GUI bits. */
810 private void addServiceListeners()
812 final java.beans.PropertyChangeListener thisListener;
813 Desktop.instance.addJalviewPropertyChangeListener("services",
814 thisListener = new java.beans.PropertyChangeListener()
817 public void propertyChange(PropertyChangeEvent evt)
819 // // System.out.println("Discoverer property change.");
820 // if (evt.getPropertyName().equals("services"))
822 SwingUtilities.invokeLater(new Runnable()
829 "Rebuild WS Menu for service change");
830 BuildWebServiceMenu();
837 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
840 public void internalFrameClosed(
841 javax.swing.event.InternalFrameEvent evt)
843 // System.out.println("deregistering discoverer listener");
844 Desktop.instance.removeJalviewPropertyChangeListener("services",
846 closeMenuItem_actionPerformed(true);
849 // Finally, build the menu once to get current service state
850 new Thread(new Runnable()
855 BuildWebServiceMenu();
861 * Configure menu items that vary according to whether the alignment is
862 * nucleotide or protein
864 public void setGUINucleotide()
866 AlignmentI al = getViewport().getAlignment();
867 boolean nucleotide = al.isNucleotide();
869 loadVcf.setVisible(nucleotide);
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 hmmBuild_actionPerformed(boolean withDefaults)
1029 if (!alignmentIsSufficient(1))
1033 List<ArgumentI> args = new ArrayList<>();
1036 // todo: construct this in HMMERPreset?
1037 String argName = MessageManager.getString("label.hmmbuild_for");
1038 String argValue = MessageManager.getString("label.alignment");
1040 new Option(argName, null, false, null, argValue, null, null));
1044 WsParamSetI set = new HMMERPreset();
1045 ParamDatastoreI store = HMMERParamStore.forBuild(viewport);
1046 WsJobParameters params = new WsJobParameters(store, set, args);
1047 if (params.showRunDialog())
1049 args = params.getJobParams();
1053 return; // user cancelled
1056 new Thread(new HMMBuild(this, args)).start();
1060 public void hmmAlign_actionPerformed(boolean withDefaults)
1062 if (!(checkForHMM() && alignmentIsSufficient(2)))
1066 List<ArgumentI> args = new ArrayList<>();
1069 WsParamSetI set = new HMMERPreset();
1070 ParamDatastoreI store = HMMERParamStore.forAlign(viewport);
1071 WsJobParameters params = new WsJobParameters(store, set, args);
1072 if (params.showRunDialog())
1074 args = params.getJobParams();
1078 return; // user cancelled
1081 new Thread(new HMMAlign(this, args)).start();
1085 public void hmmSearch_actionPerformed(boolean withDefaults)
1091 List<ArgumentI> args = new ArrayList<>();
1094 WsParamSetI set = new HMMERPreset();
1095 ParamDatastoreI store = HMMERParamStore.forSearch(viewport);
1096 WsJobParameters params = new WsJobParameters(store, set, args);
1097 if (params.showRunDialog())
1099 args = params.getJobParams();
1103 return; // user cancelled
1106 new Thread(new HMMSearch(this, args)).start();
1107 alignPanel.repaint();
1111 * Checks if the frame has a selected hidden Markov model
1115 private boolean checkForHMM()
1117 if (getSelectedHMM() == null)
1119 JOptionPane.showMessageDialog(this,
1120 MessageManager.getString("warn.no_selected_hmm"));
1127 * Checks if the alignment contains the required number of sequences.
1132 public boolean alignmentIsSufficient(int required)
1134 if (getViewport().getAlignment().getSequences().size() < required)
1136 JOptionPane.showMessageDialog(this,
1137 MessageManager.getString("warn.not_enough_sequences"));
1144 public void addDatabase_actionPerformed() throws IOException
1146 if (Cache.getProperty(Preferences.HMMSEARCH_DB_PATHS) == null)
1148 Cache.setProperty(Preferences.HMMSEARCH_DBS, "");
1149 Cache.setProperty(Preferences.HMMSEARCH_DB_PATHS, "");
1152 String path = openFileChooser(false);
1153 if (new File(path).exists())
1155 IdentifyFile identifier = new IdentifyFile();
1156 FileFormatI format = identifier.identify(path, DataSourceType.FILE);
1157 if (format == FileFormat.Fasta || format == FileFormat.Stockholm
1158 || format == FileFormat.Pfam)
1160 String currentDbs = Cache.getProperty(Preferences.HMMSEARCH_DBS);
1161 String currentDbPaths = Cache
1162 .getProperty(Preferences.HMMSEARCH_DB_PATHS);
1163 currentDbPaths += " " + path;
1165 String fileName = StringUtils.getLastToken(path, File.separator);
1166 Scanner scanner = new Scanner(fileName).useDelimiter(".");
1167 String name = scanner.next();
1169 currentDbs += " " + path; // TODO remove path from file name
1172 Cache.setProperty(Preferences.HMMSEARCH_DB_PATHS, currentDbPaths);
1173 Cache.setProperty(Preferences.HMMSEARCH_DBS, currentDbPaths);
1177 JOptionPane.showMessageDialog(this,
1178 MessageManager.getString("warn.invalid_format"));
1183 JOptionPane.showMessageDialog(this,
1184 MessageManager.getString("warn.not_enough_sequences"));
1189 * Opens a file chooser
1194 protected String openFileChooser(boolean forFolder)
1196 String choice = null;
1197 JFileChooser chooser = new JFileChooser();
1200 chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1202 chooser.setDialogTitle(
1203 MessageManager.getString("label.open_local_file"));
1204 chooser.setToolTipText(MessageManager.getString("action.open"));
1206 int value = chooser.showOpenDialog(this);
1208 if (value == JFileChooser.APPROVE_OPTION)
1210 choice = chooser.getSelectedFile().getPath();
1216 public void reload_actionPerformed(ActionEvent e)
1218 if (fileName != null)
1220 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1221 // originating file's format
1222 // TODO: work out how to recover feature settings for correct view(s) when
1223 // file is reloaded.
1224 if (FileFormat.Jalview.equals(currentFileFormat))
1226 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1227 for (int i = 0; i < frames.length; i++)
1229 if (frames[i] instanceof AlignFrame && frames[i] != this
1230 && ((AlignFrame) frames[i]).fileName != null
1231 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1235 frames[i].setSelected(true);
1236 Desktop.instance.closeAssociatedWindows();
1237 } catch (java.beans.PropertyVetoException ex)
1243 Desktop.instance.closeAssociatedWindows();
1245 FileLoader loader = new FileLoader();
1246 DataSourceType protocol = fileName.startsWith("http:")
1247 ? DataSourceType.URL
1248 : DataSourceType.FILE;
1249 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1253 Rectangle bounds = this.getBounds();
1255 FileLoader loader = new FileLoader();
1256 DataSourceType protocol = fileName.startsWith("http:")
1257 ? DataSourceType.URL
1258 : DataSourceType.FILE;
1259 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1260 protocol, currentFileFormat);
1262 newframe.setBounds(bounds);
1263 if (featureSettings != null && featureSettings.isShowing())
1265 final Rectangle fspos = featureSettings.frame.getBounds();
1266 // TODO: need a 'show feature settings' function that takes bounds -
1267 // need to refactor Desktop.addFrame
1268 newframe.featureSettings_actionPerformed(null);
1269 final FeatureSettings nfs = newframe.featureSettings;
1270 SwingUtilities.invokeLater(new Runnable()
1275 nfs.frame.setBounds(fspos);
1278 this.featureSettings.close();
1279 this.featureSettings = null;
1281 this.closeMenuItem_actionPerformed(true);
1287 public void addFromText_actionPerformed(ActionEvent e)
1290 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1294 public void addFromURL_actionPerformed(ActionEvent e)
1296 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1300 public void save_actionPerformed(ActionEvent e)
1302 if (fileName == null || (currentFileFormat == null)
1303 || fileName.startsWith("http"))
1305 saveAs_actionPerformed(null);
1309 saveAlignment(fileName, currentFileFormat);
1320 public void saveAs_actionPerformed(ActionEvent e)
1322 String format = currentFileFormat == null ? null
1323 : currentFileFormat.getName();
1324 JalviewFileChooser chooser = JalviewFileChooser
1325 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1327 chooser.setFileView(new JalviewFileView());
1328 chooser.setDialogTitle(
1329 MessageManager.getString("label.save_alignment_to_file"));
1330 chooser.setToolTipText(MessageManager.getString("action.save"));
1332 int value = chooser.showSaveDialog(this);
1334 if (value == JalviewFileChooser.APPROVE_OPTION)
1336 currentFileFormat = chooser.getSelectedFormat();
1337 while (currentFileFormat == null)
1339 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1340 MessageManager.getString(
1341 "label.select_file_format_before_saving"),
1342 MessageManager.getString("label.file_format_not_specified"),
1343 JvOptionPane.WARNING_MESSAGE);
1344 currentFileFormat = chooser.getSelectedFormat();
1345 value = chooser.showSaveDialog(this);
1346 if (value != JalviewFileChooser.APPROVE_OPTION)
1352 fileName = chooser.getSelectedFile().getPath();
1354 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1356 Cache.setProperty("LAST_DIRECTORY", fileName);
1357 saveAlignment(fileName, currentFileFormat);
1361 public boolean saveAlignment(String file, FileFormatI format)
1363 boolean success = true;
1365 if (FileFormat.Jalview.equals(format))
1367 String shortName = title;
1369 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1371 shortName = shortName.substring(
1372 shortName.lastIndexOf(java.io.File.separatorChar) + 1);
1375 success = new Jalview2XML().saveAlignment(this, file, shortName);
1377 statusBar.setText(MessageManager.formatMessage(
1378 "label.successfully_saved_to_file_in_format", new Object[]
1379 { fileName, format }));
1384 AlignmentExportData exportData = getAlignmentForExport(format,
1386 if (exportData.getSettings().isCancelled())
1390 FormatAdapter f = new FormatAdapter(alignPanel,
1391 exportData.getSettings());
1392 String output = f.formatSequences(format, exportData.getAlignment(), // class
1396 // occur in the distant future
1397 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1398 f.getCacheSuffixDefault(format),
1399 viewport.getAlignment().getHiddenColumns());
1409 PrintWriter out = new PrintWriter(new FileWriter(file));
1413 this.setTitle(file);
1414 statusBar.setText(MessageManager.formatMessage(
1415 "label.successfully_saved_to_file_in_format", new Object[]
1416 { fileName, format.getName() }));
1417 } catch (Exception ex)
1420 ex.printStackTrace();
1427 JvOptionPane.showInternalMessageDialog(this, MessageManager
1428 .formatMessage("label.couldnt_save_file", new Object[]
1430 MessageManager.getString("label.error_saving_file"),
1431 JvOptionPane.WARNING_MESSAGE);
1437 private void warningMessage(String warning, String title)
1439 if (new jalview.util.Platform().isHeadless())
1441 System.err.println("Warning: " + title + "\nWarning: " + warning);
1446 JvOptionPane.showInternalMessageDialog(this, warning, title,
1447 JvOptionPane.WARNING_MESSAGE);
1459 protected void outputText_actionPerformed(ActionEvent e)
1461 FileFormatI fileFormat = FileFormats.getInstance()
1462 .forName(e.getActionCommand());
1463 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1465 if (exportData.getSettings().isCancelled())
1469 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1470 cap.setForInput(null);
1473 FileFormatI format = fileFormat;
1474 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1475 .formatSequences(format, exportData.getAlignment(),
1476 exportData.getOmitHidden(),
1477 exportData.getStartEndPostions(),
1478 viewport.getAlignment().getHiddenColumns()));
1479 Desktop.addInternalFrame(cap, MessageManager
1480 .formatMessage("label.alignment_output_command", new Object[]
1481 { e.getActionCommand() }), 600, 500);
1482 } catch (OutOfMemoryError oom)
1484 new OOMWarning("Outputting alignment as " + e.getActionCommand(),
1491 public static AlignmentExportData getAlignmentForExport(
1492 FileFormatI format, AlignViewportI viewport,
1493 AlignExportSettingI exportSettings)
1495 AlignmentI alignmentToExport = null;
1496 AlignExportSettingI settings = exportSettings;
1497 String[] omitHidden = null;
1499 HiddenSequences hiddenSeqs = viewport.getAlignment()
1500 .getHiddenSequences();
1502 alignmentToExport = viewport.getAlignment();
1504 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1505 if (settings == null)
1507 settings = new AlignExportSettings(hasHiddenSeqs,
1508 viewport.hasHiddenColumns(), format);
1510 // settings.isExportAnnotations();
1512 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1514 omitHidden = viewport.getViewAsString(false,
1515 settings.isExportHiddenSequences());
1518 int[] alignmentStartEnd = new int[2];
1519 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1521 alignmentToExport = hiddenSeqs.getFullAlignment();
1525 alignmentToExport = viewport.getAlignment();
1527 alignmentStartEnd = viewport.getAlignment().getHiddenColumns()
1528 .getVisibleStartAndEndIndex(alignmentToExport.getWidth());
1529 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1530 omitHidden, alignmentStartEnd, settings);
1541 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1543 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1544 htmlSVG.exportHTML(null);
1548 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1550 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1551 bjs.exportHTML(null);
1554 public void createImageMap(File file, String image)
1556 alignPanel.makePNGImageMap(file, image);
1566 public void createPNG(File f)
1568 alignPanel.makePNG(f);
1578 public void createEPS(File f)
1580 alignPanel.makeEPS(f);
1584 public void createSVG(File f)
1586 alignPanel.makeSVG(f);
1590 public void pageSetup_actionPerformed(ActionEvent e)
1592 PrinterJob printJob = PrinterJob.getPrinterJob();
1593 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1603 public void printMenuItem_actionPerformed(ActionEvent e)
1605 // Putting in a thread avoids Swing painting problems
1606 PrintThread thread = new PrintThread(alignPanel);
1611 public void exportFeatures_actionPerformed(ActionEvent e)
1613 new AnnotationExporter(alignPanel).exportFeatures();
1617 public void exportAnnotations_actionPerformed(ActionEvent e)
1619 new AnnotationExporter(alignPanel).exportAnnotations();
1623 public void associatedData_actionPerformed(ActionEvent e)
1624 throws IOException, InterruptedException
1626 // Pick the tree file
1627 JalviewFileChooser chooser = new JalviewFileChooser(
1628 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1629 chooser.setFileView(new JalviewFileView());
1630 chooser.setDialogTitle(
1631 MessageManager.getString("label.load_jalview_annotations"));
1632 chooser.setToolTipText(
1633 MessageManager.getString("label.load_jalview_annotations"));
1635 int value = chooser.showOpenDialog(null);
1637 if (value == JalviewFileChooser.APPROVE_OPTION)
1639 String choice = chooser.getSelectedFile().getPath();
1640 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1641 loadJalviewDataFile(choice, null, null, null);
1647 * Close the current view or all views in the alignment frame. If the frame
1648 * only contains one view then the alignment will be removed from memory.
1650 * @param closeAllTabs
1653 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1655 if (alignPanels != null && alignPanels.size() < 2)
1657 closeAllTabs = true;
1662 if (alignPanels != null)
1666 if (this.isClosed())
1668 // really close all the windows - otherwise wait till
1669 // setClosed(true) is called
1670 for (int i = 0; i < alignPanels.size(); i++)
1672 AlignmentPanel ap = alignPanels.get(i);
1679 closeView(alignPanel);
1686 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1687 * be called recursively, with the frame now in 'closed' state
1689 this.setClosed(true);
1691 } catch (Exception ex)
1693 ex.printStackTrace();
1698 * Close the specified panel and close up tabs appropriately.
1700 * @param panelToClose
1702 public void closeView(AlignmentPanel panelToClose)
1704 int index = tabbedPane.getSelectedIndex();
1705 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1706 alignPanels.remove(panelToClose);
1707 panelToClose.closePanel();
1708 panelToClose = null;
1710 tabbedPane.removeTabAt(closedindex);
1711 tabbedPane.validate();
1713 if (index > closedindex || index == tabbedPane.getTabCount())
1715 // modify currently selected tab index if necessary.
1719 this.tabSelectionChanged(index);
1725 void updateEditMenuBar()
1728 if (viewport.getHistoryList().size() > 0)
1730 undoMenuItem.setEnabled(true);
1731 CommandI command = viewport.getHistoryList().peek();
1732 undoMenuItem.setText(MessageManager
1733 .formatMessage("label.undo_command", new Object[]
1734 { command.getDescription() }));
1738 undoMenuItem.setEnabled(false);
1739 undoMenuItem.setText(MessageManager.getString("action.undo"));
1742 if (viewport.getRedoList().size() > 0)
1744 redoMenuItem.setEnabled(true);
1746 CommandI command = viewport.getRedoList().peek();
1747 redoMenuItem.setText(MessageManager
1748 .formatMessage("label.redo_command", new Object[]
1749 { command.getDescription() }));
1753 redoMenuItem.setEnabled(false);
1754 redoMenuItem.setText(MessageManager.getString("action.redo"));
1759 public void addHistoryItem(CommandI command)
1761 if (command.getSize() > 0)
1763 viewport.addToHistoryList(command);
1764 viewport.clearRedoList();
1765 updateEditMenuBar();
1766 viewport.updateHiddenColumns();
1767 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1768 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1769 // viewport.getColumnSelection()
1770 // .getHiddenColumns().size() > 0);
1776 * @return alignment objects for all views
1778 AlignmentI[] getViewAlignments()
1780 if (alignPanels != null)
1782 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1784 for (AlignmentPanel ap : alignPanels)
1786 als[i++] = ap.av.getAlignment();
1790 if (viewport != null)
1792 return new AlignmentI[] { viewport.getAlignment() };
1804 protected void undoMenuItem_actionPerformed(ActionEvent e)
1806 if (viewport.getHistoryList().isEmpty())
1810 CommandI command = viewport.getHistoryList().pop();
1811 viewport.addToRedoList(command);
1812 command.undoCommand(getViewAlignments());
1814 AlignmentViewport originalSource = getOriginatingSource(command);
1815 updateEditMenuBar();
1817 if (originalSource != null)
1819 if (originalSource != viewport)
1822 "Implementation worry: mismatch of viewport origin for undo");
1824 originalSource.updateHiddenColumns();
1825 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1827 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1828 // viewport.getColumnSelection()
1829 // .getHiddenColumns().size() > 0);
1830 originalSource.firePropertyChange("alignment", null,
1831 originalSource.getAlignment().getSequences());
1842 protected void redoMenuItem_actionPerformed(ActionEvent e)
1844 if (viewport.getRedoList().size() < 1)
1849 CommandI command = viewport.getRedoList().pop();
1850 viewport.addToHistoryList(command);
1851 command.doCommand(getViewAlignments());
1853 AlignmentViewport originalSource = getOriginatingSource(command);
1854 updateEditMenuBar();
1856 if (originalSource != null)
1859 if (originalSource != viewport)
1862 "Implementation worry: mismatch of viewport origin for redo");
1864 originalSource.updateHiddenColumns();
1865 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1867 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1868 // viewport.getColumnSelection()
1869 // .getHiddenColumns().size() > 0);
1870 originalSource.firePropertyChange("alignment", null,
1871 originalSource.getAlignment().getSequences());
1875 AlignmentViewport getOriginatingSource(CommandI command)
1877 AlignmentViewport originalSource = null;
1878 // For sequence removal and addition, we need to fire
1879 // the property change event FROM the viewport where the
1880 // original alignment was altered
1881 AlignmentI al = null;
1882 if (command instanceof EditCommand)
1884 EditCommand editCommand = (EditCommand) command;
1885 al = editCommand.getAlignment();
1886 List<Component> comps = PaintRefresher.components
1887 .get(viewport.getSequenceSetId());
1889 for (Component comp : comps)
1891 if (comp instanceof AlignmentPanel)
1893 if (al == ((AlignmentPanel) comp).av.getAlignment())
1895 originalSource = ((AlignmentPanel) comp).av;
1902 if (originalSource == null)
1904 // The original view is closed, we must validate
1905 // the current view against the closed view first
1908 PaintRefresher.validateSequences(al, viewport.getAlignment());
1911 originalSource = viewport;
1914 return originalSource;
1923 public void moveSelectedSequences(boolean up)
1925 SequenceGroup sg = viewport.getSelectionGroup();
1931 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1932 viewport.getHiddenRepSequences(), up);
1933 alignPanel.paintAlignment(true, false);
1936 synchronized void slideSequences(boolean right, int size)
1938 List<SequenceI> sg = new ArrayList<>();
1939 if (viewport.cursorMode)
1941 sg.add(viewport.getAlignment()
1942 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1944 else if (viewport.getSelectionGroup() != null
1945 && viewport.getSelectionGroup().getSize() != viewport
1946 .getAlignment().getHeight())
1948 sg = viewport.getSelectionGroup()
1949 .getSequences(viewport.getHiddenRepSequences());
1957 List<SequenceI> invertGroup = new ArrayList<>();
1959 for (SequenceI seq : viewport.getAlignment().getSequences())
1961 if (!sg.contains(seq))
1963 invertGroup.add(seq);
1967 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1969 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1970 for (int i = 0; i < invertGroup.size(); i++)
1972 seqs2[i] = invertGroup.get(i);
1975 SlideSequencesCommand ssc;
1978 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1979 viewport.getGapCharacter());
1983 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1984 viewport.getGapCharacter());
1987 int groupAdjustment = 0;
1988 if (ssc.getGapsInsertedBegin() && right)
1990 if (viewport.cursorMode)
1992 alignPanel.getSeqPanel().moveCursor(size, 0);
1996 groupAdjustment = size;
1999 else if (!ssc.getGapsInsertedBegin() && !right)
2001 if (viewport.cursorMode)
2003 alignPanel.getSeqPanel().moveCursor(-size, 0);
2007 groupAdjustment = -size;
2011 if (groupAdjustment != 0)
2013 viewport.getSelectionGroup().setStartRes(
2014 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
2015 viewport.getSelectionGroup().setEndRes(
2016 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
2020 * just extend the last slide command if compatible; but not if in
2021 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
2023 boolean appendHistoryItem = false;
2024 Deque<CommandI> historyList = viewport.getHistoryList();
2025 boolean inSplitFrame = getSplitViewContainer() != null;
2026 if (!inSplitFrame && historyList != null && historyList.size() > 0
2027 && historyList.peek() instanceof SlideSequencesCommand)
2029 appendHistoryItem = ssc.appendSlideCommand(
2030 (SlideSequencesCommand) historyList.peek());
2033 if (!appendHistoryItem)
2035 addHistoryItem(ssc);
2048 protected void copy_actionPerformed(ActionEvent e)
2050 if (viewport.getSelectionGroup() == null)
2054 // TODO: preserve the ordering of displayed alignment annotation in any
2055 // internal paste (particularly sequence associated annotation)
2056 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2057 String[] omitHidden = null;
2059 if (viewport.hasHiddenColumns())
2061 omitHidden = viewport.getViewAsString(true);
2064 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2065 seqs, omitHidden, null);
2067 StringSelection ss = new StringSelection(output);
2071 jalview.gui.Desktop.internalCopy = true;
2072 // Its really worth setting the clipboard contents
2073 // to empty before setting the large StringSelection!!
2074 Toolkit.getDefaultToolkit().getSystemClipboard()
2075 .setContents(new StringSelection(""), null);
2077 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2079 } catch (OutOfMemoryError er)
2081 new OOMWarning("copying region", er);
2085 HiddenColumns hiddenColumns = null;
2086 if (viewport.hasHiddenColumns())
2088 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2089 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2091 // create new HiddenColumns object with copy of hidden regions
2092 // between startRes and endRes, offset by startRes
2093 hiddenColumns = new HiddenColumns(
2094 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2095 hiddenCutoff, hiddenOffset);
2098 Desktop.jalviewClipboard = new Object[] { seqs,
2099 viewport.getAlignment().getDataset(), hiddenColumns };
2100 statusBar.setText(MessageManager.formatMessage(
2101 "label.copied_sequences_to_clipboard", new Object[]
2102 { Integer.valueOf(seqs.length).toString() }));
2110 * @throws InterruptedException
2111 * @throws IOException
2114 protected void pasteNew_actionPerformed(ActionEvent e)
2115 throws IOException, InterruptedException
2125 * @throws InterruptedException
2126 * @throws IOException
2129 protected void pasteThis_actionPerformed(ActionEvent e)
2130 throws IOException, InterruptedException
2136 * Paste contents of Jalview clipboard
2138 * @param newAlignment
2139 * true to paste to a new alignment, otherwise add to this.
2140 * @throws InterruptedException
2141 * @throws IOException
2143 void paste(boolean newAlignment) throws IOException, InterruptedException
2145 boolean externalPaste = true;
2148 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2149 Transferable contents = c.getContents(this);
2151 if (contents == null)
2160 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2161 if (str.length() < 1)
2166 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2168 } catch (OutOfMemoryError er)
2170 new OOMWarning("Out of memory pasting sequences!!", er);
2174 SequenceI[] sequences;
2175 boolean annotationAdded = false;
2176 AlignmentI alignment = null;
2178 if (Desktop.jalviewClipboard != null)
2180 // The clipboard was filled from within Jalview, we must use the
2182 // And dataset from the copied alignment
2183 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2184 // be doubly sure that we create *new* sequence objects.
2185 sequences = new SequenceI[newseq.length];
2186 for (int i = 0; i < newseq.length; i++)
2188 sequences[i] = new Sequence(newseq[i]);
2190 alignment = new Alignment(sequences);
2191 externalPaste = false;
2195 // parse the clipboard as an alignment.
2196 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2198 sequences = alignment.getSequencesArray();
2202 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2208 if (Desktop.jalviewClipboard != null)
2210 // dataset is inherited
2211 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2215 // new dataset is constructed
2216 alignment.setDataset(null);
2218 alwidth = alignment.getWidth() + 1;
2222 AlignmentI pastedal = alignment; // preserve pasted alignment object
2223 // Add pasted sequences and dataset into existing alignment.
2224 alignment = viewport.getAlignment();
2225 alwidth = alignment.getWidth() + 1;
2226 // decide if we need to import sequences from an existing dataset
2227 boolean importDs = Desktop.jalviewClipboard != null
2228 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2229 // importDs==true instructs us to copy over new dataset sequences from
2230 // an existing alignment
2231 Vector newDs = (importDs) ? new Vector() : null; // used to create
2232 // minimum dataset set
2234 for (int i = 0; i < sequences.length; i++)
2238 newDs.addElement(null);
2240 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2242 if (importDs && ds != null)
2244 if (!newDs.contains(ds))
2246 newDs.setElementAt(ds, i);
2247 ds = new Sequence(ds);
2248 // update with new dataset sequence
2249 sequences[i].setDatasetSequence(ds);
2253 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2258 // copy and derive new dataset sequence
2259 sequences[i] = sequences[i].deriveSequence();
2260 alignment.getDataset()
2261 .addSequence(sequences[i].getDatasetSequence());
2262 // TODO: avoid creation of duplicate dataset sequences with a
2263 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2265 alignment.addSequence(sequences[i]); // merges dataset
2269 newDs.clear(); // tidy up
2271 if (alignment.getAlignmentAnnotation() != null)
2273 for (AlignmentAnnotation alan : alignment
2274 .getAlignmentAnnotation())
2276 if (alan.graphGroup > fgroup)
2278 fgroup = alan.graphGroup;
2282 if (pastedal.getAlignmentAnnotation() != null)
2284 // Add any annotation attached to alignment.
2285 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2286 for (int i = 0; i < alann.length; i++)
2288 annotationAdded = true;
2289 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2291 AlignmentAnnotation newann = new AlignmentAnnotation(
2293 if (newann.graphGroup > -1)
2295 if (newGraphGroups.size() <= newann.graphGroup
2296 || newGraphGroups.get(newann.graphGroup) == null)
2298 for (int q = newGraphGroups
2299 .size(); q <= newann.graphGroup; q++)
2301 newGraphGroups.add(q, null);
2303 newGraphGroups.set(newann.graphGroup,
2304 new Integer(++fgroup));
2306 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2310 newann.padAnnotation(alwidth);
2311 alignment.addAnnotation(newann);
2321 addHistoryItem(new EditCommand(
2322 MessageManager.getString("label.add_sequences"),
2323 Action.PASTE, sequences, 0, alignment.getWidth(),
2326 // Add any annotations attached to sequences
2327 for (int i = 0; i < sequences.length; i++)
2329 if (sequences[i].getAnnotation() != null)
2331 AlignmentAnnotation newann;
2332 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2334 annotationAdded = true;
2335 newann = sequences[i].getAnnotation()[a];
2336 newann.adjustForAlignment();
2337 newann.padAnnotation(alwidth);
2338 if (newann.graphGroup > -1)
2340 if (newann.graphGroup > -1)
2342 if (newGraphGroups.size() <= newann.graphGroup
2343 || newGraphGroups.get(newann.graphGroup) == null)
2345 for (int q = newGraphGroups
2346 .size(); q <= newann.graphGroup; q++)
2348 newGraphGroups.add(q, null);
2350 newGraphGroups.set(newann.graphGroup,
2351 new Integer(++fgroup));
2353 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2357 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2361 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2369 // propagate alignment changed.
2370 viewport.getRanges().setEndSeq(alignment.getHeight());
2371 if (annotationAdded)
2373 // Duplicate sequence annotation in all views.
2374 AlignmentI[] alview = this.getViewAlignments();
2375 for (int i = 0; i < sequences.length; i++)
2377 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2382 for (int avnum = 0; avnum < alview.length; avnum++)
2384 if (alview[avnum] != alignment)
2386 // duplicate in a view other than the one with input focus
2387 int avwidth = alview[avnum].getWidth() + 1;
2388 // this relies on sann being preserved after we
2389 // modify the sequence's annotation array for each duplication
2390 for (int a = 0; a < sann.length; a++)
2392 AlignmentAnnotation newann = new AlignmentAnnotation(
2394 sequences[i].addAlignmentAnnotation(newann);
2395 newann.padAnnotation(avwidth);
2396 alview[avnum].addAnnotation(newann); // annotation was
2397 // duplicated earlier
2398 // TODO JAL-1145 graphGroups are not updated for sequence
2399 // annotation added to several views. This may cause
2401 alview[avnum].setAnnotationIndex(newann, a);
2406 buildSortByAnnotationScoresMenu();
2408 viewport.firePropertyChange("alignment", null,
2409 alignment.getSequences());
2410 if (alignPanels != null)
2412 for (AlignmentPanel ap : alignPanels)
2414 ap.validateAnnotationDimensions(false);
2419 alignPanel.validateAnnotationDimensions(false);
2425 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2427 String newtitle = new String("Copied sequences");
2429 if (Desktop.jalviewClipboard != null
2430 && Desktop.jalviewClipboard[2] != null)
2432 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2433 af.viewport.setHiddenColumns(hc);
2436 // >>>This is a fix for the moment, until a better solution is
2438 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2439 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2440 .getFeatureRenderer());
2442 // TODO: maintain provenance of an alignment, rather than just make the
2443 // title a concatenation of operations.
2446 if (title.startsWith("Copied sequences"))
2452 newtitle = newtitle.concat("- from " + title);
2457 newtitle = new String("Pasted sequences");
2460 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2465 } catch (Exception ex)
2467 ex.printStackTrace();
2468 System.out.println("Exception whilst pasting: " + ex);
2469 // could be anything being pasted in here
2474 protected void expand_newalign(ActionEvent e)
2478 AlignmentI alignment = AlignmentUtils
2479 .expandContext(getViewport().getAlignment(), -1);
2480 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2482 String newtitle = new String("Flanking alignment");
2484 if (Desktop.jalviewClipboard != null
2485 && Desktop.jalviewClipboard[2] != null)
2487 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2488 af.viewport.setHiddenColumns(hc);
2491 // >>>This is a fix for the moment, until a better solution is
2493 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2494 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2495 .getFeatureRenderer());
2497 // TODO: maintain provenance of an alignment, rather than just make the
2498 // title a concatenation of operations.
2500 if (title.startsWith("Copied sequences"))
2506 newtitle = newtitle.concat("- from " + title);
2510 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2512 } catch (Exception ex)
2514 ex.printStackTrace();
2515 System.out.println("Exception whilst pasting: " + ex);
2516 // could be anything being pasted in here
2517 } catch (OutOfMemoryError oom)
2519 new OOMWarning("Viewing flanking region of alignment", oom);
2530 protected void cut_actionPerformed(ActionEvent e)
2532 copy_actionPerformed(null);
2533 delete_actionPerformed(null);
2543 protected void delete_actionPerformed(ActionEvent evt)
2546 SequenceGroup sg = viewport.getSelectionGroup();
2553 * If the cut affects all sequences, warn, remove highlighted columns
2555 if (sg.getSize() == viewport.getAlignment().getHeight())
2557 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2558 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2559 if (isEntireAlignWidth)
2561 int confirm = JvOptionPane.showConfirmDialog(this,
2562 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2563 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2564 JvOptionPane.OK_CANCEL_OPTION);
2566 if (confirm == JvOptionPane.CANCEL_OPTION
2567 || confirm == JvOptionPane.CLOSED_OPTION)
2572 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2573 sg.getEndRes() + 1);
2575 SequenceI[] cut = sg.getSequences()
2576 .toArray(new SequenceI[sg.getSize()]);
2578 addHistoryItem(new EditCommand(
2579 MessageManager.getString("label.cut_sequences"), Action.CUT,
2580 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2581 viewport.getAlignment()));
2583 viewport.setSelectionGroup(null);
2584 viewport.sendSelection();
2585 viewport.getAlignment().deleteGroup(sg);
2587 viewport.firePropertyChange("alignment", null,
2588 viewport.getAlignment().getSequences());
2589 if (viewport.getAlignment().getHeight() < 1)
2593 this.setClosed(true);
2594 } catch (Exception ex)
2607 protected void deleteGroups_actionPerformed(ActionEvent e)
2609 if (avc.deleteGroups())
2611 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2612 alignPanel.updateAnnotation();
2613 alignPanel.paintAlignment(true, true);
2624 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2626 SequenceGroup sg = new SequenceGroup();
2628 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2630 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2633 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2634 viewport.setSelectionGroup(sg);
2635 viewport.sendSelection();
2636 // JAL-2034 - should delegate to
2637 // alignPanel to decide if overview needs
2639 alignPanel.paintAlignment(false, false);
2640 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2650 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2652 if (viewport.cursorMode)
2654 alignPanel.getSeqPanel().keyboardNo1 = null;
2655 alignPanel.getSeqPanel().keyboardNo2 = null;
2657 viewport.setSelectionGroup(null);
2658 viewport.getColumnSelection().clear();
2659 viewport.setSelectionGroup(null);
2660 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2661 // JAL-2034 - should delegate to
2662 // alignPanel to decide if overview needs
2664 alignPanel.paintAlignment(false, false);
2665 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2666 viewport.sendSelection();
2676 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2678 SequenceGroup sg = viewport.getSelectionGroup();
2682 selectAllSequenceMenuItem_actionPerformed(null);
2687 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2689 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2691 // JAL-2034 - should delegate to
2692 // alignPanel to decide if overview needs
2695 alignPanel.paintAlignment(true, false);
2696 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2697 viewport.sendSelection();
2701 public void invertColSel_actionPerformed(ActionEvent e)
2703 viewport.invertColumnSelection();
2704 alignPanel.paintAlignment(true, false);
2705 viewport.sendSelection();
2715 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2717 trimAlignment(true);
2727 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2729 trimAlignment(false);
2732 void trimAlignment(boolean trimLeft)
2734 ColumnSelection colSel = viewport.getColumnSelection();
2737 if (!colSel.isEmpty())
2741 column = colSel.getMin();
2745 column = colSel.getMax();
2749 if (viewport.getSelectionGroup() != null)
2751 seqs = viewport.getSelectionGroup()
2752 .getSequencesAsArray(viewport.getHiddenRepSequences());
2756 seqs = viewport.getAlignment().getSequencesArray();
2759 TrimRegionCommand trimRegion;
2762 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2763 column, viewport.getAlignment());
2764 viewport.getRanges().setStartRes(0);
2768 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2769 column, viewport.getAlignment());
2772 statusBar.setText(MessageManager
2773 .formatMessage("label.removed_columns", new String[]
2774 { Integer.valueOf(trimRegion.getSize()).toString() }));
2776 addHistoryItem(trimRegion);
2778 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2780 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2781 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2783 viewport.getAlignment().deleteGroup(sg);
2787 viewport.firePropertyChange("alignment", null,
2788 viewport.getAlignment().getSequences());
2799 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2801 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2804 if (viewport.getSelectionGroup() != null)
2806 seqs = viewport.getSelectionGroup()
2807 .getSequencesAsArray(viewport.getHiddenRepSequences());
2808 start = viewport.getSelectionGroup().getStartRes();
2809 end = viewport.getSelectionGroup().getEndRes();
2813 seqs = viewport.getAlignment().getSequencesArray();
2816 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2817 "Remove Gapped Columns", seqs, start, end,
2818 viewport.getAlignment());
2820 addHistoryItem(removeGapCols);
2822 statusBar.setText(MessageManager
2823 .formatMessage("label.removed_empty_columns", new Object[]
2824 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2826 // This is to maintain viewport position on first residue
2827 // of first sequence
2828 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2829 ViewportRanges ranges = viewport.getRanges();
2830 int startRes = seq.findPosition(ranges.getStartRes());
2831 // ShiftList shifts;
2832 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2833 // edit.alColumnChanges=shifts.getInverse();
2834 // if (viewport.hasHiddenColumns)
2835 // viewport.getColumnSelection().compensateForEdits(shifts);
2836 ranges.setStartRes(seq.findIndex(startRes) - 1);
2837 viewport.firePropertyChange("alignment", null,
2838 viewport.getAlignment().getSequences());
2849 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2851 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2854 if (viewport.getSelectionGroup() != null)
2856 seqs = viewport.getSelectionGroup()
2857 .getSequencesAsArray(viewport.getHiddenRepSequences());
2858 start = viewport.getSelectionGroup().getStartRes();
2859 end = viewport.getSelectionGroup().getEndRes();
2863 seqs = viewport.getAlignment().getSequencesArray();
2866 // This is to maintain viewport position on first residue
2867 // of first sequence
2868 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2869 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2871 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2872 viewport.getAlignment()));
2874 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2876 viewport.firePropertyChange("alignment", null,
2877 viewport.getAlignment().getSequences());
2888 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2890 viewport.setPadGaps(padGapsMenuitem.isSelected());
2891 viewport.firePropertyChange("alignment", null,
2892 viewport.getAlignment().getSequences());
2902 public void findMenuItem_actionPerformed(ActionEvent e)
2908 * Create a new view of the current alignment.
2911 public void newView_actionPerformed(ActionEvent e)
2913 newView(null, true);
2917 * Creates and shows a new view of the current alignment.
2920 * title of newly created view; if null, one will be generated
2921 * @param copyAnnotation
2922 * if true then duplicate all annnotation, groups and settings
2923 * @return new alignment panel, already displayed.
2925 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2928 * Create a new AlignmentPanel (with its own, new Viewport)
2930 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel);
2931 if (!copyAnnotation)
2934 * remove all groups and annotation except for the automatic stuff
2936 newap.av.getAlignment().deleteAllGroups();
2937 newap.av.getAlignment().deleteAllAnnotations(false);
2940 newap.av.setGatherViewsHere(false);
2942 if (viewport.viewName == null)
2944 viewport.viewName = MessageManager
2945 .getString("label.view_name_original");
2949 * Views share the same edits undo and redo stacks
2951 newap.av.setHistoryList(viewport.getHistoryList());
2952 newap.av.setRedoList(viewport.getRedoList());
2955 * Views share the same mappings; need to deregister any new mappings
2956 * created by copyAlignPanel, and register the new reference to the shared
2959 newap.av.replaceMappings(viewport.getAlignment());
2962 * start up cDNA consensus (if applicable) now mappings are in place
2964 if (newap.av.initComplementConsensus())
2966 newap.refresh(true); // adjust layout of annotations
2969 newap.av.viewName = getNewViewName(viewTitle);
2971 addAlignmentPanel(newap, true);
2972 newap.alignmentChanged();
2974 if (alignPanels.size() == 2)
2976 viewport.setGatherViewsHere(true);
2978 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2983 * Make a new name for the view, ensuring it is unique within the current
2984 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2985 * these now use viewId. Unique view names are still desirable for usability.)
2990 protected String getNewViewName(String viewTitle)
2992 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2993 boolean addFirstIndex = false;
2994 if (viewTitle == null || viewTitle.trim().length() == 0)
2996 viewTitle = MessageManager.getString("action.view");
2997 addFirstIndex = true;
3001 index = 1;// we count from 1 if given a specific name
3003 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
3005 List<Component> comps = PaintRefresher.components
3006 .get(viewport.getSequenceSetId());
3008 List<String> existingNames = getExistingViewNames(comps);
3010 while (existingNames.contains(newViewName))
3012 newViewName = viewTitle + " " + (++index);
3018 * Returns a list of distinct view names found in the given list of
3019 * components. View names are held on the viewport of an AlignmentPanel.
3024 protected List<String> getExistingViewNames(List<Component> comps)
3026 List<String> existingNames = new ArrayList<>();
3027 for (Component comp : comps)
3029 if (comp instanceof AlignmentPanel)
3031 AlignmentPanel ap = (AlignmentPanel) comp;
3032 if (!existingNames.contains(ap.av.viewName))
3034 existingNames.add(ap.av.viewName);
3038 return existingNames;
3042 * Explode tabbed views into separate windows.
3045 public void expandViews_actionPerformed(ActionEvent e)
3047 Desktop.explodeViews(this);
3051 * Gather views in separate windows back into a tabbed presentation.
3054 public void gatherViews_actionPerformed(ActionEvent e)
3056 Desktop.instance.gatherViews(this);
3066 public void font_actionPerformed(ActionEvent e)
3068 new FontChooser(alignPanel);
3078 protected void seqLimit_actionPerformed(ActionEvent e)
3080 viewport.setShowJVSuffix(seqLimits.isSelected());
3082 alignPanel.getIdPanel().getIdCanvas()
3083 .setPreferredSize(alignPanel.calculateIdWidth());
3084 alignPanel.paintAlignment(true, false);
3088 public void idRightAlign_actionPerformed(ActionEvent e)
3090 viewport.setRightAlignIds(idRightAlign.isSelected());
3091 alignPanel.paintAlignment(false, false);
3095 public void centreColumnLabels_actionPerformed(ActionEvent e)
3097 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3098 alignPanel.paintAlignment(false, false);
3104 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3107 protected void followHighlight_actionPerformed()
3110 * Set the 'follow' flag on the Viewport (and scroll to position if now
3113 final boolean state = this.followHighlightMenuItem.getState();
3114 viewport.setFollowHighlight(state);
3117 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
3128 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3130 viewport.setColourText(colourTextMenuItem.isSelected());
3131 alignPanel.paintAlignment(false, false);
3141 public void wrapMenuItem_actionPerformed(ActionEvent e)
3143 scaleAbove.setVisible(wrapMenuItem.isSelected());
3144 scaleLeft.setVisible(wrapMenuItem.isSelected());
3145 scaleRight.setVisible(wrapMenuItem.isSelected());
3146 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3147 alignPanel.updateLayout();
3151 public void showAllSeqs_actionPerformed(ActionEvent e)
3153 viewport.showAllHiddenSeqs();
3157 public void showAllColumns_actionPerformed(ActionEvent e)
3159 viewport.showAllHiddenColumns();
3160 alignPanel.paintAlignment(true, true);
3161 viewport.sendSelection();
3165 public void hideSelSequences_actionPerformed(ActionEvent e)
3167 viewport.hideAllSelectedSeqs();
3171 * called by key handler and the hide all/show all menu items
3176 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3179 boolean hide = false;
3180 SequenceGroup sg = viewport.getSelectionGroup();
3181 if (!toggleSeqs && !toggleCols)
3183 // Hide everything by the current selection - this is a hack - we do the
3184 // invert and then hide
3185 // first check that there will be visible columns after the invert.
3186 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3187 && sg.getStartRes() <= sg.getEndRes()))
3189 // now invert the sequence set, if required - empty selection implies
3190 // that no hiding is required.
3193 invertSequenceMenuItem_actionPerformed(null);
3194 sg = viewport.getSelectionGroup();
3198 viewport.expandColSelection(sg, true);
3199 // finally invert the column selection and get the new sequence
3201 invertColSel_actionPerformed(null);
3208 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3210 hideSelSequences_actionPerformed(null);
3213 else if (!(toggleCols && viewport.hasSelectedColumns()))
3215 showAllSeqs_actionPerformed(null);
3221 if (viewport.hasSelectedColumns())
3223 hideSelColumns_actionPerformed(null);
3226 viewport.setSelectionGroup(sg);
3231 showAllColumns_actionPerformed(null);
3240 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3241 * event.ActionEvent)
3244 public void hideAllButSelection_actionPerformed(ActionEvent e)
3246 toggleHiddenRegions(false, false);
3247 viewport.sendSelection();
3254 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3258 public void hideAllSelection_actionPerformed(ActionEvent e)
3260 SequenceGroup sg = viewport.getSelectionGroup();
3261 viewport.expandColSelection(sg, false);
3262 viewport.hideAllSelectedSeqs();
3263 viewport.hideSelectedColumns();
3264 alignPanel.paintAlignment(true, true);
3265 viewport.sendSelection();
3272 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3276 public void showAllhidden_actionPerformed(ActionEvent e)
3278 viewport.showAllHiddenColumns();
3279 viewport.showAllHiddenSeqs();
3280 alignPanel.paintAlignment(true, true);
3281 viewport.sendSelection();
3285 public void hideSelColumns_actionPerformed(ActionEvent e)
3287 viewport.hideSelectedColumns();
3288 alignPanel.paintAlignment(true, true);
3289 viewport.sendSelection();
3293 public void hiddenMarkers_actionPerformed(ActionEvent e)
3295 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3306 protected void scaleAbove_actionPerformed(ActionEvent e)
3308 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3309 // TODO: do we actually need to update overview for scale above change ?
3310 alignPanel.paintAlignment(true, false);
3320 protected void scaleLeft_actionPerformed(ActionEvent e)
3322 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3323 alignPanel.paintAlignment(true, false);
3333 protected void scaleRight_actionPerformed(ActionEvent e)
3335 viewport.setScaleRightWrapped(scaleRight.isSelected());
3336 alignPanel.paintAlignment(true, false);
3346 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3348 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3349 alignPanel.paintAlignment(false, false);
3359 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3361 viewport.setShowText(viewTextMenuItem.isSelected());
3362 alignPanel.paintAlignment(false, false);
3372 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3374 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3375 alignPanel.paintAlignment(false, false);
3378 public FeatureSettings featureSettings;
3381 public FeatureSettingsControllerI getFeatureSettingsUI()
3383 return featureSettings;
3387 public void featureSettings_actionPerformed(ActionEvent e)
3389 if (featureSettings != null)
3391 featureSettings.close();
3392 featureSettings = null;
3394 if (!showSeqFeatures.isSelected())
3396 // make sure features are actually displayed
3397 showSeqFeatures.setSelected(true);
3398 showSeqFeatures_actionPerformed(null);
3400 featureSettings = new FeatureSettings(this);
3404 * Set or clear 'Show Sequence Features'
3410 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3412 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3413 alignPanel.paintAlignment(true, true);
3417 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3418 * the annotations panel as a whole.
3420 * The options to show/hide all annotations should be enabled when the panel
3421 * is shown, and disabled when the panel is hidden.
3426 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3428 final boolean setVisible = annotationPanelMenuItem.isSelected();
3429 viewport.setShowAnnotation(setVisible);
3430 this.showAllSeqAnnotations.setEnabled(setVisible);
3431 this.hideAllSeqAnnotations.setEnabled(setVisible);
3432 this.showAllAlAnnotations.setEnabled(setVisible);
3433 this.hideAllAlAnnotations.setEnabled(setVisible);
3434 alignPanel.updateLayout();
3438 public void alignmentProperties()
3440 JEditorPane editPane = new JEditorPane("text/html", "");
3441 editPane.setEditable(false);
3442 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3445 MessageManager.formatMessage("label.html_content", new Object[]
3446 { contents.toString() }));
3447 JInternalFrame frame = new JInternalFrame();
3448 frame.getContentPane().add(new JScrollPane(editPane));
3450 Desktop.addInternalFrame(frame, MessageManager
3451 .formatMessage("label.alignment_properties", new Object[]
3452 { getTitle() }), 500, 400);
3462 public void overviewMenuItem_actionPerformed(ActionEvent e)
3464 if (alignPanel.overviewPanel != null)
3469 JInternalFrame frame = new JInternalFrame();
3470 final OverviewPanel overview = new OverviewPanel(alignPanel);
3471 frame.setContentPane(overview);
3472 Desktop.addInternalFrame(frame, MessageManager
3473 .formatMessage("label.overview_params", new Object[]
3474 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3477 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3478 frame.addInternalFrameListener(
3479 new javax.swing.event.InternalFrameAdapter()
3482 public void internalFrameClosed(
3483 javax.swing.event.InternalFrameEvent evt)
3486 alignPanel.setOverviewPanel(null);
3490 alignPanel.setOverviewPanel(overview);
3494 public void textColour_actionPerformed()
3496 new TextColourChooser().chooseColour(alignPanel, null);
3500 * public void covariationColour_actionPerformed() {
3502 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3506 public void annotationColour_actionPerformed()
3508 new AnnotationColourChooser(viewport, alignPanel);
3512 public void annotationColumn_actionPerformed(ActionEvent e)
3514 new AnnotationColumnChooser(viewport, alignPanel);
3518 * Action on the user checking or unchecking the option to apply the selected
3519 * colour scheme to all groups. If unchecked, groups may have their own
3520 * independent colour schemes.
3525 public void applyToAllGroups_actionPerformed(boolean selected)
3527 viewport.setColourAppliesToAllGroups(selected);
3531 * Action on user selecting a colour from the colour menu
3534 * the name (not the menu item label!) of the colour scheme
3537 public void changeColour_actionPerformed(String name)
3540 * 'User Defined' opens a panel to configure or load a
3541 * user-defined colour scheme
3543 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3545 new UserDefinedColours(alignPanel);
3550 * otherwise set the chosen colour scheme (or null for 'None')
3552 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3553 viewport.getAlignment(), viewport.getHiddenRepSequences());
3558 * Actions on setting or changing the alignment colour scheme
3563 public void changeColour(ColourSchemeI cs)
3565 // TODO: pull up to controller method
3566 ColourMenuHelper.setColourSelected(colourMenu, cs);
3568 viewport.setGlobalColourScheme(cs);
3570 alignPanel.paintAlignment(true, true);
3574 * Show the PID threshold slider panel
3577 protected void modifyPID_actionPerformed()
3579 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3580 alignPanel.getViewName());
3581 SliderPanel.showPIDSlider();
3585 * Show the Conservation slider panel
3588 protected void modifyConservation_actionPerformed()
3590 SliderPanel.setConservationSlider(alignPanel,
3591 viewport.getResidueShading(), alignPanel.getViewName());
3592 SliderPanel.showConservationSlider();
3596 * Action on selecting or deselecting (Colour) By Conservation
3599 public void conservationMenuItem_actionPerformed(boolean selected)
3601 modifyConservation.setEnabled(selected);
3602 viewport.setConservationSelected(selected);
3603 viewport.getResidueShading().setConservationApplied(selected);
3605 changeColour(viewport.getGlobalColourScheme());
3608 modifyConservation_actionPerformed();
3612 SliderPanel.hideConservationSlider();
3617 * Action on selecting or deselecting (Colour) Above PID Threshold
3620 public void abovePIDThreshold_actionPerformed(boolean selected)
3622 modifyPID.setEnabled(selected);
3623 viewport.setAbovePIDThreshold(selected);
3626 viewport.getResidueShading().setThreshold(0,
3627 viewport.isIgnoreGapsConsensus());
3630 changeColour(viewport.getGlobalColourScheme());
3633 modifyPID_actionPerformed();
3637 SliderPanel.hidePIDSlider();
3648 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3650 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3651 AlignmentSorter.sortByPID(viewport.getAlignment(),
3652 viewport.getAlignment().getSequenceAt(0));
3653 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3654 viewport.getAlignment()));
3655 alignPanel.paintAlignment(true, false);
3665 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3667 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3668 AlignmentSorter.sortByID(viewport.getAlignment());
3670 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3671 alignPanel.paintAlignment(true, false);
3681 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3683 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3684 AlignmentSorter.sortByLength(viewport.getAlignment());
3685 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3686 viewport.getAlignment()));
3687 alignPanel.paintAlignment(true, false);
3697 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3699 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3700 AlignmentSorter.sortByGroup(viewport.getAlignment());
3701 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3702 viewport.getAlignment()));
3704 alignPanel.paintAlignment(true, false);
3714 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3716 new RedundancyPanel(alignPanel, this);
3726 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3728 if ((viewport.getSelectionGroup() == null)
3729 || (viewport.getSelectionGroup().getSize() < 2))
3731 JvOptionPane.showInternalMessageDialog(this,
3732 MessageManager.getString(
3733 "label.you_must_select_least_two_sequences"),
3734 MessageManager.getString("label.invalid_selection"),
3735 JvOptionPane.WARNING_MESSAGE);
3739 JInternalFrame frame = new JInternalFrame();
3740 frame.setContentPane(new PairwiseAlignPanel(viewport));
3741 Desktop.addInternalFrame(frame,
3742 MessageManager.getString("action.pairwise_alignment"), 600,
3748 public void autoCalculate_actionPerformed(ActionEvent e)
3750 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3751 if (viewport.autoCalculateConsensus)
3753 viewport.firePropertyChange("alignment", null,
3754 viewport.getAlignment().getSequences());
3759 public void sortByTreeOption_actionPerformed(ActionEvent e)
3761 viewport.sortByTree = sortByTree.isSelected();
3765 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3767 viewport.followSelection = listenToViewSelections.isSelected();
3771 * Constructs a tree panel and adds it to the desktop
3774 * tree type (NJ or AV)
3776 * name of score model used to compute the tree
3778 * parameters for the distance or similarity calculation
3780 void newTreePanel(String type, String modelName,
3781 SimilarityParamsI options)
3783 String frameTitle = "";
3786 boolean onSelection = false;
3787 if (viewport.getSelectionGroup() != null
3788 && viewport.getSelectionGroup().getSize() > 0)
3790 SequenceGroup sg = viewport.getSelectionGroup();
3792 /* Decide if the selection is a column region */
3793 for (SequenceI _s : sg.getSequences())
3795 if (_s.getLength() < sg.getEndRes())
3797 JvOptionPane.showMessageDialog(Desktop.desktop,
3798 MessageManager.getString(
3799 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3800 MessageManager.getString(
3801 "label.sequences_selection_not_aligned"),
3802 JvOptionPane.WARNING_MESSAGE);
3811 if (viewport.getAlignment().getHeight() < 2)
3817 tp = new TreePanel(alignPanel, type, modelName, options);
3818 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3820 frameTitle += " from ";
3822 if (viewport.viewName != null)
3824 frameTitle += viewport.viewName + " of ";
3827 frameTitle += this.title;
3829 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3840 public void addSortByOrderMenuItem(String title,
3841 final AlignmentOrder order)
3843 final JMenuItem item = new JMenuItem(MessageManager
3844 .formatMessage("action.by_title_param", new Object[]
3847 item.addActionListener(new java.awt.event.ActionListener()
3850 public void actionPerformed(ActionEvent e)
3852 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3854 // TODO: JBPNote - have to map order entries to curent SequenceI
3856 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3858 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3859 viewport.getAlignment()));
3861 alignPanel.paintAlignment(true, false);
3867 * Add a new sort by annotation score menu item
3870 * the menu to add the option to
3872 * the label used to retrieve scores for each sequence on the
3875 public void addSortByAnnotScoreMenuItem(JMenu sort,
3876 final String scoreLabel)
3878 final JMenuItem item = new JMenuItem(scoreLabel);
3880 item.addActionListener(new java.awt.event.ActionListener()
3883 public void actionPerformed(ActionEvent e)
3885 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3886 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3887 viewport.getAlignment());// ,viewport.getSelectionGroup());
3888 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3889 viewport.getAlignment()));
3890 alignPanel.paintAlignment(true, false);
3896 * last hash for alignment's annotation array - used to minimise cost of
3899 protected int _annotationScoreVectorHash;
3902 * search the alignment and rebuild the sort by annotation score submenu the
3903 * last alignment annotation vector hash is stored to minimize cost of
3904 * rebuilding in subsequence calls.
3908 public void buildSortByAnnotationScoresMenu()
3910 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3915 if (viewport.getAlignment().getAlignmentAnnotation()
3916 .hashCode() != _annotationScoreVectorHash)
3918 sortByAnnotScore.removeAll();
3919 // almost certainly a quicker way to do this - but we keep it simple
3920 Hashtable scoreSorts = new Hashtable();
3921 AlignmentAnnotation aann[];
3922 for (SequenceI sqa : viewport.getAlignment().getSequences())
3924 aann = sqa.getAnnotation();
3925 for (int i = 0; aann != null && i < aann.length; i++)
3927 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3929 scoreSorts.put(aann[i].label, aann[i].label);
3933 Enumeration labels = scoreSorts.keys();
3934 while (labels.hasMoreElements())
3936 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3937 (String) labels.nextElement());
3939 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3942 _annotationScoreVectorHash = viewport.getAlignment()
3943 .getAlignmentAnnotation().hashCode();
3948 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3949 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3950 * call. Listeners are added to remove the menu item when the treePanel is
3951 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3955 public void buildTreeSortMenu()
3957 sortByTreeMenu.removeAll();
3959 List<Component> comps = PaintRefresher.components
3960 .get(viewport.getSequenceSetId());
3961 List<TreePanel> treePanels = new ArrayList<>();
3962 for (Component comp : comps)
3964 if (comp instanceof TreePanel)
3966 treePanels.add((TreePanel) comp);
3970 if (treePanels.size() < 1)
3972 sortByTreeMenu.setVisible(false);
3976 sortByTreeMenu.setVisible(true);
3978 for (final TreePanel tp : treePanels)
3980 final JMenuItem item = new JMenuItem(tp.getTitle());
3981 item.addActionListener(new java.awt.event.ActionListener()
3984 public void actionPerformed(ActionEvent e)
3986 tp.sortByTree_actionPerformed();
3987 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3992 sortByTreeMenu.add(item);
3996 public boolean sortBy(AlignmentOrder alorder, String undoname)
3998 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3999 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4000 if (undoname != null)
4002 addHistoryItem(new OrderCommand(undoname, oldOrder,
4003 viewport.getAlignment()));
4005 alignPanel.paintAlignment(true, false);
4010 * Work out whether the whole set of sequences or just the selected set will
4011 * be submitted for multiple alignment.
4014 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4016 // Now, check we have enough sequences
4017 AlignmentView msa = null;
4019 if ((viewport.getSelectionGroup() != null)
4020 && (viewport.getSelectionGroup().getSize() > 1))
4022 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4023 // some common interface!
4025 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4026 * SequenceI[sz = seqs.getSize(false)];
4028 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4029 * seqs.getSequenceAt(i); }
4031 msa = viewport.getAlignmentView(true);
4033 else if (viewport.getSelectionGroup() != null
4034 && viewport.getSelectionGroup().getSize() == 1)
4036 int option = JvOptionPane.showConfirmDialog(this,
4037 MessageManager.getString("warn.oneseq_msainput_selection"),
4038 MessageManager.getString("label.invalid_selection"),
4039 JvOptionPane.OK_CANCEL_OPTION);
4040 if (option == JvOptionPane.OK_OPTION)
4042 msa = viewport.getAlignmentView(false);
4047 msa = viewport.getAlignmentView(false);
4053 * Decides what is submitted to a secondary structure prediction service: the
4054 * first sequence in the alignment, or in the current selection, or, if the
4055 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4056 * region or the whole alignment. (where the first sequence in the set is the
4057 * one that the prediction will be for).
4059 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4061 AlignmentView seqs = null;
4063 if ((viewport.getSelectionGroup() != null)
4064 && (viewport.getSelectionGroup().getSize() > 0))
4066 seqs = viewport.getAlignmentView(true);
4070 seqs = viewport.getAlignmentView(false);
4072 // limit sequences - JBPNote in future - could spawn multiple prediction
4074 // TODO: viewport.getAlignment().isAligned is a global state - the local
4075 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4076 if (!viewport.getAlignment().isAligned(false))
4078 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4079 // TODO: if seqs.getSequences().length>1 then should really have warned
4093 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4095 // Pick the tree file
4096 JalviewFileChooser chooser = new JalviewFileChooser(
4097 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4098 chooser.setFileView(new JalviewFileView());
4099 chooser.setDialogTitle(
4100 MessageManager.getString("label.select_newick_like_tree_file"));
4101 chooser.setToolTipText(
4102 MessageManager.getString("label.load_tree_file"));
4104 int value = chooser.showOpenDialog(null);
4106 if (value == JalviewFileChooser.APPROVE_OPTION)
4108 String filePath = chooser.getSelectedFile().getPath();
4109 Cache.setProperty("LAST_DIRECTORY", filePath);
4110 NewickFile fin = null;
4113 fin = new NewickFile(filePath, DataSourceType.FILE);
4114 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4115 } catch (Exception ex)
4117 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4118 MessageManager.getString("label.problem_reading_tree_file"),
4119 JvOptionPane.WARNING_MESSAGE);
4120 ex.printStackTrace();
4122 if (fin != null && fin.hasWarningMessage())
4124 JvOptionPane.showMessageDialog(Desktop.desktop,
4125 fin.getWarningMessage(),
4127 .getString("label.possible_problem_with_tree_file"),
4128 JvOptionPane.WARNING_MESSAGE);
4133 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4135 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4138 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4139 int h, int x, int y)
4141 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4145 * Add a treeviewer for the tree extracted from a Newick file object to the
4146 * current alignment view
4153 * Associated alignment input data (or null)
4162 * @return TreePanel handle
4164 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4165 AlignmentView input, int w, int h, int x, int y)
4167 TreePanel tp = null;
4173 if (nf.getTree() != null)
4175 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4181 tp.setLocation(x, y);
4184 Desktop.addInternalFrame(tp, treeTitle, w, h);
4186 } catch (Exception ex)
4188 ex.printStackTrace();
4194 private boolean buildingMenu = false;
4197 * Generates menu items and listener event actions for web service clients
4200 public void BuildWebServiceMenu()
4202 while (buildingMenu)
4206 System.err.println("Waiting for building menu to finish.");
4208 } catch (Exception e)
4212 final AlignFrame me = this;
4213 buildingMenu = true;
4214 new Thread(new Runnable()
4219 final List<JMenuItem> legacyItems = new ArrayList<>();
4222 // System.err.println("Building ws menu again "
4223 // + Thread.currentThread());
4224 // TODO: add support for context dependent disabling of services based
4226 // alignment and current selection
4227 // TODO: add additional serviceHandle parameter to specify abstract
4229 // class independently of AbstractName
4230 // TODO: add in rediscovery GUI function to restart discoverer
4231 // TODO: group services by location as well as function and/or
4233 // object broker mechanism.
4234 final Vector<JMenu> wsmenu = new Vector<>();
4235 final IProgressIndicator af = me;
4238 * do not i18n these strings - they are hard-coded in class
4239 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4240 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4242 final JMenu msawsmenu = new JMenu("Alignment");
4243 final JMenu secstrmenu = new JMenu(
4244 "Secondary Structure Prediction");
4245 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4246 final JMenu analymenu = new JMenu("Analysis");
4247 final JMenu dismenu = new JMenu("Protein Disorder");
4248 // JAL-940 - only show secondary structure prediction services from
4249 // the legacy server
4250 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4252 Discoverer.services != null && (Discoverer.services.size() > 0))
4254 // TODO: refactor to allow list of AbstractName/Handler bindings to
4256 // stored or retrieved from elsewhere
4257 // No MSAWS used any more:
4258 // Vector msaws = null; // (Vector)
4259 // Discoverer.services.get("MsaWS");
4260 Vector secstrpr = (Vector) Discoverer.services
4262 if (secstrpr != null)
4264 // Add any secondary structure prediction services
4265 for (int i = 0, j = secstrpr.size(); i < j; i++)
4267 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4269 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4270 .getServiceClient(sh);
4271 int p = secstrmenu.getItemCount();
4272 impl.attachWSMenuEntry(secstrmenu, me);
4273 int q = secstrmenu.getItemCount();
4274 for (int litm = p; litm < q; litm++)
4276 legacyItems.add(secstrmenu.getItem(litm));
4282 // Add all submenus in the order they should appear on the web
4284 wsmenu.add(msawsmenu);
4285 wsmenu.add(secstrmenu);
4286 wsmenu.add(dismenu);
4287 wsmenu.add(analymenu);
4288 // No search services yet
4289 // wsmenu.add(seqsrchmenu);
4291 javax.swing.SwingUtilities.invokeLater(new Runnable()
4298 webService.removeAll();
4299 // first, add discovered services onto the webservices menu
4300 if (wsmenu.size() > 0)
4302 for (int i = 0, j = wsmenu.size(); i < j; i++)
4304 webService.add(wsmenu.get(i));
4309 webService.add(me.webServiceNoServices);
4311 // TODO: move into separate menu builder class.
4312 boolean new_sspred = false;
4313 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4315 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4316 if (jws2servs != null)
4318 if (jws2servs.hasServices())
4320 jws2servs.attachWSMenuEntry(webService, me);
4321 for (Jws2Instance sv : jws2servs.getServices())
4323 if (sv.description.toLowerCase().contains("jpred"))
4325 for (JMenuItem jmi : legacyItems)
4327 jmi.setVisible(false);
4333 if (jws2servs.isRunning())
4335 JMenuItem tm = new JMenuItem(
4336 "Still discovering JABA Services");
4337 tm.setEnabled(false);
4342 build_urlServiceMenu(me.webService);
4343 build_fetchdbmenu(webService);
4344 for (JMenu item : wsmenu)
4346 if (item.getItemCount() == 0)
4348 item.setEnabled(false);
4352 item.setEnabled(true);
4355 } catch (Exception e)
4358 "Exception during web service menu building process.",
4363 } catch (Exception e)
4366 buildingMenu = false;
4373 * construct any groupURL type service menu entries.
4377 private void build_urlServiceMenu(JMenu webService)
4379 // TODO: remove this code when 2.7 is released
4380 // DEBUG - alignmentView
4382 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4383 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4385 * @Override public void actionPerformed(ActionEvent e) {
4386 * jalview.datamodel.AlignmentView
4387 * .testSelectionViews(af.viewport.getAlignment(),
4388 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4390 * }); webService.add(testAlView);
4392 // TODO: refactor to RestClient discoverer and merge menu entries for
4393 // rest-style services with other types of analysis/calculation service
4394 // SHmmr test client - still being implemented.
4395 // DEBUG - alignmentView
4397 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4400 client.attachWSMenuEntry(
4401 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4407 * Searches the alignment sequences for xRefs and builds the Show
4408 * Cross-References menu (formerly called Show Products), with database
4409 * sources for which cross-references are found (protein sources for a
4410 * nucleotide alignment and vice versa)
4412 * @return true if Show Cross-references menu should be enabled
4414 public boolean canShowProducts()
4416 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4417 AlignmentI dataset = viewport.getAlignment().getDataset();
4419 showProducts.removeAll();
4420 final boolean dna = viewport.getAlignment().isNucleotide();
4422 if (seqs == null || seqs.length == 0)
4424 // nothing to see here.
4428 boolean showp = false;
4431 List<String> ptypes = new CrossRef(seqs, dataset)
4432 .findXrefSourcesForSequences(dna);
4434 for (final String source : ptypes)
4437 final AlignFrame af = this;
4438 JMenuItem xtype = new JMenuItem(source);
4439 xtype.addActionListener(new ActionListener()
4442 public void actionPerformed(ActionEvent e)
4444 showProductsFor(af.viewport.getSequenceSelection(), dna,
4448 showProducts.add(xtype);
4450 showProducts.setVisible(showp);
4451 showProducts.setEnabled(showp);
4452 } catch (Exception e)
4455 "canShowProducts threw an exception - please report to help@jalview.org",
4463 * Finds and displays cross-references for the selected sequences (protein
4464 * products for nucleotide sequences, dna coding sequences for peptides).
4467 * the sequences to show cross-references for
4469 * true if from a nucleotide alignment (so showing proteins)
4471 * the database to show cross-references for
4473 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4474 final String source)
4476 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4481 * Construct and display a new frame containing the translation of this
4482 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4485 public void showTranslation_actionPerformed(ActionEvent e)
4487 AlignmentI al = null;
4490 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4492 al = dna.translateCdna();
4493 } catch (Exception ex)
4495 jalview.bin.Cache.log.error(
4496 "Exception during translation. Please report this !", ex);
4497 final String msg = MessageManager.getString(
4498 "label.error_when_translating_sequences_submit_bug_report");
4499 final String errorTitle = MessageManager
4500 .getString("label.implementation_error")
4501 + MessageManager.getString("label.translation_failed");
4502 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4503 JvOptionPane.ERROR_MESSAGE);
4506 if (al == null || al.getHeight() == 0)
4508 final String msg = MessageManager.getString(
4509 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4510 final String errorTitle = MessageManager
4511 .getString("label.translation_failed");
4512 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4513 JvOptionPane.WARNING_MESSAGE);
4517 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4518 af.setFileFormat(this.currentFileFormat);
4519 final String newTitle = MessageManager
4520 .formatMessage("label.translation_of_params", new Object[]
4521 { this.getTitle() });
4522 af.setTitle(newTitle);
4523 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4525 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4526 viewport.openSplitFrame(af, new Alignment(seqs));
4530 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4537 * Set the file format
4541 public void setFileFormat(FileFormatI format)
4543 this.currentFileFormat = format;
4547 * Try to load a features file onto the alignment.
4550 * contents or path to retrieve file
4552 * access mode of file (see jalview.io.AlignFile)
4553 * @return true if features file was parsed correctly.
4555 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4557 return avc.parseFeaturesFile(file, sourceType,
4558 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4563 public void refreshFeatureUI(boolean enableIfNecessary)
4565 // note - currently this is only still here rather than in the controller
4566 // because of the featureSettings hard reference that is yet to be
4568 if (enableIfNecessary)
4570 viewport.setShowSequenceFeatures(true);
4571 showSeqFeatures.setSelected(true);
4577 public void dragEnter(DropTargetDragEvent evt)
4582 public void dragExit(DropTargetEvent evt)
4587 public void dragOver(DropTargetDragEvent evt)
4592 public void dropActionChanged(DropTargetDragEvent evt)
4597 public void drop(DropTargetDropEvent evt)
4599 // JAL-1552 - acceptDrop required before getTransferable call for
4600 // Java's Transferable for native dnd
4601 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4602 Transferable t = evt.getTransferable();
4603 final AlignFrame thisaf = this;
4604 final List<String> files = new ArrayList<>();
4605 List<DataSourceType> protocols = new ArrayList<>();
4609 Desktop.transferFromDropTarget(files, protocols, evt, t);
4610 } catch (Exception e)
4612 e.printStackTrace();
4616 new Thread(new Runnable()
4623 // check to see if any of these files have names matching sequences
4626 SequenceIdMatcher idm = new SequenceIdMatcher(
4627 viewport.getAlignment().getSequencesArray());
4629 * Object[] { String,SequenceI}
4631 ArrayList<Object[]> filesmatched = new ArrayList<>();
4632 ArrayList<String> filesnotmatched = new ArrayList<>();
4633 for (int i = 0; i < files.size(); i++)
4635 String file = files.get(i).toString();
4637 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4638 if (protocol == DataSourceType.FILE)
4640 File fl = new File(file);
4641 pdbfn = fl.getName();
4643 else if (protocol == DataSourceType.URL)
4645 URL url = new URL(file);
4646 pdbfn = url.getFile();
4648 if (pdbfn.length() > 0)
4650 // attempt to find a match in the alignment
4651 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4652 int l = 0, c = pdbfn.indexOf(".");
4653 while (mtch == null && c != -1)
4658 } while ((c = pdbfn.indexOf(".", l)) > l);
4661 pdbfn = pdbfn.substring(0, l);
4663 mtch = idm.findAllIdMatches(pdbfn);
4667 FileFormatI type = null;
4670 type = new IdentifyFile().identify(file, protocol);
4671 } catch (Exception ex)
4675 if (type != null && type.isStructureFile())
4677 filesmatched.add(new Object[] { file, protocol, mtch });
4681 // File wasn't named like one of the sequences or wasn't a PDB
4683 filesnotmatched.add(file);
4687 if (filesmatched.size() > 0)
4689 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4690 || JvOptionPane.showConfirmDialog(thisaf,
4691 MessageManager.formatMessage(
4692 "label.automatically_associate_structure_files_with_sequences_same_name",
4694 { Integer.valueOf(filesmatched.size())
4696 MessageManager.getString(
4697 "label.automatically_associate_structure_files_by_name"),
4698 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION)
4701 for (Object[] fm : filesmatched)
4703 // try and associate
4704 // TODO: may want to set a standard ID naming formalism for
4705 // associating PDB files which have no IDs.
4706 for (SequenceI toassoc : (SequenceI[]) fm[2])
4708 PDBEntry pe = new AssociatePdbFileWithSeq()
4709 .associatePdbWithSeq((String) fm[0],
4710 (DataSourceType) fm[1], toassoc, false,
4714 System.err.println("Associated file : "
4715 + ((String) fm[0]) + " with "
4716 + toassoc.getDisplayId(true));
4720 // TODO: do we need to update overview ? only if features are
4722 alignPanel.paintAlignment(true, false);
4726 if (filesnotmatched.size() > 0)
4728 if (assocfiles > 0 && (Cache.getDefault(
4729 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4730 || JvOptionPane.showConfirmDialog(thisaf,
4731 "<html>" + MessageManager.formatMessage(
4732 "label.ignore_unmatched_dropped_files_info",
4735 filesnotmatched.size())
4738 MessageManager.getString(
4739 "label.ignore_unmatched_dropped_files"),
4740 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4744 for (String fn : filesnotmatched)
4746 loadJalviewDataFile(fn, null, null, null);
4750 } catch (Exception ex)
4752 ex.printStackTrace();
4760 * Attempt to load a "dropped" file or URL string, by testing in turn for
4762 * <li>an Annotation file</li>
4763 * <li>a JNet file</li>
4764 * <li>a features file</li>
4765 * <li>else try to interpret as an alignment file</li>
4769 * either a filename or a URL string.
4770 * @throws InterruptedException
4771 * @throws IOException
4773 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4774 FileFormatI format, SequenceI assocSeq)
4778 if (sourceType == null)
4780 sourceType = FormatAdapter.checkProtocol(file);
4782 // if the file isn't identified, or not positively identified as some
4783 // other filetype (PFAM is default unidentified alignment file type) then
4784 // try to parse as annotation.
4785 boolean isAnnotation = (format == null
4786 || FileFormat.Pfam.equals(format))
4787 ? new AnnotationFile().annotateAlignmentView(viewport,
4793 // first see if its a T-COFFEE score file
4794 TCoffeeScoreFile tcf = null;
4797 tcf = new TCoffeeScoreFile(file, sourceType);
4800 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4804 new TCoffeeColourScheme(viewport.getAlignment()));
4805 isAnnotation = true;
4806 statusBar.setText(MessageManager.getString(
4807 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4811 // some problem - if no warning its probable that the ID matching
4812 // process didn't work
4813 JvOptionPane.showMessageDialog(Desktop.desktop,
4814 tcf.getWarningMessage() == null
4815 ? MessageManager.getString(
4816 "label.check_file_matches_sequence_ids_alignment")
4817 : tcf.getWarningMessage(),
4818 MessageManager.getString(
4819 "label.problem_reading_tcoffee_score_file"),
4820 JvOptionPane.WARNING_MESSAGE);
4827 } catch (Exception x)
4830 "Exception when processing data source as T-COFFEE score file",
4836 // try to see if its a JNet 'concise' style annotation file *before*
4838 // try to parse it as a features file
4841 format = new IdentifyFile().identify(file, sourceType);
4843 if (FileFormat.ScoreMatrix == format)
4845 ScoreMatrixFile sm = new ScoreMatrixFile(
4846 new FileParse(file, sourceType));
4848 // todo: i18n this message
4849 statusBar.setText(MessageManager.formatMessage(
4850 "label.successfully_loaded_matrix",
4851 sm.getMatrixName()));
4853 else if (FileFormat.Jnet.equals(format))
4855 JPredFile predictions = new JPredFile(file, sourceType);
4856 new JnetAnnotationMaker();
4857 JnetAnnotationMaker.add_annotation(predictions,
4858 viewport.getAlignment(), 0, false);
4859 viewport.getAlignment().setupJPredAlignment();
4860 isAnnotation = true;
4862 // else if (IdentifyFile.FeaturesFile.equals(format))
4863 else if (FileFormat.Features.equals(format))
4865 if (parseFeaturesFile(file, sourceType))
4867 alignPanel.paintAlignment(true, true);
4872 new FileLoader().LoadFile(viewport, file, sourceType, format);
4878 alignPanel.adjustAnnotationHeight();
4879 viewport.updateSequenceIdColours();
4880 buildSortByAnnotationScoresMenu();
4881 alignPanel.paintAlignment(true, true);
4883 } catch (Exception ex)
4885 ex.printStackTrace();
4886 } catch (OutOfMemoryError oom)
4891 } catch (Exception x)
4896 + (sourceType != null
4897 ? (sourceType == DataSourceType.PASTE
4899 : "using " + sourceType + " from "
4903 ? "(parsing as '" + format + "' file)"
4905 oom, Desktop.desktop);
4910 * Method invoked by the ChangeListener on the tabbed pane, in other words
4911 * when a different tabbed pane is selected by the user or programmatically.
4914 public void tabSelectionChanged(int index)
4918 alignPanel = alignPanels.get(index);
4919 viewport = alignPanel.av;
4920 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4921 setMenusFromViewport(viewport);
4925 * 'focus' any colour slider that is open to the selected viewport
4927 if (viewport.getConservationSelected())
4929 SliderPanel.setConservationSlider(alignPanel,
4930 viewport.getResidueShading(), alignPanel.getViewName());
4934 SliderPanel.hideConservationSlider();
4936 if (viewport.getAbovePIDThreshold())
4938 SliderPanel.setPIDSliderSource(alignPanel,
4939 viewport.getResidueShading(), alignPanel.getViewName());
4943 SliderPanel.hidePIDSlider();
4947 * If there is a frame linked to this one in a SplitPane, switch it to the
4948 * same view tab index. No infinite recursion of calls should happen, since
4949 * tabSelectionChanged() should not get invoked on setting the selected
4950 * index to an unchanged value. Guard against setting an invalid index
4951 * before the new view peer tab has been created.
4953 final AlignViewportI peer = viewport.getCodingComplement();
4956 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4957 .getAlignPanel().alignFrame;
4958 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4960 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4966 * On right mouse click on view tab, prompt for and set new view name.
4969 public void tabbedPane_mousePressed(MouseEvent e)
4971 if (e.isPopupTrigger())
4973 String msg = MessageManager.getString("label.enter_view_name");
4974 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4975 JvOptionPane.QUESTION_MESSAGE);
4979 viewport.viewName = reply;
4980 // TODO warn if reply is in getExistingViewNames()?
4981 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4986 public AlignViewport getCurrentView()
4992 * Open the dialog for regex description parsing.
4995 protected void extractScores_actionPerformed(ActionEvent e)
4997 ParseProperties pp = new jalview.analysis.ParseProperties(
4998 viewport.getAlignment());
4999 // TODO: verify regex and introduce GUI dialog for version 2.5
5000 // if (pp.getScoresFromDescription("col", "score column ",
5001 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5003 if (pp.getScoresFromDescription("description column",
5004 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5006 buildSortByAnnotationScoresMenu();
5014 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5018 protected void showDbRefs_actionPerformed(ActionEvent e)
5020 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5026 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5030 protected void showNpFeats_actionPerformed(ActionEvent e)
5032 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5036 * find the viewport amongst the tabs in this alignment frame and close that
5041 public boolean closeView(AlignViewportI av)
5045 this.closeMenuItem_actionPerformed(false);
5048 Component[] comp = tabbedPane.getComponents();
5049 for (int i = 0; comp != null && i < comp.length; i++)
5051 if (comp[i] instanceof AlignmentPanel)
5053 if (((AlignmentPanel) comp[i]).av == av)
5056 closeView((AlignmentPanel) comp[i]);
5064 protected void build_fetchdbmenu(JMenu webService)
5066 // Temporary hack - DBRef Fetcher always top level ws entry.
5067 // TODO We probably want to store a sequence database checklist in
5068 // preferences and have checkboxes.. rather than individual sources selected
5070 final JMenu rfetch = new JMenu(
5071 MessageManager.getString("action.fetch_db_references"));
5072 rfetch.setToolTipText(MessageManager.getString(
5073 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5074 webService.add(rfetch);
5076 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5077 MessageManager.getString("option.trim_retrieved_seqs"));
5078 trimrs.setToolTipText(
5079 MessageManager.getString("label.trim_retrieved_sequences"));
5081 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5082 trimrs.addActionListener(new ActionListener()
5085 public void actionPerformed(ActionEvent e)
5087 trimrs.setSelected(trimrs.isSelected());
5088 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5089 Boolean.valueOf(trimrs.isSelected()).toString());
5093 JMenuItem fetchr = new JMenuItem(
5094 MessageManager.getString("label.standard_databases"));
5095 fetchr.setToolTipText(
5096 MessageManager.getString("label.fetch_embl_uniprot"));
5097 fetchr.addActionListener(new ActionListener()
5101 public void actionPerformed(ActionEvent e)
5103 new Thread(new Runnable()
5108 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5109 .getAlignment().isNucleotide();
5110 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5111 alignPanel.av.getSequenceSelection(),
5112 alignPanel.alignFrame, null,
5113 alignPanel.alignFrame.featureSettings, isNucleotide);
5114 dbRefFetcher.addListener(new FetchFinishedListenerI()
5117 public void finished()
5119 AlignFrame.this.setMenusForViewport();
5122 dbRefFetcher.fetchDBRefs(false);
5130 final AlignFrame me = this;
5131 new Thread(new Runnable()
5136 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5137 .getSequenceFetcherSingleton(me);
5138 javax.swing.SwingUtilities.invokeLater(new Runnable()
5143 String[] dbclasses = sf.getOrderedSupportedSources();
5144 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5145 // jalview.util.QuickSort.sort(otherdb, otherdb);
5146 List<DbSourceProxy> otherdb;
5147 JMenu dfetch = new JMenu();
5148 JMenu ifetch = new JMenu();
5149 JMenuItem fetchr = null;
5150 int comp = 0, icomp = 0, mcomp = 15;
5151 String mname = null;
5153 for (String dbclass : dbclasses)
5155 otherdb = sf.getSourceProxy(dbclass);
5156 // add a single entry for this class, or submenu allowing 'fetch
5158 if (otherdb == null || otherdb.size() < 1)
5162 // List<DbSourceProxy> dbs=otherdb;
5163 // otherdb=new ArrayList<DbSourceProxy>();
5164 // for (DbSourceProxy db:dbs)
5166 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5170 mname = "From " + dbclass;
5172 if (otherdb.size() == 1)
5174 final DbSourceProxy[] dassource = otherdb
5175 .toArray(new DbSourceProxy[0]);
5176 DbSourceProxy src = otherdb.get(0);
5177 fetchr = new JMenuItem(src.getDbSource());
5178 fetchr.addActionListener(new ActionListener()
5182 public void actionPerformed(ActionEvent e)
5184 new Thread(new Runnable()
5190 boolean isNucleotide = alignPanel.alignFrame
5191 .getViewport().getAlignment()
5193 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5194 alignPanel.av.getSequenceSelection(),
5195 alignPanel.alignFrame, dassource,
5196 alignPanel.alignFrame.featureSettings,
5199 .addListener(new FetchFinishedListenerI()
5202 public void finished()
5204 AlignFrame.this.setMenusForViewport();
5207 dbRefFetcher.fetchDBRefs(false);
5213 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5214 MessageManager.formatMessage(
5215 "label.fetch_retrieve_from", new Object[]
5216 { src.getDbName() })));
5222 final DbSourceProxy[] dassource = otherdb
5223 .toArray(new DbSourceProxy[0]);
5225 DbSourceProxy src = otherdb.get(0);
5226 fetchr = new JMenuItem(MessageManager
5227 .formatMessage("label.fetch_all_param", new Object[]
5228 { src.getDbSource() }));
5229 fetchr.addActionListener(new ActionListener()
5232 public void actionPerformed(ActionEvent e)
5234 new Thread(new Runnable()
5240 boolean isNucleotide = alignPanel.alignFrame
5241 .getViewport().getAlignment()
5243 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5244 alignPanel.av.getSequenceSelection(),
5245 alignPanel.alignFrame, dassource,
5246 alignPanel.alignFrame.featureSettings,
5249 .addListener(new FetchFinishedListenerI()
5252 public void finished()
5254 AlignFrame.this.setMenusForViewport();
5257 dbRefFetcher.fetchDBRefs(false);
5263 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5264 MessageManager.formatMessage(
5265 "label.fetch_retrieve_from_all_sources",
5267 { Integer.valueOf(otherdb.size())
5269 src.getDbSource(), src.getDbName() })));
5272 // and then build the rest of the individual menus
5273 ifetch = new JMenu(MessageManager.formatMessage(
5274 "label.source_from_db_source", new Object[]
5275 { src.getDbSource() }));
5277 String imname = null;
5279 for (DbSourceProxy sproxy : otherdb)
5281 String dbname = sproxy.getDbName();
5282 String sname = dbname.length() > 5
5283 ? dbname.substring(0, 5) + "..."
5285 String msname = dbname.length() > 10
5286 ? dbname.substring(0, 10) + "..."
5290 imname = MessageManager
5291 .formatMessage("label.from_msname", new Object[]
5294 fetchr = new JMenuItem(msname);
5295 final DbSourceProxy[] dassrc = { sproxy };
5296 fetchr.addActionListener(new ActionListener()
5300 public void actionPerformed(ActionEvent e)
5302 new Thread(new Runnable()
5308 boolean isNucleotide = alignPanel.alignFrame
5309 .getViewport().getAlignment()
5311 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5312 alignPanel.av.getSequenceSelection(),
5313 alignPanel.alignFrame, dassrc,
5314 alignPanel.alignFrame.featureSettings,
5317 .addListener(new FetchFinishedListenerI()
5320 public void finished()
5322 AlignFrame.this.setMenusForViewport();
5325 dbRefFetcher.fetchDBRefs(false);
5331 fetchr.setToolTipText(
5332 "<html>" + MessageManager.formatMessage(
5333 "label.fetch_retrieve_from", new Object[]
5337 if (++icomp >= mcomp || i == (otherdb.size()))
5339 ifetch.setText(MessageManager.formatMessage(
5340 "label.source_to_target", imname, sname));
5342 ifetch = new JMenu();
5350 if (comp >= mcomp || dbi >= (dbclasses.length))
5352 dfetch.setText(MessageManager.formatMessage(
5353 "label.source_to_target", mname, dbclass));
5355 dfetch = new JMenu();
5368 * Left justify the whole alignment.
5371 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5373 AlignmentI al = viewport.getAlignment();
5375 viewport.firePropertyChange("alignment", null, al);
5379 * Right justify the whole alignment.
5382 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5384 AlignmentI al = viewport.getAlignment();
5386 viewport.firePropertyChange("alignment", null, al);
5390 public void setShowSeqFeatures(boolean b)
5392 showSeqFeatures.setSelected(b);
5393 viewport.setShowSequenceFeatures(b);
5400 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5401 * awt.event.ActionEvent)
5404 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5406 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5407 alignPanel.paintAlignment(false, false);
5414 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5418 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5420 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5421 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5429 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5430 * .event.ActionEvent)
5433 protected void showGroupConservation_actionPerformed(ActionEvent e)
5435 viewport.setShowGroupConservation(showGroupConservation.getState());
5436 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5443 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5444 * .event.ActionEvent)
5447 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5449 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5450 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5457 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5458 * .event.ActionEvent)
5461 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5463 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5464 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5468 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5470 showSequenceLogo.setState(true);
5471 viewport.setShowSequenceLogo(true);
5472 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5473 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5477 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5479 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5486 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5487 * .event.ActionEvent)
5490 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5492 if (avc.makeGroupsFromSelection())
5494 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5495 alignPanel.updateAnnotation();
5496 alignPanel.paintAlignment(true, true);
5500 public void clearAlignmentSeqRep()
5502 // TODO refactor alignmentseqrep to controller
5503 if (viewport.getAlignment().hasSeqrep())
5505 viewport.getAlignment().setSeqrep(null);
5506 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5507 alignPanel.updateAnnotation();
5508 alignPanel.paintAlignment(true, true);
5513 protected void createGroup_actionPerformed(ActionEvent e)
5515 if (avc.createGroup())
5517 alignPanel.alignmentChanged();
5522 protected void unGroup_actionPerformed(ActionEvent e)
5526 alignPanel.alignmentChanged();
5531 * make the given alignmentPanel the currently selected tab
5533 * @param alignmentPanel
5535 public void setDisplayedView(AlignmentPanel alignmentPanel)
5537 if (!viewport.getSequenceSetId()
5538 .equals(alignmentPanel.av.getSequenceSetId()))
5540 throw new Error(MessageManager.getString(
5541 "error.implementation_error_cannot_show_view_alignment_frame"));
5543 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5544 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5546 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5551 * Action on selection of menu options to Show or Hide annotations.
5554 * @param forSequences
5555 * update sequence-related annotations
5556 * @param forAlignment
5557 * update non-sequence-related annotations
5560 protected void setAnnotationsVisibility(boolean visible,
5561 boolean forSequences, boolean forAlignment)
5563 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5564 .getAlignmentAnnotation();
5569 for (AlignmentAnnotation aa : anns)
5572 * don't display non-positional annotations on an alignment
5574 if (aa.annotations == null)
5578 boolean apply = (aa.sequenceRef == null && forAlignment)
5579 || (aa.sequenceRef != null && forSequences);
5582 aa.visible = visible;
5585 alignPanel.validateAnnotationDimensions(true);
5586 alignPanel.alignmentChanged();
5590 * Store selected annotation sort order for the view and repaint.
5593 protected void sortAnnotations_actionPerformed()
5595 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5597 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5598 alignPanel.paintAlignment(false, false);
5603 * @return alignment panels in this alignment frame
5605 public List<? extends AlignmentViewPanel> getAlignPanels()
5607 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5611 * Open a new alignment window, with the cDNA associated with this (protein)
5612 * alignment, aligned as is the protein.
5614 protected void viewAsCdna_actionPerformed()
5616 // TODO no longer a menu action - refactor as required
5617 final AlignmentI alignment = getViewport().getAlignment();
5618 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5619 if (mappings == null)
5623 List<SequenceI> cdnaSeqs = new ArrayList<>();
5624 for (SequenceI aaSeq : alignment.getSequences())
5626 for (AlignedCodonFrame acf : mappings)
5628 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5632 * There is a cDNA mapping for this protein sequence - add to new
5633 * alignment. It will share the same dataset sequence as other mapped
5634 * cDNA (no new mappings need to be created).
5636 final Sequence newSeq = new Sequence(dnaSeq);
5637 newSeq.setDatasetSequence(dnaSeq);
5638 cdnaSeqs.add(newSeq);
5642 if (cdnaSeqs.size() == 0)
5644 // show a warning dialog no mapped cDNA
5647 AlignmentI cdna = new Alignment(
5648 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5649 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5650 AlignFrame.DEFAULT_HEIGHT);
5651 cdna.alignAs(alignment);
5652 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5654 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5655 AlignFrame.DEFAULT_HEIGHT);
5659 * Set visibility of dna/protein complement view (available when shown in a
5665 protected void showComplement_actionPerformed(boolean show)
5667 SplitContainerI sf = getSplitViewContainer();
5670 sf.setComplementVisible(this, show);
5675 * Generate the reverse (optionally complemented) of the selected sequences,
5676 * and add them to the alignment
5679 protected void showReverse_actionPerformed(boolean complement)
5681 AlignmentI al = null;
5684 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5685 al = dna.reverseCdna(complement);
5686 viewport.addAlignment(al, "");
5687 addHistoryItem(new EditCommand(
5688 MessageManager.getString("label.add_sequences"), Action.PASTE,
5689 al.getSequencesArray(), 0, al.getWidth(),
5690 viewport.getAlignment()));
5691 } catch (Exception ex)
5693 System.err.println(ex.getMessage());
5699 * Try to run a script in the Groovy console, having first ensured that this
5700 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5701 * be targeted at this alignment.
5704 protected void runGroovy_actionPerformed()
5706 Jalview.setCurrentAlignFrame(this);
5707 groovy.ui.Console console = Desktop.getGroovyConsole();
5708 if (console != null)
5712 console.runScript();
5713 } catch (Exception ex)
5715 System.err.println((ex.toString()));
5716 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5717 MessageManager.getString("label.couldnt_run_groovy_script"),
5718 MessageManager.getString("label.groovy_support_failed"),
5719 JvOptionPane.ERROR_MESSAGE);
5724 System.err.println("Can't run Groovy script as console not found");
5729 * Hides columns containing (or not containing) a specified feature, provided
5730 * that would not leave all columns hidden
5732 * @param featureType
5733 * @param columnsContaining
5736 public boolean hideFeatureColumns(String featureType,
5737 boolean columnsContaining)
5739 boolean notForHiding = avc.markColumnsContainingFeatures(
5740 columnsContaining, false, false, featureType);
5743 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5744 false, featureType))
5746 getViewport().hideSelectedColumns();
5754 protected void selectHighlightedColumns_actionPerformed(
5755 ActionEvent actionEvent)
5757 // include key modifier check in case user selects from menu
5758 avc.markHighlightedColumns(
5759 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5760 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5761 | ActionEvent.CTRL_MASK)) != 0);
5765 * Rebuilds the Colour menu, including any user-defined colours which have
5766 * been loaded either on startup or during the session
5768 public void buildColourMenu()
5770 colourMenu.removeAll();
5772 colourMenu.add(applyToAllGroups);
5773 colourMenu.add(textColour);
5774 colourMenu.addSeparator();
5776 ColourMenuHelper.addMenuItems(colourMenu, this, viewport.getAlignment(),
5779 colourMenu.addSeparator();
5780 colourMenu.add(conservationMenuItem);
5781 colourMenu.add(modifyConservation);
5782 colourMenu.add(abovePIDThreshold);
5783 colourMenu.add(modifyPID);
5784 colourMenu.add(annotationColour);
5786 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5787 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5791 * Open a dialog (if not already open) that allows the user to select and
5792 * calculate PCA or Tree analysis
5794 protected void openTreePcaDialog()
5796 if (alignPanel.getCalculationDialog() == null)
5798 new CalculationChooser(AlignFrame.this);
5803 * Sets the status of the HMMER menu
5805 public void updateHMMERStatus()
5807 hmmerMenu.setEnabled(HmmerCommand.isHmmerAvailable());
5811 * Returns the selected hidden Markov model.
5815 public HiddenMarkovModel getSelectedHMM()
5817 if (selectedHMMSequence == null)
5821 return selectedHMMSequence.getHMM();
5825 * Returns the selected hidden Markov model.
5829 public SequenceI getSelectedHMMSequence()
5831 return selectedHMMSequence;
5835 * Sets the selected hidden Markov model
5837 * @param selectedHMM
5839 public void setSelectedHMMSequence(SequenceI selectedHMM)
5841 this.selectedHMMSequence = selectedHMM;
5842 hmmAlign.setText(MessageManager.getString("label.hmmalign") + " to "
5843 + selectedHMM.getHMM().getName());
5844 hmmSearch.setText(MessageManager.getString("label.hmmsearch") + " with "
5845 + selectedHMM.getHMM().getName());
5849 public void hmmerMenu_actionPerformed(ActionEvent e)
5851 SequenceGroup grp = getViewport().getSelectionGroup();
5854 hmmBuild.setText(MessageManager.getString("label.hmmbuild") + " from "
5859 hmmBuild.setText(MessageManager.getString("label.hmmbuild")
5860 + " from Alignment");
5865 protected void loadVcf_actionPerformed()
5867 JalviewFileChooser chooser = new JalviewFileChooser(
5868 Cache.getProperty("LAST_DIRECTORY"));
5869 chooser.setFileView(new JalviewFileView());
5870 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5871 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5873 int value = chooser.showOpenDialog(null);
5875 if (value == JalviewFileChooser.APPROVE_OPTION)
5877 String choice = chooser.getSelectedFile().getPath();
5878 Cache.setProperty("LAST_DIRECTORY", choice);
5879 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5880 new VCFLoader(choice).loadVCF(seqs, this);
5886 class PrintThread extends Thread
5890 public PrintThread(AlignmentPanel ap)
5895 static PageFormat pf;
5900 PrinterJob printJob = PrinterJob.getPrinterJob();
5904 printJob.setPrintable(ap, pf);
5908 printJob.setPrintable(ap);
5911 if (printJob.printDialog())
5916 } catch (Exception PrintException)
5918 PrintException.printStackTrace();