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.ScoreModelI;
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.HiddenSequences;
57 import jalview.datamodel.PDBEntry;
58 import jalview.datamodel.SeqCigar;
59 import jalview.datamodel.Sequence;
60 import jalview.datamodel.SequenceGroup;
61 import jalview.datamodel.SequenceI;
62 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
63 import jalview.io.AlignmentProperties;
64 import jalview.io.AnnotationFile;
65 import jalview.io.BioJsHTMLOutput;
66 import jalview.io.DataSourceType;
67 import jalview.io.FileFormat;
68 import jalview.io.FileFormatI;
69 import jalview.io.FileLoader;
70 import jalview.io.FormatAdapter;
71 import jalview.io.HtmlSvgOutput;
72 import jalview.io.IdentifyFile;
73 import jalview.io.JPredFile;
74 import jalview.io.JalviewFileChooser;
75 import jalview.io.JalviewFileView;
76 import jalview.io.JnetAnnotationMaker;
77 import jalview.io.NewickFile;
78 import jalview.io.TCoffeeScoreFile;
79 import jalview.jbgui.GAlignFrame;
80 import jalview.schemes.Blosum62ColourScheme;
81 import jalview.schemes.BuriedColourScheme;
82 import jalview.schemes.ClustalxColourScheme;
83 import jalview.schemes.ColourSchemeI;
84 import jalview.schemes.ColourSchemeProperty;
85 import jalview.schemes.HelixColourScheme;
86 import jalview.schemes.HydrophobicColourScheme;
87 import jalview.schemes.NucleotideColourScheme;
88 import jalview.schemes.PIDColourScheme;
89 import jalview.schemes.PurinePyrimidineColourScheme;
90 import jalview.schemes.RNAHelicesColour;
91 import jalview.schemes.RNAHelicesColourChooser;
92 import jalview.schemes.ResidueColourScheme;
93 import jalview.schemes.ResidueProperties;
94 import jalview.schemes.StrandColourScheme;
95 import jalview.schemes.TCoffeeColourScheme;
96 import jalview.schemes.TaylorColourScheme;
97 import jalview.schemes.TurnColourScheme;
98 import jalview.schemes.UserColourScheme;
99 import jalview.schemes.ZappoColourScheme;
100 import jalview.util.MessageManager;
101 import jalview.viewmodel.AlignmentViewport;
102 import jalview.ws.DBRefFetcher;
103 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
104 import jalview.ws.jws1.Discoverer;
105 import jalview.ws.jws2.Jws2Discoverer;
106 import jalview.ws.jws2.jabaws2.Jws2Instance;
107 import jalview.ws.seqfetcher.DbSourceProxy;
109 import java.awt.BorderLayout;
110 import java.awt.Component;
111 import java.awt.Rectangle;
112 import java.awt.Toolkit;
113 import java.awt.datatransfer.Clipboard;
114 import java.awt.datatransfer.DataFlavor;
115 import java.awt.datatransfer.StringSelection;
116 import java.awt.datatransfer.Transferable;
117 import java.awt.dnd.DnDConstants;
118 import java.awt.dnd.DropTargetDragEvent;
119 import java.awt.dnd.DropTargetDropEvent;
120 import java.awt.dnd.DropTargetEvent;
121 import java.awt.dnd.DropTargetListener;
122 import java.awt.event.ActionEvent;
123 import java.awt.event.ActionListener;
124 import java.awt.event.FocusAdapter;
125 import java.awt.event.FocusEvent;
126 import java.awt.event.ItemEvent;
127 import java.awt.event.ItemListener;
128 import java.awt.event.KeyAdapter;
129 import java.awt.event.KeyEvent;
130 import java.awt.event.MouseEvent;
131 import java.awt.print.PageFormat;
132 import java.awt.print.PrinterJob;
133 import java.beans.PropertyChangeEvent;
136 import java.util.ArrayList;
137 import java.util.Arrays;
138 import java.util.Deque;
139 import java.util.Enumeration;
140 import java.util.Hashtable;
141 import java.util.List;
142 import java.util.Vector;
144 import javax.swing.JCheckBoxMenuItem;
145 import javax.swing.JEditorPane;
146 import javax.swing.JInternalFrame;
147 import javax.swing.JLayeredPane;
148 import javax.swing.JMenu;
149 import javax.swing.JMenuItem;
150 import javax.swing.JScrollPane;
151 import javax.swing.SwingUtilities;
157 * @version $Revision$
159 public class AlignFrame extends GAlignFrame implements DropTargetListener,
160 IProgressIndicator, AlignViewControllerGuiI
163 public static final int DEFAULT_WIDTH = 700;
165 public static final int DEFAULT_HEIGHT = 500;
168 * The currently displayed panel (selected tabbed view if more than one)
170 public AlignmentPanel alignPanel;
172 AlignViewport viewport;
174 public AlignViewControllerI avc;
176 List<AlignmentPanel> alignPanels = new ArrayList<AlignmentPanel>();
179 * Last format used to load or save alignments in this window
181 FileFormatI currentFileFormat = null;
184 * Current filename for this alignment
186 String fileName = null;
189 * Creates a new AlignFrame object with specific width and height.
195 public AlignFrame(AlignmentI al, int width, int height)
197 this(al, null, width, height);
201 * Creates a new AlignFrame object with specific width, height and
207 * @param sequenceSetId
209 public AlignFrame(AlignmentI al, int width, int height,
210 String sequenceSetId)
212 this(al, null, width, height, sequenceSetId);
216 * Creates a new AlignFrame object with specific width, height and
222 * @param sequenceSetId
225 public AlignFrame(AlignmentI al, int width, int height,
226 String sequenceSetId, String viewId)
228 this(al, null, width, height, sequenceSetId, viewId);
232 * new alignment window with hidden columns
236 * @param hiddenColumns
237 * ColumnSelection or null
239 * Width of alignment frame
243 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
244 int width, int height)
246 this(al, hiddenColumns, width, height, null);
250 * Create alignment frame for al with hiddenColumns, a specific width and
251 * height, and specific sequenceId
254 * @param hiddenColumns
257 * @param sequenceSetId
260 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
261 int width, int height, String sequenceSetId)
263 this(al, hiddenColumns, width, height, sequenceSetId, null);
267 * Create alignment frame for al with hiddenColumns, a specific width and
268 * height, and specific sequenceId
271 * @param hiddenColumns
274 * @param sequenceSetId
279 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
280 int width, int height, String sequenceSetId, String viewId)
282 setSize(width, height);
284 if (al.getDataset() == null)
289 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
291 alignPanel = new AlignmentPanel(this, viewport);
293 addAlignmentPanel(alignPanel, true);
297 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
298 ColumnSelection hiddenColumns, int width, int height)
300 setSize(width, height);
302 if (al.getDataset() == null)
307 viewport = new AlignViewport(al, hiddenColumns);
309 if (hiddenSeqs != null && hiddenSeqs.length > 0)
311 viewport.hideSequence(hiddenSeqs);
313 alignPanel = new AlignmentPanel(this, viewport);
314 addAlignmentPanel(alignPanel, true);
319 * Make a new AlignFrame from existing alignmentPanels
326 public AlignFrame(AlignmentPanel ap)
330 addAlignmentPanel(ap, false);
335 * initalise the alignframe from the underlying viewport data and the
340 if (!Jalview.isHeadlessMode())
342 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
345 avc = new jalview.controller.AlignViewController(this, viewport,
347 if (viewport.getAlignmentConservationAnnotation() == null)
349 BLOSUM62Colour.setEnabled(false);
350 conservationMenuItem.setEnabled(false);
351 modifyConservation.setEnabled(false);
352 // PIDColour.setEnabled(false);
353 // abovePIDThreshold.setEnabled(false);
354 // modifyPID.setEnabled(false);
357 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
360 if (sortby.equals("Id"))
362 sortIDMenuItem_actionPerformed(null);
364 else if (sortby.equals("Pairwise Identity"))
366 sortPairwiseMenuItem_actionPerformed(null);
369 if (Desktop.desktop != null)
371 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
372 addServiceListeners();
373 setGUINucleotide(viewport.getAlignment().isNucleotide());
377 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
379 setMenusFromViewport(viewport);
380 buildSortByAnnotationScoresMenu();
383 if (viewport.getWrapAlignment())
385 wrapMenuItem_actionPerformed(null);
388 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
390 this.overviewMenuItem_actionPerformed(null);
395 final List<AlignmentPanel> selviews = new ArrayList<AlignmentPanel>();
396 final List<AlignmentPanel> origview = new ArrayList<AlignmentPanel>();
397 final String menuLabel = MessageManager
398 .getString("label.copy_format_from");
399 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
400 new ViewSetProvider()
404 public AlignmentPanel[] getAllAlignmentPanels()
407 origview.add(alignPanel);
408 // make an array of all alignment panels except for this one
409 List<AlignmentPanel> aps = new ArrayList<AlignmentPanel>(
410 Arrays.asList(Desktop.getAlignmentPanels(null)));
411 aps.remove(AlignFrame.this.alignPanel);
412 return aps.toArray(new AlignmentPanel[aps.size()]);
414 }, selviews, new ItemListener()
418 public void itemStateChanged(ItemEvent e)
420 if (origview.size() > 0)
422 final AlignmentPanel ap = origview.get(0);
425 * Copy the ViewStyle of the selected panel to 'this one'.
426 * Don't change value of 'scaleProteinAsCdna' unless copying
429 ViewStyleI vs = selviews.get(0).getAlignViewport()
431 boolean fromSplitFrame = selviews.get(0)
432 .getAlignViewport().getCodingComplement() != null;
435 vs.setScaleProteinAsCdna(ap.getAlignViewport()
436 .getViewStyle().isScaleProteinAsCdna());
438 ap.getAlignViewport().setViewStyle(vs);
441 * Also rescale ViewStyle of SplitFrame complement if there is
442 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
443 * the whole ViewStyle (allow cDNA protein to have different
446 AlignViewportI complement = ap.getAlignViewport()
447 .getCodingComplement();
448 if (complement != null && vs.isScaleProteinAsCdna())
450 AlignFrame af = Desktop.getAlignFrameFor(complement);
451 ((SplitFrame) af.getSplitViewContainer())
453 af.setMenusForViewport();
457 ap.setSelected(true);
458 ap.alignFrame.setMenusForViewport();
463 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
464 .indexOf("devel") > -1
465 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
466 .indexOf("test") > -1)
468 formatMenu.add(vsel);
470 addFocusListener(new FocusAdapter()
473 public void focusGained(FocusEvent e)
475 Jalview.setCurrentAlignFrame(AlignFrame.this);
482 * Change the filename and format for the alignment, and enable the 'reload'
483 * button functionality.
490 public void setFileName(String file, FileFormatI format)
493 setFileFormat(format);
494 reload.setEnabled(true);
498 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
501 void addKeyListener()
503 addKeyListener(new KeyAdapter()
506 public void keyPressed(KeyEvent evt)
508 if (viewport.cursorMode
509 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
510 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
511 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
512 && Character.isDigit(evt.getKeyChar()))
514 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
517 switch (evt.getKeyCode())
520 case 27: // escape key
521 deselectAllSequenceMenuItem_actionPerformed(null);
525 case KeyEvent.VK_DOWN:
526 if (evt.isAltDown() || !viewport.cursorMode)
528 moveSelectedSequences(false);
530 if (viewport.cursorMode)
532 alignPanel.getSeqPanel().moveCursor(0, 1);
537 if (evt.isAltDown() || !viewport.cursorMode)
539 moveSelectedSequences(true);
541 if (viewport.cursorMode)
543 alignPanel.getSeqPanel().moveCursor(0, -1);
548 case KeyEvent.VK_LEFT:
549 if (evt.isAltDown() || !viewport.cursorMode)
551 slideSequences(false, alignPanel.getSeqPanel().getKeyboardNo1());
555 alignPanel.getSeqPanel().moveCursor(-1, 0);
560 case KeyEvent.VK_RIGHT:
561 if (evt.isAltDown() || !viewport.cursorMode)
563 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
567 alignPanel.getSeqPanel().moveCursor(1, 0);
571 case KeyEvent.VK_SPACE:
572 if (viewport.cursorMode)
574 alignPanel.getSeqPanel().insertGapAtCursor(
575 evt.isControlDown() || evt.isShiftDown()
580 // case KeyEvent.VK_A:
581 // if (viewport.cursorMode)
583 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
584 // //System.out.println("A");
588 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
589 * System.out.println("closing bracket"); } break;
591 case KeyEvent.VK_DELETE:
592 case KeyEvent.VK_BACK_SPACE:
593 if (!viewport.cursorMode)
595 cut_actionPerformed(null);
599 alignPanel.getSeqPanel().deleteGapAtCursor(
600 evt.isControlDown() || evt.isShiftDown()
607 if (viewport.cursorMode)
609 alignPanel.getSeqPanel().setCursorRow();
613 if (viewport.cursorMode && !evt.isControlDown())
615 alignPanel.getSeqPanel().setCursorColumn();
619 if (viewport.cursorMode)
621 alignPanel.getSeqPanel().setCursorPosition();
625 case KeyEvent.VK_ENTER:
626 case KeyEvent.VK_COMMA:
627 if (viewport.cursorMode)
629 alignPanel.getSeqPanel().setCursorRowAndColumn();
634 if (viewport.cursorMode)
636 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
640 if (viewport.cursorMode)
642 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
647 viewport.cursorMode = !viewport.cursorMode;
648 statusBar.setText(MessageManager.formatMessage(
649 "label.keyboard_editing_mode",
650 new String[] { (viewport.cursorMode ? "on" : "off") }));
651 if (viewport.cursorMode)
653 alignPanel.getSeqPanel().seqCanvas.cursorX = viewport.startRes;
654 alignPanel.getSeqPanel().seqCanvas.cursorY = viewport.startSeq;
656 alignPanel.getSeqPanel().seqCanvas.repaint();
662 Help.showHelpWindow();
663 } catch (Exception ex)
665 ex.printStackTrace();
670 boolean toggleSeqs = !evt.isControlDown();
671 boolean toggleCols = !evt.isShiftDown();
672 toggleHiddenRegions(toggleSeqs, toggleCols);
677 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
678 boolean modifyExisting = true; // always modify, don't clear
679 // evt.isShiftDown();
680 boolean invertHighlighted = evt.isAltDown();
681 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
685 case KeyEvent.VK_PAGE_UP:
686 if (viewport.getWrapAlignment())
688 alignPanel.scrollUp(true);
692 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
693 - viewport.endSeq + viewport.startSeq);
696 case KeyEvent.VK_PAGE_DOWN:
697 if (viewport.getWrapAlignment())
699 alignPanel.scrollUp(false);
703 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
704 + viewport.endSeq - viewport.startSeq);
711 public void keyReleased(KeyEvent evt)
713 switch (evt.getKeyCode())
715 case KeyEvent.VK_LEFT:
716 if (evt.isAltDown() || !viewport.cursorMode)
718 viewport.firePropertyChange("alignment", null, viewport
719 .getAlignment().getSequences());
723 case KeyEvent.VK_RIGHT:
724 if (evt.isAltDown() || !viewport.cursorMode)
726 viewport.firePropertyChange("alignment", null, viewport
727 .getAlignment().getSequences());
735 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
737 ap.alignFrame = this;
738 avc = new jalview.controller.AlignViewController(this, viewport,
743 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
745 int aSize = alignPanels.size();
747 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
749 if (aSize == 1 && ap.av.viewName == null)
751 this.getContentPane().add(ap, BorderLayout.CENTER);
757 setInitialTabVisible();
760 expandViews.setEnabled(true);
761 gatherViews.setEnabled(true);
762 tabbedPane.addTab(ap.av.viewName, ap);
764 ap.setVisible(false);
769 if (ap.av.isPadGaps())
771 ap.av.getAlignment().padGaps();
773 ap.av.updateConservation(ap);
774 ap.av.updateConsensus(ap);
775 ap.av.updateStrucConsensus(ap);
779 public void setInitialTabVisible()
781 expandViews.setEnabled(true);
782 gatherViews.setEnabled(true);
783 tabbedPane.setVisible(true);
784 AlignmentPanel first = alignPanels.get(0);
785 tabbedPane.addTab(first.av.viewName, first);
786 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
789 public AlignViewport getViewport()
794 /* Set up intrinsic listeners for dynamically generated GUI bits. */
795 private void addServiceListeners()
797 final java.beans.PropertyChangeListener thisListener;
798 Desktop.instance.addJalviewPropertyChangeListener("services",
799 thisListener = new java.beans.PropertyChangeListener()
802 public void propertyChange(PropertyChangeEvent evt)
804 // // System.out.println("Discoverer property change.");
805 // if (evt.getPropertyName().equals("services"))
807 SwingUtilities.invokeLater(new Runnable()
814 .println("Rebuild WS Menu for service change");
815 BuildWebServiceMenu();
822 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
825 public void internalFrameClosed(
826 javax.swing.event.InternalFrameEvent evt)
828 // System.out.println("deregistering discoverer listener");
829 Desktop.instance.removeJalviewPropertyChangeListener("services",
831 closeMenuItem_actionPerformed(true);
834 // Finally, build the menu once to get current service state
835 new Thread(new Runnable()
840 BuildWebServiceMenu();
846 * Configure menu items that vary according to whether the alignment is
847 * nucleotide or protein
851 public void setGUINucleotide(boolean nucleotide)
853 showTranslation.setVisible(nucleotide);
854 showReverse.setVisible(nucleotide);
855 showReverseComplement.setVisible(nucleotide);
856 conservationMenuItem.setEnabled(!nucleotide);
857 modifyConservation.setEnabled(!nucleotide);
858 showGroupConservation.setEnabled(!nucleotide);
861 * enable / disable colour schemes
862 * - the old, simple way (based on the nucleotide flag), or
863 * - the new, generic way (interrogate the colour scheme)
865 AlignmentI al = getViewport().getAlignment();
866 clustalColour.setEnabled(!nucleotide);
867 zappoColour.setEnabled(!nucleotide);
868 taylorColour.setEnabled(!nucleotide);
869 hydrophobicityColour.setEnabled(!nucleotide);
870 helixColour.setEnabled(!nucleotide);
871 strandColour.setEnabled(!nucleotide);
872 turnColour.setEnabled(!nucleotide);
873 // buriedColour.setEnabled(!nucleotide);
874 // TODO make isApplicableTo static in ColourSchemeI in Java 8
875 buriedColour.setEnabled(new BuriedColourScheme().isApplicableTo(al));
876 rnahelicesColour.setEnabled(nucleotide);
877 nucleotideColour.setEnabled(nucleotide);
878 // purinePyrimidineColour.setEnabled(nucleotide);
879 purinePyrimidineColour.setEnabled(new PurinePyrimidineColourScheme()
880 .isApplicableTo(al));
882 .setEnabled(new TCoffeeColourScheme(al).isApplicableTo(al));
883 // RNAInteractionColour.setEnabled(nucleotide);
884 showComplementMenuItem.setText(nucleotide ? MessageManager
885 .getString("label.protein") : MessageManager
886 .getString("label.nucleotide"));
888 String selectedColourScheme = Cache.getDefault(
889 nucleotide ? Preferences.DEFAULT_COLOUR_NUC
890 : Preferences.DEFAULT_COLOUR_PROT,
891 ResidueColourScheme.NONE);
892 setColourSelected(selectedColourScheme);
896 * set up menus for the current viewport. This may be called after any
897 * operation that affects the data in the current view (selection changed,
898 * etc) to update the menus to reflect the new state.
901 public void setMenusForViewport()
903 setMenusFromViewport(viewport);
907 * Need to call this method when tabs are selected for multiple views, or when
908 * loading from Jalview2XML.java
913 void setMenusFromViewport(AlignViewport av)
915 padGapsMenuitem.setSelected(av.isPadGaps());
916 colourTextMenuItem.setSelected(av.isShowColourText());
917 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
918 conservationMenuItem.setSelected(av.getConservationSelected());
919 seqLimits.setSelected(av.getShowJVSuffix());
920 idRightAlign.setSelected(av.isRightAlignIds());
921 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
922 renderGapsMenuItem.setSelected(av.isRenderGaps());
923 wrapMenuItem.setSelected(av.getWrapAlignment());
924 scaleAbove.setVisible(av.getWrapAlignment());
925 scaleLeft.setVisible(av.getWrapAlignment());
926 scaleRight.setVisible(av.getWrapAlignment());
927 annotationPanelMenuItem.setState(av.isShowAnnotation());
929 * Show/hide annotations only enabled if annotation panel is shown
931 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
932 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
933 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
934 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
935 viewBoxesMenuItem.setSelected(av.getShowBoxes());
936 viewTextMenuItem.setSelected(av.getShowText());
937 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
938 showGroupConsensus.setSelected(av.isShowGroupConsensus());
939 showGroupConservation.setSelected(av.isShowGroupConservation());
940 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
941 showSequenceLogo.setSelected(av.isShowSequenceLogo());
942 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
944 setColourSelected(ColourSchemeProperty.getColourName(av
945 .getGlobalColourScheme()));
947 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
948 hiddenMarkers.setState(av.getShowHiddenMarkers());
949 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
950 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
951 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
952 autoCalculate.setSelected(av.autoCalculateConsensus);
953 sortByTree.setSelected(av.sortByTree);
954 listenToViewSelections.setSelected(av.followSelection);
955 // rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
956 rnahelicesColour.setEnabled(new RNAHelicesColour(av.getAlignment())
957 .isApplicableTo(av.getAlignment()));
959 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
961 showProducts.setEnabled(canShowProducts());
962 setGroovyEnabled(Desktop.getGroovyConsole() != null);
968 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
972 public void setGroovyEnabled(boolean b)
974 runGroovy.setEnabled(b);
977 private IProgressIndicator progressBar;
982 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
985 public void setProgressBar(String message, long id)
987 progressBar.setProgressBar(message, id);
991 public void registerHandler(final long id,
992 final IProgressIndicatorHandler handler)
994 progressBar.registerHandler(id, handler);
999 * @return true if any progress bars are still active
1002 public boolean operationInProgress()
1004 return progressBar.operationInProgress();
1008 public void setStatus(String text)
1010 statusBar.setText(text);
1014 * Added so Castor Mapping file can obtain Jalview Version
1016 public String getVersion()
1018 return jalview.bin.Cache.getProperty("VERSION");
1021 public FeatureRenderer getFeatureRenderer()
1023 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1027 public void fetchSequence_actionPerformed(ActionEvent e)
1029 new jalview.gui.SequenceFetcher(this);
1033 public void addFromFile_actionPerformed(ActionEvent e)
1035 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1039 public void reload_actionPerformed(ActionEvent e)
1041 if (fileName != null)
1043 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1044 // originating file's format
1045 // TODO: work out how to recover feature settings for correct view(s) when
1046 // file is reloaded.
1047 if (FileFormat.Jalview.equals(currentFileFormat))
1049 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1050 for (int i = 0; i < frames.length; i++)
1052 if (frames[i] instanceof AlignFrame && frames[i] != this
1053 && ((AlignFrame) frames[i]).fileName != null
1054 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1058 frames[i].setSelected(true);
1059 Desktop.instance.closeAssociatedWindows();
1060 } catch (java.beans.PropertyVetoException ex)
1066 Desktop.instance.closeAssociatedWindows();
1068 FileLoader loader = new FileLoader();
1069 DataSourceType protocol = fileName.startsWith("http:") ? DataSourceType.URL
1070 : DataSourceType.FILE;
1071 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1075 Rectangle bounds = this.getBounds();
1077 FileLoader loader = new FileLoader();
1078 DataSourceType protocol = fileName.startsWith("http:") ? DataSourceType.URL
1079 : DataSourceType.FILE;
1080 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1081 protocol, currentFileFormat);
1083 newframe.setBounds(bounds);
1084 if (featureSettings != null && featureSettings.isShowing())
1086 final Rectangle fspos = featureSettings.frame.getBounds();
1087 // TODO: need a 'show feature settings' function that takes bounds -
1088 // need to refactor Desktop.addFrame
1089 newframe.featureSettings_actionPerformed(null);
1090 final FeatureSettings nfs = newframe.featureSettings;
1091 SwingUtilities.invokeLater(new Runnable()
1096 nfs.frame.setBounds(fspos);
1099 this.featureSettings.close();
1100 this.featureSettings = null;
1102 this.closeMenuItem_actionPerformed(true);
1108 public void addFromText_actionPerformed(ActionEvent e)
1110 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport
1115 public void addFromURL_actionPerformed(ActionEvent e)
1117 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1121 public void save_actionPerformed(ActionEvent e)
1123 if (fileName == null || (currentFileFormat == null)
1124 || fileName.startsWith("http"))
1126 saveAs_actionPerformed(null);
1130 saveAlignment(fileName, currentFileFormat);
1141 public void saveAs_actionPerformed(ActionEvent e)
1143 String format = currentFileFormat == null ? null : currentFileFormat
1145 JalviewFileChooser chooser = JalviewFileChooser.forWrite(
1146 Cache.getProperty("LAST_DIRECTORY"), format);
1148 chooser.setFileView(new JalviewFileView());
1149 chooser.setDialogTitle(MessageManager
1150 .getString("label.save_alignment_to_file"));
1151 chooser.setToolTipText(MessageManager.getString("action.save"));
1153 int value = chooser.showSaveDialog(this);
1155 if (value == JalviewFileChooser.APPROVE_OPTION)
1157 currentFileFormat = chooser.getSelectedFormat();
1158 while (currentFileFormat == null)
1161 .showInternalMessageDialog(
1164 .getString("label.select_file_format_before_saving"),
1166 .getString("label.file_format_not_specified"),
1167 JvOptionPane.WARNING_MESSAGE);
1168 currentFileFormat = chooser.getSelectedFormat();
1169 value = chooser.showSaveDialog(this);
1170 if (value != JalviewFileChooser.APPROVE_OPTION)
1176 fileName = chooser.getSelectedFile().getPath();
1178 Cache.setProperty("DEFAULT_FILE_FORMAT",
1179 currentFileFormat.toString());
1181 Cache.setProperty("LAST_DIRECTORY", fileName);
1182 saveAlignment(fileName, currentFileFormat);
1186 public boolean saveAlignment(String file, FileFormatI format)
1188 boolean success = true;
1190 if (FileFormat.Jalview.equals(format))
1192 String shortName = title;
1194 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1196 shortName = shortName.substring(shortName
1197 .lastIndexOf(java.io.File.separatorChar) + 1);
1200 success = new Jalview2XML().saveAlignment(this, file, shortName);
1202 statusBar.setText(MessageManager.formatMessage(
1203 "label.successfully_saved_to_file_in_format", new Object[] {
1204 fileName, format }));
1209 // if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1211 // warningMessage("Cannot save file " + fileName + " using format "
1212 // + format, "Alignment output format not supported");
1213 // if (!Jalview.isHeadlessMode())
1215 // saveAs_actionPerformed(null);
1220 AlignmentExportData exportData = getAlignmentForExport(format,
1222 if (exportData.getSettings().isCancelled())
1226 FormatAdapter f = new FormatAdapter(alignPanel,
1227 exportData.getSettings());
1228 String output = f.formatSequences(
1230 exportData.getAlignment(), // class cast exceptions will
1231 // occur in the distant future
1232 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1233 f.getCacheSuffixDefault(format),
1234 viewport.getColumnSelection());
1244 java.io.PrintWriter out = new java.io.PrintWriter(
1245 new java.io.FileWriter(file));
1249 this.setTitle(file);
1250 statusBar.setText(MessageManager.formatMessage(
1251 "label.successfully_saved_to_file_in_format",
1252 new Object[] { fileName, format }));
1253 } catch (Exception ex)
1256 ex.printStackTrace();
1263 JvOptionPane.showInternalMessageDialog(this, MessageManager
1264 .formatMessage("label.couldnt_save_file",
1265 new Object[] { fileName }), MessageManager
1266 .getString("label.error_saving_file"),
1267 JvOptionPane.WARNING_MESSAGE);
1273 private void warningMessage(String warning, String title)
1275 if (new jalview.util.Platform().isHeadless())
1277 System.err.println("Warning: " + title + "\nWarning: " + warning);
1282 JvOptionPane.showInternalMessageDialog(this, warning, title,
1283 JvOptionPane.WARNING_MESSAGE);
1295 protected void outputText_actionPerformed(ActionEvent e)
1298 FileFormatI fileFormat = FileFormat.forName(e.getActionCommand());
1299 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1301 if (exportData.getSettings().isCancelled())
1305 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1306 cap.setForInput(null);
1309 FileFormatI format = fileFormat;
1310 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1311 .formatSequences(format,
1312 exportData.getAlignment(),
1313 exportData.getOmitHidden(),
1314 exportData.getStartEndPostions(),
1315 viewport.getColumnSelection()));
1316 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1317 "label.alignment_output_command",
1318 new Object[] { e.getActionCommand() }), 600, 500);
1319 } catch (OutOfMemoryError oom)
1321 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1327 public static AlignmentExportData getAlignmentForExport(
1328 FileFormatI format, AlignViewportI viewport,
1329 AlignExportSettingI exportSettings)
1331 AlignmentI alignmentToExport = null;
1332 AlignExportSettingI settings = exportSettings;
1333 String[] omitHidden = null;
1335 HiddenSequences hiddenSeqs = viewport.getAlignment()
1336 .getHiddenSequences();
1338 alignmentToExport = viewport.getAlignment();
1340 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1341 if (settings == null)
1343 settings = new AlignExportSettings(hasHiddenSeqs,
1344 viewport.hasHiddenColumns(), format);
1346 // settings.isExportAnnotations();
1348 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1350 omitHidden = viewport.getViewAsString(false,
1351 settings.isExportHiddenSequences());
1354 int[] alignmentStartEnd = new int[2];
1355 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1357 alignmentToExport = hiddenSeqs.getFullAlignment();
1361 alignmentToExport = viewport.getAlignment();
1363 alignmentStartEnd = alignmentToExport
1364 .getVisibleStartAndEndIndex(viewport.getColumnSelection()
1365 .getHiddenColumns());
1366 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1367 omitHidden, alignmentStartEnd, settings);
1378 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1380 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1381 htmlSVG.exportHTML(null);
1385 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1387 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1388 bjs.exportHTML(null);
1391 public void createImageMap(File file, String image)
1393 alignPanel.makePNGImageMap(file, image);
1403 public void createPNG(File f)
1405 alignPanel.makePNG(f);
1415 public void createEPS(File f)
1417 alignPanel.makeEPS(f);
1421 public void createSVG(File f)
1423 alignPanel.makeSVG(f);
1427 public void pageSetup_actionPerformed(ActionEvent e)
1429 PrinterJob printJob = PrinterJob.getPrinterJob();
1430 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1440 public void printMenuItem_actionPerformed(ActionEvent e)
1442 // Putting in a thread avoids Swing painting problems
1443 PrintThread thread = new PrintThread(alignPanel);
1448 public void exportFeatures_actionPerformed(ActionEvent e)
1450 new AnnotationExporter().exportFeatures(alignPanel);
1454 public void exportAnnotations_actionPerformed(ActionEvent e)
1456 new AnnotationExporter().exportAnnotations(alignPanel);
1460 public void associatedData_actionPerformed(ActionEvent e)
1462 // Pick the tree file
1463 JalviewFileChooser chooser = new JalviewFileChooser(
1464 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1465 chooser.setFileView(new JalviewFileView());
1466 chooser.setDialogTitle(MessageManager
1467 .getString("label.load_jalview_annotations"));
1468 chooser.setToolTipText(MessageManager
1469 .getString("label.load_jalview_annotations"));
1471 int value = chooser.showOpenDialog(null);
1473 if (value == JalviewFileChooser.APPROVE_OPTION)
1475 String choice = chooser.getSelectedFile().getPath();
1476 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1477 loadJalviewDataFile(choice, null, null, null);
1483 * Close the current view or all views in the alignment frame. If the frame
1484 * only contains one view then the alignment will be removed from memory.
1486 * @param closeAllTabs
1489 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1491 if (alignPanels != null && alignPanels.size() < 2)
1493 closeAllTabs = true;
1498 if (alignPanels != null)
1502 if (this.isClosed())
1504 // really close all the windows - otherwise wait till
1505 // setClosed(true) is called
1506 for (int i = 0; i < alignPanels.size(); i++)
1508 AlignmentPanel ap = alignPanels.get(i);
1515 closeView(alignPanel);
1522 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1523 * be called recursively, with the frame now in 'closed' state
1525 this.setClosed(true);
1527 } catch (Exception ex)
1529 ex.printStackTrace();
1534 * Close the specified panel and close up tabs appropriately.
1536 * @param panelToClose
1538 public void closeView(AlignmentPanel panelToClose)
1540 int index = tabbedPane.getSelectedIndex();
1541 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1542 alignPanels.remove(panelToClose);
1543 panelToClose.closePanel();
1544 panelToClose = null;
1546 tabbedPane.removeTabAt(closedindex);
1547 tabbedPane.validate();
1549 if (index > closedindex || index == tabbedPane.getTabCount())
1551 // modify currently selected tab index if necessary.
1555 this.tabSelectionChanged(index);
1561 void updateEditMenuBar()
1564 if (viewport.getHistoryList().size() > 0)
1566 undoMenuItem.setEnabled(true);
1567 CommandI command = viewport.getHistoryList().peek();
1568 undoMenuItem.setText(MessageManager.formatMessage(
1569 "label.undo_command",
1570 new Object[] { command.getDescription() }));
1574 undoMenuItem.setEnabled(false);
1575 undoMenuItem.setText(MessageManager.getString("action.undo"));
1578 if (viewport.getRedoList().size() > 0)
1580 redoMenuItem.setEnabled(true);
1582 CommandI command = viewport.getRedoList().peek();
1583 redoMenuItem.setText(MessageManager.formatMessage(
1584 "label.redo_command",
1585 new Object[] { command.getDescription() }));
1589 redoMenuItem.setEnabled(false);
1590 redoMenuItem.setText(MessageManager.getString("action.redo"));
1595 public void addHistoryItem(CommandI command)
1597 if (command.getSize() > 0)
1599 viewport.addToHistoryList(command);
1600 viewport.clearRedoList();
1601 updateEditMenuBar();
1602 viewport.updateHiddenColumns();
1603 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1604 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1605 // viewport.getColumnSelection()
1606 // .getHiddenColumns().size() > 0);
1612 * @return alignment objects for all views
1614 AlignmentI[] getViewAlignments()
1616 if (alignPanels != null)
1618 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1620 for (AlignmentPanel ap : alignPanels)
1622 als[i++] = ap.av.getAlignment();
1626 if (viewport != null)
1628 return new AlignmentI[] { viewport.getAlignment() };
1640 protected void undoMenuItem_actionPerformed(ActionEvent e)
1642 if (viewport.getHistoryList().isEmpty())
1646 CommandI command = viewport.getHistoryList().pop();
1647 viewport.addToRedoList(command);
1648 command.undoCommand(getViewAlignments());
1650 AlignmentViewport originalSource = getOriginatingSource(command);
1651 updateEditMenuBar();
1653 if (originalSource != null)
1655 if (originalSource != viewport)
1658 .warn("Implementation worry: mismatch of viewport origin for undo");
1660 originalSource.updateHiddenColumns();
1661 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1663 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1664 // viewport.getColumnSelection()
1665 // .getHiddenColumns().size() > 0);
1666 originalSource.firePropertyChange("alignment", null, originalSource
1667 .getAlignment().getSequences());
1678 protected void redoMenuItem_actionPerformed(ActionEvent e)
1680 if (viewport.getRedoList().size() < 1)
1685 CommandI command = viewport.getRedoList().pop();
1686 viewport.addToHistoryList(command);
1687 command.doCommand(getViewAlignments());
1689 AlignmentViewport originalSource = getOriginatingSource(command);
1690 updateEditMenuBar();
1692 if (originalSource != null)
1695 if (originalSource != viewport)
1698 .warn("Implementation worry: mismatch of viewport origin for redo");
1700 originalSource.updateHiddenColumns();
1701 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1703 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1704 // viewport.getColumnSelection()
1705 // .getHiddenColumns().size() > 0);
1706 originalSource.firePropertyChange("alignment", null, originalSource
1707 .getAlignment().getSequences());
1711 AlignmentViewport getOriginatingSource(CommandI command)
1713 AlignmentViewport originalSource = null;
1714 // For sequence removal and addition, we need to fire
1715 // the property change event FROM the viewport where the
1716 // original alignment was altered
1717 AlignmentI al = null;
1718 if (command instanceof EditCommand)
1720 EditCommand editCommand = (EditCommand) command;
1721 al = editCommand.getAlignment();
1722 List<Component> comps = PaintRefresher.components.get(viewport
1723 .getSequenceSetId());
1725 for (Component comp : comps)
1727 if (comp instanceof AlignmentPanel)
1729 if (al == ((AlignmentPanel) comp).av.getAlignment())
1731 originalSource = ((AlignmentPanel) comp).av;
1738 if (originalSource == null)
1740 // The original view is closed, we must validate
1741 // the current view against the closed view first
1744 PaintRefresher.validateSequences(al, viewport.getAlignment());
1747 originalSource = viewport;
1750 return originalSource;
1759 public void moveSelectedSequences(boolean up)
1761 SequenceGroup sg = viewport.getSelectionGroup();
1767 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1768 viewport.getHiddenRepSequences(), up);
1769 alignPanel.paintAlignment(true);
1772 synchronized void slideSequences(boolean right, int size)
1774 List<SequenceI> sg = new ArrayList<SequenceI>();
1775 if (viewport.cursorMode)
1777 sg.add(viewport.getAlignment().getSequenceAt(
1778 alignPanel.getSeqPanel().seqCanvas.cursorY));
1780 else if (viewport.getSelectionGroup() != null
1781 && viewport.getSelectionGroup().getSize() != viewport
1782 .getAlignment().getHeight())
1784 sg = viewport.getSelectionGroup().getSequences(
1785 viewport.getHiddenRepSequences());
1793 List<SequenceI> invertGroup = new ArrayList<SequenceI>();
1795 for (SequenceI seq : viewport.getAlignment().getSequences())
1797 if (!sg.contains(seq))
1799 invertGroup.add(seq);
1803 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1805 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1806 for (int i = 0; i < invertGroup.size(); i++)
1808 seqs2[i] = invertGroup.get(i);
1811 SlideSequencesCommand ssc;
1814 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1815 size, viewport.getGapCharacter());
1819 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1820 size, viewport.getGapCharacter());
1823 int groupAdjustment = 0;
1824 if (ssc.getGapsInsertedBegin() && right)
1826 if (viewport.cursorMode)
1828 alignPanel.getSeqPanel().moveCursor(size, 0);
1832 groupAdjustment = size;
1835 else if (!ssc.getGapsInsertedBegin() && !right)
1837 if (viewport.cursorMode)
1839 alignPanel.getSeqPanel().moveCursor(-size, 0);
1843 groupAdjustment = -size;
1847 if (groupAdjustment != 0)
1849 viewport.getSelectionGroup().setStartRes(
1850 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1851 viewport.getSelectionGroup().setEndRes(
1852 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1856 * just extend the last slide command if compatible; but not if in
1857 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1859 boolean appendHistoryItem = false;
1860 Deque<CommandI> historyList = viewport.getHistoryList();
1861 boolean inSplitFrame = getSplitViewContainer() != null;
1862 if (!inSplitFrame && historyList != null && historyList.size() > 0
1863 && historyList.peek() instanceof SlideSequencesCommand)
1865 appendHistoryItem = ssc
1866 .appendSlideCommand((SlideSequencesCommand) historyList
1870 if (!appendHistoryItem)
1872 addHistoryItem(ssc);
1885 protected void copy_actionPerformed(ActionEvent e)
1888 if (viewport.getSelectionGroup() == null)
1892 // TODO: preserve the ordering of displayed alignment annotation in any
1893 // internal paste (particularly sequence associated annotation)
1894 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1895 String[] omitHidden = null;
1897 if (viewport.hasHiddenColumns())
1899 omitHidden = viewport.getViewAsString(true);
1902 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1906 StringSelection ss = new StringSelection(output);
1910 jalview.gui.Desktop.internalCopy = true;
1911 // Its really worth setting the clipboard contents
1912 // to empty before setting the large StringSelection!!
1913 Toolkit.getDefaultToolkit().getSystemClipboard()
1914 .setContents(new StringSelection(""), null);
1916 Toolkit.getDefaultToolkit().getSystemClipboard()
1917 .setContents(ss, Desktop.instance);
1918 } catch (OutOfMemoryError er)
1920 new OOMWarning("copying region", er);
1924 ArrayList<int[]> hiddenColumns = null;
1925 if (viewport.hasHiddenColumns())
1927 hiddenColumns = new ArrayList<int[]>();
1928 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1929 .getSelectionGroup().getEndRes();
1930 for (int[] region : viewport.getColumnSelection().getHiddenColumns())
1932 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1934 hiddenColumns.add(new int[] { region[0] - hiddenOffset,
1935 region[1] - hiddenOffset });
1940 Desktop.jalviewClipboard = new Object[] { seqs,
1941 viewport.getAlignment().getDataset(), hiddenColumns };
1942 statusBar.setText(MessageManager.formatMessage(
1943 "label.copied_sequences_to_clipboard", new Object[] { Integer
1944 .valueOf(seqs.length).toString() }));
1954 protected void pasteNew_actionPerformed(ActionEvent e)
1966 protected void pasteThis_actionPerformed(ActionEvent e)
1972 * Paste contents of Jalview clipboard
1974 * @param newAlignment
1975 * true to paste to a new alignment, otherwise add to this.
1977 void paste(boolean newAlignment)
1979 boolean externalPaste = true;
1982 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1983 Transferable contents = c.getContents(this);
1985 if (contents == null)
1994 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1995 if (str.length() < 1)
2000 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2002 } catch (OutOfMemoryError er)
2004 new OOMWarning("Out of memory pasting sequences!!", er);
2008 SequenceI[] sequences;
2009 boolean annotationAdded = false;
2010 AlignmentI alignment = null;
2012 if (Desktop.jalviewClipboard != null)
2014 // The clipboard was filled from within Jalview, we must use the
2016 // And dataset from the copied alignment
2017 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2018 // be doubly sure that we create *new* sequence objects.
2019 sequences = new SequenceI[newseq.length];
2020 for (int i = 0; i < newseq.length; i++)
2022 sequences[i] = new Sequence(newseq[i]);
2024 alignment = new Alignment(sequences);
2025 externalPaste = false;
2029 // parse the clipboard as an alignment.
2030 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2032 sequences = alignment.getSequencesArray();
2036 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
2042 if (Desktop.jalviewClipboard != null)
2044 // dataset is inherited
2045 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2049 // new dataset is constructed
2050 alignment.setDataset(null);
2052 alwidth = alignment.getWidth() + 1;
2056 AlignmentI pastedal = alignment; // preserve pasted alignment object
2057 // Add pasted sequences and dataset into existing alignment.
2058 alignment = viewport.getAlignment();
2059 alwidth = alignment.getWidth() + 1;
2060 // decide if we need to import sequences from an existing dataset
2061 boolean importDs = Desktop.jalviewClipboard != null
2062 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2063 // importDs==true instructs us to copy over new dataset sequences from
2064 // an existing alignment
2065 Vector newDs = (importDs) ? new Vector() : null; // used to create
2066 // minimum dataset set
2068 for (int i = 0; i < sequences.length; i++)
2072 newDs.addElement(null);
2074 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2076 if (importDs && ds != null)
2078 if (!newDs.contains(ds))
2080 newDs.setElementAt(ds, i);
2081 ds = new Sequence(ds);
2082 // update with new dataset sequence
2083 sequences[i].setDatasetSequence(ds);
2087 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2092 // copy and derive new dataset sequence
2093 sequences[i] = sequences[i].deriveSequence();
2094 alignment.getDataset().addSequence(
2095 sequences[i].getDatasetSequence());
2096 // TODO: avoid creation of duplicate dataset sequences with a
2097 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2099 alignment.addSequence(sequences[i]); // merges dataset
2103 newDs.clear(); // tidy up
2105 if (alignment.getAlignmentAnnotation() != null)
2107 for (AlignmentAnnotation alan : alignment
2108 .getAlignmentAnnotation())
2110 if (alan.graphGroup > fgroup)
2112 fgroup = alan.graphGroup;
2116 if (pastedal.getAlignmentAnnotation() != null)
2118 // Add any annotation attached to alignment.
2119 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2120 for (int i = 0; i < alann.length; i++)
2122 annotationAdded = true;
2123 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2125 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2126 if (newann.graphGroup > -1)
2128 if (newGraphGroups.size() <= newann.graphGroup
2129 || newGraphGroups.get(newann.graphGroup) == null)
2131 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2133 newGraphGroups.add(q, null);
2135 newGraphGroups.set(newann.graphGroup, new Integer(
2138 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2142 newann.padAnnotation(alwidth);
2143 alignment.addAnnotation(newann);
2153 addHistoryItem(new EditCommand(
2154 MessageManager.getString("label.add_sequences"),
2155 Action.PASTE, sequences, 0, alignment.getWidth(), alignment));
2157 // Add any annotations attached to sequences
2158 for (int i = 0; i < sequences.length; i++)
2160 if (sequences[i].getAnnotation() != null)
2162 AlignmentAnnotation newann;
2163 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2165 annotationAdded = true;
2166 newann = sequences[i].getAnnotation()[a];
2167 newann.adjustForAlignment();
2168 newann.padAnnotation(alwidth);
2169 if (newann.graphGroup > -1)
2171 if (newann.graphGroup > -1)
2173 if (newGraphGroups.size() <= newann.graphGroup
2174 || newGraphGroups.get(newann.graphGroup) == null)
2176 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2178 newGraphGroups.add(q, null);
2180 newGraphGroups.set(newann.graphGroup, new Integer(
2183 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2187 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2192 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2199 // propagate alignment changed.
2200 viewport.setEndSeq(alignment.getHeight());
2201 if (annotationAdded)
2203 // Duplicate sequence annotation in all views.
2204 AlignmentI[] alview = this.getViewAlignments();
2205 for (int i = 0; i < sequences.length; i++)
2207 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2212 for (int avnum = 0; avnum < alview.length; avnum++)
2214 if (alview[avnum] != alignment)
2216 // duplicate in a view other than the one with input focus
2217 int avwidth = alview[avnum].getWidth() + 1;
2218 // this relies on sann being preserved after we
2219 // modify the sequence's annotation array for each duplication
2220 for (int a = 0; a < sann.length; a++)
2222 AlignmentAnnotation newann = new AlignmentAnnotation(
2224 sequences[i].addAlignmentAnnotation(newann);
2225 newann.padAnnotation(avwidth);
2226 alview[avnum].addAnnotation(newann); // annotation was
2227 // duplicated earlier
2228 // TODO JAL-1145 graphGroups are not updated for sequence
2229 // annotation added to several views. This may cause
2231 alview[avnum].setAnnotationIndex(newann, a);
2236 buildSortByAnnotationScoresMenu();
2238 viewport.firePropertyChange("alignment", null,
2239 alignment.getSequences());
2240 if (alignPanels != null)
2242 for (AlignmentPanel ap : alignPanels)
2244 ap.validateAnnotationDimensions(false);
2249 alignPanel.validateAnnotationDimensions(false);
2255 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2257 String newtitle = new String("Copied sequences");
2259 if (Desktop.jalviewClipboard != null
2260 && Desktop.jalviewClipboard[2] != null)
2262 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2263 for (int[] region : hc)
2265 af.viewport.hideColumns(region[0], region[1]);
2269 // >>>This is a fix for the moment, until a better solution is
2271 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2273 alignPanel.getSeqPanel().seqCanvas
2274 .getFeatureRenderer());
2276 // TODO: maintain provenance of an alignment, rather than just make the
2277 // title a concatenation of operations.
2280 if (title.startsWith("Copied sequences"))
2286 newtitle = newtitle.concat("- from " + title);
2291 newtitle = new String("Pasted sequences");
2294 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2299 } catch (Exception ex)
2301 ex.printStackTrace();
2302 System.out.println("Exception whilst pasting: " + ex);
2303 // could be anything being pasted in here
2309 protected void expand_newalign(ActionEvent e)
2313 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2314 .getAlignment(), -1);
2315 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2317 String newtitle = new String("Flanking alignment");
2319 if (Desktop.jalviewClipboard != null
2320 && Desktop.jalviewClipboard[2] != null)
2322 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2323 for (int region[] : hc)
2325 af.viewport.hideColumns(region[0], region[1]);
2329 // >>>This is a fix for the moment, until a better solution is
2331 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2333 alignPanel.getSeqPanel().seqCanvas
2334 .getFeatureRenderer());
2336 // TODO: maintain provenance of an alignment, rather than just make the
2337 // title a concatenation of operations.
2339 if (title.startsWith("Copied sequences"))
2345 newtitle = newtitle.concat("- from " + title);
2349 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2351 } catch (Exception ex)
2353 ex.printStackTrace();
2354 System.out.println("Exception whilst pasting: " + ex);
2355 // could be anything being pasted in here
2356 } catch (OutOfMemoryError oom)
2358 new OOMWarning("Viewing flanking region of alignment", oom);
2369 protected void cut_actionPerformed(ActionEvent e)
2371 copy_actionPerformed(null);
2372 delete_actionPerformed(null);
2382 protected void delete_actionPerformed(ActionEvent evt)
2385 SequenceGroup sg = viewport.getSelectionGroup();
2392 * If the cut affects all sequences, warn, remove highlighted columns
2394 if (sg.getSize() == viewport.getAlignment().getHeight())
2396 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes()) + 1) == viewport
2397 .getAlignment().getWidth()) ? true : false;
2398 if (isEntireAlignWidth)
2400 int confirm = JvOptionPane.showConfirmDialog(this,
2401 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2402 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2403 JvOptionPane.OK_CANCEL_OPTION);
2405 if (confirm == JvOptionPane.CANCEL_OPTION
2406 || confirm == JvOptionPane.CLOSED_OPTION)
2411 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2412 sg.getEndRes() + 1);
2414 SequenceI[] cut = sg.getSequences()
2415 .toArray(new SequenceI[sg.getSize()]);
2417 addHistoryItem(new EditCommand(
2418 MessageManager.getString("label.cut_sequences"), Action.CUT,
2419 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2420 viewport.getAlignment()));
2422 viewport.setSelectionGroup(null);
2423 viewport.sendSelection();
2424 viewport.getAlignment().deleteGroup(sg);
2426 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2428 if (viewport.getAlignment().getHeight() < 1)
2432 this.setClosed(true);
2433 } catch (Exception ex)
2446 protected void deleteGroups_actionPerformed(ActionEvent e)
2448 if (avc.deleteGroups())
2450 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2451 alignPanel.updateAnnotation();
2452 alignPanel.paintAlignment(true);
2463 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2465 SequenceGroup sg = new SequenceGroup();
2467 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2469 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2472 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2473 viewport.setSelectionGroup(sg);
2474 viewport.sendSelection();
2475 // JAL-2034 - should delegate to
2476 // alignPanel to decide if overview needs
2478 alignPanel.paintAlignment(false);
2479 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2489 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2491 if (viewport.cursorMode)
2493 alignPanel.getSeqPanel().keyboardNo1 = null;
2494 alignPanel.getSeqPanel().keyboardNo2 = null;
2496 viewport.setSelectionGroup(null);
2497 viewport.getColumnSelection().clear();
2498 viewport.setSelectionGroup(null);
2499 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2500 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2501 // JAL-2034 - should delegate to
2502 // alignPanel to decide if overview needs
2504 alignPanel.paintAlignment(false);
2505 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2506 viewport.sendSelection();
2516 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2518 SequenceGroup sg = viewport.getSelectionGroup();
2522 selectAllSequenceMenuItem_actionPerformed(null);
2527 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2529 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2531 // JAL-2034 - should delegate to
2532 // alignPanel to decide if overview needs
2535 alignPanel.paintAlignment(true);
2536 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2537 viewport.sendSelection();
2541 public void invertColSel_actionPerformed(ActionEvent e)
2543 viewport.invertColumnSelection();
2544 alignPanel.paintAlignment(true);
2545 viewport.sendSelection();
2555 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2557 trimAlignment(true);
2567 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2569 trimAlignment(false);
2572 void trimAlignment(boolean trimLeft)
2574 ColumnSelection colSel = viewport.getColumnSelection();
2577 if (!colSel.isEmpty())
2581 column = colSel.getMin();
2585 column = colSel.getMax();
2589 if (viewport.getSelectionGroup() != null)
2591 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2592 viewport.getHiddenRepSequences());
2596 seqs = viewport.getAlignment().getSequencesArray();
2599 TrimRegionCommand trimRegion;
2602 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2603 column, viewport.getAlignment());
2604 viewport.setStartRes(0);
2608 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2609 column, viewport.getAlignment());
2612 statusBar.setText(MessageManager.formatMessage(
2613 "label.removed_columns",
2614 new String[] { Integer.valueOf(trimRegion.getSize())
2617 addHistoryItem(trimRegion);
2619 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2621 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2622 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2624 viewport.getAlignment().deleteGroup(sg);
2628 viewport.firePropertyChange("alignment", null, viewport
2629 .getAlignment().getSequences());
2640 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2642 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2645 if (viewport.getSelectionGroup() != null)
2647 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2648 viewport.getHiddenRepSequences());
2649 start = viewport.getSelectionGroup().getStartRes();
2650 end = viewport.getSelectionGroup().getEndRes();
2654 seqs = viewport.getAlignment().getSequencesArray();
2657 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2658 "Remove Gapped Columns", seqs, start, end,
2659 viewport.getAlignment());
2661 addHistoryItem(removeGapCols);
2663 statusBar.setText(MessageManager.formatMessage(
2664 "label.removed_empty_columns",
2665 new Object[] { Integer.valueOf(removeGapCols.getSize())
2668 // This is to maintain viewport position on first residue
2669 // of first sequence
2670 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2671 int startRes = seq.findPosition(viewport.startRes);
2672 // ShiftList shifts;
2673 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2674 // edit.alColumnChanges=shifts.getInverse();
2675 // if (viewport.hasHiddenColumns)
2676 // viewport.getColumnSelection().compensateForEdits(shifts);
2677 viewport.setStartRes(seq.findIndex(startRes) - 1);
2678 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2690 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2692 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2695 if (viewport.getSelectionGroup() != null)
2697 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2698 viewport.getHiddenRepSequences());
2699 start = viewport.getSelectionGroup().getStartRes();
2700 end = viewport.getSelectionGroup().getEndRes();
2704 seqs = viewport.getAlignment().getSequencesArray();
2707 // This is to maintain viewport position on first residue
2708 // of first sequence
2709 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2710 int startRes = seq.findPosition(viewport.startRes);
2712 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2713 viewport.getAlignment()));
2715 viewport.setStartRes(seq.findIndex(startRes) - 1);
2717 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2729 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2731 viewport.setPadGaps(padGapsMenuitem.isSelected());
2732 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2743 public void findMenuItem_actionPerformed(ActionEvent e)
2749 * Create a new view of the current alignment.
2752 public void newView_actionPerformed(ActionEvent e)
2754 newView(null, true);
2758 * Creates and shows a new view of the current alignment.
2761 * title of newly created view; if null, one will be generated
2762 * @param copyAnnotation
2763 * if true then duplicate all annnotation, groups and settings
2764 * @return new alignment panel, already displayed.
2766 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2769 * Create a new AlignmentPanel (with its own, new Viewport)
2771 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2773 if (!copyAnnotation)
2776 * remove all groups and annotation except for the automatic stuff
2778 newap.av.getAlignment().deleteAllGroups();
2779 newap.av.getAlignment().deleteAllAnnotations(false);
2782 newap.av.setGatherViewsHere(false);
2784 if (viewport.viewName == null)
2786 viewport.viewName = MessageManager
2787 .getString("label.view_name_original");
2791 * Views share the same edits undo and redo stacks
2793 newap.av.setHistoryList(viewport.getHistoryList());
2794 newap.av.setRedoList(viewport.getRedoList());
2797 * Views share the same mappings; need to deregister any new mappings
2798 * created by copyAlignPanel, and register the new reference to the shared
2801 newap.av.replaceMappings(viewport.getAlignment());
2803 newap.av.viewName = getNewViewName(viewTitle);
2805 addAlignmentPanel(newap, true);
2806 newap.alignmentChanged();
2808 if (alignPanels.size() == 2)
2810 viewport.setGatherViewsHere(true);
2812 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2817 * Make a new name for the view, ensuring it is unique within the current
2818 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2819 * these now use viewId. Unique view names are still desirable for usability.)
2824 protected String getNewViewName(String viewTitle)
2826 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2827 boolean addFirstIndex = false;
2828 if (viewTitle == null || viewTitle.trim().length() == 0)
2830 viewTitle = MessageManager.getString("action.view");
2831 addFirstIndex = true;
2835 index = 1;// we count from 1 if given a specific name
2837 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2839 List<Component> comps = PaintRefresher.components.get(viewport
2840 .getSequenceSetId());
2842 List<String> existingNames = getExistingViewNames(comps);
2844 while (existingNames.contains(newViewName))
2846 newViewName = viewTitle + " " + (++index);
2852 * Returns a list of distinct view names found in the given list of
2853 * components. View names are held on the viewport of an AlignmentPanel.
2858 protected List<String> getExistingViewNames(List<Component> comps)
2860 List<String> existingNames = new ArrayList<String>();
2861 for (Component comp : comps)
2863 if (comp instanceof AlignmentPanel)
2865 AlignmentPanel ap = (AlignmentPanel) comp;
2866 if (!existingNames.contains(ap.av.viewName))
2868 existingNames.add(ap.av.viewName);
2872 return existingNames;
2876 * Explode tabbed views into separate windows.
2879 public void expandViews_actionPerformed(ActionEvent e)
2881 Desktop.explodeViews(this);
2885 * Gather views in separate windows back into a tabbed presentation.
2888 public void gatherViews_actionPerformed(ActionEvent e)
2890 Desktop.instance.gatherViews(this);
2900 public void font_actionPerformed(ActionEvent e)
2902 new FontChooser(alignPanel);
2912 protected void seqLimit_actionPerformed(ActionEvent e)
2914 viewport.setShowJVSuffix(seqLimits.isSelected());
2916 alignPanel.getIdPanel().getIdCanvas()
2917 .setPreferredSize(alignPanel.calculateIdWidth());
2918 alignPanel.paintAlignment(true);
2922 public void idRightAlign_actionPerformed(ActionEvent e)
2924 viewport.setRightAlignIds(idRightAlign.isSelected());
2925 alignPanel.paintAlignment(true);
2929 public void centreColumnLabels_actionPerformed(ActionEvent e)
2931 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2932 alignPanel.paintAlignment(true);
2938 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2941 protected void followHighlight_actionPerformed()
2944 * Set the 'follow' flag on the Viewport (and scroll to position if now
2947 final boolean state = this.followHighlightMenuItem.getState();
2948 viewport.setFollowHighlight(state);
2951 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2962 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2964 viewport.setColourText(colourTextMenuItem.isSelected());
2965 alignPanel.paintAlignment(true);
2975 public void wrapMenuItem_actionPerformed(ActionEvent e)
2977 scaleAbove.setVisible(wrapMenuItem.isSelected());
2978 scaleLeft.setVisible(wrapMenuItem.isSelected());
2979 scaleRight.setVisible(wrapMenuItem.isSelected());
2980 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2981 alignPanel.updateLayout();
2985 public void showAllSeqs_actionPerformed(ActionEvent e)
2987 viewport.showAllHiddenSeqs();
2991 public void showAllColumns_actionPerformed(ActionEvent e)
2993 viewport.showAllHiddenColumns();
2995 viewport.sendSelection();
2999 public void hideSelSequences_actionPerformed(ActionEvent e)
3001 viewport.hideAllSelectedSeqs();
3002 // alignPanel.paintAlignment(true);
3006 * called by key handler and the hide all/show all menu items
3011 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3014 boolean hide = false;
3015 SequenceGroup sg = viewport.getSelectionGroup();
3016 if (!toggleSeqs && !toggleCols)
3018 // Hide everything by the current selection - this is a hack - we do the
3019 // invert and then hide
3020 // first check that there will be visible columns after the invert.
3021 if (viewport.hasSelectedColumns()
3022 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
3025 // now invert the sequence set, if required - empty selection implies
3026 // that no hiding is required.
3029 invertSequenceMenuItem_actionPerformed(null);
3030 sg = viewport.getSelectionGroup();
3034 viewport.expandColSelection(sg, true);
3035 // finally invert the column selection and get the new sequence
3037 invertColSel_actionPerformed(null);
3044 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3046 hideSelSequences_actionPerformed(null);
3049 else if (!(toggleCols && viewport.hasSelectedColumns()))
3051 showAllSeqs_actionPerformed(null);
3057 if (viewport.hasSelectedColumns())
3059 hideSelColumns_actionPerformed(null);
3062 viewport.setSelectionGroup(sg);
3067 showAllColumns_actionPerformed(null);
3076 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3077 * event.ActionEvent)
3080 public void hideAllButSelection_actionPerformed(ActionEvent e)
3082 toggleHiddenRegions(false, false);
3083 viewport.sendSelection();
3090 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3094 public void hideAllSelection_actionPerformed(ActionEvent e)
3096 SequenceGroup sg = viewport.getSelectionGroup();
3097 viewport.expandColSelection(sg, false);
3098 viewport.hideAllSelectedSeqs();
3099 viewport.hideSelectedColumns();
3100 alignPanel.paintAlignment(true);
3101 viewport.sendSelection();
3108 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3112 public void showAllhidden_actionPerformed(ActionEvent e)
3114 viewport.showAllHiddenColumns();
3115 viewport.showAllHiddenSeqs();
3116 alignPanel.paintAlignment(true);
3117 viewport.sendSelection();
3121 public void hideSelColumns_actionPerformed(ActionEvent e)
3123 viewport.hideSelectedColumns();
3124 alignPanel.paintAlignment(true);
3125 viewport.sendSelection();
3129 public void hiddenMarkers_actionPerformed(ActionEvent e)
3131 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3142 protected void scaleAbove_actionPerformed(ActionEvent e)
3144 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3145 alignPanel.paintAlignment(true);
3155 protected void scaleLeft_actionPerformed(ActionEvent e)
3157 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3158 alignPanel.paintAlignment(true);
3168 protected void scaleRight_actionPerformed(ActionEvent e)
3170 viewport.setScaleRightWrapped(scaleRight.isSelected());
3171 alignPanel.paintAlignment(true);
3181 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3183 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3184 alignPanel.paintAlignment(true);
3194 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3196 viewport.setShowText(viewTextMenuItem.isSelected());
3197 alignPanel.paintAlignment(true);
3207 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3209 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3210 alignPanel.paintAlignment(true);
3213 public FeatureSettings featureSettings;
3216 public FeatureSettingsControllerI getFeatureSettingsUI()
3218 return featureSettings;
3222 public void featureSettings_actionPerformed(ActionEvent e)
3224 if (featureSettings != null)
3226 featureSettings.close();
3227 featureSettings = null;
3229 if (!showSeqFeatures.isSelected())
3231 // make sure features are actually displayed
3232 showSeqFeatures.setSelected(true);
3233 showSeqFeatures_actionPerformed(null);
3235 featureSettings = new FeatureSettings(this);
3239 * Set or clear 'Show Sequence Features'
3245 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3247 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3248 alignPanel.paintAlignment(true);
3249 if (alignPanel.getOverviewPanel() != null)
3251 alignPanel.getOverviewPanel().updateOverviewImage();
3256 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3257 * the annotations panel as a whole.
3259 * The options to show/hide all annotations should be enabled when the panel
3260 * is shown, and disabled when the panel is hidden.
3265 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3267 final boolean setVisible = annotationPanelMenuItem.isSelected();
3268 viewport.setShowAnnotation(setVisible);
3269 this.showAllSeqAnnotations.setEnabled(setVisible);
3270 this.hideAllSeqAnnotations.setEnabled(setVisible);
3271 this.showAllAlAnnotations.setEnabled(setVisible);
3272 this.hideAllAlAnnotations.setEnabled(setVisible);
3273 alignPanel.updateLayout();
3277 public void alignmentProperties()
3279 JEditorPane editPane = new JEditorPane("text/html", "");
3280 editPane.setEditable(false);
3281 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3283 editPane.setText(MessageManager.formatMessage("label.html_content",
3284 new Object[] { contents.toString() }));
3285 JInternalFrame frame = new JInternalFrame();
3286 frame.getContentPane().add(new JScrollPane(editPane));
3288 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3289 "label.alignment_properties", new Object[] { getTitle() }),
3300 public void overviewMenuItem_actionPerformed(ActionEvent e)
3302 if (alignPanel.overviewPanel != null)
3307 JInternalFrame frame = new JInternalFrame();
3308 OverviewPanel overview = new OverviewPanel(alignPanel);
3309 frame.setContentPane(overview);
3310 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3311 "label.overview_params", new Object[] { this.getTitle() }),
3312 frame.getWidth(), frame.getHeight());
3314 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3315 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3318 public void internalFrameClosed(
3319 javax.swing.event.InternalFrameEvent evt)
3321 alignPanel.setOverviewPanel(null);
3325 alignPanel.setOverviewPanel(overview);
3329 public void textColour_actionPerformed()
3331 new TextColourChooser().chooseColour(alignPanel, null);
3341 protected void noColourmenuItem_actionPerformed()
3353 public void clustalColour_actionPerformed()
3355 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3356 viewport.getHiddenRepSequences()));
3366 public void zappoColour_actionPerformed()
3368 changeColour(new ZappoColourScheme());
3378 public void taylorColour_actionPerformed()
3380 changeColour(new TaylorColourScheme());
3390 public void hydrophobicityColour_actionPerformed()
3392 changeColour(new HydrophobicColourScheme());
3402 public void helixColour_actionPerformed()
3404 changeColour(new HelixColourScheme());
3414 public void strandColour_actionPerformed()
3416 changeColour(new StrandColourScheme());
3426 public void turnColour_actionPerformed()
3428 changeColour(new TurnColourScheme());
3438 public void buriedColour_actionPerformed()
3440 changeColour(new BuriedColourScheme());
3450 public void nucleotideColour_actionPerformed()
3452 changeColour(new NucleotideColourScheme());
3456 public void purinePyrimidineColour_actionPerformed()
3458 changeColour(new PurinePyrimidineColourScheme());
3462 * public void covariationColour_actionPerformed() {
3464 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3468 public void annotationColour_actionPerformed()
3470 new AnnotationColourChooser(viewport, alignPanel);
3474 public void annotationColumn_actionPerformed(ActionEvent e)
3476 new AnnotationColumnChooser(viewport, alignPanel);
3480 public void rnahelicesColour_actionPerformed()
3482 new RNAHelicesColourChooser(viewport, alignPanel);
3490 protected void applyToAllGroups_actionPerformed()
3492 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3502 public void changeColour(ColourSchemeI cs)
3504 // TODO: pull up to controller method
3507 setColourSelected(cs.getSchemeName());
3508 // Make sure viewport is up to date w.r.t. any sliders
3509 if (viewport.getAbovePIDThreshold())
3511 int threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3513 viewport.setThreshold(threshold);
3516 if (viewport.getConservationSelected())
3518 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3521 if (cs instanceof TCoffeeColourScheme)
3523 tcoffeeColour.setEnabled(true);
3524 tcoffeeColour.setSelected(true);
3528 viewport.setGlobalColourScheme(cs);
3530 alignPanel.paintAlignment(true);
3540 protected void modifyPID_actionPerformed()
3542 if (viewport.getAbovePIDThreshold()
3543 && viewport.getGlobalColourScheme() != null)
3545 SliderPanel.setPIDSliderSource(alignPanel,
3546 viewport.getGlobalColourScheme(), "Background");
3547 SliderPanel.showPIDSlider();
3558 protected void modifyConservation_actionPerformed()
3560 if (viewport.getConservationSelected()
3561 && viewport.getGlobalColourScheme() != null)
3563 SliderPanel.setConservationSlider(alignPanel,
3564 viewport.getGlobalColourScheme(), "Background");
3565 SliderPanel.showConservationSlider();
3576 protected void conservationMenuItem_actionPerformed()
3578 viewport.setConservationSelected(conservationMenuItem.isSelected());
3580 viewport.setAbovePIDThreshold(false);
3581 abovePIDThreshold.setSelected(false);
3583 changeColour(viewport.getGlobalColourScheme());
3585 modifyConservation_actionPerformed();
3595 public void abovePIDThreshold_actionPerformed()
3597 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3599 conservationMenuItem.setSelected(false);
3600 viewport.setConservationSelected(false);
3602 changeColour(viewport.getGlobalColourScheme());
3604 modifyPID_actionPerformed();
3608 * Action on the user selecting either a named user-defined colour from the
3609 * colour menu, or the option "User Defined" to create or load a new colour
3615 public void userDefinedColour_actionPerformed(ActionEvent e)
3617 if (e.getActionCommand().equals(
3618 MessageManager.getString("action.user_defined")))
3621 * User Defined... option; open panel to
3622 * load / create / apply / save user defined colour
3624 new UserDefinedColours(alignPanel, null);
3629 * User chose an existing user defined colour
3631 UserColourScheme udc = UserDefinedColours
3632 .getUserColourSchemes().get(e.getActionCommand());
3644 public void PIDColour_actionPerformed()
3646 changeColour(new PIDColourScheme());
3656 public void BLOSUM62Colour_actionPerformed()
3658 changeColour(new Blosum62ColourScheme());
3668 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3670 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3671 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3672 .getAlignment().getSequenceAt(0), null);
3673 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3674 viewport.getAlignment()));
3675 alignPanel.paintAlignment(true);
3685 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3687 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3688 AlignmentSorter.sortByID(viewport.getAlignment());
3689 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3690 viewport.getAlignment()));
3691 alignPanel.paintAlignment(true);
3701 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3703 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3704 AlignmentSorter.sortByLength(viewport.getAlignment());
3705 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3706 viewport.getAlignment()));
3707 alignPanel.paintAlignment(true);
3717 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3719 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3720 AlignmentSorter.sortByGroup(viewport.getAlignment());
3721 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3722 viewport.getAlignment()));
3724 alignPanel.paintAlignment(true);
3734 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3736 new RedundancyPanel(alignPanel, this);
3746 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3748 if ((viewport.getSelectionGroup() == null)
3749 || (viewport.getSelectionGroup().getSize() < 2))
3751 JvOptionPane.showInternalMessageDialog(this, MessageManager
3752 .getString("label.you_must_select_least_two_sequences"),
3753 MessageManager.getString("label.invalid_selection"),
3754 JvOptionPane.WARNING_MESSAGE);
3758 JInternalFrame frame = new JInternalFrame();
3759 frame.setContentPane(new PairwiseAlignPanel(viewport));
3760 Desktop.addInternalFrame(frame,
3761 MessageManager.getString("action.pairwise_alignment"), 600,
3773 public void PCAMenuItem_actionPerformed(ActionEvent e)
3775 if (((viewport.getSelectionGroup() != null)
3776 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3777 .getSelectionGroup().getSize() > 0))
3778 || (viewport.getAlignment().getHeight() < 4))
3781 .showInternalMessageDialog(
3784 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3786 .getString("label.sequence_selection_insufficient"),
3787 JvOptionPane.WARNING_MESSAGE);
3792 new PCAPanel(alignPanel);
3796 public void autoCalculate_actionPerformed(ActionEvent e)
3798 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3799 if (viewport.autoCalculateConsensus)
3801 viewport.firePropertyChange("alignment", null, viewport
3802 .getAlignment().getSequences());
3807 public void sortByTreeOption_actionPerformed(ActionEvent e)
3809 viewport.sortByTree = sortByTree.isSelected();
3813 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3815 viewport.followSelection = listenToViewSelections.isSelected();
3825 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3827 newTreePanel("AV", "PID", "Average distance tree using PID");
3837 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3839 newTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3849 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3851 newTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3861 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3863 newTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3876 void newTreePanel(String type, String pwType, String title)
3880 if (viewport.getSelectionGroup() != null
3881 && viewport.getSelectionGroup().getSize() > 0)
3883 if (viewport.getSelectionGroup().getSize() < 3)
3889 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3891 .getString("label.not_enough_sequences"),
3892 JvOptionPane.WARNING_MESSAGE);
3896 SequenceGroup sg = viewport.getSelectionGroup();
3898 /* Decide if the selection is a column region */
3899 for (SequenceI _s : sg.getSequences())
3901 if (_s.getLength() < sg.getEndRes())
3907 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3909 .getString("label.sequences_selection_not_aligned"),
3910 JvOptionPane.WARNING_MESSAGE);
3916 title = title + " on region";
3917 tp = new TreePanel(alignPanel, type, pwType);
3921 // are the visible sequences aligned?
3922 if (!viewport.getAlignment().isAligned(false))
3928 .getString("label.sequences_must_be_aligned_before_creating_tree"),
3930 .getString("label.sequences_not_aligned"),
3931 JvOptionPane.WARNING_MESSAGE);
3936 if (viewport.getAlignment().getHeight() < 2)
3941 tp = new TreePanel(alignPanel, type, pwType);
3946 if (viewport.viewName != null)
3948 title += viewport.viewName + " of ";
3951 title += this.title;
3953 Desktop.addInternalFrame(tp, title, 600, 500);
3964 public void addSortByOrderMenuItem(String title,
3965 final AlignmentOrder order)
3967 final JMenuItem item = new JMenuItem(MessageManager.formatMessage(
3968 "action.by_title_param", new Object[] { title }));
3970 item.addActionListener(new java.awt.event.ActionListener()
3973 public void actionPerformed(ActionEvent e)
3975 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3977 // TODO: JBPNote - have to map order entries to curent SequenceI
3979 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3981 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
3984 alignPanel.paintAlignment(true);
3990 * Add a new sort by annotation score menu item
3993 * the menu to add the option to
3995 * the label used to retrieve scores for each sequence on the
3998 public void addSortByAnnotScoreMenuItem(JMenu sort,
3999 final String scoreLabel)
4001 final JMenuItem item = new JMenuItem(scoreLabel);
4003 item.addActionListener(new java.awt.event.ActionListener()
4006 public void actionPerformed(ActionEvent e)
4008 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4009 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4010 viewport.getAlignment());// ,viewport.getSelectionGroup());
4011 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4012 viewport.getAlignment()));
4013 alignPanel.paintAlignment(true);
4019 * last hash for alignment's annotation array - used to minimise cost of
4022 protected int _annotationScoreVectorHash;
4025 * search the alignment and rebuild the sort by annotation score submenu the
4026 * last alignment annotation vector hash is stored to minimize cost of
4027 * rebuilding in subsequence calls.
4031 public void buildSortByAnnotationScoresMenu()
4033 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4038 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4040 sortByAnnotScore.removeAll();
4041 // almost certainly a quicker way to do this - but we keep it simple
4042 Hashtable scoreSorts = new Hashtable();
4043 AlignmentAnnotation aann[];
4044 for (SequenceI sqa : viewport.getAlignment().getSequences())
4046 aann = sqa.getAnnotation();
4047 for (int i = 0; aann != null && i < aann.length; i++)
4049 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4051 scoreSorts.put(aann[i].label, aann[i].label);
4055 Enumeration labels = scoreSorts.keys();
4056 while (labels.hasMoreElements())
4058 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4059 (String) labels.nextElement());
4061 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4064 _annotationScoreVectorHash = viewport.getAlignment()
4065 .getAlignmentAnnotation().hashCode();
4070 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4071 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4072 * call. Listeners are added to remove the menu item when the treePanel is
4073 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4077 * Displayed tree window.
4079 * SortBy menu item title.
4082 public void buildTreeMenu()
4084 calculateTree.removeAll();
4085 // build the calculate menu
4087 for (final String type : new String[] { "NJ", "AV" })
4089 String treecalcnm = MessageManager.getString("label.tree_calc_"
4090 + type.toLowerCase());
4091 for (final String pwtype : ResidueProperties.scoreMatrices.keySet())
4093 JMenuItem tm = new JMenuItem();
4094 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4095 if (sm.isDNA() == viewport.getAlignment().isNucleotide()
4096 || sm.isProtein() == !viewport.getAlignment()
4099 String smn = MessageManager.getStringOrReturn(
4100 "label.score_model_", sm.getName());
4101 final String title = MessageManager.formatMessage(
4102 "label.treecalc_title", treecalcnm, smn);
4103 tm.setText(title);//
4104 tm.addActionListener(new java.awt.event.ActionListener()
4107 public void actionPerformed(ActionEvent e)
4109 newTreePanel(type, pwtype, title);
4112 calculateTree.add(tm);
4117 sortByTreeMenu.removeAll();
4119 List<Component> comps = PaintRefresher.components.get(viewport
4120 .getSequenceSetId());
4121 List<TreePanel> treePanels = new ArrayList<TreePanel>();
4122 for (Component comp : comps)
4124 if (comp instanceof TreePanel)
4126 treePanels.add((TreePanel) comp);
4130 if (treePanels.size() < 1)
4132 sortByTreeMenu.setVisible(false);
4136 sortByTreeMenu.setVisible(true);
4138 for (final TreePanel tp : treePanels)
4140 final JMenuItem item = new JMenuItem(tp.getTitle());
4141 item.addActionListener(new java.awt.event.ActionListener()
4144 public void actionPerformed(ActionEvent e)
4146 tp.sortByTree_actionPerformed();
4147 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4152 sortByTreeMenu.add(item);
4156 public boolean sortBy(AlignmentOrder alorder, String undoname)
4158 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4159 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4160 if (undoname != null)
4162 addHistoryItem(new OrderCommand(undoname, oldOrder,
4163 viewport.getAlignment()));
4165 alignPanel.paintAlignment(true);
4170 * Work out whether the whole set of sequences or just the selected set will
4171 * be submitted for multiple alignment.
4174 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4176 // Now, check we have enough sequences
4177 AlignmentView msa = null;
4179 if ((viewport.getSelectionGroup() != null)
4180 && (viewport.getSelectionGroup().getSize() > 1))
4182 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4183 // some common interface!
4185 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4186 * SequenceI[sz = seqs.getSize(false)];
4188 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4189 * seqs.getSequenceAt(i); }
4191 msa = viewport.getAlignmentView(true);
4193 else if (viewport.getSelectionGroup() != null
4194 && viewport.getSelectionGroup().getSize() == 1)
4196 int option = JvOptionPane.showConfirmDialog(this,
4197 MessageManager.getString("warn.oneseq_msainput_selection"),
4198 MessageManager.getString("label.invalid_selection"),
4199 JvOptionPane.OK_CANCEL_OPTION);
4200 if (option == JvOptionPane.OK_OPTION)
4202 msa = viewport.getAlignmentView(false);
4207 msa = viewport.getAlignmentView(false);
4213 * Decides what is submitted to a secondary structure prediction service: the
4214 * first sequence in the alignment, or in the current selection, or, if the
4215 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4216 * region or the whole alignment. (where the first sequence in the set is the
4217 * one that the prediction will be for).
4219 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4221 AlignmentView seqs = null;
4223 if ((viewport.getSelectionGroup() != null)
4224 && (viewport.getSelectionGroup().getSize() > 0))
4226 seqs = viewport.getAlignmentView(true);
4230 seqs = viewport.getAlignmentView(false);
4232 // limit sequences - JBPNote in future - could spawn multiple prediction
4234 // TODO: viewport.getAlignment().isAligned is a global state - the local
4235 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4236 if (!viewport.getAlignment().isAligned(false))
4238 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4239 // TODO: if seqs.getSequences().length>1 then should really have warned
4253 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4255 // Pick the tree file
4256 JalviewFileChooser chooser = new JalviewFileChooser(
4257 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4258 chooser.setFileView(new JalviewFileView());
4259 chooser.setDialogTitle(MessageManager
4260 .getString("label.select_newick_like_tree_file"));
4261 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4263 int value = chooser.showOpenDialog(null);
4265 if (value == JalviewFileChooser.APPROVE_OPTION)
4267 String choice = chooser.getSelectedFile().getPath();
4268 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4269 jalview.io.NewickFile fin = null;
4272 fin = new NewickFile(choice, DataSourceType.FILE);
4273 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4274 } catch (Exception ex)
4281 .getString("label.problem_reading_tree_file"),
4282 JvOptionPane.WARNING_MESSAGE);
4283 ex.printStackTrace();
4285 if (fin != null && fin.hasWarningMessage())
4287 JvOptionPane.showMessageDialog(Desktop.desktop, fin
4288 .getWarningMessage(), MessageManager
4289 .getString("label.possible_problem_with_tree_file"),
4290 JvOptionPane.WARNING_MESSAGE);
4296 protected void tcoffeeColorScheme_actionPerformed()
4298 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4301 public TreePanel ShowNewickTree(NewickFile nf, String title)
4303 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4306 public TreePanel ShowNewickTree(NewickFile nf, String title,
4307 AlignmentView input)
4309 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4312 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4313 int h, int x, int y)
4315 return ShowNewickTree(nf, title, null, w, h, x, y);
4319 * Add a treeviewer for the tree extracted from a newick file object to the
4320 * current alignment view
4327 * Associated alignment input data (or null)
4336 * @return TreePanel handle
4338 public TreePanel ShowNewickTree(NewickFile nf, String title,
4339 AlignmentView input, int w, int h, int x, int y)
4341 TreePanel tp = null;
4347 if (nf.getTree() != null)
4349 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4355 tp.setLocation(x, y);
4358 Desktop.addInternalFrame(tp, title, w, h);
4360 } catch (Exception ex)
4362 ex.printStackTrace();
4368 private boolean buildingMenu = false;
4371 * Generates menu items and listener event actions for web service clients
4374 public void BuildWebServiceMenu()
4376 while (buildingMenu)
4380 System.err.println("Waiting for building menu to finish.");
4382 } catch (Exception e)
4386 final AlignFrame me = this;
4387 buildingMenu = true;
4388 new Thread(new Runnable()
4393 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4396 // System.err.println("Building ws menu again "
4397 // + Thread.currentThread());
4398 // TODO: add support for context dependent disabling of services based
4400 // alignment and current selection
4401 // TODO: add additional serviceHandle parameter to specify abstract
4403 // class independently of AbstractName
4404 // TODO: add in rediscovery GUI function to restart discoverer
4405 // TODO: group services by location as well as function and/or
4407 // object broker mechanism.
4408 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4409 final IProgressIndicator af = me;
4412 * do not i18n these strings - they are hard-coded in class
4413 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4414 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4416 final JMenu msawsmenu = new JMenu("Alignment");
4417 final JMenu secstrmenu = new JMenu(
4418 "Secondary Structure Prediction");
4419 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4420 final JMenu analymenu = new JMenu("Analysis");
4421 final JMenu dismenu = new JMenu("Protein Disorder");
4422 // JAL-940 - only show secondary structure prediction services from
4423 // the legacy server
4424 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4426 Discoverer.services != null && (Discoverer.services.size() > 0))
4428 // TODO: refactor to allow list of AbstractName/Handler bindings to
4430 // stored or retrieved from elsewhere
4431 // No MSAWS used any more:
4432 // Vector msaws = null; // (Vector)
4433 // Discoverer.services.get("MsaWS");
4434 Vector secstrpr = (Vector) Discoverer.services
4436 if (secstrpr != null)
4438 // Add any secondary structure prediction services
4439 for (int i = 0, j = secstrpr.size(); i < j; i++)
4441 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4443 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4444 .getServiceClient(sh);
4445 int p = secstrmenu.getItemCount();
4446 impl.attachWSMenuEntry(secstrmenu, me);
4447 int q = secstrmenu.getItemCount();
4448 for (int litm = p; litm < q; litm++)
4450 legacyItems.add(secstrmenu.getItem(litm));
4456 // Add all submenus in the order they should appear on the web
4458 wsmenu.add(msawsmenu);
4459 wsmenu.add(secstrmenu);
4460 wsmenu.add(dismenu);
4461 wsmenu.add(analymenu);
4462 // No search services yet
4463 // wsmenu.add(seqsrchmenu);
4465 javax.swing.SwingUtilities.invokeLater(new Runnable()
4472 webService.removeAll();
4473 // first, add discovered services onto the webservices menu
4474 if (wsmenu.size() > 0)
4476 for (int i = 0, j = wsmenu.size(); i < j; i++)
4478 webService.add(wsmenu.get(i));
4483 webService.add(me.webServiceNoServices);
4485 // TODO: move into separate menu builder class.
4486 boolean new_sspred = false;
4487 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4489 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4490 if (jws2servs != null)
4492 if (jws2servs.hasServices())
4494 jws2servs.attachWSMenuEntry(webService, me);
4495 for (Jws2Instance sv : jws2servs.getServices())
4497 if (sv.description.toLowerCase().contains("jpred"))
4499 for (JMenuItem jmi : legacyItems)
4501 jmi.setVisible(false);
4507 if (jws2servs.isRunning())
4509 JMenuItem tm = new JMenuItem(
4510 "Still discovering JABA Services");
4511 tm.setEnabled(false);
4516 build_urlServiceMenu(me.webService);
4517 build_fetchdbmenu(webService);
4518 for (JMenu item : wsmenu)
4520 if (item.getItemCount() == 0)
4522 item.setEnabled(false);
4526 item.setEnabled(true);
4529 } catch (Exception e)
4532 .debug("Exception during web service menu building process.",
4537 } catch (Exception e)
4540 buildingMenu = false;
4547 * construct any groupURL type service menu entries.
4551 private void build_urlServiceMenu(JMenu webService)
4553 // TODO: remove this code when 2.7 is released
4554 // DEBUG - alignmentView
4556 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4557 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4559 * @Override public void actionPerformed(ActionEvent e) {
4560 * jalview.datamodel.AlignmentView
4561 * .testSelectionViews(af.viewport.getAlignment(),
4562 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4564 * }); webService.add(testAlView);
4566 // TODO: refactor to RestClient discoverer and merge menu entries for
4567 // rest-style services with other types of analysis/calculation service
4568 // SHmmr test client - still being implemented.
4569 // DEBUG - alignmentView
4571 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4574 client.attachWSMenuEntry(
4575 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4581 * Searches the alignment sequences for xRefs and builds the Show
4582 * Cross-References menu (formerly called Show Products), with database
4583 * sources for which cross-references are found (protein sources for a
4584 * nucleotide alignment and vice versa)
4586 * @return true if Show Cross-references menu should be enabled
4588 public boolean canShowProducts()
4590 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4591 AlignmentI dataset = viewport.getAlignment().getDataset();
4593 showProducts.removeAll();
4594 final boolean dna = viewport.getAlignment().isNucleotide();
4596 if (seqs == null || seqs.length == 0)
4598 // nothing to see here.
4602 boolean showp = false;
4605 List<String> ptypes = new CrossRef(seqs, dataset)
4606 .findXrefSourcesForSequences(dna);
4608 for (final String source : ptypes)
4611 final AlignFrame af = this;
4612 JMenuItem xtype = new JMenuItem(source);
4613 xtype.addActionListener(new ActionListener()
4616 public void actionPerformed(ActionEvent e)
4618 showProductsFor(af.viewport.getSequenceSelection(), dna, source);
4621 showProducts.add(xtype);
4623 showProducts.setVisible(showp);
4624 showProducts.setEnabled(showp);
4625 } catch (Exception e)
4628 .warn("canShowProducts threw an exception - please report to help@jalview.org",
4636 * Finds and displays cross-references for the selected sequences (protein
4637 * products for nucleotide sequences, dna coding sequences for peptides).
4640 * the sequences to show cross-references for
4642 * true if from a nucleotide alignment (so showing proteins)
4644 * the database to show cross-references for
4646 protected void showProductsFor(final SequenceI[] sel,
4647 final boolean _odna, final String source)
4649 new Thread(CrossRefAction.showProductsFor(sel, _odna, source, this))
4654 * Construct and display a new frame containing the translation of this
4655 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4658 public void showTranslation_actionPerformed(ActionEvent e)
4660 AlignmentI al = null;
4663 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4665 al = dna.translateCdna();
4666 } catch (Exception ex)
4668 jalview.bin.Cache.log.error(
4669 "Exception during translation. Please report this !", ex);
4670 final String msg = MessageManager
4671 .getString("label.error_when_translating_sequences_submit_bug_report");
4672 final String errorTitle = MessageManager
4673 .getString("label.implementation_error")
4674 + MessageManager.getString("label.translation_failed");
4675 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4676 JvOptionPane.ERROR_MESSAGE);
4679 if (al == null || al.getHeight() == 0)
4681 final String msg = MessageManager
4682 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4683 final String errorTitle = MessageManager
4684 .getString("label.translation_failed");
4685 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4686 JvOptionPane.WARNING_MESSAGE);
4690 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4691 af.setFileFormat(this.currentFileFormat);
4692 final String newTitle = MessageManager.formatMessage(
4693 "label.translation_of_params",
4694 new Object[] { this.getTitle() });
4695 af.setTitle(newTitle);
4696 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4698 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4699 viewport.openSplitFrame(af, new Alignment(seqs));
4703 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4710 * Set the file format
4714 public void setFileFormat(FileFormatI format)
4716 this.currentFileFormat = format;
4720 * Try to load a features file onto the alignment.
4723 * contents or path to retrieve file
4725 * access mode of file (see jalview.io.AlignFile)
4726 * @return true if features file was parsed correctly.
4728 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4730 return avc.parseFeaturesFile(file, sourceType,
4731 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4736 public void refreshFeatureUI(boolean enableIfNecessary)
4738 // note - currently this is only still here rather than in the controller
4739 // because of the featureSettings hard reference that is yet to be
4741 if (enableIfNecessary)
4743 viewport.setShowSequenceFeatures(true);
4744 showSeqFeatures.setSelected(true);
4750 public void dragEnter(DropTargetDragEvent evt)
4755 public void dragExit(DropTargetEvent evt)
4760 public void dragOver(DropTargetDragEvent evt)
4765 public void dropActionChanged(DropTargetDragEvent evt)
4770 public void drop(DropTargetDropEvent evt)
4772 // JAL-1552 - acceptDrop required before getTransferable call for
4773 // Java's Transferable for native dnd
4774 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4775 Transferable t = evt.getTransferable();
4776 List<String> files = new ArrayList<String>();
4777 List<DataSourceType> protocols = new ArrayList<DataSourceType>();
4781 Desktop.transferFromDropTarget(files, protocols, evt, t);
4782 } catch (Exception e)
4784 e.printStackTrace();
4790 // check to see if any of these files have names matching sequences in
4792 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4793 .getAlignment().getSequencesArray());
4795 * Object[] { String,SequenceI}
4797 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
4798 ArrayList<String> filesnotmatched = new ArrayList<String>();
4799 for (int i = 0; i < files.size(); i++)
4801 String file = files.get(i).toString();
4803 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4804 if (protocol == DataSourceType.FILE)
4806 File fl = new File(file);
4807 pdbfn = fl.getName();
4809 else if (protocol == DataSourceType.URL)
4811 URL url = new URL(file);
4812 pdbfn = url.getFile();
4814 if (pdbfn.length() > 0)
4816 // attempt to find a match in the alignment
4817 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4818 int l = 0, c = pdbfn.indexOf(".");
4819 while (mtch == null && c != -1)
4824 } while ((c = pdbfn.indexOf(".", l)) > l);
4827 pdbfn = pdbfn.substring(0, l);
4829 mtch = idm.findAllIdMatches(pdbfn);
4833 FileFormatI type = null;
4836 type = new IdentifyFile().identify(file, protocol);
4837 } catch (Exception ex)
4841 if (type != null && type.isStructureFile())
4843 filesmatched.add(new Object[] { file, protocol, mtch });
4847 // File wasn't named like one of the sequences or wasn't a PDB file.
4848 filesnotmatched.add(file);
4852 if (filesmatched.size() > 0)
4854 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4860 "label.automatically_associate_structure_files_with_sequences_same_name",
4861 new Object[] { Integer
4867 .getString("label.automatically_associate_structure_files_by_name"),
4868 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION)
4871 for (Object[] fm : filesmatched)
4873 // try and associate
4874 // TODO: may want to set a standard ID naming formalism for
4875 // associating PDB files which have no IDs.
4876 for (SequenceI toassoc : (SequenceI[]) fm[2])
4878 PDBEntry pe = new AssociatePdbFileWithSeq()
4879 .associatePdbWithSeq((String) fm[0],
4880 (DataSourceType) fm[1], toassoc, false,
4884 System.err.println("Associated file : "
4885 + ((String) fm[0]) + " with "
4886 + toassoc.getDisplayId(true));
4890 alignPanel.paintAlignment(true);
4894 if (filesnotmatched.size() > 0)
4897 && (Cache.getDefault(
4898 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JvOptionPane
4904 "label.ignore_unmatched_dropped_files_info",
4905 new Object[] { Integer
4912 .getString("label.ignore_unmatched_dropped_files"),
4913 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4917 for (String fn : filesnotmatched)
4919 loadJalviewDataFile(fn, null, null, null);
4923 } catch (Exception ex)
4925 ex.printStackTrace();
4931 * Attempt to load a "dropped" file or URL string: First by testing whether
4932 * it's an Annotation file, then a JNet file, and finally a features file. If
4933 * all are false then the user may have dropped an alignment file onto this
4937 * either a filename or a URL string.
4939 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4940 FileFormatI format, SequenceI assocSeq)
4944 if (sourceType == null)
4946 sourceType = FormatAdapter.checkProtocol(file);
4948 // if the file isn't identified, or not positively identified as some
4949 // other filetype (PFAM is default unidentified alignment file type) then
4950 // try to parse as annotation.
4951 boolean isAnnotation = (format == null || FileFormat.Pfam
4952 .equals(format)) ? new AnnotationFile()
4953 .annotateAlignmentView(viewport, file, sourceType) : false;
4957 // first see if its a T-COFFEE score file
4958 TCoffeeScoreFile tcf = null;
4961 tcf = new TCoffeeScoreFile(file, sourceType);
4964 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4966 tcoffeeColour.setEnabled(true);
4967 tcoffeeColour.setSelected(true);
4968 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
4969 isAnnotation = true;
4971 .setText(MessageManager
4972 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
4976 // some problem - if no warning its probable that the ID matching
4977 // process didn't work
4981 tcf.getWarningMessage() == null ? MessageManager
4982 .getString("label.check_file_matches_sequence_ids_alignment")
4983 : tcf.getWarningMessage(),
4985 .getString("label.problem_reading_tcoffee_score_file"),
4986 JvOptionPane.WARNING_MESSAGE);
4993 } catch (Exception x)
4996 .debug("Exception when processing data source as T-COFFEE score file",
5002 // try to see if its a JNet 'concise' style annotation file *before*
5004 // try to parse it as a features file
5007 format = new IdentifyFile().identify(file, sourceType);
5009 if (FileFormat.Jnet.equals(format))
5011 JPredFile predictions = new JPredFile(
5013 new JnetAnnotationMaker();
5014 JnetAnnotationMaker.add_annotation(predictions,
5015 viewport.getAlignment(), 0, false);
5016 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
5017 viewport.getAlignment().setSeqrep(repseq);
5018 ColumnSelection cs = new ColumnSelection();
5019 cs.hideInsertionsFor(repseq);
5020 viewport.setColumnSelection(cs);
5021 isAnnotation = true;
5023 // else if (IdentifyFile.FeaturesFile.equals(format))
5024 else if (FileFormat.Features.equals(format))
5026 if (parseFeaturesFile(file, sourceType))
5028 alignPanel.paintAlignment(true);
5033 new FileLoader().LoadFile(viewport, file, sourceType, format);
5040 alignPanel.adjustAnnotationHeight();
5041 viewport.updateSequenceIdColours();
5042 buildSortByAnnotationScoresMenu();
5043 alignPanel.paintAlignment(true);
5045 } catch (Exception ex)
5047 ex.printStackTrace();
5048 } catch (OutOfMemoryError oom)
5053 } catch (Exception x)
5058 + (sourceType != null ? (sourceType == DataSourceType.PASTE ? "from clipboard."
5059 : "using " + sourceType + " from " + file)
5061 + (format != null ? "(parsing as '" + format
5062 + "' file)" : ""), oom, Desktop.desktop);
5067 * Method invoked by the ChangeListener on the tabbed pane, in other words
5068 * when a different tabbed pane is selected by the user or programmatically.
5071 public void tabSelectionChanged(int index)
5075 alignPanel = alignPanels.get(index);
5076 viewport = alignPanel.av;
5077 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5078 setMenusFromViewport(viewport);
5082 * If there is a frame linked to this one in a SplitPane, switch it to the
5083 * same view tab index. No infinite recursion of calls should happen, since
5084 * tabSelectionChanged() should not get invoked on setting the selected
5085 * index to an unchanged value. Guard against setting an invalid index
5086 * before the new view peer tab has been created.
5088 final AlignViewportI peer = viewport.getCodingComplement();
5091 AlignFrame linkedAlignFrame = ((AlignViewport) peer).getAlignPanel().alignFrame;
5092 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5094 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5100 * On right mouse click on view tab, prompt for and set new view name.
5103 public void tabbedPane_mousePressed(MouseEvent e)
5105 if (e.isPopupTrigger())
5107 String msg = MessageManager.getString("label.enter_view_name");
5108 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
5109 JvOptionPane.QUESTION_MESSAGE);
5113 viewport.viewName = reply;
5114 // TODO warn if reply is in getExistingViewNames()?
5115 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5120 public AlignViewport getCurrentView()
5126 * Open the dialog for regex description parsing.
5129 protected void extractScores_actionPerformed(ActionEvent e)
5131 ParseProperties pp = new jalview.analysis.ParseProperties(
5132 viewport.getAlignment());
5133 // TODO: verify regex and introduce GUI dialog for version 2.5
5134 // if (pp.getScoresFromDescription("col", "score column ",
5135 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5137 if (pp.getScoresFromDescription("description column",
5138 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5140 buildSortByAnnotationScoresMenu();
5148 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5152 protected void showDbRefs_actionPerformed(ActionEvent e)
5154 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5160 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5164 protected void showNpFeats_actionPerformed(ActionEvent e)
5166 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5170 * find the viewport amongst the tabs in this alignment frame and close that
5175 public boolean closeView(AlignViewportI av)
5179 this.closeMenuItem_actionPerformed(false);
5182 Component[] comp = tabbedPane.getComponents();
5183 for (int i = 0; comp != null && i < comp.length; i++)
5185 if (comp[i] instanceof AlignmentPanel)
5187 if (((AlignmentPanel) comp[i]).av == av)
5190 closeView((AlignmentPanel) comp[i]);
5198 protected void build_fetchdbmenu(JMenu webService)
5200 // Temporary hack - DBRef Fetcher always top level ws entry.
5201 // TODO We probably want to store a sequence database checklist in
5202 // preferences and have checkboxes.. rather than individual sources selected
5204 final JMenu rfetch = new JMenu(
5205 MessageManager.getString("action.fetch_db_references"));
5206 rfetch.setToolTipText(MessageManager
5207 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5208 webService.add(rfetch);
5210 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5211 MessageManager.getString("option.trim_retrieved_seqs"));
5212 trimrs.setToolTipText(MessageManager
5213 .getString("label.trim_retrieved_sequences"));
5214 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5215 trimrs.addActionListener(new ActionListener()
5218 public void actionPerformed(ActionEvent e)
5220 trimrs.setSelected(trimrs.isSelected());
5221 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5222 Boolean.valueOf(trimrs.isSelected()).toString());
5226 JMenuItem fetchr = new JMenuItem(
5227 MessageManager.getString("label.standard_databases"));
5228 fetchr.setToolTipText(MessageManager
5229 .getString("label.fetch_embl_uniprot"));
5230 fetchr.addActionListener(new ActionListener()
5234 public void actionPerformed(ActionEvent e)
5236 new Thread(new Runnable()
5241 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5242 .getAlignment().isNucleotide();
5243 DBRefFetcher dbRefFetcher = new DBRefFetcher(alignPanel.av
5244 .getSequenceSelection(), alignPanel.alignFrame, null,
5245 alignPanel.alignFrame.featureSettings, isNucleotide);
5246 dbRefFetcher.addListener(new FetchFinishedListenerI()
5249 public void finished()
5251 AlignFrame.this.setMenusForViewport();
5254 dbRefFetcher.fetchDBRefs(false);
5262 final AlignFrame me = this;
5263 new Thread(new Runnable()
5268 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5269 .getSequenceFetcherSingleton(me);
5270 javax.swing.SwingUtilities.invokeLater(new Runnable()
5275 String[] dbclasses = sf.getOrderedSupportedSources();
5276 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5277 // jalview.util.QuickSort.sort(otherdb, otherdb);
5278 List<DbSourceProxy> otherdb;
5279 JMenu dfetch = new JMenu();
5280 JMenu ifetch = new JMenu();
5281 JMenuItem fetchr = null;
5282 int comp = 0, icomp = 0, mcomp = 15;
5283 String mname = null;
5285 for (String dbclass : dbclasses)
5287 otherdb = sf.getSourceProxy(dbclass);
5288 // add a single entry for this class, or submenu allowing 'fetch
5290 if (otherdb == null || otherdb.size() < 1)
5294 // List<DbSourceProxy> dbs=otherdb;
5295 // otherdb=new ArrayList<DbSourceProxy>();
5296 // for (DbSourceProxy db:dbs)
5298 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5302 mname = "From " + dbclass;
5304 if (otherdb.size() == 1)
5306 final DbSourceProxy[] dassource = otherdb
5307 .toArray(new DbSourceProxy[0]);
5308 DbSourceProxy src = otherdb.get(0);
5309 fetchr = new JMenuItem(src.getDbSource());
5310 fetchr.addActionListener(new ActionListener()
5314 public void actionPerformed(ActionEvent e)
5316 new Thread(new Runnable()
5322 boolean isNucleotide = alignPanel.alignFrame
5323 .getViewport().getAlignment()
5325 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5326 alignPanel.av.getSequenceSelection(),
5327 alignPanel.alignFrame, dassource,
5328 alignPanel.alignFrame.featureSettings,
5331 .addListener(new FetchFinishedListenerI()
5334 public void finished()
5336 AlignFrame.this.setMenusForViewport();
5339 dbRefFetcher.fetchDBRefs(false);
5345 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5346 MessageManager.formatMessage(
5347 "label.fetch_retrieve_from",
5348 new Object[] { src.getDbName() })));
5354 final DbSourceProxy[] dassource = otherdb
5355 .toArray(new DbSourceProxy[0]);
5357 DbSourceProxy src = otherdb.get(0);
5358 fetchr = new JMenuItem(MessageManager.formatMessage(
5359 "label.fetch_all_param",
5360 new Object[] { src.getDbSource() }));
5361 fetchr.addActionListener(new ActionListener()
5364 public void actionPerformed(ActionEvent e)
5366 new Thread(new Runnable()
5372 boolean isNucleotide = alignPanel.alignFrame
5373 .getViewport().getAlignment()
5375 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5376 alignPanel.av.getSequenceSelection(),
5377 alignPanel.alignFrame, dassource,
5378 alignPanel.alignFrame.featureSettings,
5381 .addListener(new FetchFinishedListenerI()
5384 public void finished()
5386 AlignFrame.this.setMenusForViewport();
5389 dbRefFetcher.fetchDBRefs(false);
5395 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5396 MessageManager.formatMessage(
5397 "label.fetch_retrieve_from_all_sources",
5399 Integer.valueOf(otherdb.size())
5400 .toString(), src.getDbSource(),
5401 src.getDbName() })));
5404 // and then build the rest of the individual menus
5405 ifetch = new JMenu(MessageManager.formatMessage(
5406 "label.source_from_db_source",
5407 new Object[] { src.getDbSource() }));
5409 String imname = null;
5411 for (DbSourceProxy sproxy : otherdb)
5413 String dbname = sproxy.getDbName();
5414 String sname = dbname.length() > 5 ? dbname.substring(0,
5415 5) + "..." : dbname;
5416 String msname = dbname.length() > 10 ? dbname.substring(
5417 0, 10) + "..." : dbname;
5420 imname = MessageManager.formatMessage(
5421 "label.from_msname", new Object[] { sname });
5423 fetchr = new JMenuItem(msname);
5424 final DbSourceProxy[] dassrc = { sproxy };
5425 fetchr.addActionListener(new ActionListener()
5429 public void actionPerformed(ActionEvent e)
5431 new Thread(new Runnable()
5437 boolean isNucleotide = alignPanel.alignFrame
5438 .getViewport().getAlignment()
5440 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5441 alignPanel.av.getSequenceSelection(),
5442 alignPanel.alignFrame, dassrc,
5443 alignPanel.alignFrame.featureSettings,
5446 .addListener(new FetchFinishedListenerI()
5449 public void finished()
5451 AlignFrame.this.setMenusForViewport();
5454 dbRefFetcher.fetchDBRefs(false);
5460 fetchr.setToolTipText("<html>"
5461 + MessageManager.formatMessage(
5462 "label.fetch_retrieve_from", new Object[]
5466 if (++icomp >= mcomp || i == (otherdb.size()))
5468 ifetch.setText(MessageManager.formatMessage(
5469 "label.source_to_target", imname, sname));
5471 ifetch = new JMenu();
5479 if (comp >= mcomp || dbi >= (dbclasses.length))
5481 dfetch.setText(MessageManager.formatMessage(
5482 "label.source_to_target", mname, dbclass));
5484 dfetch = new JMenu();
5497 * Left justify the whole alignment.
5500 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5502 AlignmentI al = viewport.getAlignment();
5504 viewport.firePropertyChange("alignment", null, al);
5508 * Right justify the whole alignment.
5511 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5513 AlignmentI al = viewport.getAlignment();
5515 viewport.firePropertyChange("alignment", null, al);
5519 public void setShowSeqFeatures(boolean b)
5521 showSeqFeatures.setSelected(b);
5522 viewport.setShowSequenceFeatures(b);
5529 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5530 * awt.event.ActionEvent)
5533 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5535 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5536 alignPanel.paintAlignment(true);
5543 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5547 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5549 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5550 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5558 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5559 * .event.ActionEvent)
5562 protected void showGroupConservation_actionPerformed(ActionEvent e)
5564 viewport.setShowGroupConservation(showGroupConservation.getState());
5565 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5572 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5573 * .event.ActionEvent)
5576 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5578 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5579 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5586 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5587 * .event.ActionEvent)
5590 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5592 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5593 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5597 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5599 showSequenceLogo.setState(true);
5600 viewport.setShowSequenceLogo(true);
5601 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5602 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5606 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5608 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5615 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5616 * .event.ActionEvent)
5619 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5621 if (avc.makeGroupsFromSelection())
5623 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5624 alignPanel.updateAnnotation();
5625 alignPanel.paintAlignment(true);
5629 public void clearAlignmentSeqRep()
5631 // TODO refactor alignmentseqrep to controller
5632 if (viewport.getAlignment().hasSeqrep())
5634 viewport.getAlignment().setSeqrep(null);
5635 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5636 alignPanel.updateAnnotation();
5637 alignPanel.paintAlignment(true);
5642 protected void createGroup_actionPerformed(ActionEvent e)
5644 if (avc.createGroup())
5646 alignPanel.alignmentChanged();
5651 protected void unGroup_actionPerformed(ActionEvent e)
5655 alignPanel.alignmentChanged();
5660 * make the given alignmentPanel the currently selected tab
5662 * @param alignmentPanel
5664 public void setDisplayedView(AlignmentPanel alignmentPanel)
5666 if (!viewport.getSequenceSetId().equals(
5667 alignmentPanel.av.getSequenceSetId()))
5671 .getString("error.implementation_error_cannot_show_view_alignment_frame"));
5673 if (tabbedPane != null
5674 && tabbedPane.getTabCount() > 0
5675 && alignPanels.indexOf(alignmentPanel) != tabbedPane
5676 .getSelectedIndex())
5678 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5683 * Action on selection of menu options to Show or Hide annotations.
5686 * @param forSequences
5687 * update sequence-related annotations
5688 * @param forAlignment
5689 * update non-sequence-related annotations
5692 protected void setAnnotationsVisibility(boolean visible,
5693 boolean forSequences, boolean forAlignment)
5695 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5696 .getAlignmentAnnotation();
5701 for (AlignmentAnnotation aa : anns)
5704 * don't display non-positional annotations on an alignment
5706 if (aa.annotations == null)
5710 boolean apply = (aa.sequenceRef == null && forAlignment)
5711 || (aa.sequenceRef != null && forSequences);
5714 aa.visible = visible;
5717 alignPanel.validateAnnotationDimensions(true);
5718 alignPanel.alignmentChanged();
5722 * Store selected annotation sort order for the view and repaint.
5725 protected void sortAnnotations_actionPerformed()
5727 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5729 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5730 alignPanel.paintAlignment(true);
5735 * @return alignment panels in this alignment frame
5737 public List<? extends AlignmentViewPanel> getAlignPanels()
5739 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5743 * Open a new alignment window, with the cDNA associated with this (protein)
5744 * alignment, aligned as is the protein.
5746 protected void viewAsCdna_actionPerformed()
5748 // TODO no longer a menu action - refactor as required
5749 final AlignmentI alignment = getViewport().getAlignment();
5750 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5751 if (mappings == null)
5755 List<SequenceI> cdnaSeqs = new ArrayList<SequenceI>();
5756 for (SequenceI aaSeq : alignment.getSequences())
5758 for (AlignedCodonFrame acf : mappings)
5760 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5764 * There is a cDNA mapping for this protein sequence - add to new
5765 * alignment. It will share the same dataset sequence as other mapped
5766 * cDNA (no new mappings need to be created).
5768 final Sequence newSeq = new Sequence(dnaSeq);
5769 newSeq.setDatasetSequence(dnaSeq);
5770 cdnaSeqs.add(newSeq);
5774 if (cdnaSeqs.size() == 0)
5776 // show a warning dialog no mapped cDNA
5779 AlignmentI cdna = new Alignment(cdnaSeqs.toArray(new SequenceI[cdnaSeqs
5781 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5782 AlignFrame.DEFAULT_HEIGHT);
5783 cdna.alignAs(alignment);
5784 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5786 Desktop.addInternalFrame(alignFrame, newtitle,
5787 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
5791 * Set visibility of dna/protein complement view (available when shown in a
5797 protected void showComplement_actionPerformed(boolean show)
5799 SplitContainerI sf = getSplitViewContainer();
5802 sf.setComplementVisible(this, show);
5807 * Generate the reverse (optionally complemented) of the selected sequences,
5808 * and add them to the alignment
5811 protected void showReverse_actionPerformed(boolean complement)
5813 AlignmentI al = null;
5816 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5817 al = dna.reverseCdna(complement);
5818 viewport.addAlignment(al, "");
5819 addHistoryItem(new EditCommand(
5820 MessageManager.getString("label.add_sequences"),
5821 Action.PASTE, al.getSequencesArray(), 0, al.getWidth(),
5822 viewport.getAlignment()));
5823 } catch (Exception ex)
5825 System.err.println(ex.getMessage());
5831 * Try to run a script in the Groovy console, having first ensured that this
5832 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5833 * be targeted at this alignment.
5836 protected void runGroovy_actionPerformed()
5838 Jalview.setCurrentAlignFrame(this);
5839 groovy.ui.Console console = Desktop.getGroovyConsole();
5840 if (console != null)
5844 console.runScript();
5845 } catch (Exception ex)
5847 System.err.println((ex.toString()));
5849 .showInternalMessageDialog(Desktop.desktop, MessageManager
5850 .getString("label.couldnt_run_groovy_script"),
5852 .getString("label.groovy_support_failed"),
5853 JvOptionPane.ERROR_MESSAGE);
5858 System.err.println("Can't run Groovy script as console not found");
5863 * Hides columns containing (or not containing) a specified feature, provided
5864 * that would not leave all columns hidden
5866 * @param featureType
5867 * @param columnsContaining
5870 public boolean hideFeatureColumns(String featureType,
5871 boolean columnsContaining)
5873 boolean notForHiding = avc.markColumnsContainingFeatures(
5874 columnsContaining, false, false, featureType);
5877 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5878 false, featureType))
5880 getViewport().hideSelectedColumns();
5888 protected void selectHighlightedColumns_actionPerformed(
5889 ActionEvent actionEvent)
5891 // include key modifier check in case user selects from menu
5892 avc.markHighlightedColumns(
5893 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0,
5895 (actionEvent.getModifiers() & (ActionEvent.META_MASK | ActionEvent.CTRL_MASK)) != 0);
5899 class PrintThread extends Thread
5903 public PrintThread(AlignmentPanel ap)
5908 static PageFormat pf;
5913 PrinterJob printJob = PrinterJob.getPrinterJob();
5917 printJob.setPrintable(ap, pf);
5921 printJob.setPrintable(ap);
5924 if (printJob.printDialog())
5929 } catch (Exception PrintException)
5931 PrintException.printStackTrace();