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.analysis.scoremodels.ScoreMatrix;
30 import jalview.analysis.scoremodels.ScoreModels;
31 import jalview.api.AlignCalcManagerI;
32 import jalview.api.AlignCalcWorkerI;
33 import jalview.api.AlignExportSettingI;
34 import jalview.api.AlignViewControllerGuiI;
35 import jalview.api.AlignViewControllerI;
36 import jalview.api.AlignViewportI;
37 import jalview.api.AlignmentViewPanel;
38 import jalview.api.FeatureSettingsControllerI;
39 import jalview.api.SplitContainerI;
40 import jalview.api.ViewStyleI;
41 import jalview.api.analysis.ScoreModelI;
42 import jalview.api.analysis.SimilarityParamsI;
43 import jalview.bin.Cache;
44 import jalview.bin.Jalview;
45 import jalview.commands.CommandI;
46 import jalview.commands.EditCommand;
47 import jalview.commands.EditCommand.Action;
48 import jalview.commands.OrderCommand;
49 import jalview.commands.RemoveGapColCommand;
50 import jalview.commands.RemoveGapsCommand;
51 import jalview.commands.SlideSequencesCommand;
52 import jalview.commands.TrimRegionCommand;
53 import jalview.datamodel.AlignedCodonFrame;
54 import jalview.datamodel.Alignment;
55 import jalview.datamodel.AlignmentAnnotation;
56 import jalview.datamodel.AlignmentExportData;
57 import jalview.datamodel.AlignmentI;
58 import jalview.datamodel.AlignmentOrder;
59 import jalview.datamodel.AlignmentView;
60 import jalview.datamodel.ColumnSelection;
61 import jalview.datamodel.HiddenSequences;
62 import jalview.datamodel.PDBEntry;
63 import jalview.datamodel.SeqCigar;
64 import jalview.datamodel.Sequence;
65 import jalview.datamodel.SequenceGroup;
66 import jalview.datamodel.SequenceI;
67 import jalview.gui.ColourMenuHelper.ColourChangeListener;
68 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
69 import jalview.io.AlignmentProperties;
70 import jalview.io.AnnotationFile;
71 import jalview.io.BioJsHTMLOutput;
72 import jalview.io.DataSourceType;
73 import jalview.io.FileFormat;
74 import jalview.io.FileFormatI;
75 import jalview.io.FileFormats;
76 import jalview.io.FileLoader;
77 import jalview.io.FileParse;
78 import jalview.io.FormatAdapter;
79 import jalview.io.HtmlSvgOutput;
80 import jalview.io.IdentifyFile;
81 import jalview.io.JPredFile;
82 import jalview.io.JalviewFileChooser;
83 import jalview.io.JalviewFileView;
84 import jalview.io.JnetAnnotationMaker;
85 import jalview.io.NewickFile;
86 import jalview.io.ScoreMatrixFile;
87 import jalview.io.TCoffeeScoreFile;
88 import jalview.jbgui.GAlignFrame;
89 import jalview.schemes.ColourSchemeI;
90 import jalview.schemes.ColourSchemes;
91 import jalview.schemes.ResidueColourScheme;
92 import jalview.schemes.TCoffeeColourScheme;
93 import jalview.util.MessageManager;
94 import jalview.viewmodel.AlignmentViewport;
95 import jalview.viewmodel.ViewportRanges;
96 import jalview.workers.ConservationThread;
97 import jalview.ws.DBRefFetcher;
98 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
99 import jalview.ws.jws1.Discoverer;
100 import jalview.ws.jws2.Jws2Discoverer;
101 import jalview.ws.jws2.jabaws2.Jws2Instance;
102 import jalview.ws.seqfetcher.DbSourceProxy;
104 import java.awt.BorderLayout;
105 import java.awt.Component;
106 import java.awt.Rectangle;
107 import java.awt.Toolkit;
108 import java.awt.datatransfer.Clipboard;
109 import java.awt.datatransfer.DataFlavor;
110 import java.awt.datatransfer.StringSelection;
111 import java.awt.datatransfer.Transferable;
112 import java.awt.dnd.DnDConstants;
113 import java.awt.dnd.DropTargetDragEvent;
114 import java.awt.dnd.DropTargetDropEvent;
115 import java.awt.dnd.DropTargetEvent;
116 import java.awt.dnd.DropTargetListener;
117 import java.awt.event.ActionEvent;
118 import java.awt.event.ActionListener;
119 import java.awt.event.FocusAdapter;
120 import java.awt.event.FocusEvent;
121 import java.awt.event.ItemEvent;
122 import java.awt.event.ItemListener;
123 import java.awt.event.KeyAdapter;
124 import java.awt.event.KeyEvent;
125 import java.awt.event.MouseEvent;
126 import java.awt.print.PageFormat;
127 import java.awt.print.PrinterJob;
128 import java.beans.PropertyChangeEvent;
130 import java.io.FileWriter;
131 import java.io.PrintWriter;
133 import java.util.ArrayList;
134 import java.util.Arrays;
135 import java.util.Deque;
136 import java.util.Enumeration;
137 import java.util.Hashtable;
138 import java.util.List;
139 import java.util.Vector;
141 import javax.swing.JCheckBoxMenuItem;
142 import javax.swing.JEditorPane;
143 import javax.swing.JInternalFrame;
144 import javax.swing.JLayeredPane;
145 import javax.swing.JMenu;
146 import javax.swing.JMenuItem;
147 import javax.swing.JScrollPane;
148 import javax.swing.SwingUtilities;
154 * @version $Revision$
156 public class AlignFrame extends GAlignFrame implements DropTargetListener,
157 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
160 public static final int DEFAULT_WIDTH = 700;
162 public static final int DEFAULT_HEIGHT = 500;
165 * The currently displayed panel (selected tabbed view if more than one)
167 public AlignmentPanel alignPanel;
169 AlignViewport viewport;
171 ViewportRanges vpRanges;
173 public AlignViewControllerI avc;
175 List<AlignmentPanel> alignPanels = new ArrayList<AlignmentPanel>();
178 * Last format used to load or save alignments in this window
180 FileFormatI currentFileFormat = null;
183 * Current filename for this alignment
185 String fileName = null;
188 * Creates a new AlignFrame object with specific width and height.
194 public AlignFrame(AlignmentI al, int width, int height)
196 this(al, null, width, height);
200 * Creates a new AlignFrame object with specific width, height and
206 * @param sequenceSetId
208 public AlignFrame(AlignmentI al, int width, int height,
209 String sequenceSetId)
211 this(al, null, width, height, sequenceSetId);
215 * Creates a new AlignFrame object with specific width, height and
221 * @param sequenceSetId
224 public AlignFrame(AlignmentI al, int width, int height,
225 String sequenceSetId, String viewId)
227 this(al, null, width, height, sequenceSetId, viewId);
231 * new alignment window with hidden columns
235 * @param hiddenColumns
236 * ColumnSelection or null
238 * Width of alignment frame
242 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
243 int width, int height)
245 this(al, hiddenColumns, width, height, null);
249 * Create alignment frame for al with hiddenColumns, a specific width and
250 * height, and specific sequenceId
253 * @param hiddenColumns
256 * @param sequenceSetId
259 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
260 int width, int height, String sequenceSetId)
262 this(al, hiddenColumns, width, height, sequenceSetId, null);
266 * Create alignment frame for al with hiddenColumns, a specific width and
267 * height, and specific sequenceId
270 * @param hiddenColumns
273 * @param sequenceSetId
278 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
279 int width, int height, String sequenceSetId, String viewId)
281 setSize(width, height);
283 if (al.getDataset() == null)
288 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
290 alignPanel = new AlignmentPanel(this, viewport);
292 addAlignmentPanel(alignPanel, true);
296 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
297 ColumnSelection hiddenColumns, int width, int height)
299 setSize(width, height);
301 if (al.getDataset() == null)
306 viewport = new AlignViewport(al, hiddenColumns);
308 if (hiddenSeqs != null && hiddenSeqs.length > 0)
310 viewport.hideSequence(hiddenSeqs);
312 alignPanel = new AlignmentPanel(this, viewport);
313 addAlignmentPanel(alignPanel, true);
318 * Make a new AlignFrame from existing alignmentPanels
325 public AlignFrame(AlignmentPanel ap)
329 addAlignmentPanel(ap, false);
334 * initalise the alignframe from the underlying viewport data and the
339 if (!Jalview.isHeadlessMode())
341 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
344 vpRanges = viewport.getRanges();
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);
370 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
372 setMenusFromViewport(viewport);
373 buildSortByAnnotationScoresMenu();
374 calculateTree.addActionListener(new ActionListener()
378 public void actionPerformed(ActionEvent e)
380 new CalculationChooser(AlignFrame.this);
385 if (Desktop.desktop != null)
387 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
388 addServiceListeners();
392 if (viewport.getWrapAlignment())
394 wrapMenuItem_actionPerformed(null);
397 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
399 this.overviewMenuItem_actionPerformed(null);
404 final List<AlignmentPanel> selviews = new ArrayList<AlignmentPanel>();
405 final List<AlignmentPanel> origview = new ArrayList<AlignmentPanel>();
406 final String menuLabel = MessageManager
407 .getString("label.copy_format_from");
408 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
409 new ViewSetProvider()
413 public AlignmentPanel[] getAllAlignmentPanels()
416 origview.add(alignPanel);
417 // make an array of all alignment panels except for this one
418 List<AlignmentPanel> aps = new ArrayList<AlignmentPanel>(
419 Arrays.asList(Desktop.getAlignmentPanels(null)));
420 aps.remove(AlignFrame.this.alignPanel);
421 return aps.toArray(new AlignmentPanel[aps.size()]);
423 }, selviews, new ItemListener()
427 public void itemStateChanged(ItemEvent e)
429 if (origview.size() > 0)
431 final AlignmentPanel ap = origview.get(0);
434 * Copy the ViewStyle of the selected panel to 'this one'.
435 * Don't change value of 'scaleProteinAsCdna' unless copying
438 ViewStyleI vs = selviews.get(0).getAlignViewport()
440 boolean fromSplitFrame = selviews.get(0)
441 .getAlignViewport().getCodingComplement() != null;
444 vs.setScaleProteinAsCdna(ap.getAlignViewport()
445 .getViewStyle().isScaleProteinAsCdna());
447 ap.getAlignViewport().setViewStyle(vs);
450 * Also rescale ViewStyle of SplitFrame complement if there is
451 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
452 * the whole ViewStyle (allow cDNA protein to have different
455 AlignViewportI complement = ap.getAlignViewport()
456 .getCodingComplement();
457 if (complement != null && vs.isScaleProteinAsCdna())
459 AlignFrame af = Desktop.getAlignFrameFor(complement);
460 ((SplitFrame) af.getSplitViewContainer())
462 af.setMenusForViewport();
466 ap.setSelected(true);
467 ap.alignFrame.setMenusForViewport();
472 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
473 .indexOf("devel") > -1
474 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
475 .indexOf("test") > -1)
477 formatMenu.add(vsel);
479 addFocusListener(new FocusAdapter()
482 public void focusGained(FocusEvent e)
484 Jalview.setCurrentAlignFrame(AlignFrame.this);
491 * Change the filename and format for the alignment, and enable the 'reload'
492 * button functionality.
499 public void setFileName(String file, FileFormatI format)
502 setFileFormat(format);
503 reload.setEnabled(true);
507 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
510 void addKeyListener()
512 addKeyListener(new KeyAdapter()
515 public void keyPressed(KeyEvent evt)
517 if (viewport.cursorMode
518 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
519 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
520 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
521 && Character.isDigit(evt.getKeyChar()))
523 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
526 switch (evt.getKeyCode())
529 case 27: // escape key
530 deselectAllSequenceMenuItem_actionPerformed(null);
534 case KeyEvent.VK_DOWN:
535 if (evt.isAltDown() || !viewport.cursorMode)
537 moveSelectedSequences(false);
539 if (viewport.cursorMode)
541 alignPanel.getSeqPanel().moveCursor(0, 1);
546 if (evt.isAltDown() || !viewport.cursorMode)
548 moveSelectedSequences(true);
550 if (viewport.cursorMode)
552 alignPanel.getSeqPanel().moveCursor(0, -1);
557 case KeyEvent.VK_LEFT:
558 if (evt.isAltDown() || !viewport.cursorMode)
560 slideSequences(false, alignPanel.getSeqPanel().getKeyboardNo1());
564 alignPanel.getSeqPanel().moveCursor(-1, 0);
569 case KeyEvent.VK_RIGHT:
570 if (evt.isAltDown() || !viewport.cursorMode)
572 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
576 alignPanel.getSeqPanel().moveCursor(1, 0);
580 case KeyEvent.VK_SPACE:
581 if (viewport.cursorMode)
583 alignPanel.getSeqPanel().insertGapAtCursor(
584 evt.isControlDown() || evt.isShiftDown()
589 // case KeyEvent.VK_A:
590 // if (viewport.cursorMode)
592 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
593 // //System.out.println("A");
597 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
598 * System.out.println("closing bracket"); } break;
600 case KeyEvent.VK_DELETE:
601 case KeyEvent.VK_BACK_SPACE:
602 if (!viewport.cursorMode)
604 cut_actionPerformed(null);
608 alignPanel.getSeqPanel().deleteGapAtCursor(
609 evt.isControlDown() || evt.isShiftDown()
616 if (viewport.cursorMode)
618 alignPanel.getSeqPanel().setCursorRow();
622 if (viewport.cursorMode && !evt.isControlDown())
624 alignPanel.getSeqPanel().setCursorColumn();
628 if (viewport.cursorMode)
630 alignPanel.getSeqPanel().setCursorPosition();
634 case KeyEvent.VK_ENTER:
635 case KeyEvent.VK_COMMA:
636 if (viewport.cursorMode)
638 alignPanel.getSeqPanel().setCursorRowAndColumn();
643 if (viewport.cursorMode)
645 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
649 if (viewport.cursorMode)
651 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
656 viewport.cursorMode = !viewport.cursorMode;
657 statusBar.setText(MessageManager.formatMessage(
658 "label.keyboard_editing_mode",
659 new String[] { (viewport.cursorMode ? "on" : "off") }));
660 if (viewport.cursorMode)
662 alignPanel.getSeqPanel().seqCanvas.cursorX = vpRanges
664 alignPanel.getSeqPanel().seqCanvas.cursorY = vpRanges
667 alignPanel.getSeqPanel().seqCanvas.repaint();
673 Help.showHelpWindow();
674 } catch (Exception ex)
676 ex.printStackTrace();
681 boolean toggleSeqs = !evt.isControlDown();
682 boolean toggleCols = !evt.isShiftDown();
683 toggleHiddenRegions(toggleSeqs, toggleCols);
688 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
689 boolean modifyExisting = true; // always modify, don't clear
690 // evt.isShiftDown();
691 boolean invertHighlighted = evt.isAltDown();
692 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
696 case KeyEvent.VK_PAGE_UP:
697 if (viewport.getWrapAlignment())
699 alignPanel.scrollUp(true);
703 alignPanel.setScrollValues(vpRanges.getStartRes(),
704 2 * vpRanges.getStartSeq() - vpRanges.getEndSeq());
707 case KeyEvent.VK_PAGE_DOWN:
708 if (viewport.getWrapAlignment())
710 alignPanel.scrollUp(false);
714 alignPanel.setScrollValues(vpRanges.getStartRes(),
715 vpRanges.getEndSeq());
722 public void keyReleased(KeyEvent evt)
724 switch (evt.getKeyCode())
726 case KeyEvent.VK_LEFT:
727 if (evt.isAltDown() || !viewport.cursorMode)
729 viewport.firePropertyChange("alignment", null, viewport
730 .getAlignment().getSequences());
734 case KeyEvent.VK_RIGHT:
735 if (evt.isAltDown() || !viewport.cursorMode)
737 viewport.firePropertyChange("alignment", null, viewport
738 .getAlignment().getSequences());
746 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
748 ap.alignFrame = this;
749 avc = new jalview.controller.AlignViewController(this, viewport,
754 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
756 int aSize = alignPanels.size();
758 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
760 if (aSize == 1 && ap.av.viewName == null)
762 this.getContentPane().add(ap, BorderLayout.CENTER);
768 setInitialTabVisible();
771 expandViews.setEnabled(true);
772 gatherViews.setEnabled(true);
773 tabbedPane.addTab(ap.av.viewName, ap);
775 ap.setVisible(false);
780 if (ap.av.isPadGaps())
782 ap.av.getAlignment().padGaps();
784 ap.av.updateConservation(ap);
785 ap.av.updateConsensus(ap);
786 ap.av.updateStrucConsensus(ap);
790 public void setInitialTabVisible()
792 expandViews.setEnabled(true);
793 gatherViews.setEnabled(true);
794 tabbedPane.setVisible(true);
795 AlignmentPanel first = alignPanels.get(0);
796 tabbedPane.addTab(first.av.viewName, first);
797 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
800 public AlignViewport getViewport()
805 /* Set up intrinsic listeners for dynamically generated GUI bits. */
806 private void addServiceListeners()
808 final java.beans.PropertyChangeListener thisListener;
809 Desktop.instance.addJalviewPropertyChangeListener("services",
810 thisListener = new java.beans.PropertyChangeListener()
813 public void propertyChange(PropertyChangeEvent evt)
815 // // System.out.println("Discoverer property change.");
816 // if (evt.getPropertyName().equals("services"))
818 SwingUtilities.invokeLater(new Runnable()
825 .println("Rebuild WS Menu for service change");
826 BuildWebServiceMenu();
833 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
836 public void internalFrameClosed(
837 javax.swing.event.InternalFrameEvent evt)
839 // System.out.println("deregistering discoverer listener");
840 Desktop.instance.removeJalviewPropertyChangeListener("services",
842 closeMenuItem_actionPerformed(true);
845 // Finally, build the menu once to get current service state
846 new Thread(new Runnable()
851 BuildWebServiceMenu();
857 * Configure menu items that vary according to whether the alignment is
858 * nucleotide or protein
860 public void setGUINucleotide()
862 AlignmentI al = getViewport().getAlignment();
863 boolean nucleotide = al.isNucleotide();
865 showTranslation.setVisible(nucleotide);
866 showReverse.setVisible(nucleotide);
867 showReverseComplement.setVisible(nucleotide);
868 conservationMenuItem.setEnabled(!nucleotide);
869 modifyConservation.setEnabled(!nucleotide
870 && conservationMenuItem.isSelected());
871 showGroupConservation.setEnabled(!nucleotide);
872 qualityScoreModel.setEnabled(!nucleotide);
874 showComplementMenuItem.setText(nucleotide ? MessageManager
875 .getString("label.protein") : MessageManager
876 .getString("label.nucleotide"));
880 * set up menus for the current viewport. This may be called after any
881 * operation that affects the data in the current view (selection changed,
882 * etc) to update the menus to reflect the new state.
885 public void setMenusForViewport()
887 setMenusFromViewport(viewport);
891 * Need to call this method when tabs are selected for multiple views, or when
892 * loading from Jalview2XML.java
897 void setMenusFromViewport(AlignViewport av)
899 padGapsMenuitem.setSelected(av.isPadGaps());
900 colourTextMenuItem.setSelected(av.isShowColourText());
901 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
902 modifyPID.setEnabled(abovePIDThreshold.isSelected());
903 conservationMenuItem.setSelected(av.getConservationSelected());
904 modifyConservation.setEnabled(conservationMenuItem.isSelected());
905 seqLimits.setSelected(av.getShowJVSuffix());
906 idRightAlign.setSelected(av.isRightAlignIds());
907 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
908 renderGapsMenuItem.setSelected(av.isRenderGaps());
909 wrapMenuItem.setSelected(av.getWrapAlignment());
910 scaleAbove.setVisible(av.getWrapAlignment());
911 scaleLeft.setVisible(av.getWrapAlignment());
912 scaleRight.setVisible(av.getWrapAlignment());
913 annotationPanelMenuItem.setState(av.isShowAnnotation());
915 * Show/hide annotations only enabled if annotation panel is shown
917 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
918 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
919 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
920 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
921 viewBoxesMenuItem.setSelected(av.getShowBoxes());
922 viewTextMenuItem.setSelected(av.getShowText());
923 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
924 showGroupConsensus.setSelected(av.isShowGroupConsensus());
925 showGroupConservation.setSelected(av.isShowGroupConservation());
926 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
927 showSequenceLogo.setSelected(av.isShowSequenceLogo());
928 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
930 ColourMenuHelper.setColourSelected(colourMenu,
931 av.getGlobalColourScheme());
933 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
934 hiddenMarkers.setState(av.getShowHiddenMarkers());
935 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
936 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
937 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
938 autoCalculate.setSelected(av.autoCalculateConsensus);
939 sortByTree.setSelected(av.sortByTree);
940 listenToViewSelections.setSelected(av.followSelection);
942 showProducts.setEnabled(canShowProducts());
943 setGroovyEnabled(Desktop.getGroovyConsole() != null);
949 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
953 public void setGroovyEnabled(boolean b)
955 runGroovy.setEnabled(b);
958 private IProgressIndicator progressBar;
963 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
966 public void setProgressBar(String message, long id)
968 progressBar.setProgressBar(message, id);
972 public void registerHandler(final long id,
973 final IProgressIndicatorHandler handler)
975 progressBar.registerHandler(id, handler);
980 * @return true if any progress bars are still active
983 public boolean operationInProgress()
985 return progressBar.operationInProgress();
989 public void setStatus(String text)
991 statusBar.setText(text);
995 * Added so Castor Mapping file can obtain Jalview Version
997 public String getVersion()
999 return jalview.bin.Cache.getProperty("VERSION");
1002 public FeatureRenderer getFeatureRenderer()
1004 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1008 public void fetchSequence_actionPerformed(ActionEvent e)
1010 new jalview.gui.SequenceFetcher(this);
1014 public void addFromFile_actionPerformed(ActionEvent e)
1016 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1020 public void reload_actionPerformed(ActionEvent e)
1022 if (fileName != null)
1024 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1025 // originating file's format
1026 // TODO: work out how to recover feature settings for correct view(s) when
1027 // file is reloaded.
1028 if (FileFormat.Jalview.equals(currentFileFormat))
1030 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1031 for (int i = 0; i < frames.length; i++)
1033 if (frames[i] instanceof AlignFrame && frames[i] != this
1034 && ((AlignFrame) frames[i]).fileName != null
1035 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1039 frames[i].setSelected(true);
1040 Desktop.instance.closeAssociatedWindows();
1041 } catch (java.beans.PropertyVetoException ex)
1047 Desktop.instance.closeAssociatedWindows();
1049 FileLoader loader = new FileLoader();
1050 DataSourceType protocol = fileName.startsWith("http:") ? DataSourceType.URL
1051 : DataSourceType.FILE;
1052 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1056 Rectangle bounds = this.getBounds();
1058 FileLoader loader = new FileLoader();
1059 DataSourceType protocol = fileName.startsWith("http:") ? DataSourceType.URL
1060 : DataSourceType.FILE;
1061 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1062 protocol, currentFileFormat);
1064 newframe.setBounds(bounds);
1065 if (featureSettings != null && featureSettings.isShowing())
1067 final Rectangle fspos = featureSettings.frame.getBounds();
1068 // TODO: need a 'show feature settings' function that takes bounds -
1069 // need to refactor Desktop.addFrame
1070 newframe.featureSettings_actionPerformed(null);
1071 final FeatureSettings nfs = newframe.featureSettings;
1072 SwingUtilities.invokeLater(new Runnable()
1077 nfs.frame.setBounds(fspos);
1080 this.featureSettings.close();
1081 this.featureSettings = null;
1083 this.closeMenuItem_actionPerformed(true);
1089 public void addFromText_actionPerformed(ActionEvent e)
1091 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport
1096 public void addFromURL_actionPerformed(ActionEvent e)
1098 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1102 public void save_actionPerformed(ActionEvent e)
1104 if (fileName == null || (currentFileFormat == null)
1105 || fileName.startsWith("http"))
1107 saveAs_actionPerformed(null);
1111 saveAlignment(fileName, currentFileFormat);
1122 public void saveAs_actionPerformed(ActionEvent e)
1124 String format = currentFileFormat == null ? null : currentFileFormat
1126 JalviewFileChooser chooser = JalviewFileChooser.forWrite(
1127 Cache.getProperty("LAST_DIRECTORY"), format);
1129 chooser.setFileView(new JalviewFileView());
1130 chooser.setDialogTitle(MessageManager
1131 .getString("label.save_alignment_to_file"));
1132 chooser.setToolTipText(MessageManager.getString("action.save"));
1134 int value = chooser.showSaveDialog(this);
1136 if (value == JalviewFileChooser.APPROVE_OPTION)
1138 currentFileFormat = chooser.getSelectedFormat();
1139 while (currentFileFormat == null)
1142 .showInternalMessageDialog(
1145 .getString("label.select_file_format_before_saving"),
1147 .getString("label.file_format_not_specified"),
1148 JvOptionPane.WARNING_MESSAGE);
1149 currentFileFormat = chooser.getSelectedFormat();
1150 value = chooser.showSaveDialog(this);
1151 if (value != JalviewFileChooser.APPROVE_OPTION)
1157 fileName = chooser.getSelectedFile().getPath();
1159 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1161 Cache.setProperty("LAST_DIRECTORY", fileName);
1162 saveAlignment(fileName, currentFileFormat);
1166 public boolean saveAlignment(String file, FileFormatI format)
1168 boolean success = true;
1170 if (FileFormat.Jalview.equals(format))
1172 String shortName = title;
1174 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1176 shortName = shortName.substring(shortName
1177 .lastIndexOf(java.io.File.separatorChar) + 1);
1180 success = new Jalview2XML().saveAlignment(this, file, shortName);
1182 statusBar.setText(MessageManager.formatMessage(
1183 "label.successfully_saved_to_file_in_format", new Object[] {
1184 fileName, format }));
1189 AlignmentExportData exportData = getAlignmentForExport(format,
1191 if (exportData.getSettings().isCancelled())
1195 FormatAdapter f = new FormatAdapter(alignPanel,
1196 exportData.getSettings());
1197 String output = f.formatSequences(
1199 exportData.getAlignment(), // class cast exceptions will
1200 // occur in the distant future
1201 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1202 f.getCacheSuffixDefault(format),
1203 viewport.getColumnSelection());
1213 PrintWriter out = new PrintWriter(new FileWriter(file));
1217 this.setTitle(file);
1218 statusBar.setText(MessageManager.formatMessage(
1219 "label.successfully_saved_to_file_in_format",
1220 new Object[] { fileName, format.getName() }));
1221 } catch (Exception ex)
1224 ex.printStackTrace();
1231 JvOptionPane.showInternalMessageDialog(this, MessageManager
1232 .formatMessage("label.couldnt_save_file",
1233 new Object[] { fileName }), MessageManager
1234 .getString("label.error_saving_file"),
1235 JvOptionPane.WARNING_MESSAGE);
1241 private void warningMessage(String warning, String title)
1243 if (new jalview.util.Platform().isHeadless())
1245 System.err.println("Warning: " + title + "\nWarning: " + warning);
1250 JvOptionPane.showInternalMessageDialog(this, warning, title,
1251 JvOptionPane.WARNING_MESSAGE);
1263 protected void outputText_actionPerformed(ActionEvent e)
1265 FileFormatI fileFormat = FileFormats.getInstance().forName(
1266 e.getActionCommand());
1267 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1269 if (exportData.getSettings().isCancelled())
1273 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1274 cap.setForInput(null);
1277 FileFormatI format = fileFormat;
1278 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1279 .formatSequences(format, exportData.getAlignment(),
1280 exportData.getOmitHidden(),
1281 exportData.getStartEndPostions(),
1282 viewport.getColumnSelection()));
1283 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1284 "label.alignment_output_command",
1285 new Object[] { e.getActionCommand() }), 600, 500);
1286 } catch (OutOfMemoryError oom)
1288 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1294 public static AlignmentExportData getAlignmentForExport(
1295 FileFormatI format, AlignViewportI viewport,
1296 AlignExportSettingI exportSettings)
1298 AlignmentI alignmentToExport = null;
1299 AlignExportSettingI settings = exportSettings;
1300 String[] omitHidden = null;
1302 HiddenSequences hiddenSeqs = viewport.getAlignment()
1303 .getHiddenSequences();
1305 alignmentToExport = viewport.getAlignment();
1307 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1308 if (settings == null)
1310 settings = new AlignExportSettings(hasHiddenSeqs,
1311 viewport.hasHiddenColumns(), format);
1313 // settings.isExportAnnotations();
1315 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1317 omitHidden = viewport.getViewAsString(false,
1318 settings.isExportHiddenSequences());
1321 int[] alignmentStartEnd = new int[2];
1322 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1324 alignmentToExport = hiddenSeqs.getFullAlignment();
1328 alignmentToExport = viewport.getAlignment();
1330 alignmentStartEnd = alignmentToExport
1331 .getVisibleStartAndEndIndex(viewport.getColumnSelection()
1332 .getHiddenColumns());
1333 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1334 omitHidden, alignmentStartEnd, settings);
1345 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1347 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1348 htmlSVG.exportHTML(null);
1352 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1354 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1355 bjs.exportHTML(null);
1358 public void createImageMap(File file, String image)
1360 alignPanel.makePNGImageMap(file, image);
1370 public void createPNG(File f)
1372 alignPanel.makePNG(f);
1382 public void createEPS(File f)
1384 alignPanel.makeEPS(f);
1388 public void createSVG(File f)
1390 alignPanel.makeSVG(f);
1394 public void pageSetup_actionPerformed(ActionEvent e)
1396 PrinterJob printJob = PrinterJob.getPrinterJob();
1397 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1407 public void printMenuItem_actionPerformed(ActionEvent e)
1409 // Putting in a thread avoids Swing painting problems
1410 PrintThread thread = new PrintThread(alignPanel);
1415 public void exportFeatures_actionPerformed(ActionEvent e)
1417 new AnnotationExporter().exportFeatures(alignPanel);
1421 public void exportAnnotations_actionPerformed(ActionEvent e)
1423 new AnnotationExporter().exportAnnotations(alignPanel);
1427 public void associatedData_actionPerformed(ActionEvent e)
1429 // Pick the tree file
1430 JalviewFileChooser chooser = new JalviewFileChooser(
1431 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1432 chooser.setFileView(new JalviewFileView());
1433 chooser.setDialogTitle(MessageManager
1434 .getString("label.load_jalview_annotations"));
1435 chooser.setToolTipText(MessageManager
1436 .getString("label.load_jalview_annotations"));
1438 int value = chooser.showOpenDialog(null);
1440 if (value == JalviewFileChooser.APPROVE_OPTION)
1442 String choice = chooser.getSelectedFile().getPath();
1443 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1444 loadJalviewDataFile(choice, null, null, null);
1450 * Close the current view or all views in the alignment frame. If the frame
1451 * only contains one view then the alignment will be removed from memory.
1453 * @param closeAllTabs
1456 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1458 if (alignPanels != null && alignPanels.size() < 2)
1460 closeAllTabs = true;
1465 if (alignPanels != null)
1469 if (this.isClosed())
1471 // really close all the windows - otherwise wait till
1472 // setClosed(true) is called
1473 for (int i = 0; i < alignPanels.size(); i++)
1475 AlignmentPanel ap = alignPanels.get(i);
1482 closeView(alignPanel);
1489 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1490 * be called recursively, with the frame now in 'closed' state
1492 this.setClosed(true);
1494 } catch (Exception ex)
1496 ex.printStackTrace();
1501 * Close the specified panel and close up tabs appropriately.
1503 * @param panelToClose
1505 public void closeView(AlignmentPanel panelToClose)
1507 int index = tabbedPane.getSelectedIndex();
1508 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1509 alignPanels.remove(panelToClose);
1510 panelToClose.closePanel();
1511 panelToClose = null;
1513 tabbedPane.removeTabAt(closedindex);
1514 tabbedPane.validate();
1516 if (index > closedindex || index == tabbedPane.getTabCount())
1518 // modify currently selected tab index if necessary.
1522 this.tabSelectionChanged(index);
1528 void updateEditMenuBar()
1531 if (viewport.getHistoryList().size() > 0)
1533 undoMenuItem.setEnabled(true);
1534 CommandI command = viewport.getHistoryList().peek();
1535 undoMenuItem.setText(MessageManager.formatMessage(
1536 "label.undo_command",
1537 new Object[] { command.getDescription() }));
1541 undoMenuItem.setEnabled(false);
1542 undoMenuItem.setText(MessageManager.getString("action.undo"));
1545 if (viewport.getRedoList().size() > 0)
1547 redoMenuItem.setEnabled(true);
1549 CommandI command = viewport.getRedoList().peek();
1550 redoMenuItem.setText(MessageManager.formatMessage(
1551 "label.redo_command",
1552 new Object[] { command.getDescription() }));
1556 redoMenuItem.setEnabled(false);
1557 redoMenuItem.setText(MessageManager.getString("action.redo"));
1562 public void addHistoryItem(CommandI command)
1564 if (command.getSize() > 0)
1566 viewport.addToHistoryList(command);
1567 viewport.clearRedoList();
1568 updateEditMenuBar();
1569 viewport.updateHiddenColumns();
1570 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1571 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1572 // viewport.getColumnSelection()
1573 // .getHiddenColumns().size() > 0);
1579 * @return alignment objects for all views
1581 AlignmentI[] getViewAlignments()
1583 if (alignPanels != null)
1585 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1587 for (AlignmentPanel ap : alignPanels)
1589 als[i++] = ap.av.getAlignment();
1593 if (viewport != null)
1595 return new AlignmentI[] { viewport.getAlignment() };
1607 protected void undoMenuItem_actionPerformed(ActionEvent e)
1609 if (viewport.getHistoryList().isEmpty())
1613 CommandI command = viewport.getHistoryList().pop();
1614 viewport.addToRedoList(command);
1615 command.undoCommand(getViewAlignments());
1617 AlignmentViewport originalSource = getOriginatingSource(command);
1618 updateEditMenuBar();
1620 if (originalSource != null)
1622 if (originalSource != viewport)
1625 .warn("Implementation worry: mismatch of viewport origin for undo");
1627 originalSource.updateHiddenColumns();
1628 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1630 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1631 // viewport.getColumnSelection()
1632 // .getHiddenColumns().size() > 0);
1633 originalSource.firePropertyChange("alignment", null, originalSource
1634 .getAlignment().getSequences());
1645 protected void redoMenuItem_actionPerformed(ActionEvent e)
1647 if (viewport.getRedoList().size() < 1)
1652 CommandI command = viewport.getRedoList().pop();
1653 viewport.addToHistoryList(command);
1654 command.doCommand(getViewAlignments());
1656 AlignmentViewport originalSource = getOriginatingSource(command);
1657 updateEditMenuBar();
1659 if (originalSource != null)
1662 if (originalSource != viewport)
1665 .warn("Implementation worry: mismatch of viewport origin for redo");
1667 originalSource.updateHiddenColumns();
1668 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1670 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1671 // viewport.getColumnSelection()
1672 // .getHiddenColumns().size() > 0);
1673 originalSource.firePropertyChange("alignment", null, originalSource
1674 .getAlignment().getSequences());
1678 AlignmentViewport getOriginatingSource(CommandI command)
1680 AlignmentViewport originalSource = null;
1681 // For sequence removal and addition, we need to fire
1682 // the property change event FROM the viewport where the
1683 // original alignment was altered
1684 AlignmentI al = null;
1685 if (command instanceof EditCommand)
1687 EditCommand editCommand = (EditCommand) command;
1688 al = editCommand.getAlignment();
1689 List<Component> comps = PaintRefresher.components.get(viewport
1690 .getSequenceSetId());
1692 for (Component comp : comps)
1694 if (comp instanceof AlignmentPanel)
1696 if (al == ((AlignmentPanel) comp).av.getAlignment())
1698 originalSource = ((AlignmentPanel) comp).av;
1705 if (originalSource == null)
1707 // The original view is closed, we must validate
1708 // the current view against the closed view first
1711 PaintRefresher.validateSequences(al, viewport.getAlignment());
1714 originalSource = viewport;
1717 return originalSource;
1726 public void moveSelectedSequences(boolean up)
1728 SequenceGroup sg = viewport.getSelectionGroup();
1734 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1735 viewport.getHiddenRepSequences(), up);
1736 alignPanel.paintAlignment(true);
1739 synchronized void slideSequences(boolean right, int size)
1741 List<SequenceI> sg = new ArrayList<SequenceI>();
1742 if (viewport.cursorMode)
1744 sg.add(viewport.getAlignment().getSequenceAt(
1745 alignPanel.getSeqPanel().seqCanvas.cursorY));
1747 else if (viewport.getSelectionGroup() != null
1748 && viewport.getSelectionGroup().getSize() != viewport
1749 .getAlignment().getHeight())
1751 sg = viewport.getSelectionGroup().getSequences(
1752 viewport.getHiddenRepSequences());
1760 List<SequenceI> invertGroup = new ArrayList<SequenceI>();
1762 for (SequenceI seq : viewport.getAlignment().getSequences())
1764 if (!sg.contains(seq))
1766 invertGroup.add(seq);
1770 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1772 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1773 for (int i = 0; i < invertGroup.size(); i++)
1775 seqs2[i] = invertGroup.get(i);
1778 SlideSequencesCommand ssc;
1781 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1782 size, viewport.getGapCharacter());
1786 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1787 size, viewport.getGapCharacter());
1790 int groupAdjustment = 0;
1791 if (ssc.getGapsInsertedBegin() && right)
1793 if (viewport.cursorMode)
1795 alignPanel.getSeqPanel().moveCursor(size, 0);
1799 groupAdjustment = size;
1802 else if (!ssc.getGapsInsertedBegin() && !right)
1804 if (viewport.cursorMode)
1806 alignPanel.getSeqPanel().moveCursor(-size, 0);
1810 groupAdjustment = -size;
1814 if (groupAdjustment != 0)
1816 viewport.getSelectionGroup().setStartRes(
1817 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1818 viewport.getSelectionGroup().setEndRes(
1819 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1823 * just extend the last slide command if compatible; but not if in
1824 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1826 boolean appendHistoryItem = false;
1827 Deque<CommandI> historyList = viewport.getHistoryList();
1828 boolean inSplitFrame = getSplitViewContainer() != null;
1829 if (!inSplitFrame && historyList != null && historyList.size() > 0
1830 && historyList.peek() instanceof SlideSequencesCommand)
1832 appendHistoryItem = ssc
1833 .appendSlideCommand((SlideSequencesCommand) historyList
1837 if (!appendHistoryItem)
1839 addHistoryItem(ssc);
1852 protected void copy_actionPerformed(ActionEvent e)
1855 if (viewport.getSelectionGroup() == null)
1859 // TODO: preserve the ordering of displayed alignment annotation in any
1860 // internal paste (particularly sequence associated annotation)
1861 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1862 String[] omitHidden = null;
1864 if (viewport.hasHiddenColumns())
1866 omitHidden = viewport.getViewAsString(true);
1869 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1870 seqs, omitHidden, null);
1872 StringSelection ss = new StringSelection(output);
1876 jalview.gui.Desktop.internalCopy = true;
1877 // Its really worth setting the clipboard contents
1878 // to empty before setting the large StringSelection!!
1879 Toolkit.getDefaultToolkit().getSystemClipboard()
1880 .setContents(new StringSelection(""), null);
1882 Toolkit.getDefaultToolkit().getSystemClipboard()
1883 .setContents(ss, Desktop.instance);
1884 } catch (OutOfMemoryError er)
1886 new OOMWarning("copying region", er);
1890 ArrayList<int[]> hiddenColumns = null;
1891 if (viewport.hasHiddenColumns())
1893 hiddenColumns = new ArrayList<int[]>();
1894 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1895 .getSelectionGroup().getEndRes();
1896 for (int[] region : viewport.getColumnSelection().getHiddenColumns())
1898 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1900 hiddenColumns.add(new int[] { region[0] - hiddenOffset,
1901 region[1] - hiddenOffset });
1906 Desktop.jalviewClipboard = new Object[] { seqs,
1907 viewport.getAlignment().getDataset(), hiddenColumns };
1908 statusBar.setText(MessageManager.formatMessage(
1909 "label.copied_sequences_to_clipboard", new Object[] { Integer
1910 .valueOf(seqs.length).toString() }));
1920 protected void pasteNew_actionPerformed(ActionEvent e)
1932 protected void pasteThis_actionPerformed(ActionEvent e)
1938 * Paste contents of Jalview clipboard
1940 * @param newAlignment
1941 * true to paste to a new alignment, otherwise add to this.
1943 void paste(boolean newAlignment)
1945 boolean externalPaste = true;
1948 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1949 Transferable contents = c.getContents(this);
1951 if (contents == null)
1960 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1961 if (str.length() < 1)
1966 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
1968 } catch (OutOfMemoryError er)
1970 new OOMWarning("Out of memory pasting sequences!!", er);
1974 SequenceI[] sequences;
1975 boolean annotationAdded = false;
1976 AlignmentI alignment = null;
1978 if (Desktop.jalviewClipboard != null)
1980 // The clipboard was filled from within Jalview, we must use the
1982 // And dataset from the copied alignment
1983 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1984 // be doubly sure that we create *new* sequence objects.
1985 sequences = new SequenceI[newseq.length];
1986 for (int i = 0; i < newseq.length; i++)
1988 sequences[i] = new Sequence(newseq[i]);
1990 alignment = new Alignment(sequences);
1991 externalPaste = false;
1995 // parse the clipboard as an alignment.
1996 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
1998 sequences = alignment.getSequencesArray();
2002 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
2008 if (Desktop.jalviewClipboard != null)
2010 // dataset is inherited
2011 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2015 // new dataset is constructed
2016 alignment.setDataset(null);
2018 alwidth = alignment.getWidth() + 1;
2022 AlignmentI pastedal = alignment; // preserve pasted alignment object
2023 // Add pasted sequences and dataset into existing alignment.
2024 alignment = viewport.getAlignment();
2025 alwidth = alignment.getWidth() + 1;
2026 // decide if we need to import sequences from an existing dataset
2027 boolean importDs = Desktop.jalviewClipboard != null
2028 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2029 // importDs==true instructs us to copy over new dataset sequences from
2030 // an existing alignment
2031 Vector newDs = (importDs) ? new Vector() : null; // used to create
2032 // minimum dataset set
2034 for (int i = 0; i < sequences.length; i++)
2038 newDs.addElement(null);
2040 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2042 if (importDs && ds != null)
2044 if (!newDs.contains(ds))
2046 newDs.setElementAt(ds, i);
2047 ds = new Sequence(ds);
2048 // update with new dataset sequence
2049 sequences[i].setDatasetSequence(ds);
2053 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2058 // copy and derive new dataset sequence
2059 sequences[i] = sequences[i].deriveSequence();
2060 alignment.getDataset().addSequence(
2061 sequences[i].getDatasetSequence());
2062 // TODO: avoid creation of duplicate dataset sequences with a
2063 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2065 alignment.addSequence(sequences[i]); // merges dataset
2069 newDs.clear(); // tidy up
2071 if (alignment.getAlignmentAnnotation() != null)
2073 for (AlignmentAnnotation alan : alignment
2074 .getAlignmentAnnotation())
2076 if (alan.graphGroup > fgroup)
2078 fgroup = alan.graphGroup;
2082 if (pastedal.getAlignmentAnnotation() != null)
2084 // Add any annotation attached to alignment.
2085 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2086 for (int i = 0; i < alann.length; i++)
2088 annotationAdded = true;
2089 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2091 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2092 if (newann.graphGroup > -1)
2094 if (newGraphGroups.size() <= newann.graphGroup
2095 || newGraphGroups.get(newann.graphGroup) == null)
2097 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2099 newGraphGroups.add(q, null);
2101 newGraphGroups.set(newann.graphGroup, new Integer(
2104 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2108 newann.padAnnotation(alwidth);
2109 alignment.addAnnotation(newann);
2119 addHistoryItem(new EditCommand(
2120 MessageManager.getString("label.add_sequences"),
2121 Action.PASTE, sequences, 0, alignment.getWidth(), alignment));
2123 // Add any annotations attached to sequences
2124 for (int i = 0; i < sequences.length; i++)
2126 if (sequences[i].getAnnotation() != null)
2128 AlignmentAnnotation newann;
2129 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2131 annotationAdded = true;
2132 newann = sequences[i].getAnnotation()[a];
2133 newann.adjustForAlignment();
2134 newann.padAnnotation(alwidth);
2135 if (newann.graphGroup > -1)
2137 if (newann.graphGroup > -1)
2139 if (newGraphGroups.size() <= newann.graphGroup
2140 || newGraphGroups.get(newann.graphGroup) == null)
2142 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2144 newGraphGroups.add(q, null);
2146 newGraphGroups.set(newann.graphGroup, new Integer(
2149 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2153 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2158 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2165 // propagate alignment changed.
2166 vpRanges.setEndSeq(alignment.getHeight());
2167 if (annotationAdded)
2169 // Duplicate sequence annotation in all views.
2170 AlignmentI[] alview = this.getViewAlignments();
2171 for (int i = 0; i < sequences.length; i++)
2173 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2178 for (int avnum = 0; avnum < alview.length; avnum++)
2180 if (alview[avnum] != alignment)
2182 // duplicate in a view other than the one with input focus
2183 int avwidth = alview[avnum].getWidth() + 1;
2184 // this relies on sann being preserved after we
2185 // modify the sequence's annotation array for each duplication
2186 for (int a = 0; a < sann.length; a++)
2188 AlignmentAnnotation newann = new AlignmentAnnotation(
2190 sequences[i].addAlignmentAnnotation(newann);
2191 newann.padAnnotation(avwidth);
2192 alview[avnum].addAnnotation(newann); // annotation was
2193 // duplicated earlier
2194 // TODO JAL-1145 graphGroups are not updated for sequence
2195 // annotation added to several views. This may cause
2197 alview[avnum].setAnnotationIndex(newann, a);
2202 buildSortByAnnotationScoresMenu();
2204 viewport.firePropertyChange("alignment", null,
2205 alignment.getSequences());
2206 if (alignPanels != null)
2208 for (AlignmentPanel ap : alignPanels)
2210 ap.validateAnnotationDimensions(false);
2215 alignPanel.validateAnnotationDimensions(false);
2221 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2223 String newtitle = new String("Copied sequences");
2225 if (Desktop.jalviewClipboard != null
2226 && Desktop.jalviewClipboard[2] != null)
2228 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2229 for (int[] region : hc)
2231 af.viewport.hideColumns(region[0], region[1]);
2235 // >>>This is a fix for the moment, until a better solution is
2237 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2239 alignPanel.getSeqPanel().seqCanvas
2240 .getFeatureRenderer());
2242 // TODO: maintain provenance of an alignment, rather than just make the
2243 // title a concatenation of operations.
2246 if (title.startsWith("Copied sequences"))
2252 newtitle = newtitle.concat("- from " + title);
2257 newtitle = new String("Pasted sequences");
2260 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2265 } catch (Exception ex)
2267 ex.printStackTrace();
2268 System.out.println("Exception whilst pasting: " + ex);
2269 // could be anything being pasted in here
2275 protected void expand_newalign(ActionEvent e)
2279 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2280 .getAlignment(), -1);
2281 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2283 String newtitle = new String("Flanking alignment");
2285 if (Desktop.jalviewClipboard != null
2286 && Desktop.jalviewClipboard[2] != null)
2288 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2289 for (int region[] : hc)
2291 af.viewport.hideColumns(region[0], region[1]);
2295 // >>>This is a fix for the moment, until a better solution is
2297 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2299 alignPanel.getSeqPanel().seqCanvas
2300 .getFeatureRenderer());
2302 // TODO: maintain provenance of an alignment, rather than just make the
2303 // title a concatenation of operations.
2305 if (title.startsWith("Copied sequences"))
2311 newtitle = newtitle.concat("- from " + title);
2315 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2317 } catch (Exception ex)
2319 ex.printStackTrace();
2320 System.out.println("Exception whilst pasting: " + ex);
2321 // could be anything being pasted in here
2322 } catch (OutOfMemoryError oom)
2324 new OOMWarning("Viewing flanking region of alignment", oom);
2335 protected void cut_actionPerformed(ActionEvent e)
2337 copy_actionPerformed(null);
2338 delete_actionPerformed(null);
2348 protected void delete_actionPerformed(ActionEvent evt)
2351 SequenceGroup sg = viewport.getSelectionGroup();
2358 * If the cut affects all sequences, warn, remove highlighted columns
2360 if (sg.getSize() == viewport.getAlignment().getHeight())
2362 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes()) + 1) == viewport
2363 .getAlignment().getWidth()) ? true : false;
2364 if (isEntireAlignWidth)
2366 int confirm = JvOptionPane.showConfirmDialog(this,
2367 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2368 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2369 JvOptionPane.OK_CANCEL_OPTION);
2371 if (confirm == JvOptionPane.CANCEL_OPTION
2372 || confirm == JvOptionPane.CLOSED_OPTION)
2377 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2378 sg.getEndRes() + 1);
2380 SequenceI[] cut = sg.getSequences()
2381 .toArray(new SequenceI[sg.getSize()]);
2383 addHistoryItem(new EditCommand(
2384 MessageManager.getString("label.cut_sequences"), Action.CUT,
2385 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2386 viewport.getAlignment()));
2388 viewport.setSelectionGroup(null);
2389 viewport.sendSelection();
2390 viewport.getAlignment().deleteGroup(sg);
2392 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2394 if (viewport.getAlignment().getHeight() < 1)
2398 this.setClosed(true);
2399 } catch (Exception ex)
2412 protected void deleteGroups_actionPerformed(ActionEvent e)
2414 if (avc.deleteGroups())
2416 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2417 alignPanel.updateAnnotation();
2418 alignPanel.paintAlignment(true);
2429 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2431 SequenceGroup sg = new SequenceGroup();
2433 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2435 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2438 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2439 viewport.setSelectionGroup(sg);
2440 viewport.sendSelection();
2441 // JAL-2034 - should delegate to
2442 // alignPanel to decide if overview needs
2444 alignPanel.paintAlignment(false);
2445 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2455 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2457 if (viewport.cursorMode)
2459 alignPanel.getSeqPanel().keyboardNo1 = null;
2460 alignPanel.getSeqPanel().keyboardNo2 = null;
2462 viewport.setSelectionGroup(null);
2463 viewport.getColumnSelection().clear();
2464 viewport.setSelectionGroup(null);
2465 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2466 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2467 // JAL-2034 - should delegate to
2468 // alignPanel to decide if overview needs
2470 alignPanel.paintAlignment(false);
2471 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2472 viewport.sendSelection();
2482 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2484 SequenceGroup sg = viewport.getSelectionGroup();
2488 selectAllSequenceMenuItem_actionPerformed(null);
2493 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2495 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2497 // JAL-2034 - should delegate to
2498 // alignPanel to decide if overview needs
2501 alignPanel.paintAlignment(true);
2502 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2503 viewport.sendSelection();
2507 public void invertColSel_actionPerformed(ActionEvent e)
2509 viewport.invertColumnSelection();
2510 alignPanel.paintAlignment(true);
2511 viewport.sendSelection();
2521 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2523 trimAlignment(true);
2533 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2535 trimAlignment(false);
2538 void trimAlignment(boolean trimLeft)
2540 ColumnSelection colSel = viewport.getColumnSelection();
2543 if (!colSel.isEmpty())
2547 column = colSel.getMin();
2551 column = colSel.getMax();
2555 if (viewport.getSelectionGroup() != null)
2557 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2558 viewport.getHiddenRepSequences());
2562 seqs = viewport.getAlignment().getSequencesArray();
2565 TrimRegionCommand trimRegion;
2568 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2569 column, viewport.getAlignment());
2570 vpRanges.setStartRes(0);
2574 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2575 column, viewport.getAlignment());
2578 statusBar.setText(MessageManager.formatMessage(
2579 "label.removed_columns",
2580 new String[] { Integer.valueOf(trimRegion.getSize())
2583 addHistoryItem(trimRegion);
2585 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2587 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2588 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2590 viewport.getAlignment().deleteGroup(sg);
2594 viewport.firePropertyChange("alignment", null, viewport
2595 .getAlignment().getSequences());
2606 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2608 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2611 if (viewport.getSelectionGroup() != null)
2613 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2614 viewport.getHiddenRepSequences());
2615 start = viewport.getSelectionGroup().getStartRes();
2616 end = viewport.getSelectionGroup().getEndRes();
2620 seqs = viewport.getAlignment().getSequencesArray();
2623 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2624 "Remove Gapped Columns", seqs, start, end,
2625 viewport.getAlignment());
2627 addHistoryItem(removeGapCols);
2629 statusBar.setText(MessageManager.formatMessage(
2630 "label.removed_empty_columns",
2631 new Object[] { Integer.valueOf(removeGapCols.getSize())
2634 // This is to maintain viewport position on first residue
2635 // of first sequence
2636 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2637 int startRes = seq.findPosition(vpRanges.getStartRes());
2638 // ShiftList shifts;
2639 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2640 // edit.alColumnChanges=shifts.getInverse();
2641 // if (viewport.hasHiddenColumns)
2642 // viewport.getColumnSelection().compensateForEdits(shifts);
2643 vpRanges.setStartRes(seq.findIndex(startRes) - 1);
2644 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2656 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2658 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2661 if (viewport.getSelectionGroup() != null)
2663 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2664 viewport.getHiddenRepSequences());
2665 start = viewport.getSelectionGroup().getStartRes();
2666 end = viewport.getSelectionGroup().getEndRes();
2670 seqs = viewport.getAlignment().getSequencesArray();
2673 // This is to maintain viewport position on first residue
2674 // of first sequence
2675 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2676 int startRes = seq.findPosition(vpRanges.getStartRes());
2678 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2679 viewport.getAlignment()));
2681 vpRanges.setStartRes(seq.findIndex(startRes) - 1);
2683 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2695 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2697 viewport.setPadGaps(padGapsMenuitem.isSelected());
2698 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2709 public void findMenuItem_actionPerformed(ActionEvent e)
2715 * Create a new view of the current alignment.
2718 public void newView_actionPerformed(ActionEvent e)
2720 newView(null, true);
2724 * Creates and shows a new view of the current alignment.
2727 * title of newly created view; if null, one will be generated
2728 * @param copyAnnotation
2729 * if true then duplicate all annnotation, groups and settings
2730 * @return new alignment panel, already displayed.
2732 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2735 * Create a new AlignmentPanel (with its own, new Viewport)
2737 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2739 if (!copyAnnotation)
2742 * remove all groups and annotation except for the automatic stuff
2744 newap.av.getAlignment().deleteAllGroups();
2745 newap.av.getAlignment().deleteAllAnnotations(false);
2748 newap.av.setGatherViewsHere(false);
2750 if (viewport.viewName == null)
2752 viewport.viewName = MessageManager
2753 .getString("label.view_name_original");
2757 * Views share the same edits undo and redo stacks
2759 newap.av.setHistoryList(viewport.getHistoryList());
2760 newap.av.setRedoList(viewport.getRedoList());
2763 * Views share the same mappings; need to deregister any new mappings
2764 * created by copyAlignPanel, and register the new reference to the shared
2767 newap.av.replaceMappings(viewport.getAlignment());
2769 newap.av.viewName = getNewViewName(viewTitle);
2771 addAlignmentPanel(newap, true);
2772 newap.alignmentChanged();
2774 if (alignPanels.size() == 2)
2776 viewport.setGatherViewsHere(true);
2778 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2783 * Make a new name for the view, ensuring it is unique within the current
2784 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2785 * these now use viewId. Unique view names are still desirable for usability.)
2790 protected String getNewViewName(String viewTitle)
2792 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2793 boolean addFirstIndex = false;
2794 if (viewTitle == null || viewTitle.trim().length() == 0)
2796 viewTitle = MessageManager.getString("action.view");
2797 addFirstIndex = true;
2801 index = 1;// we count from 1 if given a specific name
2803 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2805 List<Component> comps = PaintRefresher.components.get(viewport
2806 .getSequenceSetId());
2808 List<String> existingNames = getExistingViewNames(comps);
2810 while (existingNames.contains(newViewName))
2812 newViewName = viewTitle + " " + (++index);
2818 * Returns a list of distinct view names found in the given list of
2819 * components. View names are held on the viewport of an AlignmentPanel.
2824 protected List<String> getExistingViewNames(List<Component> comps)
2826 List<String> existingNames = new ArrayList<String>();
2827 for (Component comp : comps)
2829 if (comp instanceof AlignmentPanel)
2831 AlignmentPanel ap = (AlignmentPanel) comp;
2832 if (!existingNames.contains(ap.av.viewName))
2834 existingNames.add(ap.av.viewName);
2838 return existingNames;
2842 * Explode tabbed views into separate windows.
2845 public void expandViews_actionPerformed(ActionEvent e)
2847 Desktop.explodeViews(this);
2851 * Gather views in separate windows back into a tabbed presentation.
2854 public void gatherViews_actionPerformed(ActionEvent e)
2856 Desktop.instance.gatherViews(this);
2866 public void font_actionPerformed(ActionEvent e)
2868 new FontChooser(alignPanel);
2878 protected void seqLimit_actionPerformed(ActionEvent e)
2880 viewport.setShowJVSuffix(seqLimits.isSelected());
2882 alignPanel.getIdPanel().getIdCanvas()
2883 .setPreferredSize(alignPanel.calculateIdWidth());
2884 alignPanel.paintAlignment(true);
2888 public void idRightAlign_actionPerformed(ActionEvent e)
2890 viewport.setRightAlignIds(idRightAlign.isSelected());
2891 alignPanel.paintAlignment(true);
2895 public void centreColumnLabels_actionPerformed(ActionEvent e)
2897 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2898 alignPanel.paintAlignment(true);
2904 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2907 protected void followHighlight_actionPerformed()
2910 * Set the 'follow' flag on the Viewport (and scroll to position if now
2913 final boolean state = this.followHighlightMenuItem.getState();
2914 viewport.setFollowHighlight(state);
2917 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2928 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2930 viewport.setColourText(colourTextMenuItem.isSelected());
2931 alignPanel.paintAlignment(true);
2941 public void wrapMenuItem_actionPerformed(ActionEvent e)
2943 scaleAbove.setVisible(wrapMenuItem.isSelected());
2944 scaleLeft.setVisible(wrapMenuItem.isSelected());
2945 scaleRight.setVisible(wrapMenuItem.isSelected());
2946 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2947 alignPanel.updateLayout();
2951 public void showAllSeqs_actionPerformed(ActionEvent e)
2953 viewport.showAllHiddenSeqs();
2957 public void showAllColumns_actionPerformed(ActionEvent e)
2959 viewport.showAllHiddenColumns();
2961 viewport.sendSelection();
2965 public void hideSelSequences_actionPerformed(ActionEvent e)
2967 viewport.hideAllSelectedSeqs();
2968 // alignPanel.paintAlignment(true);
2972 * called by key handler and the hide all/show all menu items
2977 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2980 boolean hide = false;
2981 SequenceGroup sg = viewport.getSelectionGroup();
2982 if (!toggleSeqs && !toggleCols)
2984 // Hide everything by the current selection - this is a hack - we do the
2985 // invert and then hide
2986 // first check that there will be visible columns after the invert.
2987 if (viewport.hasSelectedColumns()
2988 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2991 // now invert the sequence set, if required - empty selection implies
2992 // that no hiding is required.
2995 invertSequenceMenuItem_actionPerformed(null);
2996 sg = viewport.getSelectionGroup();
3000 viewport.expandColSelection(sg, true);
3001 // finally invert the column selection and get the new sequence
3003 invertColSel_actionPerformed(null);
3010 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3012 hideSelSequences_actionPerformed(null);
3015 else if (!(toggleCols && viewport.hasSelectedColumns()))
3017 showAllSeqs_actionPerformed(null);
3023 if (viewport.hasSelectedColumns())
3025 hideSelColumns_actionPerformed(null);
3028 viewport.setSelectionGroup(sg);
3033 showAllColumns_actionPerformed(null);
3042 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3043 * event.ActionEvent)
3046 public void hideAllButSelection_actionPerformed(ActionEvent e)
3048 toggleHiddenRegions(false, false);
3049 viewport.sendSelection();
3056 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3060 public void hideAllSelection_actionPerformed(ActionEvent e)
3062 SequenceGroup sg = viewport.getSelectionGroup();
3063 viewport.expandColSelection(sg, false);
3064 viewport.hideAllSelectedSeqs();
3065 viewport.hideSelectedColumns();
3066 alignPanel.paintAlignment(true);
3067 viewport.sendSelection();
3074 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3078 public void showAllhidden_actionPerformed(ActionEvent e)
3080 viewport.showAllHiddenColumns();
3081 viewport.showAllHiddenSeqs();
3082 alignPanel.paintAlignment(true);
3083 viewport.sendSelection();
3087 public void hideSelColumns_actionPerformed(ActionEvent e)
3089 viewport.hideSelectedColumns();
3090 alignPanel.paintAlignment(true);
3091 viewport.sendSelection();
3095 public void hiddenMarkers_actionPerformed(ActionEvent e)
3097 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3108 protected void scaleAbove_actionPerformed(ActionEvent e)
3110 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3111 alignPanel.paintAlignment(true);
3121 protected void scaleLeft_actionPerformed(ActionEvent e)
3123 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3124 alignPanel.paintAlignment(true);
3134 protected void scaleRight_actionPerformed(ActionEvent e)
3136 viewport.setScaleRightWrapped(scaleRight.isSelected());
3137 alignPanel.paintAlignment(true);
3147 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3149 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3150 alignPanel.paintAlignment(true);
3160 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3162 viewport.setShowText(viewTextMenuItem.isSelected());
3163 alignPanel.paintAlignment(true);
3173 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3175 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3176 alignPanel.paintAlignment(true);
3179 public FeatureSettings featureSettings;
3182 public FeatureSettingsControllerI getFeatureSettingsUI()
3184 return featureSettings;
3188 public void featureSettings_actionPerformed(ActionEvent e)
3190 if (featureSettings != null)
3192 featureSettings.close();
3193 featureSettings = null;
3195 if (!showSeqFeatures.isSelected())
3197 // make sure features are actually displayed
3198 showSeqFeatures.setSelected(true);
3199 showSeqFeatures_actionPerformed(null);
3201 featureSettings = new FeatureSettings(this);
3205 * Set or clear 'Show Sequence Features'
3211 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3213 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3214 alignPanel.paintAlignment(true);
3215 if (alignPanel.getOverviewPanel() != null)
3217 alignPanel.getOverviewPanel().updateOverviewImage();
3222 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3223 * the annotations panel as a whole.
3225 * The options to show/hide all annotations should be enabled when the panel
3226 * is shown, and disabled when the panel is hidden.
3231 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3233 final boolean setVisible = annotationPanelMenuItem.isSelected();
3234 viewport.setShowAnnotation(setVisible);
3235 this.showAllSeqAnnotations.setEnabled(setVisible);
3236 this.hideAllSeqAnnotations.setEnabled(setVisible);
3237 this.showAllAlAnnotations.setEnabled(setVisible);
3238 this.hideAllAlAnnotations.setEnabled(setVisible);
3239 alignPanel.updateLayout();
3243 public void alignmentProperties()
3245 JEditorPane editPane = new JEditorPane("text/html", "");
3246 editPane.setEditable(false);
3247 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3249 editPane.setText(MessageManager.formatMessage("label.html_content",
3250 new Object[] { contents.toString() }));
3251 JInternalFrame frame = new JInternalFrame();
3252 frame.getContentPane().add(new JScrollPane(editPane));
3254 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3255 "label.alignment_properties", new Object[] { getTitle() }),
3266 public void overviewMenuItem_actionPerformed(ActionEvent e)
3268 if (alignPanel.overviewPanel != null)
3273 JInternalFrame frame = new JInternalFrame();
3274 OverviewPanel overview = new OverviewPanel(alignPanel);
3275 frame.setContentPane(overview);
3276 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3277 "label.overview_params", new Object[] { this.getTitle() }),
3278 frame.getWidth(), frame.getHeight());
3280 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3281 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3284 public void internalFrameClosed(
3285 javax.swing.event.InternalFrameEvent evt)
3287 alignPanel.setOverviewPanel(null);
3291 alignPanel.setOverviewPanel(overview);
3295 public void textColour_actionPerformed()
3297 new TextColourChooser().chooseColour(alignPanel, null);
3301 * public void covariationColour_actionPerformed() {
3303 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3307 public void annotationColour_actionPerformed()
3309 new AnnotationColourChooser(viewport, alignPanel);
3313 public void annotationColumn_actionPerformed(ActionEvent e)
3315 new AnnotationColumnChooser(viewport, alignPanel);
3319 * Action on the user checking or unchecking the option to apply the selected
3320 * colour scheme to all groups. If unchecked, groups may have their own
3321 * independent colour schemes.
3326 public void applyToAllGroups_actionPerformed(boolean selected)
3328 viewport.setColourAppliesToAllGroups(selected);
3332 * Action on user selecting a colour from the colour menu
3335 * the name (not the menu item label!) of the colour scheme
3338 public void changeColour_actionPerformed(String name)
3341 * 'User Defined' opens a panel to configure or load a
3342 * user-defined colour scheme
3344 if (ResidueColourScheme.USER_DEFINED.equals(name))
3346 new UserDefinedColours(alignPanel, null);
3351 * otherwise set the chosen colour scheme (or null for 'None')
3353 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3354 viewport.getAlignment(), viewport.getHiddenRepSequences());
3359 * Actions on setting or changing the alignment colour scheme
3364 public void changeColour(ColourSchemeI cs)
3366 // TODO: pull up to controller method
3369 ColourMenuHelper.setColourSelected(colourMenu, cs.getSchemeName());
3372 viewport.setGlobalColourScheme(cs);
3374 alignPanel.paintAlignment(true);
3378 * Show the PID threshold slider panel
3381 protected void modifyPID_actionPerformed()
3383 SliderPanel.setPIDSliderSource(alignPanel,
3384 viewport.getResidueShading(), alignPanel.getViewName());
3385 SliderPanel.showPIDSlider();
3389 * Show the Conservation slider panel
3392 protected void modifyConservation_actionPerformed()
3394 SliderPanel.setConservationSlider(alignPanel,
3395 viewport.getResidueShading(), alignPanel.getViewName());
3396 SliderPanel.showConservationSlider();
3400 * Action on selecting or deselecting (Colour) By Conservation
3403 public void conservationMenuItem_actionPerformed(boolean selected)
3405 modifyConservation.setEnabled(selected);
3406 viewport.setConservationSelected(selected);
3407 viewport.getResidueShading().setConservationApplied(selected);
3409 changeColour(viewport.getGlobalColourScheme());
3412 modifyConservation_actionPerformed();
3416 SliderPanel.hideConservationSlider();
3421 * Action on selecting or deselecting (Colour) Above PID Threshold
3424 public void abovePIDThreshold_actionPerformed(boolean selected)
3426 modifyPID.setEnabled(selected);
3427 viewport.setAbovePIDThreshold(selected);
3430 viewport.getResidueShading().setThreshold(0,
3431 viewport.isIgnoreGapsConsensus());
3434 changeColour(viewport.getGlobalColourScheme());
3437 modifyPID_actionPerformed();
3441 SliderPanel.hidePIDSlider();
3452 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3454 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3455 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3456 .getAlignment().getSequenceAt(0));
3457 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3458 viewport.getAlignment()));
3459 alignPanel.paintAlignment(true);
3469 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3471 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3472 AlignmentSorter.sortByID(viewport.getAlignment());
3473 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3474 viewport.getAlignment()));
3475 alignPanel.paintAlignment(true);
3485 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3487 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3488 AlignmentSorter.sortByLength(viewport.getAlignment());
3489 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3490 viewport.getAlignment()));
3491 alignPanel.paintAlignment(true);
3501 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3503 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3504 AlignmentSorter.sortByGroup(viewport.getAlignment());
3505 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3506 viewport.getAlignment()));
3508 alignPanel.paintAlignment(true);
3518 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3520 new RedundancyPanel(alignPanel, this);
3530 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3532 if ((viewport.getSelectionGroup() == null)
3533 || (viewport.getSelectionGroup().getSize() < 2))
3535 JvOptionPane.showInternalMessageDialog(this, MessageManager
3536 .getString("label.you_must_select_least_two_sequences"),
3537 MessageManager.getString("label.invalid_selection"),
3538 JvOptionPane.WARNING_MESSAGE);
3542 JInternalFrame frame = new JInternalFrame();
3543 frame.setContentPane(new PairwiseAlignPanel(viewport));
3544 Desktop.addInternalFrame(frame,
3545 MessageManager.getString("action.pairwise_alignment"), 600,
3557 public void PCAMenuItem_actionPerformed(ActionEvent e)
3559 if (((viewport.getSelectionGroup() != null)
3560 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3561 .getSelectionGroup().getSize() > 0))
3562 || (viewport.getAlignment().getHeight() < 4))
3565 .showInternalMessageDialog(
3568 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3570 .getString("label.sequence_selection_insufficient"),
3571 JvOptionPane.WARNING_MESSAGE);
3576 new PCAPanel(alignPanel);
3580 public void autoCalculate_actionPerformed(ActionEvent e)
3582 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3583 if (viewport.autoCalculateConsensus)
3585 viewport.firePropertyChange("alignment", null, viewport
3586 .getAlignment().getSequences());
3591 public void sortByTreeOption_actionPerformed(ActionEvent e)
3593 viewport.sortByTree = sortByTree.isSelected();
3597 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3599 viewport.followSelection = listenToViewSelections.isSelected();
3603 * Constructs a tree panel and adds it to the desktop
3606 * tree type (NJ or AV)
3608 * distance or similarity score model used to compute the tree
3610 * parameters for the distance or similarity calculation
3612 void newTreePanel(String type, ScoreModelI sm, SimilarityParamsI options)
3614 String frameTitle = "";
3617 if (viewport.getSelectionGroup() != null
3618 && viewport.getSelectionGroup().getSize() > 0)
3620 if (viewport.getSelectionGroup().getSize() < 3)
3626 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3628 .getString("label.not_enough_sequences"),
3629 JvOptionPane.WARNING_MESSAGE);
3633 SequenceGroup sg = viewport.getSelectionGroup();
3635 /* Decide if the selection is a column region */
3636 for (SequenceI _s : sg.getSequences())
3638 if (_s.getLength() < sg.getEndRes())
3644 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3646 .getString("label.sequences_selection_not_aligned"),
3647 JvOptionPane.WARNING_MESSAGE);
3653 tp = new TreePanel(alignPanel, type, sm, options);
3654 frameTitle = tp.getPanelTitle() + " on region";
3658 // are the visible sequences aligned?
3659 if (!viewport.getAlignment().isAligned(false))
3665 .getString("label.sequences_must_be_aligned_before_creating_tree"),
3667 .getString("label.sequences_not_aligned"),
3668 JvOptionPane.WARNING_MESSAGE);
3673 if (viewport.getAlignment().getHeight() < 2)
3678 tp = new TreePanel(alignPanel, type, sm, options);
3679 frameTitle = tp.getPanelTitle();
3682 frameTitle += " from ";
3684 if (viewport.viewName != null)
3686 frameTitle += viewport.viewName + " of ";
3689 frameTitle += this.title;
3691 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3702 public void addSortByOrderMenuItem(String title,
3703 final AlignmentOrder order)
3705 final JMenuItem item = new JMenuItem(MessageManager.formatMessage(
3706 "action.by_title_param", new Object[] { title }));
3708 item.addActionListener(new java.awt.event.ActionListener()
3711 public void actionPerformed(ActionEvent e)
3713 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3715 // TODO: JBPNote - have to map order entries to curent SequenceI
3717 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3719 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
3722 alignPanel.paintAlignment(true);
3728 * Add a new sort by annotation score menu item
3731 * the menu to add the option to
3733 * the label used to retrieve scores for each sequence on the
3736 public void addSortByAnnotScoreMenuItem(JMenu sort,
3737 final String scoreLabel)
3739 final JMenuItem item = new JMenuItem(scoreLabel);
3741 item.addActionListener(new java.awt.event.ActionListener()
3744 public void actionPerformed(ActionEvent e)
3746 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3747 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3748 viewport.getAlignment());// ,viewport.getSelectionGroup());
3749 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3750 viewport.getAlignment()));
3751 alignPanel.paintAlignment(true);
3757 * last hash for alignment's annotation array - used to minimise cost of
3760 protected int _annotationScoreVectorHash;
3763 * search the alignment and rebuild the sort by annotation score submenu the
3764 * last alignment annotation vector hash is stored to minimize cost of
3765 * rebuilding in subsequence calls.
3769 public void buildSortByAnnotationScoresMenu()
3771 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3776 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
3778 sortByAnnotScore.removeAll();
3779 // almost certainly a quicker way to do this - but we keep it simple
3780 Hashtable scoreSorts = new Hashtable();
3781 AlignmentAnnotation aann[];
3782 for (SequenceI sqa : viewport.getAlignment().getSequences())
3784 aann = sqa.getAnnotation();
3785 for (int i = 0; aann != null && i < aann.length; i++)
3787 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3789 scoreSorts.put(aann[i].label, aann[i].label);
3793 Enumeration labels = scoreSorts.keys();
3794 while (labels.hasMoreElements())
3796 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3797 (String) labels.nextElement());
3799 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3802 _annotationScoreVectorHash = viewport.getAlignment()
3803 .getAlignmentAnnotation().hashCode();
3808 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3809 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3810 * call. Listeners are added to remove the menu item when the treePanel is
3811 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3815 public void buildTreeSortMenu()
3817 sortByTreeMenu.removeAll();
3819 List<Component> comps = PaintRefresher.components.get(viewport
3820 .getSequenceSetId());
3821 List<TreePanel> treePanels = new ArrayList<TreePanel>();
3822 for (Component comp : comps)
3824 if (comp instanceof TreePanel)
3826 treePanels.add((TreePanel) comp);
3830 if (treePanels.size() < 1)
3832 sortByTreeMenu.setVisible(false);
3836 sortByTreeMenu.setVisible(true);
3838 for (final TreePanel tp : treePanels)
3840 final JMenuItem item = new JMenuItem(tp.getTitle());
3841 item.addActionListener(new java.awt.event.ActionListener()
3844 public void actionPerformed(ActionEvent e)
3846 tp.sortByTree_actionPerformed();
3847 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3852 sortByTreeMenu.add(item);
3856 public boolean sortBy(AlignmentOrder alorder, String undoname)
3858 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3859 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3860 if (undoname != null)
3862 addHistoryItem(new OrderCommand(undoname, oldOrder,
3863 viewport.getAlignment()));
3865 alignPanel.paintAlignment(true);
3870 * Work out whether the whole set of sequences or just the selected set will
3871 * be submitted for multiple alignment.
3874 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3876 // Now, check we have enough sequences
3877 AlignmentView msa = null;
3879 if ((viewport.getSelectionGroup() != null)
3880 && (viewport.getSelectionGroup().getSize() > 1))
3882 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3883 // some common interface!
3885 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3886 * SequenceI[sz = seqs.getSize(false)];
3888 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3889 * seqs.getSequenceAt(i); }
3891 msa = viewport.getAlignmentView(true);
3893 else if (viewport.getSelectionGroup() != null
3894 && viewport.getSelectionGroup().getSize() == 1)
3896 int option = JvOptionPane.showConfirmDialog(this,
3897 MessageManager.getString("warn.oneseq_msainput_selection"),
3898 MessageManager.getString("label.invalid_selection"),
3899 JvOptionPane.OK_CANCEL_OPTION);
3900 if (option == JvOptionPane.OK_OPTION)
3902 msa = viewport.getAlignmentView(false);
3907 msa = viewport.getAlignmentView(false);
3913 * Decides what is submitted to a secondary structure prediction service: the
3914 * first sequence in the alignment, or in the current selection, or, if the
3915 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3916 * region or the whole alignment. (where the first sequence in the set is the
3917 * one that the prediction will be for).
3919 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3921 AlignmentView seqs = null;
3923 if ((viewport.getSelectionGroup() != null)
3924 && (viewport.getSelectionGroup().getSize() > 0))
3926 seqs = viewport.getAlignmentView(true);
3930 seqs = viewport.getAlignmentView(false);
3932 // limit sequences - JBPNote in future - could spawn multiple prediction
3934 // TODO: viewport.getAlignment().isAligned is a global state - the local
3935 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3936 if (!viewport.getAlignment().isAligned(false))
3938 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3939 // TODO: if seqs.getSequences().length>1 then should really have warned
3953 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3955 // Pick the tree file
3956 JalviewFileChooser chooser = new JalviewFileChooser(
3957 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3958 chooser.setFileView(new JalviewFileView());
3959 chooser.setDialogTitle(MessageManager
3960 .getString("label.select_newick_like_tree_file"));
3961 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
3963 int value = chooser.showOpenDialog(null);
3965 if (value == JalviewFileChooser.APPROVE_OPTION)
3967 String filePath = chooser.getSelectedFile().getPath();
3968 Cache.setProperty("LAST_DIRECTORY", filePath);
3969 NewickFile fin = null;
3972 fin = new NewickFile(filePath, DataSourceType.FILE);
3973 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
3974 } catch (Exception ex)
3981 .getString("label.problem_reading_tree_file"),
3982 JvOptionPane.WARNING_MESSAGE);
3983 ex.printStackTrace();
3985 if (fin != null && fin.hasWarningMessage())
3987 JvOptionPane.showMessageDialog(Desktop.desktop, fin
3988 .getWarningMessage(), MessageManager
3989 .getString("label.possible_problem_with_tree_file"),
3990 JvOptionPane.WARNING_MESSAGE);
3995 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
3997 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4000 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4001 int h, int x, int y)
4003 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4007 * Add a treeviewer for the tree extracted from a Newick file object to the
4008 * current alignment view
4015 * Associated alignment input data (or null)
4024 * @return TreePanel handle
4026 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4027 AlignmentView input, int w, int h, int x, int y)
4029 TreePanel tp = null;
4035 if (nf.getTree() != null)
4037 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4043 tp.setLocation(x, y);
4046 Desktop.addInternalFrame(tp, treeTitle, w, h);
4048 } catch (Exception ex)
4050 ex.printStackTrace();
4056 private boolean buildingMenu = false;
4059 * Generates menu items and listener event actions for web service clients
4062 public void BuildWebServiceMenu()
4064 while (buildingMenu)
4068 System.err.println("Waiting for building menu to finish.");
4070 } catch (Exception e)
4074 final AlignFrame me = this;
4075 buildingMenu = true;
4076 new Thread(new Runnable()
4081 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4084 // System.err.println("Building ws menu again "
4085 // + Thread.currentThread());
4086 // TODO: add support for context dependent disabling of services based
4088 // alignment and current selection
4089 // TODO: add additional serviceHandle parameter to specify abstract
4091 // class independently of AbstractName
4092 // TODO: add in rediscovery GUI function to restart discoverer
4093 // TODO: group services by location as well as function and/or
4095 // object broker mechanism.
4096 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4097 final IProgressIndicator af = me;
4100 * do not i18n these strings - they are hard-coded in class
4101 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4102 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4104 final JMenu msawsmenu = new JMenu("Alignment");
4105 final JMenu secstrmenu = new JMenu(
4106 "Secondary Structure Prediction");
4107 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4108 final JMenu analymenu = new JMenu("Analysis");
4109 final JMenu dismenu = new JMenu("Protein Disorder");
4110 // JAL-940 - only show secondary structure prediction services from
4111 // the legacy server
4112 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4114 Discoverer.services != null && (Discoverer.services.size() > 0))
4116 // TODO: refactor to allow list of AbstractName/Handler bindings to
4118 // stored or retrieved from elsewhere
4119 // No MSAWS used any more:
4120 // Vector msaws = null; // (Vector)
4121 // Discoverer.services.get("MsaWS");
4122 Vector secstrpr = (Vector) Discoverer.services
4124 if (secstrpr != null)
4126 // Add any secondary structure prediction services
4127 for (int i = 0, j = secstrpr.size(); i < j; i++)
4129 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4131 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4132 .getServiceClient(sh);
4133 int p = secstrmenu.getItemCount();
4134 impl.attachWSMenuEntry(secstrmenu, me);
4135 int q = secstrmenu.getItemCount();
4136 for (int litm = p; litm < q; litm++)
4138 legacyItems.add(secstrmenu.getItem(litm));
4144 // Add all submenus in the order they should appear on the web
4146 wsmenu.add(msawsmenu);
4147 wsmenu.add(secstrmenu);
4148 wsmenu.add(dismenu);
4149 wsmenu.add(analymenu);
4150 // No search services yet
4151 // wsmenu.add(seqsrchmenu);
4153 javax.swing.SwingUtilities.invokeLater(new Runnable()
4160 webService.removeAll();
4161 // first, add discovered services onto the webservices menu
4162 if (wsmenu.size() > 0)
4164 for (int i = 0, j = wsmenu.size(); i < j; i++)
4166 webService.add(wsmenu.get(i));
4171 webService.add(me.webServiceNoServices);
4173 // TODO: move into separate menu builder class.
4174 boolean new_sspred = false;
4175 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4177 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4178 if (jws2servs != null)
4180 if (jws2servs.hasServices())
4182 jws2servs.attachWSMenuEntry(webService, me);
4183 for (Jws2Instance sv : jws2servs.getServices())
4185 if (sv.description.toLowerCase().contains("jpred"))
4187 for (JMenuItem jmi : legacyItems)
4189 jmi.setVisible(false);
4195 if (jws2servs.isRunning())
4197 JMenuItem tm = new JMenuItem(
4198 "Still discovering JABA Services");
4199 tm.setEnabled(false);
4204 build_urlServiceMenu(me.webService);
4205 build_fetchdbmenu(webService);
4206 for (JMenu item : wsmenu)
4208 if (item.getItemCount() == 0)
4210 item.setEnabled(false);
4214 item.setEnabled(true);
4217 } catch (Exception e)
4220 .debug("Exception during web service menu building process.",
4225 } catch (Exception e)
4228 buildingMenu = false;
4235 * construct any groupURL type service menu entries.
4239 private void build_urlServiceMenu(JMenu webService)
4241 // TODO: remove this code when 2.7 is released
4242 // DEBUG - alignmentView
4244 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4245 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4247 * @Override public void actionPerformed(ActionEvent e) {
4248 * jalview.datamodel.AlignmentView
4249 * .testSelectionViews(af.viewport.getAlignment(),
4250 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4252 * }); webService.add(testAlView);
4254 // TODO: refactor to RestClient discoverer and merge menu entries for
4255 // rest-style services with other types of analysis/calculation service
4256 // SHmmr test client - still being implemented.
4257 // DEBUG - alignmentView
4259 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4262 client.attachWSMenuEntry(
4263 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4269 * Searches the alignment sequences for xRefs and builds the Show
4270 * Cross-References menu (formerly called Show Products), with database
4271 * sources for which cross-references are found (protein sources for a
4272 * nucleotide alignment and vice versa)
4274 * @return true if Show Cross-references menu should be enabled
4276 public boolean canShowProducts()
4278 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4279 AlignmentI dataset = viewport.getAlignment().getDataset();
4281 showProducts.removeAll();
4282 final boolean dna = viewport.getAlignment().isNucleotide();
4284 if (seqs == null || seqs.length == 0)
4286 // nothing to see here.
4290 boolean showp = false;
4293 List<String> ptypes = new CrossRef(seqs, dataset)
4294 .findXrefSourcesForSequences(dna);
4296 for (final String source : ptypes)
4299 final AlignFrame af = this;
4300 JMenuItem xtype = new JMenuItem(source);
4301 xtype.addActionListener(new ActionListener()
4304 public void actionPerformed(ActionEvent e)
4306 showProductsFor(af.viewport.getSequenceSelection(), dna, source);
4309 showProducts.add(xtype);
4311 showProducts.setVisible(showp);
4312 showProducts.setEnabled(showp);
4313 } catch (Exception e)
4316 .warn("canShowProducts threw an exception - please report to help@jalview.org",
4324 * Finds and displays cross-references for the selected sequences (protein
4325 * products for nucleotide sequences, dna coding sequences for peptides).
4328 * the sequences to show cross-references for
4330 * true if from a nucleotide alignment (so showing proteins)
4332 * the database to show cross-references for
4334 protected void showProductsFor(final SequenceI[] sel,
4335 final boolean _odna, final String source)
4337 new Thread(CrossRefAction.showProductsFor(sel, _odna, source, this))
4342 * Construct and display a new frame containing the translation of this
4343 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4346 public void showTranslation_actionPerformed(ActionEvent e)
4348 AlignmentI al = null;
4351 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4353 al = dna.translateCdna();
4354 } catch (Exception ex)
4356 jalview.bin.Cache.log.error(
4357 "Exception during translation. Please report this !", ex);
4358 final String msg = MessageManager
4359 .getString("label.error_when_translating_sequences_submit_bug_report");
4360 final String errorTitle = MessageManager
4361 .getString("label.implementation_error")
4362 + MessageManager.getString("label.translation_failed");
4363 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4364 JvOptionPane.ERROR_MESSAGE);
4367 if (al == null || al.getHeight() == 0)
4369 final String msg = MessageManager
4370 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4371 final String errorTitle = MessageManager
4372 .getString("label.translation_failed");
4373 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4374 JvOptionPane.WARNING_MESSAGE);
4378 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4379 af.setFileFormat(this.currentFileFormat);
4380 final String newTitle = MessageManager.formatMessage(
4381 "label.translation_of_params",
4382 new Object[] { this.getTitle() });
4383 af.setTitle(newTitle);
4384 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4386 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4387 viewport.openSplitFrame(af, new Alignment(seqs));
4391 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4398 * Set the file format
4402 public void setFileFormat(FileFormatI format)
4404 this.currentFileFormat = format;
4408 * Try to load a features file onto the alignment.
4411 * contents or path to retrieve file
4413 * access mode of file (see jalview.io.AlignFile)
4414 * @return true if features file was parsed correctly.
4416 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4418 return avc.parseFeaturesFile(file, sourceType,
4419 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4424 public void refreshFeatureUI(boolean enableIfNecessary)
4426 // note - currently this is only still here rather than in the controller
4427 // because of the featureSettings hard reference that is yet to be
4429 if (enableIfNecessary)
4431 viewport.setShowSequenceFeatures(true);
4432 showSeqFeatures.setSelected(true);
4438 public void dragEnter(DropTargetDragEvent evt)
4443 public void dragExit(DropTargetEvent evt)
4448 public void dragOver(DropTargetDragEvent evt)
4453 public void dropActionChanged(DropTargetDragEvent evt)
4458 public void drop(DropTargetDropEvent evt)
4460 // JAL-1552 - acceptDrop required before getTransferable call for
4461 // Java's Transferable for native dnd
4462 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4463 Transferable t = evt.getTransferable();
4464 List<String> files = new ArrayList<String>();
4465 List<DataSourceType> protocols = new ArrayList<DataSourceType>();
4469 Desktop.transferFromDropTarget(files, protocols, evt, t);
4470 } catch (Exception e)
4472 e.printStackTrace();
4478 // check to see if any of these files have names matching sequences in
4480 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4481 .getAlignment().getSequencesArray());
4483 * Object[] { String,SequenceI}
4485 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
4486 ArrayList<String> filesnotmatched = new ArrayList<String>();
4487 for (int i = 0; i < files.size(); i++)
4489 String file = files.get(i).toString();
4491 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4492 if (protocol == DataSourceType.FILE)
4494 File fl = new File(file);
4495 pdbfn = fl.getName();
4497 else if (protocol == DataSourceType.URL)
4499 URL url = new URL(file);
4500 pdbfn = url.getFile();
4502 if (pdbfn.length() > 0)
4504 // attempt to find a match in the alignment
4505 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4506 int l = 0, c = pdbfn.indexOf(".");
4507 while (mtch == null && c != -1)
4512 } while ((c = pdbfn.indexOf(".", l)) > l);
4515 pdbfn = pdbfn.substring(0, l);
4517 mtch = idm.findAllIdMatches(pdbfn);
4521 FileFormatI type = null;
4524 type = new IdentifyFile().identify(file, protocol);
4525 } catch (Exception ex)
4529 if (type != null && type.isStructureFile())
4531 filesmatched.add(new Object[] { file, protocol, mtch });
4535 // File wasn't named like one of the sequences or wasn't a PDB file.
4536 filesnotmatched.add(file);
4540 if (filesmatched.size() > 0)
4542 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4548 "label.automatically_associate_structure_files_with_sequences_same_name",
4549 new Object[] { Integer
4555 .getString("label.automatically_associate_structure_files_by_name"),
4556 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION)
4559 for (Object[] fm : filesmatched)
4561 // try and associate
4562 // TODO: may want to set a standard ID naming formalism for
4563 // associating PDB files which have no IDs.
4564 for (SequenceI toassoc : (SequenceI[]) fm[2])
4566 PDBEntry pe = new AssociatePdbFileWithSeq()
4567 .associatePdbWithSeq((String) fm[0],
4568 (DataSourceType) fm[1], toassoc, false,
4572 System.err.println("Associated file : "
4573 + ((String) fm[0]) + " with "
4574 + toassoc.getDisplayId(true));
4578 alignPanel.paintAlignment(true);
4582 if (filesnotmatched.size() > 0)
4585 && (Cache.getDefault(
4586 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JvOptionPane
4592 "label.ignore_unmatched_dropped_files_info",
4593 new Object[] { Integer
4600 .getString("label.ignore_unmatched_dropped_files"),
4601 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4605 for (String fn : filesnotmatched)
4607 loadJalviewDataFile(fn, null, null, null);
4611 } catch (Exception ex)
4613 ex.printStackTrace();
4619 * Attempt to load a "dropped" file or URL string, by testing in turn for
4621 * <li>an Annotation file</li>
4622 * <li>a JNet file</li>
4623 * <li>a features file</li>
4624 * <li>else try to interpret as an alignment file</li>
4628 * either a filename or a URL string.
4630 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4631 FileFormatI format, SequenceI assocSeq)
4635 if (sourceType == null)
4637 sourceType = FormatAdapter.checkProtocol(file);
4639 // if the file isn't identified, or not positively identified as some
4640 // other filetype (PFAM is default unidentified alignment file type) then
4641 // try to parse as annotation.
4642 boolean isAnnotation = (format == null || FileFormat.Pfam
4643 .equals(format)) ? new AnnotationFile()
4644 .annotateAlignmentView(viewport, file, sourceType) : false;
4648 // first see if its a T-COFFEE score file
4649 TCoffeeScoreFile tcf = null;
4652 tcf = new TCoffeeScoreFile(file, sourceType);
4655 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4658 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
4659 isAnnotation = true;
4661 .setText(MessageManager
4662 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
4666 // some problem - if no warning its probable that the ID matching
4667 // process didn't work
4671 tcf.getWarningMessage() == null ? MessageManager
4672 .getString("label.check_file_matches_sequence_ids_alignment")
4673 : tcf.getWarningMessage(),
4675 .getString("label.problem_reading_tcoffee_score_file"),
4676 JvOptionPane.WARNING_MESSAGE);
4683 } catch (Exception x)
4686 .debug("Exception when processing data source as T-COFFEE score file",
4692 // try to see if its a JNet 'concise' style annotation file *before*
4694 // try to parse it as a features file
4697 format = new IdentifyFile().identify(file, sourceType);
4699 if (FileFormat.ScoreMatrix == format)
4701 ScoreMatrixFile sm = new ScoreMatrixFile(new FileParse(file,
4704 // todo: i18n this message
4706 .setText(MessageManager.formatMessage(
4707 "label.successfully_loaded_matrix",
4708 sm.getMatrixName()));
4710 else if (FileFormat.Jnet.equals(format))
4712 JPredFile predictions = new JPredFile(file, sourceType);
4713 new JnetAnnotationMaker();
4714 JnetAnnotationMaker.add_annotation(predictions,
4715 viewport.getAlignment(), 0, false);
4716 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
4717 viewport.getAlignment().setSeqrep(repseq);
4718 ColumnSelection cs = new ColumnSelection();
4719 cs.hideInsertionsFor(repseq);
4720 viewport.setColumnSelection(cs);
4721 isAnnotation = true;
4723 // else if (IdentifyFile.FeaturesFile.equals(format))
4724 else if (FileFormat.Features.equals(format))
4726 if (parseFeaturesFile(file, sourceType))
4728 alignPanel.paintAlignment(true);
4733 new FileLoader().LoadFile(viewport, file, sourceType, format);
4740 alignPanel.adjustAnnotationHeight();
4741 viewport.updateSequenceIdColours();
4742 buildSortByAnnotationScoresMenu();
4743 alignPanel.paintAlignment(true);
4745 } catch (Exception ex)
4747 ex.printStackTrace();
4748 } catch (OutOfMemoryError oom)
4753 } catch (Exception x)
4758 + (sourceType != null ? (sourceType == DataSourceType.PASTE ? "from clipboard."
4759 : "using " + sourceType + " from " + file)
4761 + (format != null ? "(parsing as '" + format
4762 + "' file)" : ""), oom, Desktop.desktop);
4767 * Method invoked by the ChangeListener on the tabbed pane, in other words
4768 * when a different tabbed pane is selected by the user or programmatically.
4771 public void tabSelectionChanged(int index)
4775 alignPanel = alignPanels.get(index);
4776 viewport = alignPanel.av;
4777 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4778 setMenusFromViewport(viewport);
4782 * 'focus' any colour slider that is open to the selected viewport
4784 if (viewport.getConservationSelected())
4786 SliderPanel.setConservationSlider(alignPanel,
4787 viewport.getResidueShading(), alignPanel.getViewName());
4791 SliderPanel.hideConservationSlider();
4793 if (viewport.getAbovePIDThreshold())
4795 SliderPanel.setPIDSliderSource(alignPanel,
4796 viewport.getResidueShading(), alignPanel.getViewName());
4800 SliderPanel.hidePIDSlider();
4804 * If there is a frame linked to this one in a SplitPane, switch it to the
4805 * same view tab index. No infinite recursion of calls should happen, since
4806 * tabSelectionChanged() should not get invoked on setting the selected
4807 * index to an unchanged value. Guard against setting an invalid index
4808 * before the new view peer tab has been created.
4810 final AlignViewportI peer = viewport.getCodingComplement();
4813 AlignFrame linkedAlignFrame = ((AlignViewport) peer).getAlignPanel().alignFrame;
4814 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4816 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4822 * On right mouse click on view tab, prompt for and set new view name.
4825 public void tabbedPane_mousePressed(MouseEvent e)
4827 if (e.isPopupTrigger())
4829 String msg = MessageManager.getString("label.enter_view_name");
4830 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4831 JvOptionPane.QUESTION_MESSAGE);
4835 viewport.viewName = reply;
4836 // TODO warn if reply is in getExistingViewNames()?
4837 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4842 public AlignViewport getCurrentView()
4848 * Open the dialog for regex description parsing.
4851 protected void extractScores_actionPerformed(ActionEvent e)
4853 ParseProperties pp = new jalview.analysis.ParseProperties(
4854 viewport.getAlignment());
4855 // TODO: verify regex and introduce GUI dialog for version 2.5
4856 // if (pp.getScoresFromDescription("col", "score column ",
4857 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4859 if (pp.getScoresFromDescription("description column",
4860 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4862 buildSortByAnnotationScoresMenu();
4870 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4874 protected void showDbRefs_actionPerformed(ActionEvent e)
4876 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4882 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4886 protected void showNpFeats_actionPerformed(ActionEvent e)
4888 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4892 * find the viewport amongst the tabs in this alignment frame and close that
4897 public boolean closeView(AlignViewportI av)
4901 this.closeMenuItem_actionPerformed(false);
4904 Component[] comp = tabbedPane.getComponents();
4905 for (int i = 0; comp != null && i < comp.length; i++)
4907 if (comp[i] instanceof AlignmentPanel)
4909 if (((AlignmentPanel) comp[i]).av == av)
4912 closeView((AlignmentPanel) comp[i]);
4920 protected void build_fetchdbmenu(JMenu webService)
4922 // Temporary hack - DBRef Fetcher always top level ws entry.
4923 // TODO We probably want to store a sequence database checklist in
4924 // preferences and have checkboxes.. rather than individual sources selected
4926 final JMenu rfetch = new JMenu(
4927 MessageManager.getString("action.fetch_db_references"));
4928 rfetch.setToolTipText(MessageManager
4929 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4930 webService.add(rfetch);
4932 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4933 MessageManager.getString("option.trim_retrieved_seqs"));
4934 trimrs.setToolTipText(MessageManager
4935 .getString("label.trim_retrieved_sequences"));
4936 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
4937 trimrs.addActionListener(new ActionListener()
4940 public void actionPerformed(ActionEvent e)
4942 trimrs.setSelected(trimrs.isSelected());
4943 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
4944 Boolean.valueOf(trimrs.isSelected()).toString());
4948 JMenuItem fetchr = new JMenuItem(
4949 MessageManager.getString("label.standard_databases"));
4950 fetchr.setToolTipText(MessageManager
4951 .getString("label.fetch_embl_uniprot"));
4952 fetchr.addActionListener(new ActionListener()
4956 public void actionPerformed(ActionEvent e)
4958 new Thread(new Runnable()
4963 boolean isNucleotide = alignPanel.alignFrame.getViewport()
4964 .getAlignment().isNucleotide();
4965 DBRefFetcher dbRefFetcher = new DBRefFetcher(alignPanel.av
4966 .getSequenceSelection(), alignPanel.alignFrame, null,
4967 alignPanel.alignFrame.featureSettings, isNucleotide);
4968 dbRefFetcher.addListener(new FetchFinishedListenerI()
4971 public void finished()
4973 AlignFrame.this.setMenusForViewport();
4976 dbRefFetcher.fetchDBRefs(false);
4984 final AlignFrame me = this;
4985 new Thread(new Runnable()
4990 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
4991 .getSequenceFetcherSingleton(me);
4992 javax.swing.SwingUtilities.invokeLater(new Runnable()
4997 String[] dbclasses = sf.getOrderedSupportedSources();
4998 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
4999 // jalview.util.QuickSort.sort(otherdb, otherdb);
5000 List<DbSourceProxy> otherdb;
5001 JMenu dfetch = new JMenu();
5002 JMenu ifetch = new JMenu();
5003 JMenuItem fetchr = null;
5004 int comp = 0, icomp = 0, mcomp = 15;
5005 String mname = null;
5007 for (String dbclass : dbclasses)
5009 otherdb = sf.getSourceProxy(dbclass);
5010 // add a single entry for this class, or submenu allowing 'fetch
5012 if (otherdb == null || otherdb.size() < 1)
5016 // List<DbSourceProxy> dbs=otherdb;
5017 // otherdb=new ArrayList<DbSourceProxy>();
5018 // for (DbSourceProxy db:dbs)
5020 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5024 mname = "From " + dbclass;
5026 if (otherdb.size() == 1)
5028 final DbSourceProxy[] dassource = otherdb
5029 .toArray(new DbSourceProxy[0]);
5030 DbSourceProxy src = otherdb.get(0);
5031 fetchr = new JMenuItem(src.getDbSource());
5032 fetchr.addActionListener(new ActionListener()
5036 public void actionPerformed(ActionEvent e)
5038 new Thread(new Runnable()
5044 boolean isNucleotide = alignPanel.alignFrame
5045 .getViewport().getAlignment()
5047 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5048 alignPanel.av.getSequenceSelection(),
5049 alignPanel.alignFrame, dassource,
5050 alignPanel.alignFrame.featureSettings,
5053 .addListener(new FetchFinishedListenerI()
5056 public void finished()
5058 AlignFrame.this.setMenusForViewport();
5061 dbRefFetcher.fetchDBRefs(false);
5067 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5068 MessageManager.formatMessage(
5069 "label.fetch_retrieve_from",
5070 new Object[] { src.getDbName() })));
5076 final DbSourceProxy[] dassource = otherdb
5077 .toArray(new DbSourceProxy[0]);
5079 DbSourceProxy src = otherdb.get(0);
5080 fetchr = new JMenuItem(MessageManager.formatMessage(
5081 "label.fetch_all_param",
5082 new Object[] { src.getDbSource() }));
5083 fetchr.addActionListener(new ActionListener()
5086 public void actionPerformed(ActionEvent e)
5088 new Thread(new Runnable()
5094 boolean isNucleotide = alignPanel.alignFrame
5095 .getViewport().getAlignment()
5097 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5098 alignPanel.av.getSequenceSelection(),
5099 alignPanel.alignFrame, dassource,
5100 alignPanel.alignFrame.featureSettings,
5103 .addListener(new FetchFinishedListenerI()
5106 public void finished()
5108 AlignFrame.this.setMenusForViewport();
5111 dbRefFetcher.fetchDBRefs(false);
5117 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5118 MessageManager.formatMessage(
5119 "label.fetch_retrieve_from_all_sources",
5121 Integer.valueOf(otherdb.size())
5122 .toString(), src.getDbSource(),
5123 src.getDbName() })));
5126 // and then build the rest of the individual menus
5127 ifetch = new JMenu(MessageManager.formatMessage(
5128 "label.source_from_db_source",
5129 new Object[] { src.getDbSource() }));
5131 String imname = null;
5133 for (DbSourceProxy sproxy : otherdb)
5135 String dbname = sproxy.getDbName();
5136 String sname = dbname.length() > 5 ? dbname.substring(0,
5137 5) + "..." : dbname;
5138 String msname = dbname.length() > 10 ? dbname.substring(
5139 0, 10) + "..." : dbname;
5142 imname = MessageManager.formatMessage(
5143 "label.from_msname", new Object[] { sname });
5145 fetchr = new JMenuItem(msname);
5146 final DbSourceProxy[] dassrc = { sproxy };
5147 fetchr.addActionListener(new ActionListener()
5151 public void actionPerformed(ActionEvent e)
5153 new Thread(new Runnable()
5159 boolean isNucleotide = alignPanel.alignFrame
5160 .getViewport().getAlignment()
5162 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5163 alignPanel.av.getSequenceSelection(),
5164 alignPanel.alignFrame, dassrc,
5165 alignPanel.alignFrame.featureSettings,
5168 .addListener(new FetchFinishedListenerI()
5171 public void finished()
5173 AlignFrame.this.setMenusForViewport();
5176 dbRefFetcher.fetchDBRefs(false);
5182 fetchr.setToolTipText("<html>"
5183 + MessageManager.formatMessage(
5184 "label.fetch_retrieve_from", new Object[]
5188 if (++icomp >= mcomp || i == (otherdb.size()))
5190 ifetch.setText(MessageManager.formatMessage(
5191 "label.source_to_target", imname, sname));
5193 ifetch = new JMenu();
5201 if (comp >= mcomp || dbi >= (dbclasses.length))
5203 dfetch.setText(MessageManager.formatMessage(
5204 "label.source_to_target", mname, dbclass));
5206 dfetch = new JMenu();
5219 * Left justify the whole alignment.
5222 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5224 AlignmentI al = viewport.getAlignment();
5226 viewport.firePropertyChange("alignment", null, al);
5230 * Right justify the whole alignment.
5233 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5235 AlignmentI al = viewport.getAlignment();
5237 viewport.firePropertyChange("alignment", null, al);
5241 public void setShowSeqFeatures(boolean b)
5243 showSeqFeatures.setSelected(b);
5244 viewport.setShowSequenceFeatures(b);
5251 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5252 * awt.event.ActionEvent)
5255 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5257 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5258 alignPanel.paintAlignment(true);
5265 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5269 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5271 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5272 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5280 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5281 * .event.ActionEvent)
5284 protected void showGroupConservation_actionPerformed(ActionEvent e)
5286 viewport.setShowGroupConservation(showGroupConservation.getState());
5287 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5294 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5295 * .event.ActionEvent)
5298 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5300 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5301 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5308 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5309 * .event.ActionEvent)
5312 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5314 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5315 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5319 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5321 showSequenceLogo.setState(true);
5322 viewport.setShowSequenceLogo(true);
5323 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5324 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5328 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5330 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5337 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5338 * .event.ActionEvent)
5341 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5343 if (avc.makeGroupsFromSelection())
5345 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5346 alignPanel.updateAnnotation();
5347 alignPanel.paintAlignment(true);
5351 public void clearAlignmentSeqRep()
5353 // TODO refactor alignmentseqrep to controller
5354 if (viewport.getAlignment().hasSeqrep())
5356 viewport.getAlignment().setSeqrep(null);
5357 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5358 alignPanel.updateAnnotation();
5359 alignPanel.paintAlignment(true);
5364 protected void createGroup_actionPerformed(ActionEvent e)
5366 if (avc.createGroup())
5368 alignPanel.alignmentChanged();
5373 protected void unGroup_actionPerformed(ActionEvent e)
5377 alignPanel.alignmentChanged();
5382 * make the given alignmentPanel the currently selected tab
5384 * @param alignmentPanel
5386 public void setDisplayedView(AlignmentPanel alignmentPanel)
5388 if (!viewport.getSequenceSetId().equals(
5389 alignmentPanel.av.getSequenceSetId()))
5393 .getString("error.implementation_error_cannot_show_view_alignment_frame"));
5395 if (tabbedPane != null
5396 && tabbedPane.getTabCount() > 0
5397 && alignPanels.indexOf(alignmentPanel) != tabbedPane
5398 .getSelectedIndex())
5400 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5405 * Action on selection of menu options to Show or Hide annotations.
5408 * @param forSequences
5409 * update sequence-related annotations
5410 * @param forAlignment
5411 * update non-sequence-related annotations
5414 protected void setAnnotationsVisibility(boolean visible,
5415 boolean forSequences, boolean forAlignment)
5417 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5418 .getAlignmentAnnotation();
5423 for (AlignmentAnnotation aa : anns)
5426 * don't display non-positional annotations on an alignment
5428 if (aa.annotations == null)
5432 boolean apply = (aa.sequenceRef == null && forAlignment)
5433 || (aa.sequenceRef != null && forSequences);
5436 aa.visible = visible;
5439 alignPanel.validateAnnotationDimensions(true);
5440 alignPanel.alignmentChanged();
5444 * Store selected annotation sort order for the view and repaint.
5447 protected void sortAnnotations_actionPerformed()
5449 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5451 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5452 alignPanel.paintAlignment(true);
5457 * @return alignment panels in this alignment frame
5459 public List<? extends AlignmentViewPanel> getAlignPanels()
5461 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5465 * Open a new alignment window, with the cDNA associated with this (protein)
5466 * alignment, aligned as is the protein.
5468 protected void viewAsCdna_actionPerformed()
5470 // TODO no longer a menu action - refactor as required
5471 final AlignmentI alignment = getViewport().getAlignment();
5472 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5473 if (mappings == null)
5477 List<SequenceI> cdnaSeqs = new ArrayList<SequenceI>();
5478 for (SequenceI aaSeq : alignment.getSequences())
5480 for (AlignedCodonFrame acf : mappings)
5482 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5486 * There is a cDNA mapping for this protein sequence - add to new
5487 * alignment. It will share the same dataset sequence as other mapped
5488 * cDNA (no new mappings need to be created).
5490 final Sequence newSeq = new Sequence(dnaSeq);
5491 newSeq.setDatasetSequence(dnaSeq);
5492 cdnaSeqs.add(newSeq);
5496 if (cdnaSeqs.size() == 0)
5498 // show a warning dialog no mapped cDNA
5501 AlignmentI cdna = new Alignment(cdnaSeqs.toArray(new SequenceI[cdnaSeqs
5503 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5504 AlignFrame.DEFAULT_HEIGHT);
5505 cdna.alignAs(alignment);
5506 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5508 Desktop.addInternalFrame(alignFrame, newtitle,
5509 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
5513 * Set visibility of dna/protein complement view (available when shown in a
5519 protected void showComplement_actionPerformed(boolean show)
5521 SplitContainerI sf = getSplitViewContainer();
5524 sf.setComplementVisible(this, show);
5529 * Generate the reverse (optionally complemented) of the selected sequences,
5530 * and add them to the alignment
5533 protected void showReverse_actionPerformed(boolean complement)
5535 AlignmentI al = null;
5538 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5539 al = dna.reverseCdna(complement);
5540 viewport.addAlignment(al, "");
5541 addHistoryItem(new EditCommand(
5542 MessageManager.getString("label.add_sequences"),
5543 Action.PASTE, al.getSequencesArray(), 0, al.getWidth(),
5544 viewport.getAlignment()));
5545 } catch (Exception ex)
5547 System.err.println(ex.getMessage());
5553 * Try to run a script in the Groovy console, having first ensured that this
5554 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5555 * be targeted at this alignment.
5558 protected void runGroovy_actionPerformed()
5560 Jalview.setCurrentAlignFrame(this);
5561 groovy.ui.Console console = Desktop.getGroovyConsole();
5562 if (console != null)
5566 console.runScript();
5567 } catch (Exception ex)
5569 System.err.println((ex.toString()));
5571 .showInternalMessageDialog(Desktop.desktop, MessageManager
5572 .getString("label.couldnt_run_groovy_script"),
5574 .getString("label.groovy_support_failed"),
5575 JvOptionPane.ERROR_MESSAGE);
5580 System.err.println("Can't run Groovy script as console not found");
5585 * Hides columns containing (or not containing) a specified feature, provided
5586 * that would not leave all columns hidden
5588 * @param featureType
5589 * @param columnsContaining
5592 public boolean hideFeatureColumns(String featureType,
5593 boolean columnsContaining)
5595 boolean notForHiding = avc.markColumnsContainingFeatures(
5596 columnsContaining, false, false, featureType);
5599 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5600 false, featureType))
5602 getViewport().hideSelectedColumns();
5610 protected void selectHighlightedColumns_actionPerformed(
5611 ActionEvent actionEvent)
5613 // include key modifier check in case user selects from menu
5614 avc.markHighlightedColumns(
5615 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0,
5617 (actionEvent.getModifiers() & (ActionEvent.META_MASK | ActionEvent.CTRL_MASK)) != 0);
5621 * Rebuilds the Colour menu, including any user-defined colours which have
5622 * been loaded either on startup or during the session
5624 public void buildColourMenu()
5626 colourMenu.removeAll();
5628 colourMenu.add(applyToAllGroups);
5629 colourMenu.add(textColour);
5630 colourMenu.addSeparator();
5632 ColourMenuHelper.addMenuItems(colourMenu, this,
5633 viewport.getAlignment(), false);
5635 colourMenu.addSeparator();
5636 colourMenu.add(conservationMenuItem);
5637 colourMenu.add(modifyConservation);
5638 colourMenu.add(abovePIDThreshold);
5639 colourMenu.add(modifyPID);
5640 colourMenu.add(annotationColour);
5642 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5643 String schemeName = colourScheme == null ? null : colourScheme
5646 ColourMenuHelper.setColourSelected(colourMenu, schemeName);
5650 * Repopulates the sub-menu with choice of score matrices each time the menu
5651 * is selected, in case matrices have been added dynamically
5654 protected void scoreModel_menuSelected()
5656 qualityScoreModel.removeAll();
5657 boolean nucleotide = getViewport().getAlignment().isNucleotide();
5658 final AlignCalcManagerI calcManager = getViewport().getCalcManager();
5661 * which model is currently selected?
5663 String modelName = null;
5664 final List<AlignCalcWorkerI> cons = calcManager
5665 .getRegisteredWorkersOfClass(ConservationThread.class);
5666 if (cons == null || cons.isEmpty())
5670 for (AlignCalcWorkerI worker : cons)
5672 modelName = ((ConservationThread) worker).getScoreModel().getName();
5678 final ScoreModels scoreModels = ScoreModels.getInstance();
5679 for (final ScoreModelI sm : scoreModels.getModels())
5681 final String name = sm.getName();
5682 JCheckBoxMenuItem menuItem = new JCheckBoxMenuItem(name);
5685 * if the score model doesn't provide a description, try to look one
5686 * up in the text bundle, falling back on its name
5687 * TODO push this inside ScoreModels?
5689 String tooltip = sm.getDescription();
5690 if (tooltip == null)
5692 tooltip = MessageManager.getStringOrReturn("label.score_model_",
5695 menuItem.setToolTipText(tooltip);
5696 menuItem.setSelected(modelName.equals(name));
5697 if (sm.isProtein() && (sm instanceof ScoreMatrix))
5699 menuItem.addActionListener(new ActionListener()
5702 public void actionPerformed(ActionEvent e)
5704 // set model on ConservationThread, restart thread
5705 for (AlignCalcWorkerI worker : cons)
5707 ((ConservationThread) worker)
5708 .setScoreModel((ScoreMatrix) scoreModels
5711 getViewport().alignmentChanged(alignPanel);
5714 qualityScoreModel.add(menuItem);
5720 class PrintThread extends Thread
5724 public PrintThread(AlignmentPanel ap)
5729 static PageFormat pf;
5734 PrinterJob printJob = PrinterJob.getPrinterJob();
5738 printJob.setPrintable(ap, pf);
5742 printJob.setPrintable(ap);
5745 if (printJob.printDialog())
5750 } catch (Exception PrintException)
5752 PrintException.printStackTrace();