2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AlignmentSorter;
24 import jalview.analysis.AlignmentUtils;
25 import jalview.analysis.CrossRef;
26 import jalview.analysis.Dna;
27 import jalview.analysis.ParseProperties;
28 import jalview.analysis.SequenceIdMatcher;
29 import jalview.api.AlignExportSettingI;
30 import jalview.api.AlignViewControllerGuiI;
31 import jalview.api.AlignViewControllerI;
32 import jalview.api.AlignViewportI;
33 import jalview.api.AlignmentViewPanel;
34 import jalview.api.FeatureSettingsControllerI;
35 import jalview.api.SplitContainerI;
36 import jalview.api.ViewStyleI;
37 import jalview.api.analysis.ScoreModelI;
38 import jalview.bin.Cache;
39 import jalview.bin.Jalview;
40 import jalview.commands.CommandI;
41 import jalview.commands.EditCommand;
42 import jalview.commands.EditCommand.Action;
43 import jalview.commands.OrderCommand;
44 import jalview.commands.RemoveGapColCommand;
45 import jalview.commands.RemoveGapsCommand;
46 import jalview.commands.SlideSequencesCommand;
47 import jalview.commands.TrimRegionCommand;
48 import jalview.datamodel.AlignedCodonFrame;
49 import jalview.datamodel.Alignment;
50 import jalview.datamodel.AlignmentAnnotation;
51 import jalview.datamodel.AlignmentExportData;
52 import jalview.datamodel.AlignmentI;
53 import jalview.datamodel.AlignmentOrder;
54 import jalview.datamodel.AlignmentView;
55 import jalview.datamodel.ColumnSelection;
56 import jalview.datamodel.HiddenSequences;
57 import jalview.datamodel.PDBEntry;
58 import jalview.datamodel.SeqCigar;
59 import jalview.datamodel.Sequence;
60 import jalview.datamodel.SequenceGroup;
61 import jalview.datamodel.SequenceI;
62 import jalview.gui.ColourMenuHelper.ColourChangeListener;
63 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
64 import jalview.io.AlignmentProperties;
65 import jalview.io.AnnotationFile;
66 import jalview.io.BioJsHTMLOutput;
67 import jalview.io.DataSourceType;
68 import jalview.io.FileFormat;
69 import jalview.io.FileFormatI;
70 import jalview.io.FileLoader;
71 import jalview.io.FormatAdapter;
72 import jalview.io.HtmlSvgOutput;
73 import jalview.io.IdentifyFile;
74 import jalview.io.JPredFile;
75 import jalview.io.JalviewFileChooser;
76 import jalview.io.JalviewFileView;
77 import jalview.io.JnetAnnotationMaker;
78 import jalview.io.NewickFile;
79 import jalview.io.TCoffeeScoreFile;
80 import jalview.jbgui.GAlignFrame;
81 import jalview.schemes.ColourSchemeI;
82 import jalview.schemes.ColourSchemes;
83 import jalview.schemes.ResidueColourScheme;
84 import jalview.schemes.ResidueProperties;
85 import jalview.schemes.TCoffeeColourScheme;
86 import jalview.util.MessageManager;
87 import jalview.viewmodel.AlignmentViewport;
88 import jalview.ws.DBRefFetcher;
89 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
90 import jalview.ws.jws1.Discoverer;
91 import jalview.ws.jws2.Jws2Discoverer;
92 import jalview.ws.jws2.jabaws2.Jws2Instance;
93 import jalview.ws.seqfetcher.DbSourceProxy;
95 import java.awt.BorderLayout;
96 import java.awt.Component;
97 import java.awt.Rectangle;
98 import java.awt.Toolkit;
99 import java.awt.datatransfer.Clipboard;
100 import java.awt.datatransfer.DataFlavor;
101 import java.awt.datatransfer.StringSelection;
102 import java.awt.datatransfer.Transferable;
103 import java.awt.dnd.DnDConstants;
104 import java.awt.dnd.DropTargetDragEvent;
105 import java.awt.dnd.DropTargetDropEvent;
106 import java.awt.dnd.DropTargetEvent;
107 import java.awt.dnd.DropTargetListener;
108 import java.awt.event.ActionEvent;
109 import java.awt.event.ActionListener;
110 import java.awt.event.FocusAdapter;
111 import java.awt.event.FocusEvent;
112 import java.awt.event.ItemEvent;
113 import java.awt.event.ItemListener;
114 import java.awt.event.KeyAdapter;
115 import java.awt.event.KeyEvent;
116 import java.awt.event.MouseEvent;
117 import java.awt.print.PageFormat;
118 import java.awt.print.PrinterJob;
119 import java.beans.PropertyChangeEvent;
122 import java.util.ArrayList;
123 import java.util.Arrays;
124 import java.util.Deque;
125 import java.util.Enumeration;
126 import java.util.Hashtable;
127 import java.util.List;
128 import java.util.Vector;
130 import javax.swing.JCheckBoxMenuItem;
131 import javax.swing.JEditorPane;
132 import javax.swing.JInternalFrame;
133 import javax.swing.JLayeredPane;
134 import javax.swing.JMenu;
135 import javax.swing.JMenuItem;
136 import javax.swing.JScrollPane;
137 import javax.swing.SwingUtilities;
143 * @version $Revision$
145 public class AlignFrame extends GAlignFrame implements DropTargetListener,
146 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
149 public static final int DEFAULT_WIDTH = 700;
151 public static final int DEFAULT_HEIGHT = 500;
154 * The currently displayed panel (selected tabbed view if more than one)
156 public AlignmentPanel alignPanel;
158 AlignViewport viewport;
160 public AlignViewControllerI avc;
162 List<AlignmentPanel> alignPanels = new ArrayList<AlignmentPanel>();
165 * Last format used to load or save alignments in this window
167 FileFormatI currentFileFormat = null;
170 * Current filename for this alignment
172 String fileName = null;
175 * Creates a new AlignFrame object with specific width and height.
181 public AlignFrame(AlignmentI al, int width, int height)
183 this(al, null, width, height);
187 * Creates a new AlignFrame object with specific width, height and
193 * @param sequenceSetId
195 public AlignFrame(AlignmentI al, int width, int height,
196 String sequenceSetId)
198 this(al, null, width, height, sequenceSetId);
202 * Creates a new AlignFrame object with specific width, height and
208 * @param sequenceSetId
211 public AlignFrame(AlignmentI al, int width, int height,
212 String sequenceSetId, String viewId)
214 this(al, null, width, height, sequenceSetId, viewId);
218 * new alignment window with hidden columns
222 * @param hiddenColumns
223 * ColumnSelection or null
225 * Width of alignment frame
229 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
230 int width, int height)
232 this(al, hiddenColumns, width, height, null);
236 * Create alignment frame for al with hiddenColumns, a specific width and
237 * height, and specific sequenceId
240 * @param hiddenColumns
243 * @param sequenceSetId
246 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
247 int width, int height, String sequenceSetId)
249 this(al, hiddenColumns, width, height, sequenceSetId, null);
253 * Create alignment frame for al with hiddenColumns, a specific width and
254 * height, and specific sequenceId
257 * @param hiddenColumns
260 * @param sequenceSetId
265 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
266 int width, int height, String sequenceSetId, String viewId)
268 setSize(width, height);
270 if (al.getDataset() == null)
275 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
277 alignPanel = new AlignmentPanel(this, viewport);
279 addAlignmentPanel(alignPanel, true);
283 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
284 ColumnSelection hiddenColumns, int width, int height)
286 setSize(width, height);
288 if (al.getDataset() == null)
293 viewport = new AlignViewport(al, hiddenColumns);
295 if (hiddenSeqs != null && hiddenSeqs.length > 0)
297 viewport.hideSequence(hiddenSeqs);
299 alignPanel = new AlignmentPanel(this, viewport);
300 addAlignmentPanel(alignPanel, true);
305 * Make a new AlignFrame from existing alignmentPanels
312 public AlignFrame(AlignmentPanel ap)
316 addAlignmentPanel(ap, false);
321 * initalise the alignframe from the underlying viewport data and the
326 if (!Jalview.isHeadlessMode())
328 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
331 avc = new jalview.controller.AlignViewController(this, viewport,
333 if (viewport.getAlignmentConservationAnnotation() == null)
335 // BLOSUM62Colour.setEnabled(false);
336 conservationMenuItem.setEnabled(false);
337 modifyConservation.setEnabled(false);
338 // PIDColour.setEnabled(false);
339 // abovePIDThreshold.setEnabled(false);
340 // modifyPID.setEnabled(false);
343 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
346 if (sortby.equals("Id"))
348 sortIDMenuItem_actionPerformed(null);
350 else if (sortby.equals("Pairwise Identity"))
352 sortPairwiseMenuItem_actionPerformed(null);
356 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
358 setMenusFromViewport(viewport);
359 buildSortByAnnotationScoresMenu();
363 if (Desktop.desktop != null)
365 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
366 addServiceListeners();
370 if (viewport.getWrapAlignment())
372 wrapMenuItem_actionPerformed(null);
375 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
377 this.overviewMenuItem_actionPerformed(null);
382 final List<AlignmentPanel> selviews = new ArrayList<AlignmentPanel>();
383 final List<AlignmentPanel> origview = new ArrayList<AlignmentPanel>();
384 final String menuLabel = MessageManager
385 .getString("label.copy_format_from");
386 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
387 new ViewSetProvider()
391 public AlignmentPanel[] getAllAlignmentPanels()
394 origview.add(alignPanel);
395 // make an array of all alignment panels except for this one
396 List<AlignmentPanel> aps = new ArrayList<AlignmentPanel>(
397 Arrays.asList(Desktop.getAlignmentPanels(null)));
398 aps.remove(AlignFrame.this.alignPanel);
399 return aps.toArray(new AlignmentPanel[aps.size()]);
401 }, selviews, new ItemListener()
405 public void itemStateChanged(ItemEvent e)
407 if (origview.size() > 0)
409 final AlignmentPanel ap = origview.get(0);
412 * Copy the ViewStyle of the selected panel to 'this one'.
413 * Don't change value of 'scaleProteinAsCdna' unless copying
416 ViewStyleI vs = selviews.get(0).getAlignViewport()
418 boolean fromSplitFrame = selviews.get(0)
419 .getAlignViewport().getCodingComplement() != null;
422 vs.setScaleProteinAsCdna(ap.getAlignViewport()
423 .getViewStyle().isScaleProteinAsCdna());
425 ap.getAlignViewport().setViewStyle(vs);
428 * Also rescale ViewStyle of SplitFrame complement if there is
429 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
430 * the whole ViewStyle (allow cDNA protein to have different
433 AlignViewportI complement = ap.getAlignViewport()
434 .getCodingComplement();
435 if (complement != null && vs.isScaleProteinAsCdna())
437 AlignFrame af = Desktop.getAlignFrameFor(complement);
438 ((SplitFrame) af.getSplitViewContainer())
440 af.setMenusForViewport();
444 ap.setSelected(true);
445 ap.alignFrame.setMenusForViewport();
450 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
451 .indexOf("devel") > -1
452 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
453 .indexOf("test") > -1)
455 formatMenu.add(vsel);
457 addFocusListener(new FocusAdapter()
460 public void focusGained(FocusEvent e)
462 Jalview.setCurrentAlignFrame(AlignFrame.this);
469 * Change the filename and format for the alignment, and enable the 'reload'
470 * button functionality.
477 public void setFileName(String file, FileFormatI format)
480 setFileFormat(format);
481 reload.setEnabled(true);
485 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
488 void addKeyListener()
490 addKeyListener(new KeyAdapter()
493 public void keyPressed(KeyEvent evt)
495 if (viewport.cursorMode
496 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
497 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
498 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
499 && Character.isDigit(evt.getKeyChar()))
501 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
504 switch (evt.getKeyCode())
507 case 27: // escape key
508 deselectAllSequenceMenuItem_actionPerformed(null);
512 case KeyEvent.VK_DOWN:
513 if (evt.isAltDown() || !viewport.cursorMode)
515 moveSelectedSequences(false);
517 if (viewport.cursorMode)
519 alignPanel.getSeqPanel().moveCursor(0, 1);
524 if (evt.isAltDown() || !viewport.cursorMode)
526 moveSelectedSequences(true);
528 if (viewport.cursorMode)
530 alignPanel.getSeqPanel().moveCursor(0, -1);
535 case KeyEvent.VK_LEFT:
536 if (evt.isAltDown() || !viewport.cursorMode)
538 slideSequences(false, alignPanel.getSeqPanel().getKeyboardNo1());
542 alignPanel.getSeqPanel().moveCursor(-1, 0);
547 case KeyEvent.VK_RIGHT:
548 if (evt.isAltDown() || !viewport.cursorMode)
550 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
554 alignPanel.getSeqPanel().moveCursor(1, 0);
558 case KeyEvent.VK_SPACE:
559 if (viewport.cursorMode)
561 alignPanel.getSeqPanel().insertGapAtCursor(
562 evt.isControlDown() || evt.isShiftDown()
567 // case KeyEvent.VK_A:
568 // if (viewport.cursorMode)
570 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
571 // //System.out.println("A");
575 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
576 * System.out.println("closing bracket"); } break;
578 case KeyEvent.VK_DELETE:
579 case KeyEvent.VK_BACK_SPACE:
580 if (!viewport.cursorMode)
582 cut_actionPerformed(null);
586 alignPanel.getSeqPanel().deleteGapAtCursor(
587 evt.isControlDown() || evt.isShiftDown()
594 if (viewport.cursorMode)
596 alignPanel.getSeqPanel().setCursorRow();
600 if (viewport.cursorMode && !evt.isControlDown())
602 alignPanel.getSeqPanel().setCursorColumn();
606 if (viewport.cursorMode)
608 alignPanel.getSeqPanel().setCursorPosition();
612 case KeyEvent.VK_ENTER:
613 case KeyEvent.VK_COMMA:
614 if (viewport.cursorMode)
616 alignPanel.getSeqPanel().setCursorRowAndColumn();
621 if (viewport.cursorMode)
623 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
627 if (viewport.cursorMode)
629 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
634 viewport.cursorMode = !viewport.cursorMode;
635 statusBar.setText(MessageManager.formatMessage(
636 "label.keyboard_editing_mode",
637 new String[] { (viewport.cursorMode ? "on" : "off") }));
638 if (viewport.cursorMode)
640 alignPanel.getSeqPanel().seqCanvas.cursorX = viewport.startRes;
641 alignPanel.getSeqPanel().seqCanvas.cursorY = viewport.startSeq;
643 alignPanel.getSeqPanel().seqCanvas.repaint();
649 Help.showHelpWindow();
650 } catch (Exception ex)
652 ex.printStackTrace();
657 boolean toggleSeqs = !evt.isControlDown();
658 boolean toggleCols = !evt.isShiftDown();
659 toggleHiddenRegions(toggleSeqs, toggleCols);
664 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
665 boolean modifyExisting = true; // always modify, don't clear
666 // evt.isShiftDown();
667 boolean invertHighlighted = evt.isAltDown();
668 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
672 case KeyEvent.VK_PAGE_UP:
673 if (viewport.getWrapAlignment())
675 alignPanel.scrollUp(true);
679 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
680 - viewport.endSeq + viewport.startSeq);
683 case KeyEvent.VK_PAGE_DOWN:
684 if (viewport.getWrapAlignment())
686 alignPanel.scrollUp(false);
690 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
691 + viewport.endSeq - viewport.startSeq);
698 public void keyReleased(KeyEvent evt)
700 switch (evt.getKeyCode())
702 case KeyEvent.VK_LEFT:
703 if (evt.isAltDown() || !viewport.cursorMode)
705 viewport.firePropertyChange("alignment", null, viewport
706 .getAlignment().getSequences());
710 case KeyEvent.VK_RIGHT:
711 if (evt.isAltDown() || !viewport.cursorMode)
713 viewport.firePropertyChange("alignment", null, viewport
714 .getAlignment().getSequences());
722 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
724 ap.alignFrame = this;
725 avc = new jalview.controller.AlignViewController(this, viewport,
730 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
732 int aSize = alignPanels.size();
734 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
736 if (aSize == 1 && ap.av.viewName == null)
738 this.getContentPane().add(ap, BorderLayout.CENTER);
744 setInitialTabVisible();
747 expandViews.setEnabled(true);
748 gatherViews.setEnabled(true);
749 tabbedPane.addTab(ap.av.viewName, ap);
751 ap.setVisible(false);
756 if (ap.av.isPadGaps())
758 ap.av.getAlignment().padGaps();
760 ap.av.updateConservation(ap);
761 ap.av.updateConsensus(ap);
762 ap.av.updateStrucConsensus(ap);
766 public void setInitialTabVisible()
768 expandViews.setEnabled(true);
769 gatherViews.setEnabled(true);
770 tabbedPane.setVisible(true);
771 AlignmentPanel first = alignPanels.get(0);
772 tabbedPane.addTab(first.av.viewName, first);
773 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
776 public AlignViewport getViewport()
781 /* Set up intrinsic listeners for dynamically generated GUI bits. */
782 private void addServiceListeners()
784 final java.beans.PropertyChangeListener thisListener;
785 Desktop.instance.addJalviewPropertyChangeListener("services",
786 thisListener = new java.beans.PropertyChangeListener()
789 public void propertyChange(PropertyChangeEvent evt)
791 // // System.out.println("Discoverer property change.");
792 // if (evt.getPropertyName().equals("services"))
794 SwingUtilities.invokeLater(new Runnable()
801 .println("Rebuild WS Menu for service change");
802 BuildWebServiceMenu();
809 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
812 public void internalFrameClosed(
813 javax.swing.event.InternalFrameEvent evt)
815 // System.out.println("deregistering discoverer listener");
816 Desktop.instance.removeJalviewPropertyChangeListener("services",
818 closeMenuItem_actionPerformed(true);
821 // Finally, build the menu once to get current service state
822 new Thread(new Runnable()
827 BuildWebServiceMenu();
833 * Configure menu items that vary according to whether the alignment is
834 * nucleotide or protein
836 public void setGUINucleotide()
838 AlignmentI al = getViewport().getAlignment();
839 boolean nucleotide = al.isNucleotide();
841 showTranslation.setVisible(nucleotide);
842 showReverse.setVisible(nucleotide);
843 showReverseComplement.setVisible(nucleotide);
844 conservationMenuItem.setEnabled(!nucleotide);
845 modifyConservation.setEnabled(!nucleotide);
846 showGroupConservation.setEnabled(!nucleotide);
848 showComplementMenuItem.setText(nucleotide ? MessageManager
849 .getString("label.protein") : MessageManager
850 .getString("label.nucleotide"));
854 * set up menus for the current viewport. This may be called after any
855 * operation that affects the data in the current view (selection changed,
856 * etc) to update the menus to reflect the new state.
859 public void setMenusForViewport()
861 setMenusFromViewport(viewport);
865 * Need to call this method when tabs are selected for multiple views, or when
866 * loading from Jalview2XML.java
871 void setMenusFromViewport(AlignViewport av)
873 padGapsMenuitem.setSelected(av.isPadGaps());
874 colourTextMenuItem.setSelected(av.isShowColourText());
875 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
876 conservationMenuItem.setSelected(av.getConservationSelected());
877 seqLimits.setSelected(av.getShowJVSuffix());
878 idRightAlign.setSelected(av.isRightAlignIds());
879 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
880 renderGapsMenuItem.setSelected(av.isRenderGaps());
881 wrapMenuItem.setSelected(av.getWrapAlignment());
882 scaleAbove.setVisible(av.getWrapAlignment());
883 scaleLeft.setVisible(av.getWrapAlignment());
884 scaleRight.setVisible(av.getWrapAlignment());
885 annotationPanelMenuItem.setState(av.isShowAnnotation());
887 * Show/hide annotations only enabled if annotation panel is shown
889 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
890 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
891 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
892 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
893 viewBoxesMenuItem.setSelected(av.getShowBoxes());
894 viewTextMenuItem.setSelected(av.getShowText());
895 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
896 showGroupConsensus.setSelected(av.isShowGroupConsensus());
897 showGroupConservation.setSelected(av.isShowGroupConservation());
898 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
899 showSequenceLogo.setSelected(av.isShowSequenceLogo());
900 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
902 ColourMenuHelper.setColourSelected(colourMenu,
903 av.getGlobalColourScheme());
905 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
906 hiddenMarkers.setState(av.getShowHiddenMarkers());
907 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
908 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
909 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
910 autoCalculate.setSelected(av.autoCalculateConsensus);
911 sortByTree.setSelected(av.sortByTree);
912 listenToViewSelections.setSelected(av.followSelection);
914 showProducts.setEnabled(canShowProducts());
915 setGroovyEnabled(Desktop.getGroovyConsole() != null);
921 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
925 public void setGroovyEnabled(boolean b)
927 runGroovy.setEnabled(b);
930 private IProgressIndicator progressBar;
935 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
938 public void setProgressBar(String message, long id)
940 progressBar.setProgressBar(message, id);
944 public void registerHandler(final long id,
945 final IProgressIndicatorHandler handler)
947 progressBar.registerHandler(id, handler);
952 * @return true if any progress bars are still active
955 public boolean operationInProgress()
957 return progressBar.operationInProgress();
961 public void setStatus(String text)
963 statusBar.setText(text);
967 * Added so Castor Mapping file can obtain Jalview Version
969 public String getVersion()
971 return jalview.bin.Cache.getProperty("VERSION");
974 public FeatureRenderer getFeatureRenderer()
976 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
980 public void fetchSequence_actionPerformed(ActionEvent e)
982 new jalview.gui.SequenceFetcher(this);
986 public void addFromFile_actionPerformed(ActionEvent e)
988 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
992 public void reload_actionPerformed(ActionEvent e)
994 if (fileName != null)
996 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
997 // originating file's format
998 // TODO: work out how to recover feature settings for correct view(s) when
1000 if (FileFormat.Jalview.equals(currentFileFormat))
1002 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1003 for (int i = 0; i < frames.length; i++)
1005 if (frames[i] instanceof AlignFrame && frames[i] != this
1006 && ((AlignFrame) frames[i]).fileName != null
1007 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1011 frames[i].setSelected(true);
1012 Desktop.instance.closeAssociatedWindows();
1013 } catch (java.beans.PropertyVetoException ex)
1019 Desktop.instance.closeAssociatedWindows();
1021 FileLoader loader = new FileLoader();
1022 DataSourceType protocol = fileName.startsWith("http:") ? DataSourceType.URL
1023 : DataSourceType.FILE;
1024 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1028 Rectangle bounds = this.getBounds();
1030 FileLoader loader = new FileLoader();
1031 DataSourceType protocol = fileName.startsWith("http:") ? DataSourceType.URL
1032 : DataSourceType.FILE;
1033 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1034 protocol, currentFileFormat);
1036 newframe.setBounds(bounds);
1037 if (featureSettings != null && featureSettings.isShowing())
1039 final Rectangle fspos = featureSettings.frame.getBounds();
1040 // TODO: need a 'show feature settings' function that takes bounds -
1041 // need to refactor Desktop.addFrame
1042 newframe.featureSettings_actionPerformed(null);
1043 final FeatureSettings nfs = newframe.featureSettings;
1044 SwingUtilities.invokeLater(new Runnable()
1049 nfs.frame.setBounds(fspos);
1052 this.featureSettings.close();
1053 this.featureSettings = null;
1055 this.closeMenuItem_actionPerformed(true);
1061 public void addFromText_actionPerformed(ActionEvent e)
1063 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport
1068 public void addFromURL_actionPerformed(ActionEvent e)
1070 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1074 public void save_actionPerformed(ActionEvent e)
1076 if (fileName == null || (currentFileFormat == null)
1077 || fileName.startsWith("http"))
1079 saveAs_actionPerformed(null);
1083 saveAlignment(fileName, currentFileFormat);
1094 public void saveAs_actionPerformed(ActionEvent e)
1096 String format = currentFileFormat == null ? null : currentFileFormat
1098 JalviewFileChooser chooser = JalviewFileChooser.forWrite(
1099 Cache.getProperty("LAST_DIRECTORY"), format);
1101 chooser.setFileView(new JalviewFileView());
1102 chooser.setDialogTitle(MessageManager
1103 .getString("label.save_alignment_to_file"));
1104 chooser.setToolTipText(MessageManager.getString("action.save"));
1106 int value = chooser.showSaveDialog(this);
1108 if (value == JalviewFileChooser.APPROVE_OPTION)
1110 currentFileFormat = chooser.getSelectedFormat();
1111 while (currentFileFormat == null)
1114 .showInternalMessageDialog(
1117 .getString("label.select_file_format_before_saving"),
1119 .getString("label.file_format_not_specified"),
1120 JvOptionPane.WARNING_MESSAGE);
1121 currentFileFormat = chooser.getSelectedFormat();
1122 value = chooser.showSaveDialog(this);
1123 if (value != JalviewFileChooser.APPROVE_OPTION)
1129 fileName = chooser.getSelectedFile().getPath();
1131 Cache.setProperty("DEFAULT_FILE_FORMAT",
1132 currentFileFormat.toString());
1134 Cache.setProperty("LAST_DIRECTORY", fileName);
1135 saveAlignment(fileName, currentFileFormat);
1139 public boolean saveAlignment(String file, FileFormatI format)
1141 boolean success = true;
1143 if (FileFormat.Jalview.equals(format))
1145 String shortName = title;
1147 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1149 shortName = shortName.substring(shortName
1150 .lastIndexOf(java.io.File.separatorChar) + 1);
1153 success = new Jalview2XML().saveAlignment(this, file, shortName);
1155 statusBar.setText(MessageManager.formatMessage(
1156 "label.successfully_saved_to_file_in_format", new Object[] {
1157 fileName, format }));
1162 // if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1164 // warningMessage("Cannot save file " + fileName + " using format "
1165 // + format, "Alignment output format not supported");
1166 // if (!Jalview.isHeadlessMode())
1168 // saveAs_actionPerformed(null);
1173 AlignmentExportData exportData = getAlignmentForExport(format,
1175 if (exportData.getSettings().isCancelled())
1179 FormatAdapter f = new FormatAdapter(alignPanel,
1180 exportData.getSettings());
1181 String output = f.formatSequences(
1183 exportData.getAlignment(), // class cast exceptions will
1184 // occur in the distant future
1185 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1186 f.getCacheSuffixDefault(format),
1187 viewport.getColumnSelection());
1197 java.io.PrintWriter out = new java.io.PrintWriter(
1198 new java.io.FileWriter(file));
1202 this.setTitle(file);
1203 statusBar.setText(MessageManager.formatMessage(
1204 "label.successfully_saved_to_file_in_format",
1205 new Object[] { fileName, format }));
1206 } catch (Exception ex)
1209 ex.printStackTrace();
1216 JvOptionPane.showInternalMessageDialog(this, MessageManager
1217 .formatMessage("label.couldnt_save_file",
1218 new Object[] { fileName }), MessageManager
1219 .getString("label.error_saving_file"),
1220 JvOptionPane.WARNING_MESSAGE);
1226 private void warningMessage(String warning, String title)
1228 if (new jalview.util.Platform().isHeadless())
1230 System.err.println("Warning: " + title + "\nWarning: " + warning);
1235 JvOptionPane.showInternalMessageDialog(this, warning, title,
1236 JvOptionPane.WARNING_MESSAGE);
1248 protected void outputText_actionPerformed(ActionEvent e)
1251 FileFormatI fileFormat = FileFormat.forName(e.getActionCommand());
1252 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1254 if (exportData.getSettings().isCancelled())
1258 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1259 cap.setForInput(null);
1262 FileFormatI format = fileFormat;
1263 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1264 .formatSequences(format,
1265 exportData.getAlignment(),
1266 exportData.getOmitHidden(),
1267 exportData.getStartEndPostions(),
1268 viewport.getColumnSelection()));
1269 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1270 "label.alignment_output_command",
1271 new Object[] { e.getActionCommand() }), 600, 500);
1272 } catch (OutOfMemoryError oom)
1274 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1280 public static AlignmentExportData getAlignmentForExport(
1281 FileFormatI format, AlignViewportI viewport,
1282 AlignExportSettingI exportSettings)
1284 AlignmentI alignmentToExport = null;
1285 AlignExportSettingI settings = exportSettings;
1286 String[] omitHidden = null;
1288 HiddenSequences hiddenSeqs = viewport.getAlignment()
1289 .getHiddenSequences();
1291 alignmentToExport = viewport.getAlignment();
1293 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1294 if (settings == null)
1296 settings = new AlignExportSettings(hasHiddenSeqs,
1297 viewport.hasHiddenColumns(), format);
1299 // settings.isExportAnnotations();
1301 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1303 omitHidden = viewport.getViewAsString(false,
1304 settings.isExportHiddenSequences());
1307 int[] alignmentStartEnd = new int[2];
1308 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1310 alignmentToExport = hiddenSeqs.getFullAlignment();
1314 alignmentToExport = viewport.getAlignment();
1316 alignmentStartEnd = alignmentToExport
1317 .getVisibleStartAndEndIndex(viewport.getColumnSelection()
1318 .getHiddenColumns());
1319 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1320 omitHidden, alignmentStartEnd, settings);
1331 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1333 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1334 htmlSVG.exportHTML(null);
1338 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1340 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1341 bjs.exportHTML(null);
1344 public void createImageMap(File file, String image)
1346 alignPanel.makePNGImageMap(file, image);
1356 public void createPNG(File f)
1358 alignPanel.makePNG(f);
1368 public void createEPS(File f)
1370 alignPanel.makeEPS(f);
1374 public void createSVG(File f)
1376 alignPanel.makeSVG(f);
1380 public void pageSetup_actionPerformed(ActionEvent e)
1382 PrinterJob printJob = PrinterJob.getPrinterJob();
1383 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1393 public void printMenuItem_actionPerformed(ActionEvent e)
1395 // Putting in a thread avoids Swing painting problems
1396 PrintThread thread = new PrintThread(alignPanel);
1401 public void exportFeatures_actionPerformed(ActionEvent e)
1403 new AnnotationExporter().exportFeatures(alignPanel);
1407 public void exportAnnotations_actionPerformed(ActionEvent e)
1409 new AnnotationExporter().exportAnnotations(alignPanel);
1413 public void associatedData_actionPerformed(ActionEvent e)
1415 // Pick the tree file
1416 JalviewFileChooser chooser = new JalviewFileChooser(
1417 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1418 chooser.setFileView(new JalviewFileView());
1419 chooser.setDialogTitle(MessageManager
1420 .getString("label.load_jalview_annotations"));
1421 chooser.setToolTipText(MessageManager
1422 .getString("label.load_jalview_annotations"));
1424 int value = chooser.showOpenDialog(null);
1426 if (value == JalviewFileChooser.APPROVE_OPTION)
1428 String choice = chooser.getSelectedFile().getPath();
1429 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1430 loadJalviewDataFile(choice, null, null, null);
1436 * Close the current view or all views in the alignment frame. If the frame
1437 * only contains one view then the alignment will be removed from memory.
1439 * @param closeAllTabs
1442 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1444 if (alignPanels != null && alignPanels.size() < 2)
1446 closeAllTabs = true;
1451 if (alignPanels != null)
1455 if (this.isClosed())
1457 // really close all the windows - otherwise wait till
1458 // setClosed(true) is called
1459 for (int i = 0; i < alignPanels.size(); i++)
1461 AlignmentPanel ap = alignPanels.get(i);
1468 closeView(alignPanel);
1475 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1476 * be called recursively, with the frame now in 'closed' state
1478 this.setClosed(true);
1480 } catch (Exception ex)
1482 ex.printStackTrace();
1487 * Close the specified panel and close up tabs appropriately.
1489 * @param panelToClose
1491 public void closeView(AlignmentPanel panelToClose)
1493 int index = tabbedPane.getSelectedIndex();
1494 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1495 alignPanels.remove(panelToClose);
1496 panelToClose.closePanel();
1497 panelToClose = null;
1499 tabbedPane.removeTabAt(closedindex);
1500 tabbedPane.validate();
1502 if (index > closedindex || index == tabbedPane.getTabCount())
1504 // modify currently selected tab index if necessary.
1508 this.tabSelectionChanged(index);
1514 void updateEditMenuBar()
1517 if (viewport.getHistoryList().size() > 0)
1519 undoMenuItem.setEnabled(true);
1520 CommandI command = viewport.getHistoryList().peek();
1521 undoMenuItem.setText(MessageManager.formatMessage(
1522 "label.undo_command",
1523 new Object[] { command.getDescription() }));
1527 undoMenuItem.setEnabled(false);
1528 undoMenuItem.setText(MessageManager.getString("action.undo"));
1531 if (viewport.getRedoList().size() > 0)
1533 redoMenuItem.setEnabled(true);
1535 CommandI command = viewport.getRedoList().peek();
1536 redoMenuItem.setText(MessageManager.formatMessage(
1537 "label.redo_command",
1538 new Object[] { command.getDescription() }));
1542 redoMenuItem.setEnabled(false);
1543 redoMenuItem.setText(MessageManager.getString("action.redo"));
1548 public void addHistoryItem(CommandI command)
1550 if (command.getSize() > 0)
1552 viewport.addToHistoryList(command);
1553 viewport.clearRedoList();
1554 updateEditMenuBar();
1555 viewport.updateHiddenColumns();
1556 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1557 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1558 // viewport.getColumnSelection()
1559 // .getHiddenColumns().size() > 0);
1565 * @return alignment objects for all views
1567 AlignmentI[] getViewAlignments()
1569 if (alignPanels != null)
1571 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1573 for (AlignmentPanel ap : alignPanels)
1575 als[i++] = ap.av.getAlignment();
1579 if (viewport != null)
1581 return new AlignmentI[] { viewport.getAlignment() };
1593 protected void undoMenuItem_actionPerformed(ActionEvent e)
1595 if (viewport.getHistoryList().isEmpty())
1599 CommandI command = viewport.getHistoryList().pop();
1600 viewport.addToRedoList(command);
1601 command.undoCommand(getViewAlignments());
1603 AlignmentViewport originalSource = getOriginatingSource(command);
1604 updateEditMenuBar();
1606 if (originalSource != null)
1608 if (originalSource != viewport)
1611 .warn("Implementation worry: mismatch of viewport origin for undo");
1613 originalSource.updateHiddenColumns();
1614 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1616 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1617 // viewport.getColumnSelection()
1618 // .getHiddenColumns().size() > 0);
1619 originalSource.firePropertyChange("alignment", null, originalSource
1620 .getAlignment().getSequences());
1631 protected void redoMenuItem_actionPerformed(ActionEvent e)
1633 if (viewport.getRedoList().size() < 1)
1638 CommandI command = viewport.getRedoList().pop();
1639 viewport.addToHistoryList(command);
1640 command.doCommand(getViewAlignments());
1642 AlignmentViewport originalSource = getOriginatingSource(command);
1643 updateEditMenuBar();
1645 if (originalSource != null)
1648 if (originalSource != viewport)
1651 .warn("Implementation worry: mismatch of viewport origin for redo");
1653 originalSource.updateHiddenColumns();
1654 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1656 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1657 // viewport.getColumnSelection()
1658 // .getHiddenColumns().size() > 0);
1659 originalSource.firePropertyChange("alignment", null, originalSource
1660 .getAlignment().getSequences());
1664 AlignmentViewport getOriginatingSource(CommandI command)
1666 AlignmentViewport originalSource = null;
1667 // For sequence removal and addition, we need to fire
1668 // the property change event FROM the viewport where the
1669 // original alignment was altered
1670 AlignmentI al = null;
1671 if (command instanceof EditCommand)
1673 EditCommand editCommand = (EditCommand) command;
1674 al = editCommand.getAlignment();
1675 List<Component> comps = PaintRefresher.components.get(viewport
1676 .getSequenceSetId());
1678 for (Component comp : comps)
1680 if (comp instanceof AlignmentPanel)
1682 if (al == ((AlignmentPanel) comp).av.getAlignment())
1684 originalSource = ((AlignmentPanel) comp).av;
1691 if (originalSource == null)
1693 // The original view is closed, we must validate
1694 // the current view against the closed view first
1697 PaintRefresher.validateSequences(al, viewport.getAlignment());
1700 originalSource = viewport;
1703 return originalSource;
1712 public void moveSelectedSequences(boolean up)
1714 SequenceGroup sg = viewport.getSelectionGroup();
1720 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1721 viewport.getHiddenRepSequences(), up);
1722 alignPanel.paintAlignment(true);
1725 synchronized void slideSequences(boolean right, int size)
1727 List<SequenceI> sg = new ArrayList<SequenceI>();
1728 if (viewport.cursorMode)
1730 sg.add(viewport.getAlignment().getSequenceAt(
1731 alignPanel.getSeqPanel().seqCanvas.cursorY));
1733 else if (viewport.getSelectionGroup() != null
1734 && viewport.getSelectionGroup().getSize() != viewport
1735 .getAlignment().getHeight())
1737 sg = viewport.getSelectionGroup().getSequences(
1738 viewport.getHiddenRepSequences());
1746 List<SequenceI> invertGroup = new ArrayList<SequenceI>();
1748 for (SequenceI seq : viewport.getAlignment().getSequences())
1750 if (!sg.contains(seq))
1752 invertGroup.add(seq);
1756 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1758 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1759 for (int i = 0; i < invertGroup.size(); i++)
1761 seqs2[i] = invertGroup.get(i);
1764 SlideSequencesCommand ssc;
1767 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1768 size, viewport.getGapCharacter());
1772 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1773 size, viewport.getGapCharacter());
1776 int groupAdjustment = 0;
1777 if (ssc.getGapsInsertedBegin() && right)
1779 if (viewport.cursorMode)
1781 alignPanel.getSeqPanel().moveCursor(size, 0);
1785 groupAdjustment = size;
1788 else if (!ssc.getGapsInsertedBegin() && !right)
1790 if (viewport.cursorMode)
1792 alignPanel.getSeqPanel().moveCursor(-size, 0);
1796 groupAdjustment = -size;
1800 if (groupAdjustment != 0)
1802 viewport.getSelectionGroup().setStartRes(
1803 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1804 viewport.getSelectionGroup().setEndRes(
1805 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1809 * just extend the last slide command if compatible; but not if in
1810 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1812 boolean appendHistoryItem = false;
1813 Deque<CommandI> historyList = viewport.getHistoryList();
1814 boolean inSplitFrame = getSplitViewContainer() != null;
1815 if (!inSplitFrame && historyList != null && historyList.size() > 0
1816 && historyList.peek() instanceof SlideSequencesCommand)
1818 appendHistoryItem = ssc
1819 .appendSlideCommand((SlideSequencesCommand) historyList
1823 if (!appendHistoryItem)
1825 addHistoryItem(ssc);
1838 protected void copy_actionPerformed(ActionEvent e)
1841 if (viewport.getSelectionGroup() == null)
1845 // TODO: preserve the ordering of displayed alignment annotation in any
1846 // internal paste (particularly sequence associated annotation)
1847 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1848 String[] omitHidden = null;
1850 if (viewport.hasHiddenColumns())
1852 omitHidden = viewport.getViewAsString(true);
1855 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1859 StringSelection ss = new StringSelection(output);
1863 jalview.gui.Desktop.internalCopy = true;
1864 // Its really worth setting the clipboard contents
1865 // to empty before setting the large StringSelection!!
1866 Toolkit.getDefaultToolkit().getSystemClipboard()
1867 .setContents(new StringSelection(""), null);
1869 Toolkit.getDefaultToolkit().getSystemClipboard()
1870 .setContents(ss, Desktop.instance);
1871 } catch (OutOfMemoryError er)
1873 new OOMWarning("copying region", er);
1877 ArrayList<int[]> hiddenColumns = null;
1878 if (viewport.hasHiddenColumns())
1880 hiddenColumns = new ArrayList<int[]>();
1881 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1882 .getSelectionGroup().getEndRes();
1883 for (int[] region : viewport.getColumnSelection().getHiddenColumns())
1885 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1887 hiddenColumns.add(new int[] { region[0] - hiddenOffset,
1888 region[1] - hiddenOffset });
1893 Desktop.jalviewClipboard = new Object[] { seqs,
1894 viewport.getAlignment().getDataset(), hiddenColumns };
1895 statusBar.setText(MessageManager.formatMessage(
1896 "label.copied_sequences_to_clipboard", new Object[] { Integer
1897 .valueOf(seqs.length).toString() }));
1907 protected void pasteNew_actionPerformed(ActionEvent e)
1919 protected void pasteThis_actionPerformed(ActionEvent e)
1925 * Paste contents of Jalview clipboard
1927 * @param newAlignment
1928 * true to paste to a new alignment, otherwise add to this.
1930 void paste(boolean newAlignment)
1932 boolean externalPaste = true;
1935 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1936 Transferable contents = c.getContents(this);
1938 if (contents == null)
1947 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1948 if (str.length() < 1)
1953 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
1955 } catch (OutOfMemoryError er)
1957 new OOMWarning("Out of memory pasting sequences!!", er);
1961 SequenceI[] sequences;
1962 boolean annotationAdded = false;
1963 AlignmentI alignment = null;
1965 if (Desktop.jalviewClipboard != null)
1967 // The clipboard was filled from within Jalview, we must use the
1969 // And dataset from the copied alignment
1970 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1971 // be doubly sure that we create *new* sequence objects.
1972 sequences = new SequenceI[newseq.length];
1973 for (int i = 0; i < newseq.length; i++)
1975 sequences[i] = new Sequence(newseq[i]);
1977 alignment = new Alignment(sequences);
1978 externalPaste = false;
1982 // parse the clipboard as an alignment.
1983 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
1985 sequences = alignment.getSequencesArray();
1989 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1995 if (Desktop.jalviewClipboard != null)
1997 // dataset is inherited
1998 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2002 // new dataset is constructed
2003 alignment.setDataset(null);
2005 alwidth = alignment.getWidth() + 1;
2009 AlignmentI pastedal = alignment; // preserve pasted alignment object
2010 // Add pasted sequences and dataset into existing alignment.
2011 alignment = viewport.getAlignment();
2012 alwidth = alignment.getWidth() + 1;
2013 // decide if we need to import sequences from an existing dataset
2014 boolean importDs = Desktop.jalviewClipboard != null
2015 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2016 // importDs==true instructs us to copy over new dataset sequences from
2017 // an existing alignment
2018 Vector newDs = (importDs) ? new Vector() : null; // used to create
2019 // minimum dataset set
2021 for (int i = 0; i < sequences.length; i++)
2025 newDs.addElement(null);
2027 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2029 if (importDs && ds != null)
2031 if (!newDs.contains(ds))
2033 newDs.setElementAt(ds, i);
2034 ds = new Sequence(ds);
2035 // update with new dataset sequence
2036 sequences[i].setDatasetSequence(ds);
2040 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2045 // copy and derive new dataset sequence
2046 sequences[i] = sequences[i].deriveSequence();
2047 alignment.getDataset().addSequence(
2048 sequences[i].getDatasetSequence());
2049 // TODO: avoid creation of duplicate dataset sequences with a
2050 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2052 alignment.addSequence(sequences[i]); // merges dataset
2056 newDs.clear(); // tidy up
2058 if (alignment.getAlignmentAnnotation() != null)
2060 for (AlignmentAnnotation alan : alignment
2061 .getAlignmentAnnotation())
2063 if (alan.graphGroup > fgroup)
2065 fgroup = alan.graphGroup;
2069 if (pastedal.getAlignmentAnnotation() != null)
2071 // Add any annotation attached to alignment.
2072 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2073 for (int i = 0; i < alann.length; i++)
2075 annotationAdded = true;
2076 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2078 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2079 if (newann.graphGroup > -1)
2081 if (newGraphGroups.size() <= newann.graphGroup
2082 || newGraphGroups.get(newann.graphGroup) == null)
2084 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2086 newGraphGroups.add(q, null);
2088 newGraphGroups.set(newann.graphGroup, new Integer(
2091 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2095 newann.padAnnotation(alwidth);
2096 alignment.addAnnotation(newann);
2106 addHistoryItem(new EditCommand(
2107 MessageManager.getString("label.add_sequences"),
2108 Action.PASTE, sequences, 0, alignment.getWidth(), alignment));
2110 // Add any annotations attached to sequences
2111 for (int i = 0; i < sequences.length; i++)
2113 if (sequences[i].getAnnotation() != null)
2115 AlignmentAnnotation newann;
2116 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2118 annotationAdded = true;
2119 newann = sequences[i].getAnnotation()[a];
2120 newann.adjustForAlignment();
2121 newann.padAnnotation(alwidth);
2122 if (newann.graphGroup > -1)
2124 if (newann.graphGroup > -1)
2126 if (newGraphGroups.size() <= newann.graphGroup
2127 || newGraphGroups.get(newann.graphGroup) == null)
2129 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2131 newGraphGroups.add(q, null);
2133 newGraphGroups.set(newann.graphGroup, new Integer(
2136 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2140 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2145 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2152 // propagate alignment changed.
2153 viewport.setEndSeq(alignment.getHeight());
2154 if (annotationAdded)
2156 // Duplicate sequence annotation in all views.
2157 AlignmentI[] alview = this.getViewAlignments();
2158 for (int i = 0; i < sequences.length; i++)
2160 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2165 for (int avnum = 0; avnum < alview.length; avnum++)
2167 if (alview[avnum] != alignment)
2169 // duplicate in a view other than the one with input focus
2170 int avwidth = alview[avnum].getWidth() + 1;
2171 // this relies on sann being preserved after we
2172 // modify the sequence's annotation array for each duplication
2173 for (int a = 0; a < sann.length; a++)
2175 AlignmentAnnotation newann = new AlignmentAnnotation(
2177 sequences[i].addAlignmentAnnotation(newann);
2178 newann.padAnnotation(avwidth);
2179 alview[avnum].addAnnotation(newann); // annotation was
2180 // duplicated earlier
2181 // TODO JAL-1145 graphGroups are not updated for sequence
2182 // annotation added to several views. This may cause
2184 alview[avnum].setAnnotationIndex(newann, a);
2189 buildSortByAnnotationScoresMenu();
2191 viewport.firePropertyChange("alignment", null,
2192 alignment.getSequences());
2193 if (alignPanels != null)
2195 for (AlignmentPanel ap : alignPanels)
2197 ap.validateAnnotationDimensions(false);
2202 alignPanel.validateAnnotationDimensions(false);
2208 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2210 String newtitle = new String("Copied sequences");
2212 if (Desktop.jalviewClipboard != null
2213 && Desktop.jalviewClipboard[2] != null)
2215 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2216 for (int[] region : hc)
2218 af.viewport.hideColumns(region[0], region[1]);
2222 // >>>This is a fix for the moment, until a better solution is
2224 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2226 alignPanel.getSeqPanel().seqCanvas
2227 .getFeatureRenderer());
2229 // TODO: maintain provenance of an alignment, rather than just make the
2230 // title a concatenation of operations.
2233 if (title.startsWith("Copied sequences"))
2239 newtitle = newtitle.concat("- from " + title);
2244 newtitle = new String("Pasted sequences");
2247 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2252 } catch (Exception ex)
2254 ex.printStackTrace();
2255 System.out.println("Exception whilst pasting: " + ex);
2256 // could be anything being pasted in here
2262 protected void expand_newalign(ActionEvent e)
2266 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2267 .getAlignment(), -1);
2268 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2270 String newtitle = new String("Flanking alignment");
2272 if (Desktop.jalviewClipboard != null
2273 && Desktop.jalviewClipboard[2] != null)
2275 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2276 for (int region[] : hc)
2278 af.viewport.hideColumns(region[0], region[1]);
2282 // >>>This is a fix for the moment, until a better solution is
2284 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2286 alignPanel.getSeqPanel().seqCanvas
2287 .getFeatureRenderer());
2289 // TODO: maintain provenance of an alignment, rather than just make the
2290 // title a concatenation of operations.
2292 if (title.startsWith("Copied sequences"))
2298 newtitle = newtitle.concat("- from " + title);
2302 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2304 } catch (Exception ex)
2306 ex.printStackTrace();
2307 System.out.println("Exception whilst pasting: " + ex);
2308 // could be anything being pasted in here
2309 } catch (OutOfMemoryError oom)
2311 new OOMWarning("Viewing flanking region of alignment", oom);
2322 protected void cut_actionPerformed(ActionEvent e)
2324 copy_actionPerformed(null);
2325 delete_actionPerformed(null);
2335 protected void delete_actionPerformed(ActionEvent evt)
2338 SequenceGroup sg = viewport.getSelectionGroup();
2345 * If the cut affects all sequences, warn, remove highlighted columns
2347 if (sg.getSize() == viewport.getAlignment().getHeight())
2349 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes()) + 1) == viewport
2350 .getAlignment().getWidth()) ? true : false;
2351 if (isEntireAlignWidth)
2353 int confirm = JvOptionPane.showConfirmDialog(this,
2354 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2355 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2356 JvOptionPane.OK_CANCEL_OPTION);
2358 if (confirm == JvOptionPane.CANCEL_OPTION
2359 || confirm == JvOptionPane.CLOSED_OPTION)
2364 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2365 sg.getEndRes() + 1);
2367 SequenceI[] cut = sg.getSequences()
2368 .toArray(new SequenceI[sg.getSize()]);
2370 addHistoryItem(new EditCommand(
2371 MessageManager.getString("label.cut_sequences"), Action.CUT,
2372 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2373 viewport.getAlignment()));
2375 viewport.setSelectionGroup(null);
2376 viewport.sendSelection();
2377 viewport.getAlignment().deleteGroup(sg);
2379 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2381 if (viewport.getAlignment().getHeight() < 1)
2385 this.setClosed(true);
2386 } catch (Exception ex)
2399 protected void deleteGroups_actionPerformed(ActionEvent e)
2401 if (avc.deleteGroups())
2403 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2404 alignPanel.updateAnnotation();
2405 alignPanel.paintAlignment(true);
2416 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2418 SequenceGroup sg = new SequenceGroup();
2420 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2422 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2425 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2426 viewport.setSelectionGroup(sg);
2427 viewport.sendSelection();
2428 // JAL-2034 - should delegate to
2429 // alignPanel to decide if overview needs
2431 alignPanel.paintAlignment(false);
2432 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2442 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2444 if (viewport.cursorMode)
2446 alignPanel.getSeqPanel().keyboardNo1 = null;
2447 alignPanel.getSeqPanel().keyboardNo2 = null;
2449 viewport.setSelectionGroup(null);
2450 viewport.getColumnSelection().clear();
2451 viewport.setSelectionGroup(null);
2452 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2453 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2454 // JAL-2034 - should delegate to
2455 // alignPanel to decide if overview needs
2457 alignPanel.paintAlignment(false);
2458 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2459 viewport.sendSelection();
2469 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2471 SequenceGroup sg = viewport.getSelectionGroup();
2475 selectAllSequenceMenuItem_actionPerformed(null);
2480 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2482 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2484 // JAL-2034 - should delegate to
2485 // alignPanel to decide if overview needs
2488 alignPanel.paintAlignment(true);
2489 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2490 viewport.sendSelection();
2494 public void invertColSel_actionPerformed(ActionEvent e)
2496 viewport.invertColumnSelection();
2497 alignPanel.paintAlignment(true);
2498 viewport.sendSelection();
2508 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2510 trimAlignment(true);
2520 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2522 trimAlignment(false);
2525 void trimAlignment(boolean trimLeft)
2527 ColumnSelection colSel = viewport.getColumnSelection();
2530 if (!colSel.isEmpty())
2534 column = colSel.getMin();
2538 column = colSel.getMax();
2542 if (viewport.getSelectionGroup() != null)
2544 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2545 viewport.getHiddenRepSequences());
2549 seqs = viewport.getAlignment().getSequencesArray();
2552 TrimRegionCommand trimRegion;
2555 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2556 column, viewport.getAlignment());
2557 viewport.setStartRes(0);
2561 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2562 column, viewport.getAlignment());
2565 statusBar.setText(MessageManager.formatMessage(
2566 "label.removed_columns",
2567 new String[] { Integer.valueOf(trimRegion.getSize())
2570 addHistoryItem(trimRegion);
2572 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2574 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2575 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2577 viewport.getAlignment().deleteGroup(sg);
2581 viewport.firePropertyChange("alignment", null, viewport
2582 .getAlignment().getSequences());
2593 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2595 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2598 if (viewport.getSelectionGroup() != null)
2600 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2601 viewport.getHiddenRepSequences());
2602 start = viewport.getSelectionGroup().getStartRes();
2603 end = viewport.getSelectionGroup().getEndRes();
2607 seqs = viewport.getAlignment().getSequencesArray();
2610 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2611 "Remove Gapped Columns", seqs, start, end,
2612 viewport.getAlignment());
2614 addHistoryItem(removeGapCols);
2616 statusBar.setText(MessageManager.formatMessage(
2617 "label.removed_empty_columns",
2618 new Object[] { Integer.valueOf(removeGapCols.getSize())
2621 // This is to maintain viewport position on first residue
2622 // of first sequence
2623 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2624 int startRes = seq.findPosition(viewport.startRes);
2625 // ShiftList shifts;
2626 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2627 // edit.alColumnChanges=shifts.getInverse();
2628 // if (viewport.hasHiddenColumns)
2629 // viewport.getColumnSelection().compensateForEdits(shifts);
2630 viewport.setStartRes(seq.findIndex(startRes) - 1);
2631 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2643 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2645 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2648 if (viewport.getSelectionGroup() != null)
2650 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2651 viewport.getHiddenRepSequences());
2652 start = viewport.getSelectionGroup().getStartRes();
2653 end = viewport.getSelectionGroup().getEndRes();
2657 seqs = viewport.getAlignment().getSequencesArray();
2660 // This is to maintain viewport position on first residue
2661 // of first sequence
2662 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2663 int startRes = seq.findPosition(viewport.startRes);
2665 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2666 viewport.getAlignment()));
2668 viewport.setStartRes(seq.findIndex(startRes) - 1);
2670 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2682 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2684 viewport.setPadGaps(padGapsMenuitem.isSelected());
2685 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2696 public void findMenuItem_actionPerformed(ActionEvent e)
2702 * Create a new view of the current alignment.
2705 public void newView_actionPerformed(ActionEvent e)
2707 newView(null, true);
2711 * Creates and shows a new view of the current alignment.
2714 * title of newly created view; if null, one will be generated
2715 * @param copyAnnotation
2716 * if true then duplicate all annnotation, groups and settings
2717 * @return new alignment panel, already displayed.
2719 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2722 * Create a new AlignmentPanel (with its own, new Viewport)
2724 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2726 if (!copyAnnotation)
2729 * remove all groups and annotation except for the automatic stuff
2731 newap.av.getAlignment().deleteAllGroups();
2732 newap.av.getAlignment().deleteAllAnnotations(false);
2735 newap.av.setGatherViewsHere(false);
2737 if (viewport.viewName == null)
2739 viewport.viewName = MessageManager
2740 .getString("label.view_name_original");
2744 * Views share the same edits undo and redo stacks
2746 newap.av.setHistoryList(viewport.getHistoryList());
2747 newap.av.setRedoList(viewport.getRedoList());
2750 * Views share the same mappings; need to deregister any new mappings
2751 * created by copyAlignPanel, and register the new reference to the shared
2754 newap.av.replaceMappings(viewport.getAlignment());
2756 newap.av.viewName = getNewViewName(viewTitle);
2758 addAlignmentPanel(newap, true);
2759 newap.alignmentChanged();
2761 if (alignPanels.size() == 2)
2763 viewport.setGatherViewsHere(true);
2765 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2770 * Make a new name for the view, ensuring it is unique within the current
2771 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2772 * these now use viewId. Unique view names are still desirable for usability.)
2777 protected String getNewViewName(String viewTitle)
2779 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2780 boolean addFirstIndex = false;
2781 if (viewTitle == null || viewTitle.trim().length() == 0)
2783 viewTitle = MessageManager.getString("action.view");
2784 addFirstIndex = true;
2788 index = 1;// we count from 1 if given a specific name
2790 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2792 List<Component> comps = PaintRefresher.components.get(viewport
2793 .getSequenceSetId());
2795 List<String> existingNames = getExistingViewNames(comps);
2797 while (existingNames.contains(newViewName))
2799 newViewName = viewTitle + " " + (++index);
2805 * Returns a list of distinct view names found in the given list of
2806 * components. View names are held on the viewport of an AlignmentPanel.
2811 protected List<String> getExistingViewNames(List<Component> comps)
2813 List<String> existingNames = new ArrayList<String>();
2814 for (Component comp : comps)
2816 if (comp instanceof AlignmentPanel)
2818 AlignmentPanel ap = (AlignmentPanel) comp;
2819 if (!existingNames.contains(ap.av.viewName))
2821 existingNames.add(ap.av.viewName);
2825 return existingNames;
2829 * Explode tabbed views into separate windows.
2832 public void expandViews_actionPerformed(ActionEvent e)
2834 Desktop.explodeViews(this);
2838 * Gather views in separate windows back into a tabbed presentation.
2841 public void gatherViews_actionPerformed(ActionEvent e)
2843 Desktop.instance.gatherViews(this);
2853 public void font_actionPerformed(ActionEvent e)
2855 new FontChooser(alignPanel);
2865 protected void seqLimit_actionPerformed(ActionEvent e)
2867 viewport.setShowJVSuffix(seqLimits.isSelected());
2869 alignPanel.getIdPanel().getIdCanvas()
2870 .setPreferredSize(alignPanel.calculateIdWidth());
2871 alignPanel.paintAlignment(true);
2875 public void idRightAlign_actionPerformed(ActionEvent e)
2877 viewport.setRightAlignIds(idRightAlign.isSelected());
2878 alignPanel.paintAlignment(true);
2882 public void centreColumnLabels_actionPerformed(ActionEvent e)
2884 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2885 alignPanel.paintAlignment(true);
2891 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2894 protected void followHighlight_actionPerformed()
2897 * Set the 'follow' flag on the Viewport (and scroll to position if now
2900 final boolean state = this.followHighlightMenuItem.getState();
2901 viewport.setFollowHighlight(state);
2904 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2915 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2917 viewport.setColourText(colourTextMenuItem.isSelected());
2918 alignPanel.paintAlignment(true);
2928 public void wrapMenuItem_actionPerformed(ActionEvent e)
2930 scaleAbove.setVisible(wrapMenuItem.isSelected());
2931 scaleLeft.setVisible(wrapMenuItem.isSelected());
2932 scaleRight.setVisible(wrapMenuItem.isSelected());
2933 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2934 alignPanel.updateLayout();
2938 public void showAllSeqs_actionPerformed(ActionEvent e)
2940 viewport.showAllHiddenSeqs();
2944 public void showAllColumns_actionPerformed(ActionEvent e)
2946 viewport.showAllHiddenColumns();
2948 viewport.sendSelection();
2952 public void hideSelSequences_actionPerformed(ActionEvent e)
2954 viewport.hideAllSelectedSeqs();
2955 // alignPanel.paintAlignment(true);
2959 * called by key handler and the hide all/show all menu items
2964 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2967 boolean hide = false;
2968 SequenceGroup sg = viewport.getSelectionGroup();
2969 if (!toggleSeqs && !toggleCols)
2971 // Hide everything by the current selection - this is a hack - we do the
2972 // invert and then hide
2973 // first check that there will be visible columns after the invert.
2974 if (viewport.hasSelectedColumns()
2975 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2978 // now invert the sequence set, if required - empty selection implies
2979 // that no hiding is required.
2982 invertSequenceMenuItem_actionPerformed(null);
2983 sg = viewport.getSelectionGroup();
2987 viewport.expandColSelection(sg, true);
2988 // finally invert the column selection and get the new sequence
2990 invertColSel_actionPerformed(null);
2997 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
2999 hideSelSequences_actionPerformed(null);
3002 else if (!(toggleCols && viewport.hasSelectedColumns()))
3004 showAllSeqs_actionPerformed(null);
3010 if (viewport.hasSelectedColumns())
3012 hideSelColumns_actionPerformed(null);
3015 viewport.setSelectionGroup(sg);
3020 showAllColumns_actionPerformed(null);
3029 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3030 * event.ActionEvent)
3033 public void hideAllButSelection_actionPerformed(ActionEvent e)
3035 toggleHiddenRegions(false, false);
3036 viewport.sendSelection();
3043 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3047 public void hideAllSelection_actionPerformed(ActionEvent e)
3049 SequenceGroup sg = viewport.getSelectionGroup();
3050 viewport.expandColSelection(sg, false);
3051 viewport.hideAllSelectedSeqs();
3052 viewport.hideSelectedColumns();
3053 alignPanel.paintAlignment(true);
3054 viewport.sendSelection();
3061 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3065 public void showAllhidden_actionPerformed(ActionEvent e)
3067 viewport.showAllHiddenColumns();
3068 viewport.showAllHiddenSeqs();
3069 alignPanel.paintAlignment(true);
3070 viewport.sendSelection();
3074 public void hideSelColumns_actionPerformed(ActionEvent e)
3076 viewport.hideSelectedColumns();
3077 alignPanel.paintAlignment(true);
3078 viewport.sendSelection();
3082 public void hiddenMarkers_actionPerformed(ActionEvent e)
3084 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3095 protected void scaleAbove_actionPerformed(ActionEvent e)
3097 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3098 alignPanel.paintAlignment(true);
3108 protected void scaleLeft_actionPerformed(ActionEvent e)
3110 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3111 alignPanel.paintAlignment(true);
3121 protected void scaleRight_actionPerformed(ActionEvent e)
3123 viewport.setScaleRightWrapped(scaleRight.isSelected());
3124 alignPanel.paintAlignment(true);
3134 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3136 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3137 alignPanel.paintAlignment(true);
3147 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3149 viewport.setShowText(viewTextMenuItem.isSelected());
3150 alignPanel.paintAlignment(true);
3160 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3162 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3163 alignPanel.paintAlignment(true);
3166 public FeatureSettings featureSettings;
3169 public FeatureSettingsControllerI getFeatureSettingsUI()
3171 return featureSettings;
3175 public void featureSettings_actionPerformed(ActionEvent e)
3177 if (featureSettings != null)
3179 featureSettings.close();
3180 featureSettings = null;
3182 if (!showSeqFeatures.isSelected())
3184 // make sure features are actually displayed
3185 showSeqFeatures.setSelected(true);
3186 showSeqFeatures_actionPerformed(null);
3188 featureSettings = new FeatureSettings(this);
3192 * Set or clear 'Show Sequence Features'
3198 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3200 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3201 alignPanel.paintAlignment(true);
3202 if (alignPanel.getOverviewPanel() != null)
3204 alignPanel.getOverviewPanel().updateOverviewImage();
3209 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3210 * the annotations panel as a whole.
3212 * The options to show/hide all annotations should be enabled when the panel
3213 * is shown, and disabled when the panel is hidden.
3218 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3220 final boolean setVisible = annotationPanelMenuItem.isSelected();
3221 viewport.setShowAnnotation(setVisible);
3222 this.showAllSeqAnnotations.setEnabled(setVisible);
3223 this.hideAllSeqAnnotations.setEnabled(setVisible);
3224 this.showAllAlAnnotations.setEnabled(setVisible);
3225 this.hideAllAlAnnotations.setEnabled(setVisible);
3226 alignPanel.updateLayout();
3230 public void alignmentProperties()
3232 JEditorPane editPane = new JEditorPane("text/html", "");
3233 editPane.setEditable(false);
3234 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3236 editPane.setText(MessageManager.formatMessage("label.html_content",
3237 new Object[] { contents.toString() }));
3238 JInternalFrame frame = new JInternalFrame();
3239 frame.getContentPane().add(new JScrollPane(editPane));
3241 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3242 "label.alignment_properties", new Object[] { getTitle() }),
3253 public void overviewMenuItem_actionPerformed(ActionEvent e)
3255 if (alignPanel.overviewPanel != null)
3260 JInternalFrame frame = new JInternalFrame();
3261 OverviewPanel overview = new OverviewPanel(alignPanel);
3262 frame.setContentPane(overview);
3263 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3264 "label.overview_params", new Object[] { this.getTitle() }),
3265 frame.getWidth(), frame.getHeight());
3267 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3268 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3271 public void internalFrameClosed(
3272 javax.swing.event.InternalFrameEvent evt)
3274 alignPanel.setOverviewPanel(null);
3278 alignPanel.setOverviewPanel(overview);
3282 public void textColour_actionPerformed()
3284 new TextColourChooser().chooseColour(alignPanel, null);
3288 * public void covariationColour_actionPerformed() {
3290 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3294 public void annotationColour_actionPerformed()
3296 new AnnotationColourChooser(viewport, alignPanel);
3300 public void annotationColumn_actionPerformed(ActionEvent e)
3302 new AnnotationColumnChooser(viewport, alignPanel);
3306 * Action on the user checking or unchecking the option to apply the selected
3307 * colour scheme to all groups. If unchecked, groups may have their own
3308 * independent colour schemes.
3312 protected void applyToAllGroups_actionPerformed()
3314 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3318 * Action on user selecting a colour from the colour menu
3321 * the name (not the menu item label!) of the colour scheme
3324 public void changeColour_actionPerformed(String name)
3327 * 'User Defined' opens a panel to configure or load a
3328 * user-defined colour scheme
3330 if (ResidueColourScheme.USER_DEFINED.equals(name))
3332 new UserDefinedColours(alignPanel, null);
3337 * otherwise set the chosen colour scheme (or null for 'None')
3339 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3340 viewport.getAlignment(), viewport.getHiddenRepSequences());
3345 * Actions on setting or changing the alignment colour scheme
3350 public void changeColour(ColourSchemeI cs)
3352 // TODO: pull up to controller method
3355 ColourMenuHelper.setColourSelected(colourMenu, cs.getSchemeName());
3356 // Make sure viewport is up to date w.r.t. any sliders
3357 if (viewport.getAbovePIDThreshold())
3359 int threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3361 viewport.setThreshold(threshold);
3364 if (viewport.getConservationSelected())
3366 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3371 viewport.setGlobalColourScheme(cs);
3373 alignPanel.paintAlignment(true);
3383 protected void modifyPID_actionPerformed()
3385 if (viewport.getAbovePIDThreshold()
3386 && viewport.getGlobalColourScheme() != null)
3388 SliderPanel.setPIDSliderSource(alignPanel,
3389 viewport.getGlobalColourScheme(), "Background");
3390 SliderPanel.showPIDSlider();
3401 protected void modifyConservation_actionPerformed()
3403 if (viewport.getConservationSelected()
3404 && viewport.getGlobalColourScheme() != null)
3406 SliderPanel.setConservationSlider(alignPanel,
3407 viewport.getGlobalColourScheme(), "Background");
3408 SliderPanel.showConservationSlider();
3419 protected void conservationMenuItem_actionPerformed()
3421 viewport.setConservationSelected(conservationMenuItem.isSelected());
3423 viewport.setAbovePIDThreshold(false);
3424 abovePIDThreshold.setSelected(false);
3426 changeColour(viewport.getGlobalColourScheme());
3428 modifyConservation_actionPerformed();
3438 public void abovePIDThreshold_actionPerformed()
3440 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3442 conservationMenuItem.setSelected(false);
3443 viewport.setConservationSelected(false);
3445 changeColour(viewport.getGlobalColourScheme());
3447 modifyPID_actionPerformed();
3457 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3459 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3460 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3461 .getAlignment().getSequenceAt(0), null);
3462 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3463 viewport.getAlignment()));
3464 alignPanel.paintAlignment(true);
3474 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3476 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3477 AlignmentSorter.sortByID(viewport.getAlignment());
3478 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3479 viewport.getAlignment()));
3480 alignPanel.paintAlignment(true);
3490 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3492 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3493 AlignmentSorter.sortByLength(viewport.getAlignment());
3494 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3495 viewport.getAlignment()));
3496 alignPanel.paintAlignment(true);
3506 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3508 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3509 AlignmentSorter.sortByGroup(viewport.getAlignment());
3510 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3511 viewport.getAlignment()));
3513 alignPanel.paintAlignment(true);
3523 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3525 new RedundancyPanel(alignPanel, this);
3535 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3537 if ((viewport.getSelectionGroup() == null)
3538 || (viewport.getSelectionGroup().getSize() < 2))
3540 JvOptionPane.showInternalMessageDialog(this, MessageManager
3541 .getString("label.you_must_select_least_two_sequences"),
3542 MessageManager.getString("label.invalid_selection"),
3543 JvOptionPane.WARNING_MESSAGE);
3547 JInternalFrame frame = new JInternalFrame();
3548 frame.setContentPane(new PairwiseAlignPanel(viewport));
3549 Desktop.addInternalFrame(frame,
3550 MessageManager.getString("action.pairwise_alignment"), 600,
3562 public void PCAMenuItem_actionPerformed(ActionEvent e)
3564 if (((viewport.getSelectionGroup() != null)
3565 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3566 .getSelectionGroup().getSize() > 0))
3567 || (viewport.getAlignment().getHeight() < 4))
3570 .showInternalMessageDialog(
3573 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3575 .getString("label.sequence_selection_insufficient"),
3576 JvOptionPane.WARNING_MESSAGE);
3581 new PCAPanel(alignPanel);
3585 public void autoCalculate_actionPerformed(ActionEvent e)
3587 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3588 if (viewport.autoCalculateConsensus)
3590 viewport.firePropertyChange("alignment", null, viewport
3591 .getAlignment().getSequences());
3596 public void sortByTreeOption_actionPerformed(ActionEvent e)
3598 viewport.sortByTree = sortByTree.isSelected();
3602 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3604 viewport.followSelection = listenToViewSelections.isSelected();
3614 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3616 newTreePanel("AV", "PID", "Average distance tree using PID");
3626 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3628 newTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3638 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3640 newTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3650 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3652 newTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3665 void newTreePanel(String type, String pwType, String title)
3669 if (viewport.getSelectionGroup() != null
3670 && viewport.getSelectionGroup().getSize() > 0)
3672 if (viewport.getSelectionGroup().getSize() < 3)
3678 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3680 .getString("label.not_enough_sequences"),
3681 JvOptionPane.WARNING_MESSAGE);
3685 SequenceGroup sg = viewport.getSelectionGroup();
3687 /* Decide if the selection is a column region */
3688 for (SequenceI _s : sg.getSequences())
3690 if (_s.getLength() < sg.getEndRes())
3696 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3698 .getString("label.sequences_selection_not_aligned"),
3699 JvOptionPane.WARNING_MESSAGE);
3705 title = title + " on region";
3706 tp = new TreePanel(alignPanel, type, pwType);
3710 // are the visible sequences aligned?
3711 if (!viewport.getAlignment().isAligned(false))
3717 .getString("label.sequences_must_be_aligned_before_creating_tree"),
3719 .getString("label.sequences_not_aligned"),
3720 JvOptionPane.WARNING_MESSAGE);
3725 if (viewport.getAlignment().getHeight() < 2)
3730 tp = new TreePanel(alignPanel, type, pwType);
3735 if (viewport.viewName != null)
3737 title += viewport.viewName + " of ";
3740 title += this.title;
3742 Desktop.addInternalFrame(tp, title, 600, 500);
3753 public void addSortByOrderMenuItem(String title,
3754 final AlignmentOrder order)
3756 final JMenuItem item = new JMenuItem(MessageManager.formatMessage(
3757 "action.by_title_param", new Object[] { title }));
3759 item.addActionListener(new java.awt.event.ActionListener()
3762 public void actionPerformed(ActionEvent e)
3764 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3766 // TODO: JBPNote - have to map order entries to curent SequenceI
3768 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3770 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
3773 alignPanel.paintAlignment(true);
3779 * Add a new sort by annotation score menu item
3782 * the menu to add the option to
3784 * the label used to retrieve scores for each sequence on the
3787 public void addSortByAnnotScoreMenuItem(JMenu sort,
3788 final String scoreLabel)
3790 final JMenuItem item = new JMenuItem(scoreLabel);
3792 item.addActionListener(new java.awt.event.ActionListener()
3795 public void actionPerformed(ActionEvent e)
3797 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3798 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3799 viewport.getAlignment());// ,viewport.getSelectionGroup());
3800 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3801 viewport.getAlignment()));
3802 alignPanel.paintAlignment(true);
3808 * last hash for alignment's annotation array - used to minimise cost of
3811 protected int _annotationScoreVectorHash;
3814 * search the alignment and rebuild the sort by annotation score submenu the
3815 * last alignment annotation vector hash is stored to minimize cost of
3816 * rebuilding in subsequence calls.
3820 public void buildSortByAnnotationScoresMenu()
3822 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3827 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
3829 sortByAnnotScore.removeAll();
3830 // almost certainly a quicker way to do this - but we keep it simple
3831 Hashtable scoreSorts = new Hashtable();
3832 AlignmentAnnotation aann[];
3833 for (SequenceI sqa : viewport.getAlignment().getSequences())
3835 aann = sqa.getAnnotation();
3836 for (int i = 0; aann != null && i < aann.length; i++)
3838 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3840 scoreSorts.put(aann[i].label, aann[i].label);
3844 Enumeration labels = scoreSorts.keys();
3845 while (labels.hasMoreElements())
3847 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3848 (String) labels.nextElement());
3850 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3853 _annotationScoreVectorHash = viewport.getAlignment()
3854 .getAlignmentAnnotation().hashCode();
3859 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3860 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3861 * call. Listeners are added to remove the menu item when the treePanel is
3862 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3866 * Displayed tree window.
3868 * SortBy menu item title.
3871 public void buildTreeMenu()
3873 calculateTree.removeAll();
3874 // build the calculate menu
3876 for (final String type : new String[] { "NJ", "AV" })
3878 String treecalcnm = MessageManager.getString("label.tree_calc_"
3879 + type.toLowerCase());
3880 for (final String pwtype : ResidueProperties.scoreMatrices.keySet())
3882 JMenuItem tm = new JMenuItem();
3883 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
3884 if (sm.isDNA() == viewport.getAlignment().isNucleotide()
3885 || sm.isProtein() == !viewport.getAlignment()
3888 String smn = MessageManager.getStringOrReturn(
3889 "label.score_model_", sm.getName());
3890 final String title = MessageManager.formatMessage(
3891 "label.treecalc_title", treecalcnm, smn);
3892 tm.setText(title);//
3893 tm.addActionListener(new java.awt.event.ActionListener()
3896 public void actionPerformed(ActionEvent e)
3898 newTreePanel(type, pwtype, title);
3901 calculateTree.add(tm);
3906 sortByTreeMenu.removeAll();
3908 List<Component> comps = PaintRefresher.components.get(viewport
3909 .getSequenceSetId());
3910 List<TreePanel> treePanels = new ArrayList<TreePanel>();
3911 for (Component comp : comps)
3913 if (comp instanceof TreePanel)
3915 treePanels.add((TreePanel) comp);
3919 if (treePanels.size() < 1)
3921 sortByTreeMenu.setVisible(false);
3925 sortByTreeMenu.setVisible(true);
3927 for (final TreePanel tp : treePanels)
3929 final JMenuItem item = new JMenuItem(tp.getTitle());
3930 item.addActionListener(new java.awt.event.ActionListener()
3933 public void actionPerformed(ActionEvent e)
3935 tp.sortByTree_actionPerformed();
3936 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3941 sortByTreeMenu.add(item);
3945 public boolean sortBy(AlignmentOrder alorder, String undoname)
3947 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3948 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3949 if (undoname != null)
3951 addHistoryItem(new OrderCommand(undoname, oldOrder,
3952 viewport.getAlignment()));
3954 alignPanel.paintAlignment(true);
3959 * Work out whether the whole set of sequences or just the selected set will
3960 * be submitted for multiple alignment.
3963 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3965 // Now, check we have enough sequences
3966 AlignmentView msa = null;
3968 if ((viewport.getSelectionGroup() != null)
3969 && (viewport.getSelectionGroup().getSize() > 1))
3971 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3972 // some common interface!
3974 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3975 * SequenceI[sz = seqs.getSize(false)];
3977 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3978 * seqs.getSequenceAt(i); }
3980 msa = viewport.getAlignmentView(true);
3982 else if (viewport.getSelectionGroup() != null
3983 && viewport.getSelectionGroup().getSize() == 1)
3985 int option = JvOptionPane.showConfirmDialog(this,
3986 MessageManager.getString("warn.oneseq_msainput_selection"),
3987 MessageManager.getString("label.invalid_selection"),
3988 JvOptionPane.OK_CANCEL_OPTION);
3989 if (option == JvOptionPane.OK_OPTION)
3991 msa = viewport.getAlignmentView(false);
3996 msa = viewport.getAlignmentView(false);
4002 * Decides what is submitted to a secondary structure prediction service: the
4003 * first sequence in the alignment, or in the current selection, or, if the
4004 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4005 * region or the whole alignment. (where the first sequence in the set is the
4006 * one that the prediction will be for).
4008 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4010 AlignmentView seqs = null;
4012 if ((viewport.getSelectionGroup() != null)
4013 && (viewport.getSelectionGroup().getSize() > 0))
4015 seqs = viewport.getAlignmentView(true);
4019 seqs = viewport.getAlignmentView(false);
4021 // limit sequences - JBPNote in future - could spawn multiple prediction
4023 // TODO: viewport.getAlignment().isAligned is a global state - the local
4024 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4025 if (!viewport.getAlignment().isAligned(false))
4027 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4028 // TODO: if seqs.getSequences().length>1 then should really have warned
4042 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4044 // Pick the tree file
4045 JalviewFileChooser chooser = new JalviewFileChooser(
4046 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4047 chooser.setFileView(new JalviewFileView());
4048 chooser.setDialogTitle(MessageManager
4049 .getString("label.select_newick_like_tree_file"));
4050 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4052 int value = chooser.showOpenDialog(null);
4054 if (value == JalviewFileChooser.APPROVE_OPTION)
4056 String choice = chooser.getSelectedFile().getPath();
4057 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4058 jalview.io.NewickFile fin = null;
4061 fin = new NewickFile(choice, DataSourceType.FILE);
4062 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4063 } catch (Exception ex)
4070 .getString("label.problem_reading_tree_file"),
4071 JvOptionPane.WARNING_MESSAGE);
4072 ex.printStackTrace();
4074 if (fin != null && fin.hasWarningMessage())
4076 JvOptionPane.showMessageDialog(Desktop.desktop, fin
4077 .getWarningMessage(), MessageManager
4078 .getString("label.possible_problem_with_tree_file"),
4079 JvOptionPane.WARNING_MESSAGE);
4084 public TreePanel ShowNewickTree(NewickFile nf, String title)
4086 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4089 public TreePanel ShowNewickTree(NewickFile nf, String title,
4090 AlignmentView input)
4092 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4095 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4096 int h, int x, int y)
4098 return ShowNewickTree(nf, title, null, w, h, x, y);
4102 * Add a treeviewer for the tree extracted from a newick file object to the
4103 * current alignment view
4110 * Associated alignment input data (or null)
4119 * @return TreePanel handle
4121 public TreePanel ShowNewickTree(NewickFile nf, String title,
4122 AlignmentView input, int w, int h, int x, int y)
4124 TreePanel tp = null;
4130 if (nf.getTree() != null)
4132 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4138 tp.setLocation(x, y);
4141 Desktop.addInternalFrame(tp, title, w, h);
4143 } catch (Exception ex)
4145 ex.printStackTrace();
4151 private boolean buildingMenu = false;
4154 * Generates menu items and listener event actions for web service clients
4157 public void BuildWebServiceMenu()
4159 while (buildingMenu)
4163 System.err.println("Waiting for building menu to finish.");
4165 } catch (Exception e)
4169 final AlignFrame me = this;
4170 buildingMenu = true;
4171 new Thread(new Runnable()
4176 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4179 // System.err.println("Building ws menu again "
4180 // + Thread.currentThread());
4181 // TODO: add support for context dependent disabling of services based
4183 // alignment and current selection
4184 // TODO: add additional serviceHandle parameter to specify abstract
4186 // class independently of AbstractName
4187 // TODO: add in rediscovery GUI function to restart discoverer
4188 // TODO: group services by location as well as function and/or
4190 // object broker mechanism.
4191 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4192 final IProgressIndicator af = me;
4195 * do not i18n these strings - they are hard-coded in class
4196 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4197 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4199 final JMenu msawsmenu = new JMenu("Alignment");
4200 final JMenu secstrmenu = new JMenu(
4201 "Secondary Structure Prediction");
4202 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4203 final JMenu analymenu = new JMenu("Analysis");
4204 final JMenu dismenu = new JMenu("Protein Disorder");
4205 // JAL-940 - only show secondary structure prediction services from
4206 // the legacy server
4207 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4209 Discoverer.services != null && (Discoverer.services.size() > 0))
4211 // TODO: refactor to allow list of AbstractName/Handler bindings to
4213 // stored or retrieved from elsewhere
4214 // No MSAWS used any more:
4215 // Vector msaws = null; // (Vector)
4216 // Discoverer.services.get("MsaWS");
4217 Vector secstrpr = (Vector) Discoverer.services
4219 if (secstrpr != null)
4221 // Add any secondary structure prediction services
4222 for (int i = 0, j = secstrpr.size(); i < j; i++)
4224 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4226 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4227 .getServiceClient(sh);
4228 int p = secstrmenu.getItemCount();
4229 impl.attachWSMenuEntry(secstrmenu, me);
4230 int q = secstrmenu.getItemCount();
4231 for (int litm = p; litm < q; litm++)
4233 legacyItems.add(secstrmenu.getItem(litm));
4239 // Add all submenus in the order they should appear on the web
4241 wsmenu.add(msawsmenu);
4242 wsmenu.add(secstrmenu);
4243 wsmenu.add(dismenu);
4244 wsmenu.add(analymenu);
4245 // No search services yet
4246 // wsmenu.add(seqsrchmenu);
4248 javax.swing.SwingUtilities.invokeLater(new Runnable()
4255 webService.removeAll();
4256 // first, add discovered services onto the webservices menu
4257 if (wsmenu.size() > 0)
4259 for (int i = 0, j = wsmenu.size(); i < j; i++)
4261 webService.add(wsmenu.get(i));
4266 webService.add(me.webServiceNoServices);
4268 // TODO: move into separate menu builder class.
4269 boolean new_sspred = false;
4270 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4272 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4273 if (jws2servs != null)
4275 if (jws2servs.hasServices())
4277 jws2servs.attachWSMenuEntry(webService, me);
4278 for (Jws2Instance sv : jws2servs.getServices())
4280 if (sv.description.toLowerCase().contains("jpred"))
4282 for (JMenuItem jmi : legacyItems)
4284 jmi.setVisible(false);
4290 if (jws2servs.isRunning())
4292 JMenuItem tm = new JMenuItem(
4293 "Still discovering JABA Services");
4294 tm.setEnabled(false);
4299 build_urlServiceMenu(me.webService);
4300 build_fetchdbmenu(webService);
4301 for (JMenu item : wsmenu)
4303 if (item.getItemCount() == 0)
4305 item.setEnabled(false);
4309 item.setEnabled(true);
4312 } catch (Exception e)
4315 .debug("Exception during web service menu building process.",
4320 } catch (Exception e)
4323 buildingMenu = false;
4330 * construct any groupURL type service menu entries.
4334 private void build_urlServiceMenu(JMenu webService)
4336 // TODO: remove this code when 2.7 is released
4337 // DEBUG - alignmentView
4339 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4340 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4342 * @Override public void actionPerformed(ActionEvent e) {
4343 * jalview.datamodel.AlignmentView
4344 * .testSelectionViews(af.viewport.getAlignment(),
4345 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4347 * }); webService.add(testAlView);
4349 // TODO: refactor to RestClient discoverer and merge menu entries for
4350 // rest-style services with other types of analysis/calculation service
4351 // SHmmr test client - still being implemented.
4352 // DEBUG - alignmentView
4354 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4357 client.attachWSMenuEntry(
4358 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4364 * Searches the alignment sequences for xRefs and builds the Show
4365 * Cross-References menu (formerly called Show Products), with database
4366 * sources for which cross-references are found (protein sources for a
4367 * nucleotide alignment and vice versa)
4369 * @return true if Show Cross-references menu should be enabled
4371 public boolean canShowProducts()
4373 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4374 AlignmentI dataset = viewport.getAlignment().getDataset();
4376 showProducts.removeAll();
4377 final boolean dna = viewport.getAlignment().isNucleotide();
4379 if (seqs == null || seqs.length == 0)
4381 // nothing to see here.
4385 boolean showp = false;
4388 List<String> ptypes = new CrossRef(seqs, dataset)
4389 .findXrefSourcesForSequences(dna);
4391 for (final String source : ptypes)
4394 final AlignFrame af = this;
4395 JMenuItem xtype = new JMenuItem(source);
4396 xtype.addActionListener(new ActionListener()
4399 public void actionPerformed(ActionEvent e)
4401 showProductsFor(af.viewport.getSequenceSelection(), dna, source);
4404 showProducts.add(xtype);
4406 showProducts.setVisible(showp);
4407 showProducts.setEnabled(showp);
4408 } catch (Exception e)
4411 .warn("canShowProducts threw an exception - please report to help@jalview.org",
4419 * Finds and displays cross-references for the selected sequences (protein
4420 * products for nucleotide sequences, dna coding sequences for peptides).
4423 * the sequences to show cross-references for
4425 * true if from a nucleotide alignment (so showing proteins)
4427 * the database to show cross-references for
4429 protected void showProductsFor(final SequenceI[] sel,
4430 final boolean _odna, final String source)
4432 new Thread(CrossRefAction.showProductsFor(sel, _odna, source, this))
4437 * Construct and display a new frame containing the translation of this
4438 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4441 public void showTranslation_actionPerformed(ActionEvent e)
4443 AlignmentI al = null;
4446 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4448 al = dna.translateCdna();
4449 } catch (Exception ex)
4451 jalview.bin.Cache.log.error(
4452 "Exception during translation. Please report this !", ex);
4453 final String msg = MessageManager
4454 .getString("label.error_when_translating_sequences_submit_bug_report");
4455 final String errorTitle = MessageManager
4456 .getString("label.implementation_error")
4457 + MessageManager.getString("label.translation_failed");
4458 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4459 JvOptionPane.ERROR_MESSAGE);
4462 if (al == null || al.getHeight() == 0)
4464 final String msg = MessageManager
4465 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4466 final String errorTitle = MessageManager
4467 .getString("label.translation_failed");
4468 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4469 JvOptionPane.WARNING_MESSAGE);
4473 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4474 af.setFileFormat(this.currentFileFormat);
4475 final String newTitle = MessageManager.formatMessage(
4476 "label.translation_of_params",
4477 new Object[] { this.getTitle() });
4478 af.setTitle(newTitle);
4479 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4481 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4482 viewport.openSplitFrame(af, new Alignment(seqs));
4486 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4493 * Set the file format
4497 public void setFileFormat(FileFormatI format)
4499 this.currentFileFormat = format;
4503 * Try to load a features file onto the alignment.
4506 * contents or path to retrieve file
4508 * access mode of file (see jalview.io.AlignFile)
4509 * @return true if features file was parsed correctly.
4511 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4513 return avc.parseFeaturesFile(file, sourceType,
4514 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4519 public void refreshFeatureUI(boolean enableIfNecessary)
4521 // note - currently this is only still here rather than in the controller
4522 // because of the featureSettings hard reference that is yet to be
4524 if (enableIfNecessary)
4526 viewport.setShowSequenceFeatures(true);
4527 showSeqFeatures.setSelected(true);
4533 public void dragEnter(DropTargetDragEvent evt)
4538 public void dragExit(DropTargetEvent evt)
4543 public void dragOver(DropTargetDragEvent evt)
4548 public void dropActionChanged(DropTargetDragEvent evt)
4553 public void drop(DropTargetDropEvent evt)
4555 // JAL-1552 - acceptDrop required before getTransferable call for
4556 // Java's Transferable for native dnd
4557 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4558 Transferable t = evt.getTransferable();
4559 List<String> files = new ArrayList<String>();
4560 List<DataSourceType> protocols = new ArrayList<DataSourceType>();
4564 Desktop.transferFromDropTarget(files, protocols, evt, t);
4565 } catch (Exception e)
4567 e.printStackTrace();
4573 // check to see if any of these files have names matching sequences in
4575 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4576 .getAlignment().getSequencesArray());
4578 * Object[] { String,SequenceI}
4580 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
4581 ArrayList<String> filesnotmatched = new ArrayList<String>();
4582 for (int i = 0; i < files.size(); i++)
4584 String file = files.get(i).toString();
4586 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4587 if (protocol == DataSourceType.FILE)
4589 File fl = new File(file);
4590 pdbfn = fl.getName();
4592 else if (protocol == DataSourceType.URL)
4594 URL url = new URL(file);
4595 pdbfn = url.getFile();
4597 if (pdbfn.length() > 0)
4599 // attempt to find a match in the alignment
4600 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4601 int l = 0, c = pdbfn.indexOf(".");
4602 while (mtch == null && c != -1)
4607 } while ((c = pdbfn.indexOf(".", l)) > l);
4610 pdbfn = pdbfn.substring(0, l);
4612 mtch = idm.findAllIdMatches(pdbfn);
4616 FileFormatI type = null;
4619 type = new IdentifyFile().identify(file, protocol);
4620 } catch (Exception ex)
4624 if (type != null && type.isStructureFile())
4626 filesmatched.add(new Object[] { file, protocol, mtch });
4630 // File wasn't named like one of the sequences or wasn't a PDB file.
4631 filesnotmatched.add(file);
4635 if (filesmatched.size() > 0)
4637 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4643 "label.automatically_associate_structure_files_with_sequences_same_name",
4644 new Object[] { Integer
4650 .getString("label.automatically_associate_structure_files_by_name"),
4651 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION)
4654 for (Object[] fm : filesmatched)
4656 // try and associate
4657 // TODO: may want to set a standard ID naming formalism for
4658 // associating PDB files which have no IDs.
4659 for (SequenceI toassoc : (SequenceI[]) fm[2])
4661 PDBEntry pe = new AssociatePdbFileWithSeq()
4662 .associatePdbWithSeq((String) fm[0],
4663 (DataSourceType) fm[1], toassoc, false,
4667 System.err.println("Associated file : "
4668 + ((String) fm[0]) + " with "
4669 + toassoc.getDisplayId(true));
4673 alignPanel.paintAlignment(true);
4677 if (filesnotmatched.size() > 0)
4680 && (Cache.getDefault(
4681 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JvOptionPane
4687 "label.ignore_unmatched_dropped_files_info",
4688 new Object[] { Integer
4695 .getString("label.ignore_unmatched_dropped_files"),
4696 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4700 for (String fn : filesnotmatched)
4702 loadJalviewDataFile(fn, null, null, null);
4706 } catch (Exception ex)
4708 ex.printStackTrace();
4714 * Attempt to load a "dropped" file or URL string: First by testing whether
4715 * it's an Annotation file, then a JNet file, and finally a features file. If
4716 * all are false then the user may have dropped an alignment file onto this
4720 * either a filename or a URL string.
4722 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4723 FileFormatI format, SequenceI assocSeq)
4727 if (sourceType == null)
4729 sourceType = FormatAdapter.checkProtocol(file);
4731 // if the file isn't identified, or not positively identified as some
4732 // other filetype (PFAM is default unidentified alignment file type) then
4733 // try to parse as annotation.
4734 boolean isAnnotation = (format == null || FileFormat.Pfam
4735 .equals(format)) ? new AnnotationFile()
4736 .annotateAlignmentView(viewport, file, sourceType) : false;
4740 // first see if its a T-COFFEE score file
4741 TCoffeeScoreFile tcf = null;
4744 tcf = new TCoffeeScoreFile(file, sourceType);
4747 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4750 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
4751 isAnnotation = true;
4753 .setText(MessageManager
4754 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
4758 // some problem - if no warning its probable that the ID matching
4759 // process didn't work
4763 tcf.getWarningMessage() == null ? MessageManager
4764 .getString("label.check_file_matches_sequence_ids_alignment")
4765 : tcf.getWarningMessage(),
4767 .getString("label.problem_reading_tcoffee_score_file"),
4768 JvOptionPane.WARNING_MESSAGE);
4775 } catch (Exception x)
4778 .debug("Exception when processing data source as T-COFFEE score file",
4784 // try to see if its a JNet 'concise' style annotation file *before*
4786 // try to parse it as a features file
4789 format = new IdentifyFile().identify(file, sourceType);
4791 if (FileFormat.Jnet.equals(format))
4793 JPredFile predictions = new JPredFile(
4795 new JnetAnnotationMaker();
4796 JnetAnnotationMaker.add_annotation(predictions,
4797 viewport.getAlignment(), 0, false);
4798 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
4799 viewport.getAlignment().setSeqrep(repseq);
4800 ColumnSelection cs = new ColumnSelection();
4801 cs.hideInsertionsFor(repseq);
4802 viewport.setColumnSelection(cs);
4803 isAnnotation = true;
4805 // else if (IdentifyFile.FeaturesFile.equals(format))
4806 else if (FileFormat.Features.equals(format))
4808 if (parseFeaturesFile(file, sourceType))
4810 alignPanel.paintAlignment(true);
4815 new FileLoader().LoadFile(viewport, file, sourceType, format);
4822 alignPanel.adjustAnnotationHeight();
4823 viewport.updateSequenceIdColours();
4824 buildSortByAnnotationScoresMenu();
4825 alignPanel.paintAlignment(true);
4827 } catch (Exception ex)
4829 ex.printStackTrace();
4830 } catch (OutOfMemoryError oom)
4835 } catch (Exception x)
4840 + (sourceType != null ? (sourceType == DataSourceType.PASTE ? "from clipboard."
4841 : "using " + sourceType + " from " + file)
4843 + (format != null ? "(parsing as '" + format
4844 + "' file)" : ""), oom, Desktop.desktop);
4849 * Method invoked by the ChangeListener on the tabbed pane, in other words
4850 * when a different tabbed pane is selected by the user or programmatically.
4853 public void tabSelectionChanged(int index)
4857 alignPanel = alignPanels.get(index);
4858 viewport = alignPanel.av;
4859 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4860 setMenusFromViewport(viewport);
4864 * If there is a frame linked to this one in a SplitPane, switch it to the
4865 * same view tab index. No infinite recursion of calls should happen, since
4866 * tabSelectionChanged() should not get invoked on setting the selected
4867 * index to an unchanged value. Guard against setting an invalid index
4868 * before the new view peer tab has been created.
4870 final AlignViewportI peer = viewport.getCodingComplement();
4873 AlignFrame linkedAlignFrame = ((AlignViewport) peer).getAlignPanel().alignFrame;
4874 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4876 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4882 * On right mouse click on view tab, prompt for and set new view name.
4885 public void tabbedPane_mousePressed(MouseEvent e)
4887 if (e.isPopupTrigger())
4889 String msg = MessageManager.getString("label.enter_view_name");
4890 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4891 JvOptionPane.QUESTION_MESSAGE);
4895 viewport.viewName = reply;
4896 // TODO warn if reply is in getExistingViewNames()?
4897 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4902 public AlignViewport getCurrentView()
4908 * Open the dialog for regex description parsing.
4911 protected void extractScores_actionPerformed(ActionEvent e)
4913 ParseProperties pp = new jalview.analysis.ParseProperties(
4914 viewport.getAlignment());
4915 // TODO: verify regex and introduce GUI dialog for version 2.5
4916 // if (pp.getScoresFromDescription("col", "score column ",
4917 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4919 if (pp.getScoresFromDescription("description column",
4920 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4922 buildSortByAnnotationScoresMenu();
4930 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4934 protected void showDbRefs_actionPerformed(ActionEvent e)
4936 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4942 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4946 protected void showNpFeats_actionPerformed(ActionEvent e)
4948 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4952 * find the viewport amongst the tabs in this alignment frame and close that
4957 public boolean closeView(AlignViewportI av)
4961 this.closeMenuItem_actionPerformed(false);
4964 Component[] comp = tabbedPane.getComponents();
4965 for (int i = 0; comp != null && i < comp.length; i++)
4967 if (comp[i] instanceof AlignmentPanel)
4969 if (((AlignmentPanel) comp[i]).av == av)
4972 closeView((AlignmentPanel) comp[i]);
4980 protected void build_fetchdbmenu(JMenu webService)
4982 // Temporary hack - DBRef Fetcher always top level ws entry.
4983 // TODO We probably want to store a sequence database checklist in
4984 // preferences and have checkboxes.. rather than individual sources selected
4986 final JMenu rfetch = new JMenu(
4987 MessageManager.getString("action.fetch_db_references"));
4988 rfetch.setToolTipText(MessageManager
4989 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4990 webService.add(rfetch);
4992 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4993 MessageManager.getString("option.trim_retrieved_seqs"));
4994 trimrs.setToolTipText(MessageManager
4995 .getString("label.trim_retrieved_sequences"));
4996 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
4997 trimrs.addActionListener(new ActionListener()
5000 public void actionPerformed(ActionEvent e)
5002 trimrs.setSelected(trimrs.isSelected());
5003 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5004 Boolean.valueOf(trimrs.isSelected()).toString());
5008 JMenuItem fetchr = new JMenuItem(
5009 MessageManager.getString("label.standard_databases"));
5010 fetchr.setToolTipText(MessageManager
5011 .getString("label.fetch_embl_uniprot"));
5012 fetchr.addActionListener(new ActionListener()
5016 public void actionPerformed(ActionEvent e)
5018 new Thread(new Runnable()
5023 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5024 .getAlignment().isNucleotide();
5025 DBRefFetcher dbRefFetcher = new DBRefFetcher(alignPanel.av
5026 .getSequenceSelection(), alignPanel.alignFrame, null,
5027 alignPanel.alignFrame.featureSettings, isNucleotide);
5028 dbRefFetcher.addListener(new FetchFinishedListenerI()
5031 public void finished()
5033 AlignFrame.this.setMenusForViewport();
5036 dbRefFetcher.fetchDBRefs(false);
5044 final AlignFrame me = this;
5045 new Thread(new Runnable()
5050 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5051 .getSequenceFetcherSingleton(me);
5052 javax.swing.SwingUtilities.invokeLater(new Runnable()
5057 String[] dbclasses = sf.getOrderedSupportedSources();
5058 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5059 // jalview.util.QuickSort.sort(otherdb, otherdb);
5060 List<DbSourceProxy> otherdb;
5061 JMenu dfetch = new JMenu();
5062 JMenu ifetch = new JMenu();
5063 JMenuItem fetchr = null;
5064 int comp = 0, icomp = 0, mcomp = 15;
5065 String mname = null;
5067 for (String dbclass : dbclasses)
5069 otherdb = sf.getSourceProxy(dbclass);
5070 // add a single entry for this class, or submenu allowing 'fetch
5072 if (otherdb == null || otherdb.size() < 1)
5076 // List<DbSourceProxy> dbs=otherdb;
5077 // otherdb=new ArrayList<DbSourceProxy>();
5078 // for (DbSourceProxy db:dbs)
5080 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5084 mname = "From " + dbclass;
5086 if (otherdb.size() == 1)
5088 final DbSourceProxy[] dassource = otherdb
5089 .toArray(new DbSourceProxy[0]);
5090 DbSourceProxy src = otherdb.get(0);
5091 fetchr = new JMenuItem(src.getDbSource());
5092 fetchr.addActionListener(new ActionListener()
5096 public void actionPerformed(ActionEvent e)
5098 new Thread(new Runnable()
5104 boolean isNucleotide = alignPanel.alignFrame
5105 .getViewport().getAlignment()
5107 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5108 alignPanel.av.getSequenceSelection(),
5109 alignPanel.alignFrame, dassource,
5110 alignPanel.alignFrame.featureSettings,
5113 .addListener(new FetchFinishedListenerI()
5116 public void finished()
5118 AlignFrame.this.setMenusForViewport();
5121 dbRefFetcher.fetchDBRefs(false);
5127 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5128 MessageManager.formatMessage(
5129 "label.fetch_retrieve_from",
5130 new Object[] { src.getDbName() })));
5136 final DbSourceProxy[] dassource = otherdb
5137 .toArray(new DbSourceProxy[0]);
5139 DbSourceProxy src = otherdb.get(0);
5140 fetchr = new JMenuItem(MessageManager.formatMessage(
5141 "label.fetch_all_param",
5142 new Object[] { src.getDbSource() }));
5143 fetchr.addActionListener(new ActionListener()
5146 public void actionPerformed(ActionEvent e)
5148 new Thread(new Runnable()
5154 boolean isNucleotide = alignPanel.alignFrame
5155 .getViewport().getAlignment()
5157 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5158 alignPanel.av.getSequenceSelection(),
5159 alignPanel.alignFrame, dassource,
5160 alignPanel.alignFrame.featureSettings,
5163 .addListener(new FetchFinishedListenerI()
5166 public void finished()
5168 AlignFrame.this.setMenusForViewport();
5171 dbRefFetcher.fetchDBRefs(false);
5177 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5178 MessageManager.formatMessage(
5179 "label.fetch_retrieve_from_all_sources",
5181 Integer.valueOf(otherdb.size())
5182 .toString(), src.getDbSource(),
5183 src.getDbName() })));
5186 // and then build the rest of the individual menus
5187 ifetch = new JMenu(MessageManager.formatMessage(
5188 "label.source_from_db_source",
5189 new Object[] { src.getDbSource() }));
5191 String imname = null;
5193 for (DbSourceProxy sproxy : otherdb)
5195 String dbname = sproxy.getDbName();
5196 String sname = dbname.length() > 5 ? dbname.substring(0,
5197 5) + "..." : dbname;
5198 String msname = dbname.length() > 10 ? dbname.substring(
5199 0, 10) + "..." : dbname;
5202 imname = MessageManager.formatMessage(
5203 "label.from_msname", new Object[] { sname });
5205 fetchr = new JMenuItem(msname);
5206 final DbSourceProxy[] dassrc = { sproxy };
5207 fetchr.addActionListener(new ActionListener()
5211 public void actionPerformed(ActionEvent e)
5213 new Thread(new Runnable()
5219 boolean isNucleotide = alignPanel.alignFrame
5220 .getViewport().getAlignment()
5222 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5223 alignPanel.av.getSequenceSelection(),
5224 alignPanel.alignFrame, dassrc,
5225 alignPanel.alignFrame.featureSettings,
5228 .addListener(new FetchFinishedListenerI()
5231 public void finished()
5233 AlignFrame.this.setMenusForViewport();
5236 dbRefFetcher.fetchDBRefs(false);
5242 fetchr.setToolTipText("<html>"
5243 + MessageManager.formatMessage(
5244 "label.fetch_retrieve_from", new Object[]
5248 if (++icomp >= mcomp || i == (otherdb.size()))
5250 ifetch.setText(MessageManager.formatMessage(
5251 "label.source_to_target", imname, sname));
5253 ifetch = new JMenu();
5261 if (comp >= mcomp || dbi >= (dbclasses.length))
5263 dfetch.setText(MessageManager.formatMessage(
5264 "label.source_to_target", mname, dbclass));
5266 dfetch = new JMenu();
5279 * Left justify the whole alignment.
5282 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5284 AlignmentI al = viewport.getAlignment();
5286 viewport.firePropertyChange("alignment", null, al);
5290 * Right justify the whole alignment.
5293 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5295 AlignmentI al = viewport.getAlignment();
5297 viewport.firePropertyChange("alignment", null, al);
5301 public void setShowSeqFeatures(boolean b)
5303 showSeqFeatures.setSelected(b);
5304 viewport.setShowSequenceFeatures(b);
5311 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5312 * awt.event.ActionEvent)
5315 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5317 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5318 alignPanel.paintAlignment(true);
5325 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5329 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5331 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5332 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5340 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5341 * .event.ActionEvent)
5344 protected void showGroupConservation_actionPerformed(ActionEvent e)
5346 viewport.setShowGroupConservation(showGroupConservation.getState());
5347 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5354 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5355 * .event.ActionEvent)
5358 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5360 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5361 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5368 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5369 * .event.ActionEvent)
5372 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5374 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5375 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5379 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5381 showSequenceLogo.setState(true);
5382 viewport.setShowSequenceLogo(true);
5383 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5384 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5388 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5390 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5397 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5398 * .event.ActionEvent)
5401 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5403 if (avc.makeGroupsFromSelection())
5405 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5406 alignPanel.updateAnnotation();
5407 alignPanel.paintAlignment(true);
5411 public void clearAlignmentSeqRep()
5413 // TODO refactor alignmentseqrep to controller
5414 if (viewport.getAlignment().hasSeqrep())
5416 viewport.getAlignment().setSeqrep(null);
5417 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5418 alignPanel.updateAnnotation();
5419 alignPanel.paintAlignment(true);
5424 protected void createGroup_actionPerformed(ActionEvent e)
5426 if (avc.createGroup())
5428 alignPanel.alignmentChanged();
5433 protected void unGroup_actionPerformed(ActionEvent e)
5437 alignPanel.alignmentChanged();
5442 * make the given alignmentPanel the currently selected tab
5444 * @param alignmentPanel
5446 public void setDisplayedView(AlignmentPanel alignmentPanel)
5448 if (!viewport.getSequenceSetId().equals(
5449 alignmentPanel.av.getSequenceSetId()))
5453 .getString("error.implementation_error_cannot_show_view_alignment_frame"));
5455 if (tabbedPane != null
5456 && tabbedPane.getTabCount() > 0
5457 && alignPanels.indexOf(alignmentPanel) != tabbedPane
5458 .getSelectedIndex())
5460 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5465 * Action on selection of menu options to Show or Hide annotations.
5468 * @param forSequences
5469 * update sequence-related annotations
5470 * @param forAlignment
5471 * update non-sequence-related annotations
5474 protected void setAnnotationsVisibility(boolean visible,
5475 boolean forSequences, boolean forAlignment)
5477 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5478 .getAlignmentAnnotation();
5483 for (AlignmentAnnotation aa : anns)
5486 * don't display non-positional annotations on an alignment
5488 if (aa.annotations == null)
5492 boolean apply = (aa.sequenceRef == null && forAlignment)
5493 || (aa.sequenceRef != null && forSequences);
5496 aa.visible = visible;
5499 alignPanel.validateAnnotationDimensions(true);
5500 alignPanel.alignmentChanged();
5504 * Store selected annotation sort order for the view and repaint.
5507 protected void sortAnnotations_actionPerformed()
5509 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5511 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5512 alignPanel.paintAlignment(true);
5517 * @return alignment panels in this alignment frame
5519 public List<? extends AlignmentViewPanel> getAlignPanels()
5521 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5525 * Open a new alignment window, with the cDNA associated with this (protein)
5526 * alignment, aligned as is the protein.
5528 protected void viewAsCdna_actionPerformed()
5530 // TODO no longer a menu action - refactor as required
5531 final AlignmentI alignment = getViewport().getAlignment();
5532 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5533 if (mappings == null)
5537 List<SequenceI> cdnaSeqs = new ArrayList<SequenceI>();
5538 for (SequenceI aaSeq : alignment.getSequences())
5540 for (AlignedCodonFrame acf : mappings)
5542 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5546 * There is a cDNA mapping for this protein sequence - add to new
5547 * alignment. It will share the same dataset sequence as other mapped
5548 * cDNA (no new mappings need to be created).
5550 final Sequence newSeq = new Sequence(dnaSeq);
5551 newSeq.setDatasetSequence(dnaSeq);
5552 cdnaSeqs.add(newSeq);
5556 if (cdnaSeqs.size() == 0)
5558 // show a warning dialog no mapped cDNA
5561 AlignmentI cdna = new Alignment(cdnaSeqs.toArray(new SequenceI[cdnaSeqs
5563 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5564 AlignFrame.DEFAULT_HEIGHT);
5565 cdna.alignAs(alignment);
5566 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5568 Desktop.addInternalFrame(alignFrame, newtitle,
5569 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
5573 * Set visibility of dna/protein complement view (available when shown in a
5579 protected void showComplement_actionPerformed(boolean show)
5581 SplitContainerI sf = getSplitViewContainer();
5584 sf.setComplementVisible(this, show);
5589 * Generate the reverse (optionally complemented) of the selected sequences,
5590 * and add them to the alignment
5593 protected void showReverse_actionPerformed(boolean complement)
5595 AlignmentI al = null;
5598 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5599 al = dna.reverseCdna(complement);
5600 viewport.addAlignment(al, "");
5601 addHistoryItem(new EditCommand(
5602 MessageManager.getString("label.add_sequences"),
5603 Action.PASTE, al.getSequencesArray(), 0, al.getWidth(),
5604 viewport.getAlignment()));
5605 } catch (Exception ex)
5607 System.err.println(ex.getMessage());
5613 * Try to run a script in the Groovy console, having first ensured that this
5614 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5615 * be targeted at this alignment.
5618 protected void runGroovy_actionPerformed()
5620 Jalview.setCurrentAlignFrame(this);
5621 groovy.ui.Console console = Desktop.getGroovyConsole();
5622 if (console != null)
5626 console.runScript();
5627 } catch (Exception ex)
5629 System.err.println((ex.toString()));
5631 .showInternalMessageDialog(Desktop.desktop, MessageManager
5632 .getString("label.couldnt_run_groovy_script"),
5634 .getString("label.groovy_support_failed"),
5635 JvOptionPane.ERROR_MESSAGE);
5640 System.err.println("Can't run Groovy script as console not found");
5645 * Hides columns containing (or not containing) a specified feature, provided
5646 * that would not leave all columns hidden
5648 * @param featureType
5649 * @param columnsContaining
5652 public boolean hideFeatureColumns(String featureType,
5653 boolean columnsContaining)
5655 boolean notForHiding = avc.markColumnsContainingFeatures(
5656 columnsContaining, false, false, featureType);
5659 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5660 false, featureType))
5662 getViewport().hideSelectedColumns();
5670 protected void selectHighlightedColumns_actionPerformed(
5671 ActionEvent actionEvent)
5673 // include key modifier check in case user selects from menu
5674 avc.markHighlightedColumns(
5675 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0,
5677 (actionEvent.getModifiers() & (ActionEvent.META_MASK | ActionEvent.CTRL_MASK)) != 0);
5681 * Rebuilds the Colour menu, including any user-defined colours which have
5682 * been loaded either on startup or during the session
5684 public void buildColourMenu()
5686 colourMenu.removeAll();
5688 colourMenu.add(applyToAllGroups);
5689 colourMenu.add(textColour);
5690 colourMenu.addSeparator();
5692 ColourMenuHelper.addMenuItems(colourMenu, this,
5693 viewport.getAlignment(), false);
5695 colourMenu.addSeparator();
5696 colourMenu.add(conservationMenuItem);
5697 colourMenu.add(modifyConservation);
5698 colourMenu.add(abovePIDThreshold);
5699 colourMenu.add(modifyPID);
5700 colourMenu.add(annotationColour);
5703 * select the default colour for the alignment (this may be
5706 boolean nucleotide = viewport.getAlignment().isNucleotide();
5707 String defaultColourScheme = Cache.getDefault(
5708 nucleotide ? Preferences.DEFAULT_COLOUR_NUC
5709 : Preferences.DEFAULT_COLOUR_PROT,
5710 ResidueColourScheme.NONE);
5712 ColourMenuHelper.setColourSelected(colourMenu, defaultColourScheme);
5716 class PrintThread extends Thread
5720 public PrintThread(AlignmentPanel ap)
5725 static PageFormat pf;
5730 PrinterJob printJob = PrinterJob.getPrinterJob();
5734 printJob.setPrintable(ap, pf);
5738 printJob.setPrintable(ap);
5741 if (printJob.printDialog())
5746 } catch (Exception PrintException)
5748 PrintException.printStackTrace();