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.NJTree;
28 import jalview.analysis.ParseProperties;
29 import jalview.analysis.SequenceIdMatcher;
30 import jalview.api.AlignExportSettingI;
31 import jalview.api.AlignViewControllerGuiI;
32 import jalview.api.AlignViewControllerI;
33 import jalview.api.AlignViewportI;
34 import jalview.api.AlignmentViewPanel;
35 import jalview.api.FeatureSettingsControllerI;
36 import jalview.api.SplitContainerI;
37 import jalview.api.ViewStyleI;
38 import jalview.api.analysis.ScoreModelI;
39 import jalview.bin.Cache;
40 import jalview.bin.Jalview;
41 import jalview.commands.CommandI;
42 import jalview.commands.EditCommand;
43 import jalview.commands.EditCommand.Action;
44 import jalview.commands.OrderCommand;
45 import jalview.commands.RemoveGapColCommand;
46 import jalview.commands.RemoveGapsCommand;
47 import jalview.commands.SlideSequencesCommand;
48 import jalview.commands.TrimRegionCommand;
49 import jalview.datamodel.AlignedCodonFrame;
50 import jalview.datamodel.Alignment;
51 import jalview.datamodel.AlignmentAnnotation;
52 import jalview.datamodel.AlignmentExportData;
53 import jalview.datamodel.AlignmentI;
54 import jalview.datamodel.AlignmentOrder;
55 import jalview.datamodel.AlignmentView;
56 import jalview.datamodel.ColumnSelection;
57 import jalview.datamodel.HiddenSequences;
58 import jalview.datamodel.PDBEntry;
59 import jalview.datamodel.SeqCigar;
60 import jalview.datamodel.Sequence;
61 import jalview.datamodel.SequenceGroup;
62 import jalview.datamodel.SequenceI;
63 import jalview.gui.ColourMenuHelper.ColourChangeListener;
64 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
65 import jalview.io.AlignmentProperties;
66 import jalview.io.AnnotationFile;
67 import jalview.io.BioJsHTMLOutput;
68 import jalview.io.DataSourceType;
69 import jalview.io.FileFormat;
70 import jalview.io.FileFormatI;
71 import jalview.io.FileFormats;
72 import jalview.io.FileLoader;
73 import jalview.io.FileParse;
74 import jalview.io.FormatAdapter;
75 import jalview.io.HtmlSvgOutput;
76 import jalview.io.IdentifyFile;
77 import jalview.io.JPredFile;
78 import jalview.io.JalviewFileChooser;
79 import jalview.io.JalviewFileView;
80 import jalview.io.JnetAnnotationMaker;
81 import jalview.io.NewickFile;
82 import jalview.io.ScoreMatrixFile;
83 import jalview.io.TCoffeeScoreFile;
84 import jalview.jbgui.GAlignFrame;
85 import jalview.schemes.ColourSchemeI;
86 import jalview.schemes.ColourSchemes;
87 import jalview.schemes.ResidueColourScheme;
88 import jalview.schemes.TCoffeeColourScheme;
89 import jalview.util.MessageManager;
90 import jalview.viewmodel.AlignmentViewport;
91 import jalview.ws.DBRefFetcher;
92 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
93 import jalview.ws.jws1.Discoverer;
94 import jalview.ws.jws2.Jws2Discoverer;
95 import jalview.ws.jws2.jabaws2.Jws2Instance;
96 import jalview.ws.seqfetcher.DbSourceProxy;
98 import java.awt.BorderLayout;
99 import java.awt.Component;
100 import java.awt.Rectangle;
101 import java.awt.Toolkit;
102 import java.awt.datatransfer.Clipboard;
103 import java.awt.datatransfer.DataFlavor;
104 import java.awt.datatransfer.StringSelection;
105 import java.awt.datatransfer.Transferable;
106 import java.awt.dnd.DnDConstants;
107 import java.awt.dnd.DropTargetDragEvent;
108 import java.awt.dnd.DropTargetDropEvent;
109 import java.awt.dnd.DropTargetEvent;
110 import java.awt.dnd.DropTargetListener;
111 import java.awt.event.ActionEvent;
112 import java.awt.event.ActionListener;
113 import java.awt.event.FocusAdapter;
114 import java.awt.event.FocusEvent;
115 import java.awt.event.ItemEvent;
116 import java.awt.event.ItemListener;
117 import java.awt.event.KeyAdapter;
118 import java.awt.event.KeyEvent;
119 import java.awt.event.MouseEvent;
120 import java.awt.print.PageFormat;
121 import java.awt.print.PrinterJob;
122 import java.beans.PropertyChangeEvent;
124 import java.io.FileWriter;
125 import java.io.PrintWriter;
127 import java.util.ArrayList;
128 import java.util.Arrays;
129 import java.util.Deque;
130 import java.util.Enumeration;
131 import java.util.Hashtable;
132 import java.util.List;
133 import java.util.Vector;
135 import javax.swing.JCheckBoxMenuItem;
136 import javax.swing.JEditorPane;
137 import javax.swing.JInternalFrame;
138 import javax.swing.JLayeredPane;
139 import javax.swing.JMenu;
140 import javax.swing.JMenuItem;
141 import javax.swing.JScrollPane;
142 import javax.swing.SwingUtilities;
148 * @version $Revision$
150 public class AlignFrame extends GAlignFrame implements DropTargetListener,
151 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
154 public static final int DEFAULT_WIDTH = 700;
156 public static final int DEFAULT_HEIGHT = 500;
159 * The currently displayed panel (selected tabbed view if more than one)
161 public AlignmentPanel alignPanel;
163 AlignViewport viewport;
165 public AlignViewControllerI avc;
167 List<AlignmentPanel> alignPanels = new ArrayList<AlignmentPanel>();
170 * Last format used to load or save alignments in this window
172 FileFormatI currentFileFormat = null;
175 * Current filename for this alignment
177 String fileName = null;
180 * Creates a new AlignFrame object with specific width and height.
186 public AlignFrame(AlignmentI al, int width, int height)
188 this(al, null, width, height);
192 * Creates a new AlignFrame object with specific width, height and
198 * @param sequenceSetId
200 public AlignFrame(AlignmentI al, int width, int height,
201 String sequenceSetId)
203 this(al, null, width, height, sequenceSetId);
207 * Creates a new AlignFrame object with specific width, height and
213 * @param sequenceSetId
216 public AlignFrame(AlignmentI al, int width, int height,
217 String sequenceSetId, String viewId)
219 this(al, null, width, height, sequenceSetId, viewId);
223 * new alignment window with hidden columns
227 * @param hiddenColumns
228 * ColumnSelection or null
230 * Width of alignment frame
234 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
235 int width, int height)
237 this(al, hiddenColumns, width, height, null);
241 * Create alignment frame for al with hiddenColumns, a specific width and
242 * height, and specific sequenceId
245 * @param hiddenColumns
248 * @param sequenceSetId
251 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
252 int width, int height, String sequenceSetId)
254 this(al, hiddenColumns, width, height, sequenceSetId, null);
258 * Create alignment frame for al with hiddenColumns, a specific width and
259 * height, and specific sequenceId
262 * @param hiddenColumns
265 * @param sequenceSetId
270 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
271 int width, int height, String sequenceSetId, String viewId)
273 setSize(width, height);
275 if (al.getDataset() == null)
280 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
282 alignPanel = new AlignmentPanel(this, viewport);
284 addAlignmentPanel(alignPanel, true);
288 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
289 ColumnSelection hiddenColumns, int width, int height)
291 setSize(width, height);
293 if (al.getDataset() == null)
298 viewport = new AlignViewport(al, hiddenColumns);
300 if (hiddenSeqs != null && hiddenSeqs.length > 0)
302 viewport.hideSequence(hiddenSeqs);
304 alignPanel = new AlignmentPanel(this, viewport);
305 addAlignmentPanel(alignPanel, true);
310 * Make a new AlignFrame from existing alignmentPanels
317 public AlignFrame(AlignmentPanel ap)
321 addAlignmentPanel(ap, false);
326 * initalise the alignframe from the underlying viewport data and the
331 if (!Jalview.isHeadlessMode())
333 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
336 avc = new jalview.controller.AlignViewController(this, viewport,
338 if (viewport.getAlignmentConservationAnnotation() == null)
340 // BLOSUM62Colour.setEnabled(false);
341 conservationMenuItem.setEnabled(false);
342 modifyConservation.setEnabled(false);
343 // PIDColour.setEnabled(false);
344 // abovePIDThreshold.setEnabled(false);
345 // modifyPID.setEnabled(false);
348 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
351 if (sortby.equals("Id"))
353 sortIDMenuItem_actionPerformed(null);
355 else if (sortby.equals("Pairwise Identity"))
357 sortPairwiseMenuItem_actionPerformed(null);
361 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
363 setMenusFromViewport(viewport);
364 buildSortByAnnotationScoresMenu();
365 calculateTree.addActionListener(new ActionListener()
369 public void actionPerformed(ActionEvent e)
371 new TreeChooser(AlignFrame.this);
376 if (Desktop.desktop != null)
378 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
379 addServiceListeners();
383 if (viewport.getWrapAlignment())
385 wrapMenuItem_actionPerformed(null);
388 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
390 this.overviewMenuItem_actionPerformed(null);
395 final List<AlignmentPanel> selviews = new ArrayList<AlignmentPanel>();
396 final List<AlignmentPanel> origview = new ArrayList<AlignmentPanel>();
397 final String menuLabel = MessageManager
398 .getString("label.copy_format_from");
399 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
400 new ViewSetProvider()
404 public AlignmentPanel[] getAllAlignmentPanels()
407 origview.add(alignPanel);
408 // make an array of all alignment panels except for this one
409 List<AlignmentPanel> aps = new ArrayList<AlignmentPanel>(
410 Arrays.asList(Desktop.getAlignmentPanels(null)));
411 aps.remove(AlignFrame.this.alignPanel);
412 return aps.toArray(new AlignmentPanel[aps.size()]);
414 }, selviews, new ItemListener()
418 public void itemStateChanged(ItemEvent e)
420 if (origview.size() > 0)
422 final AlignmentPanel ap = origview.get(0);
425 * Copy the ViewStyle of the selected panel to 'this one'.
426 * Don't change value of 'scaleProteinAsCdna' unless copying
429 ViewStyleI vs = selviews.get(0).getAlignViewport()
431 boolean fromSplitFrame = selviews.get(0)
432 .getAlignViewport().getCodingComplement() != null;
435 vs.setScaleProteinAsCdna(ap.getAlignViewport()
436 .getViewStyle().isScaleProteinAsCdna());
438 ap.getAlignViewport().setViewStyle(vs);
441 * Also rescale ViewStyle of SplitFrame complement if there is
442 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
443 * the whole ViewStyle (allow cDNA protein to have different
446 AlignViewportI complement = ap.getAlignViewport()
447 .getCodingComplement();
448 if (complement != null && vs.isScaleProteinAsCdna())
450 AlignFrame af = Desktop.getAlignFrameFor(complement);
451 ((SplitFrame) af.getSplitViewContainer())
453 af.setMenusForViewport();
457 ap.setSelected(true);
458 ap.alignFrame.setMenusForViewport();
463 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
464 .indexOf("devel") > -1
465 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
466 .indexOf("test") > -1)
468 formatMenu.add(vsel);
470 addFocusListener(new FocusAdapter()
473 public void focusGained(FocusEvent e)
475 Jalview.setCurrentAlignFrame(AlignFrame.this);
482 * Change the filename and format for the alignment, and enable the 'reload'
483 * button functionality.
490 public void setFileName(String file, FileFormatI format)
493 setFileFormat(format);
494 reload.setEnabled(true);
498 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
501 void addKeyListener()
503 addKeyListener(new KeyAdapter()
506 public void keyPressed(KeyEvent evt)
508 if (viewport.cursorMode
509 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
510 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
511 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
512 && Character.isDigit(evt.getKeyChar()))
514 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
517 switch (evt.getKeyCode())
520 case 27: // escape key
521 deselectAllSequenceMenuItem_actionPerformed(null);
525 case KeyEvent.VK_DOWN:
526 if (evt.isAltDown() || !viewport.cursorMode)
528 moveSelectedSequences(false);
530 if (viewport.cursorMode)
532 alignPanel.getSeqPanel().moveCursor(0, 1);
537 if (evt.isAltDown() || !viewport.cursorMode)
539 moveSelectedSequences(true);
541 if (viewport.cursorMode)
543 alignPanel.getSeqPanel().moveCursor(0, -1);
548 case KeyEvent.VK_LEFT:
549 if (evt.isAltDown() || !viewport.cursorMode)
551 slideSequences(false, alignPanel.getSeqPanel().getKeyboardNo1());
555 alignPanel.getSeqPanel().moveCursor(-1, 0);
560 case KeyEvent.VK_RIGHT:
561 if (evt.isAltDown() || !viewport.cursorMode)
563 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
567 alignPanel.getSeqPanel().moveCursor(1, 0);
571 case KeyEvent.VK_SPACE:
572 if (viewport.cursorMode)
574 alignPanel.getSeqPanel().insertGapAtCursor(
575 evt.isControlDown() || evt.isShiftDown()
580 // case KeyEvent.VK_A:
581 // if (viewport.cursorMode)
583 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
584 // //System.out.println("A");
588 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
589 * System.out.println("closing bracket"); } break;
591 case KeyEvent.VK_DELETE:
592 case KeyEvent.VK_BACK_SPACE:
593 if (!viewport.cursorMode)
595 cut_actionPerformed(null);
599 alignPanel.getSeqPanel().deleteGapAtCursor(
600 evt.isControlDown() || evt.isShiftDown()
607 if (viewport.cursorMode)
609 alignPanel.getSeqPanel().setCursorRow();
613 if (viewport.cursorMode && !evt.isControlDown())
615 alignPanel.getSeqPanel().setCursorColumn();
619 if (viewport.cursorMode)
621 alignPanel.getSeqPanel().setCursorPosition();
625 case KeyEvent.VK_ENTER:
626 case KeyEvent.VK_COMMA:
627 if (viewport.cursorMode)
629 alignPanel.getSeqPanel().setCursorRowAndColumn();
634 if (viewport.cursorMode)
636 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
640 if (viewport.cursorMode)
642 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
647 viewport.cursorMode = !viewport.cursorMode;
648 statusBar.setText(MessageManager.formatMessage(
649 "label.keyboard_editing_mode",
650 new String[] { (viewport.cursorMode ? "on" : "off") }));
651 if (viewport.cursorMode)
653 alignPanel.getSeqPanel().seqCanvas.cursorX = viewport.startRes;
654 alignPanel.getSeqPanel().seqCanvas.cursorY = viewport.startSeq;
656 alignPanel.getSeqPanel().seqCanvas.repaint();
662 Help.showHelpWindow();
663 } catch (Exception ex)
665 ex.printStackTrace();
670 boolean toggleSeqs = !evt.isControlDown();
671 boolean toggleCols = !evt.isShiftDown();
672 toggleHiddenRegions(toggleSeqs, toggleCols);
677 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
678 boolean modifyExisting = true; // always modify, don't clear
679 // evt.isShiftDown();
680 boolean invertHighlighted = evt.isAltDown();
681 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
685 case KeyEvent.VK_PAGE_UP:
686 if (viewport.getWrapAlignment())
688 alignPanel.scrollUp(true);
692 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
693 - viewport.endSeq + viewport.startSeq);
696 case KeyEvent.VK_PAGE_DOWN:
697 if (viewport.getWrapAlignment())
699 alignPanel.scrollUp(false);
703 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
704 + viewport.endSeq - viewport.startSeq);
711 public void keyReleased(KeyEvent evt)
713 switch (evt.getKeyCode())
715 case KeyEvent.VK_LEFT:
716 if (evt.isAltDown() || !viewport.cursorMode)
718 viewport.firePropertyChange("alignment", null, viewport
719 .getAlignment().getSequences());
723 case KeyEvent.VK_RIGHT:
724 if (evt.isAltDown() || !viewport.cursorMode)
726 viewport.firePropertyChange("alignment", null, viewport
727 .getAlignment().getSequences());
735 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
737 ap.alignFrame = this;
738 avc = new jalview.controller.AlignViewController(this, viewport,
743 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
745 int aSize = alignPanels.size();
747 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
749 if (aSize == 1 && ap.av.viewName == null)
751 this.getContentPane().add(ap, BorderLayout.CENTER);
757 setInitialTabVisible();
760 expandViews.setEnabled(true);
761 gatherViews.setEnabled(true);
762 tabbedPane.addTab(ap.av.viewName, ap);
764 ap.setVisible(false);
769 if (ap.av.isPadGaps())
771 ap.av.getAlignment().padGaps();
773 ap.av.updateConservation(ap);
774 ap.av.updateConsensus(ap);
775 ap.av.updateStrucConsensus(ap);
779 public void setInitialTabVisible()
781 expandViews.setEnabled(true);
782 gatherViews.setEnabled(true);
783 tabbedPane.setVisible(true);
784 AlignmentPanel first = alignPanels.get(0);
785 tabbedPane.addTab(first.av.viewName, first);
786 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
789 public AlignViewport getViewport()
794 /* Set up intrinsic listeners for dynamically generated GUI bits. */
795 private void addServiceListeners()
797 final java.beans.PropertyChangeListener thisListener;
798 Desktop.instance.addJalviewPropertyChangeListener("services",
799 thisListener = new java.beans.PropertyChangeListener()
802 public void propertyChange(PropertyChangeEvent evt)
804 // // System.out.println("Discoverer property change.");
805 // if (evt.getPropertyName().equals("services"))
807 SwingUtilities.invokeLater(new Runnable()
814 .println("Rebuild WS Menu for service change");
815 BuildWebServiceMenu();
822 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
825 public void internalFrameClosed(
826 javax.swing.event.InternalFrameEvent evt)
828 // System.out.println("deregistering discoverer listener");
829 Desktop.instance.removeJalviewPropertyChangeListener("services",
831 closeMenuItem_actionPerformed(true);
834 // Finally, build the menu once to get current service state
835 new Thread(new Runnable()
840 BuildWebServiceMenu();
846 * Configure menu items that vary according to whether the alignment is
847 * nucleotide or protein
849 public void setGUINucleotide()
851 AlignmentI al = getViewport().getAlignment();
852 boolean nucleotide = al.isNucleotide();
854 showTranslation.setVisible(nucleotide);
855 showReverse.setVisible(nucleotide);
856 showReverseComplement.setVisible(nucleotide);
857 conservationMenuItem.setEnabled(!nucleotide);
858 modifyConservation.setEnabled(!nucleotide
859 && conservationMenuItem.isSelected());
860 showGroupConservation.setEnabled(!nucleotide);
862 showComplementMenuItem.setText(nucleotide ? MessageManager
863 .getString("label.protein") : MessageManager
864 .getString("label.nucleotide"));
868 * set up menus for the current viewport. This may be called after any
869 * operation that affects the data in the current view (selection changed,
870 * etc) to update the menus to reflect the new state.
873 public void setMenusForViewport()
875 setMenusFromViewport(viewport);
879 * Need to call this method when tabs are selected for multiple views, or when
880 * loading from Jalview2XML.java
885 void setMenusFromViewport(AlignViewport av)
887 padGapsMenuitem.setSelected(av.isPadGaps());
888 colourTextMenuItem.setSelected(av.isShowColourText());
889 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
890 modifyPID.setEnabled(abovePIDThreshold.isSelected());
891 conservationMenuItem.setSelected(av.getConservationSelected());
892 modifyConservation.setEnabled(conservationMenuItem.isSelected());
893 seqLimits.setSelected(av.getShowJVSuffix());
894 idRightAlign.setSelected(av.isRightAlignIds());
895 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
896 renderGapsMenuItem.setSelected(av.isRenderGaps());
897 wrapMenuItem.setSelected(av.getWrapAlignment());
898 scaleAbove.setVisible(av.getWrapAlignment());
899 scaleLeft.setVisible(av.getWrapAlignment());
900 scaleRight.setVisible(av.getWrapAlignment());
901 annotationPanelMenuItem.setState(av.isShowAnnotation());
903 * Show/hide annotations only enabled if annotation panel is shown
905 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
906 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
907 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
908 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
909 viewBoxesMenuItem.setSelected(av.getShowBoxes());
910 viewTextMenuItem.setSelected(av.getShowText());
911 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
912 showGroupConsensus.setSelected(av.isShowGroupConsensus());
913 showGroupConservation.setSelected(av.isShowGroupConservation());
914 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
915 showSequenceLogo.setSelected(av.isShowSequenceLogo());
916 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
918 ColourMenuHelper.setColourSelected(colourMenu,
919 av.getGlobalColourScheme());
921 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
922 hiddenMarkers.setState(av.getShowHiddenMarkers());
923 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
924 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
925 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
926 autoCalculate.setSelected(av.autoCalculateConsensus);
927 sortByTree.setSelected(av.sortByTree);
928 listenToViewSelections.setSelected(av.followSelection);
930 showProducts.setEnabled(canShowProducts());
931 setGroovyEnabled(Desktop.getGroovyConsole() != null);
937 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
941 public void setGroovyEnabled(boolean b)
943 runGroovy.setEnabled(b);
946 private IProgressIndicator progressBar;
951 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
954 public void setProgressBar(String message, long id)
956 progressBar.setProgressBar(message, id);
960 public void registerHandler(final long id,
961 final IProgressIndicatorHandler handler)
963 progressBar.registerHandler(id, handler);
968 * @return true if any progress bars are still active
971 public boolean operationInProgress()
973 return progressBar.operationInProgress();
977 public void setStatus(String text)
979 statusBar.setText(text);
983 * Added so Castor Mapping file can obtain Jalview Version
985 public String getVersion()
987 return jalview.bin.Cache.getProperty("VERSION");
990 public FeatureRenderer getFeatureRenderer()
992 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
996 public void fetchSequence_actionPerformed(ActionEvent e)
998 new jalview.gui.SequenceFetcher(this);
1002 public void addFromFile_actionPerformed(ActionEvent e)
1004 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1008 public void reload_actionPerformed(ActionEvent e)
1010 if (fileName != null)
1012 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1013 // originating file's format
1014 // TODO: work out how to recover feature settings for correct view(s) when
1015 // file is reloaded.
1016 if (FileFormat.Jalview.equals(currentFileFormat))
1018 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1019 for (int i = 0; i < frames.length; i++)
1021 if (frames[i] instanceof AlignFrame && frames[i] != this
1022 && ((AlignFrame) frames[i]).fileName != null
1023 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1027 frames[i].setSelected(true);
1028 Desktop.instance.closeAssociatedWindows();
1029 } catch (java.beans.PropertyVetoException ex)
1035 Desktop.instance.closeAssociatedWindows();
1037 FileLoader loader = new FileLoader();
1038 DataSourceType protocol = fileName.startsWith("http:") ? DataSourceType.URL
1039 : DataSourceType.FILE;
1040 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1044 Rectangle bounds = this.getBounds();
1046 FileLoader loader = new FileLoader();
1047 DataSourceType protocol = fileName.startsWith("http:") ? DataSourceType.URL
1048 : DataSourceType.FILE;
1049 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1050 protocol, currentFileFormat);
1052 newframe.setBounds(bounds);
1053 if (featureSettings != null && featureSettings.isShowing())
1055 final Rectangle fspos = featureSettings.frame.getBounds();
1056 // TODO: need a 'show feature settings' function that takes bounds -
1057 // need to refactor Desktop.addFrame
1058 newframe.featureSettings_actionPerformed(null);
1059 final FeatureSettings nfs = newframe.featureSettings;
1060 SwingUtilities.invokeLater(new Runnable()
1065 nfs.frame.setBounds(fspos);
1068 this.featureSettings.close();
1069 this.featureSettings = null;
1071 this.closeMenuItem_actionPerformed(true);
1077 public void addFromText_actionPerformed(ActionEvent e)
1079 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport
1084 public void addFromURL_actionPerformed(ActionEvent e)
1086 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1090 public void save_actionPerformed(ActionEvent e)
1092 if (fileName == null || (currentFileFormat == null)
1093 || fileName.startsWith("http"))
1095 saveAs_actionPerformed(null);
1099 saveAlignment(fileName, currentFileFormat);
1110 public void saveAs_actionPerformed(ActionEvent e)
1112 String format = currentFileFormat == null ? null : currentFileFormat
1114 JalviewFileChooser chooser = JalviewFileChooser.forWrite(
1115 Cache.getProperty("LAST_DIRECTORY"), format);
1117 chooser.setFileView(new JalviewFileView());
1118 chooser.setDialogTitle(MessageManager
1119 .getString("label.save_alignment_to_file"));
1120 chooser.setToolTipText(MessageManager.getString("action.save"));
1122 int value = chooser.showSaveDialog(this);
1124 if (value == JalviewFileChooser.APPROVE_OPTION)
1126 currentFileFormat = chooser.getSelectedFormat();
1127 while (currentFileFormat == null)
1130 .showInternalMessageDialog(
1133 .getString("label.select_file_format_before_saving"),
1135 .getString("label.file_format_not_specified"),
1136 JvOptionPane.WARNING_MESSAGE);
1137 currentFileFormat = chooser.getSelectedFormat();
1138 value = chooser.showSaveDialog(this);
1139 if (value != JalviewFileChooser.APPROVE_OPTION)
1145 fileName = chooser.getSelectedFile().getPath();
1147 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1149 Cache.setProperty("LAST_DIRECTORY", fileName);
1150 saveAlignment(fileName, currentFileFormat);
1154 public boolean saveAlignment(String file, FileFormatI format)
1156 boolean success = true;
1158 if (FileFormat.Jalview.equals(format))
1160 String shortName = title;
1162 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1164 shortName = shortName.substring(shortName
1165 .lastIndexOf(java.io.File.separatorChar) + 1);
1168 success = new Jalview2XML().saveAlignment(this, file, shortName);
1170 statusBar.setText(MessageManager.formatMessage(
1171 "label.successfully_saved_to_file_in_format", new Object[] {
1172 fileName, format }));
1177 AlignmentExportData exportData = getAlignmentForExport(format,
1179 if (exportData.getSettings().isCancelled())
1183 FormatAdapter f = new FormatAdapter(alignPanel,
1184 exportData.getSettings());
1185 String output = f.formatSequences(
1187 exportData.getAlignment(), // class cast exceptions will
1188 // occur in the distant future
1189 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1190 f.getCacheSuffixDefault(format),
1191 viewport.getColumnSelection());
1201 PrintWriter out = new PrintWriter(new FileWriter(file));
1205 this.setTitle(file);
1206 statusBar.setText(MessageManager.formatMessage(
1207 "label.successfully_saved_to_file_in_format",
1208 new Object[] { fileName, format.getName() }));
1209 } catch (Exception ex)
1212 ex.printStackTrace();
1219 JvOptionPane.showInternalMessageDialog(this, MessageManager
1220 .formatMessage("label.couldnt_save_file",
1221 new Object[] { fileName }), MessageManager
1222 .getString("label.error_saving_file"),
1223 JvOptionPane.WARNING_MESSAGE);
1229 private void warningMessage(String warning, String title)
1231 if (new jalview.util.Platform().isHeadless())
1233 System.err.println("Warning: " + title + "\nWarning: " + warning);
1238 JvOptionPane.showInternalMessageDialog(this, warning, title,
1239 JvOptionPane.WARNING_MESSAGE);
1251 protected void outputText_actionPerformed(ActionEvent e)
1253 FileFormatI fileFormat = FileFormats.getInstance().forName(
1254 e.getActionCommand());
1255 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1257 if (exportData.getSettings().isCancelled())
1261 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1262 cap.setForInput(null);
1265 FileFormatI format = fileFormat;
1266 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1267 .formatSequences(format, exportData.getAlignment(),
1268 exportData.getOmitHidden(),
1269 exportData.getStartEndPostions(),
1270 viewport.getColumnSelection()));
1271 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1272 "label.alignment_output_command",
1273 new Object[] { e.getActionCommand() }), 600, 500);
1274 } catch (OutOfMemoryError oom)
1276 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1282 public static AlignmentExportData getAlignmentForExport(
1283 FileFormatI format, AlignViewportI viewport,
1284 AlignExportSettingI exportSettings)
1286 AlignmentI alignmentToExport = null;
1287 AlignExportSettingI settings = exportSettings;
1288 String[] omitHidden = null;
1290 HiddenSequences hiddenSeqs = viewport.getAlignment()
1291 .getHiddenSequences();
1293 alignmentToExport = viewport.getAlignment();
1295 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1296 if (settings == null)
1298 settings = new AlignExportSettings(hasHiddenSeqs,
1299 viewport.hasHiddenColumns(), format);
1301 // settings.isExportAnnotations();
1303 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1305 omitHidden = viewport.getViewAsString(false,
1306 settings.isExportHiddenSequences());
1309 int[] alignmentStartEnd = new int[2];
1310 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1312 alignmentToExport = hiddenSeqs.getFullAlignment();
1316 alignmentToExport = viewport.getAlignment();
1318 alignmentStartEnd = alignmentToExport
1319 .getVisibleStartAndEndIndex(viewport.getColumnSelection()
1320 .getHiddenColumns());
1321 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1322 omitHidden, alignmentStartEnd, settings);
1333 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1335 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1336 htmlSVG.exportHTML(null);
1340 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1342 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1343 bjs.exportHTML(null);
1346 public void createImageMap(File file, String image)
1348 alignPanel.makePNGImageMap(file, image);
1358 public void createPNG(File f)
1360 alignPanel.makePNG(f);
1370 public void createEPS(File f)
1372 alignPanel.makeEPS(f);
1376 public void createSVG(File f)
1378 alignPanel.makeSVG(f);
1382 public void pageSetup_actionPerformed(ActionEvent e)
1384 PrinterJob printJob = PrinterJob.getPrinterJob();
1385 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1395 public void printMenuItem_actionPerformed(ActionEvent e)
1397 // Putting in a thread avoids Swing painting problems
1398 PrintThread thread = new PrintThread(alignPanel);
1403 public void exportFeatures_actionPerformed(ActionEvent e)
1405 new AnnotationExporter().exportFeatures(alignPanel);
1409 public void exportAnnotations_actionPerformed(ActionEvent e)
1411 new AnnotationExporter().exportAnnotations(alignPanel);
1415 public void associatedData_actionPerformed(ActionEvent e)
1417 // Pick the tree file
1418 JalviewFileChooser chooser = new JalviewFileChooser(
1419 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1420 chooser.setFileView(new JalviewFileView());
1421 chooser.setDialogTitle(MessageManager
1422 .getString("label.load_jalview_annotations"));
1423 chooser.setToolTipText(MessageManager
1424 .getString("label.load_jalview_annotations"));
1426 int value = chooser.showOpenDialog(null);
1428 if (value == JalviewFileChooser.APPROVE_OPTION)
1430 String choice = chooser.getSelectedFile().getPath();
1431 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1432 loadJalviewDataFile(choice, null, null, null);
1438 * Close the current view or all views in the alignment frame. If the frame
1439 * only contains one view then the alignment will be removed from memory.
1441 * @param closeAllTabs
1444 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1446 if (alignPanels != null && alignPanels.size() < 2)
1448 closeAllTabs = true;
1453 if (alignPanels != null)
1457 if (this.isClosed())
1459 // really close all the windows - otherwise wait till
1460 // setClosed(true) is called
1461 for (int i = 0; i < alignPanels.size(); i++)
1463 AlignmentPanel ap = alignPanels.get(i);
1470 closeView(alignPanel);
1477 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1478 * be called recursively, with the frame now in 'closed' state
1480 this.setClosed(true);
1482 } catch (Exception ex)
1484 ex.printStackTrace();
1489 * Close the specified panel and close up tabs appropriately.
1491 * @param panelToClose
1493 public void closeView(AlignmentPanel panelToClose)
1495 int index = tabbedPane.getSelectedIndex();
1496 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1497 alignPanels.remove(panelToClose);
1498 panelToClose.closePanel();
1499 panelToClose = null;
1501 tabbedPane.removeTabAt(closedindex);
1502 tabbedPane.validate();
1504 if (index > closedindex || index == tabbedPane.getTabCount())
1506 // modify currently selected tab index if necessary.
1510 this.tabSelectionChanged(index);
1516 void updateEditMenuBar()
1519 if (viewport.getHistoryList().size() > 0)
1521 undoMenuItem.setEnabled(true);
1522 CommandI command = viewport.getHistoryList().peek();
1523 undoMenuItem.setText(MessageManager.formatMessage(
1524 "label.undo_command",
1525 new Object[] { command.getDescription() }));
1529 undoMenuItem.setEnabled(false);
1530 undoMenuItem.setText(MessageManager.getString("action.undo"));
1533 if (viewport.getRedoList().size() > 0)
1535 redoMenuItem.setEnabled(true);
1537 CommandI command = viewport.getRedoList().peek();
1538 redoMenuItem.setText(MessageManager.formatMessage(
1539 "label.redo_command",
1540 new Object[] { command.getDescription() }));
1544 redoMenuItem.setEnabled(false);
1545 redoMenuItem.setText(MessageManager.getString("action.redo"));
1550 public void addHistoryItem(CommandI command)
1552 if (command.getSize() > 0)
1554 viewport.addToHistoryList(command);
1555 viewport.clearRedoList();
1556 updateEditMenuBar();
1557 viewport.updateHiddenColumns();
1558 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1559 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1560 // viewport.getColumnSelection()
1561 // .getHiddenColumns().size() > 0);
1567 * @return alignment objects for all views
1569 AlignmentI[] getViewAlignments()
1571 if (alignPanels != null)
1573 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1575 for (AlignmentPanel ap : alignPanels)
1577 als[i++] = ap.av.getAlignment();
1581 if (viewport != null)
1583 return new AlignmentI[] { viewport.getAlignment() };
1595 protected void undoMenuItem_actionPerformed(ActionEvent e)
1597 if (viewport.getHistoryList().isEmpty())
1601 CommandI command = viewport.getHistoryList().pop();
1602 viewport.addToRedoList(command);
1603 command.undoCommand(getViewAlignments());
1605 AlignmentViewport originalSource = getOriginatingSource(command);
1606 updateEditMenuBar();
1608 if (originalSource != null)
1610 if (originalSource != viewport)
1613 .warn("Implementation worry: mismatch of viewport origin for undo");
1615 originalSource.updateHiddenColumns();
1616 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1618 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1619 // viewport.getColumnSelection()
1620 // .getHiddenColumns().size() > 0);
1621 originalSource.firePropertyChange("alignment", null, originalSource
1622 .getAlignment().getSequences());
1633 protected void redoMenuItem_actionPerformed(ActionEvent e)
1635 if (viewport.getRedoList().size() < 1)
1640 CommandI command = viewport.getRedoList().pop();
1641 viewport.addToHistoryList(command);
1642 command.doCommand(getViewAlignments());
1644 AlignmentViewport originalSource = getOriginatingSource(command);
1645 updateEditMenuBar();
1647 if (originalSource != null)
1650 if (originalSource != viewport)
1653 .warn("Implementation worry: mismatch of viewport origin for redo");
1655 originalSource.updateHiddenColumns();
1656 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1658 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1659 // viewport.getColumnSelection()
1660 // .getHiddenColumns().size() > 0);
1661 originalSource.firePropertyChange("alignment", null, originalSource
1662 .getAlignment().getSequences());
1666 AlignmentViewport getOriginatingSource(CommandI command)
1668 AlignmentViewport originalSource = null;
1669 // For sequence removal and addition, we need to fire
1670 // the property change event FROM the viewport where the
1671 // original alignment was altered
1672 AlignmentI al = null;
1673 if (command instanceof EditCommand)
1675 EditCommand editCommand = (EditCommand) command;
1676 al = editCommand.getAlignment();
1677 List<Component> comps = PaintRefresher.components.get(viewport
1678 .getSequenceSetId());
1680 for (Component comp : comps)
1682 if (comp instanceof AlignmentPanel)
1684 if (al == ((AlignmentPanel) comp).av.getAlignment())
1686 originalSource = ((AlignmentPanel) comp).av;
1693 if (originalSource == null)
1695 // The original view is closed, we must validate
1696 // the current view against the closed view first
1699 PaintRefresher.validateSequences(al, viewport.getAlignment());
1702 originalSource = viewport;
1705 return originalSource;
1714 public void moveSelectedSequences(boolean up)
1716 SequenceGroup sg = viewport.getSelectionGroup();
1722 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1723 viewport.getHiddenRepSequences(), up);
1724 alignPanel.paintAlignment(true);
1727 synchronized void slideSequences(boolean right, int size)
1729 List<SequenceI> sg = new ArrayList<SequenceI>();
1730 if (viewport.cursorMode)
1732 sg.add(viewport.getAlignment().getSequenceAt(
1733 alignPanel.getSeqPanel().seqCanvas.cursorY));
1735 else if (viewport.getSelectionGroup() != null
1736 && viewport.getSelectionGroup().getSize() != viewport
1737 .getAlignment().getHeight())
1739 sg = viewport.getSelectionGroup().getSequences(
1740 viewport.getHiddenRepSequences());
1748 List<SequenceI> invertGroup = new ArrayList<SequenceI>();
1750 for (SequenceI seq : viewport.getAlignment().getSequences())
1752 if (!sg.contains(seq))
1754 invertGroup.add(seq);
1758 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1760 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1761 for (int i = 0; i < invertGroup.size(); i++)
1763 seqs2[i] = invertGroup.get(i);
1766 SlideSequencesCommand ssc;
1769 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1770 size, viewport.getGapCharacter());
1774 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1775 size, viewport.getGapCharacter());
1778 int groupAdjustment = 0;
1779 if (ssc.getGapsInsertedBegin() && right)
1781 if (viewport.cursorMode)
1783 alignPanel.getSeqPanel().moveCursor(size, 0);
1787 groupAdjustment = size;
1790 else if (!ssc.getGapsInsertedBegin() && !right)
1792 if (viewport.cursorMode)
1794 alignPanel.getSeqPanel().moveCursor(-size, 0);
1798 groupAdjustment = -size;
1802 if (groupAdjustment != 0)
1804 viewport.getSelectionGroup().setStartRes(
1805 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1806 viewport.getSelectionGroup().setEndRes(
1807 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1811 * just extend the last slide command if compatible; but not if in
1812 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1814 boolean appendHistoryItem = false;
1815 Deque<CommandI> historyList = viewport.getHistoryList();
1816 boolean inSplitFrame = getSplitViewContainer() != null;
1817 if (!inSplitFrame && historyList != null && historyList.size() > 0
1818 && historyList.peek() instanceof SlideSequencesCommand)
1820 appendHistoryItem = ssc
1821 .appendSlideCommand((SlideSequencesCommand) historyList
1825 if (!appendHistoryItem)
1827 addHistoryItem(ssc);
1840 protected void copy_actionPerformed(ActionEvent e)
1843 if (viewport.getSelectionGroup() == null)
1847 // TODO: preserve the ordering of displayed alignment annotation in any
1848 // internal paste (particularly sequence associated annotation)
1849 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1850 String[] omitHidden = null;
1852 if (viewport.hasHiddenColumns())
1854 omitHidden = viewport.getViewAsString(true);
1857 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1858 seqs, omitHidden, null);
1860 StringSelection ss = new StringSelection(output);
1864 jalview.gui.Desktop.internalCopy = true;
1865 // Its really worth setting the clipboard contents
1866 // to empty before setting the large StringSelection!!
1867 Toolkit.getDefaultToolkit().getSystemClipboard()
1868 .setContents(new StringSelection(""), null);
1870 Toolkit.getDefaultToolkit().getSystemClipboard()
1871 .setContents(ss, Desktop.instance);
1872 } catch (OutOfMemoryError er)
1874 new OOMWarning("copying region", er);
1878 ArrayList<int[]> hiddenColumns = null;
1879 if (viewport.hasHiddenColumns())
1881 hiddenColumns = new ArrayList<int[]>();
1882 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1883 .getSelectionGroup().getEndRes();
1884 for (int[] region : viewport.getColumnSelection().getHiddenColumns())
1886 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1888 hiddenColumns.add(new int[] { region[0] - hiddenOffset,
1889 region[1] - hiddenOffset });
1894 Desktop.jalviewClipboard = new Object[] { seqs,
1895 viewport.getAlignment().getDataset(), hiddenColumns };
1896 statusBar.setText(MessageManager.formatMessage(
1897 "label.copied_sequences_to_clipboard", new Object[] { Integer
1898 .valueOf(seqs.length).toString() }));
1908 protected void pasteNew_actionPerformed(ActionEvent e)
1920 protected void pasteThis_actionPerformed(ActionEvent e)
1926 * Paste contents of Jalview clipboard
1928 * @param newAlignment
1929 * true to paste to a new alignment, otherwise add to this.
1931 void paste(boolean newAlignment)
1933 boolean externalPaste = true;
1936 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1937 Transferable contents = c.getContents(this);
1939 if (contents == null)
1948 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1949 if (str.length() < 1)
1954 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
1956 } catch (OutOfMemoryError er)
1958 new OOMWarning("Out of memory pasting sequences!!", er);
1962 SequenceI[] sequences;
1963 boolean annotationAdded = false;
1964 AlignmentI alignment = null;
1966 if (Desktop.jalviewClipboard != null)
1968 // The clipboard was filled from within Jalview, we must use the
1970 // And dataset from the copied alignment
1971 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1972 // be doubly sure that we create *new* sequence objects.
1973 sequences = new SequenceI[newseq.length];
1974 for (int i = 0; i < newseq.length; i++)
1976 sequences[i] = new Sequence(newseq[i]);
1978 alignment = new Alignment(sequences);
1979 externalPaste = false;
1983 // parse the clipboard as an alignment.
1984 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
1986 sequences = alignment.getSequencesArray();
1990 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1996 if (Desktop.jalviewClipboard != null)
1998 // dataset is inherited
1999 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2003 // new dataset is constructed
2004 alignment.setDataset(null);
2006 alwidth = alignment.getWidth() + 1;
2010 AlignmentI pastedal = alignment; // preserve pasted alignment object
2011 // Add pasted sequences and dataset into existing alignment.
2012 alignment = viewport.getAlignment();
2013 alwidth = alignment.getWidth() + 1;
2014 // decide if we need to import sequences from an existing dataset
2015 boolean importDs = Desktop.jalviewClipboard != null
2016 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2017 // importDs==true instructs us to copy over new dataset sequences from
2018 // an existing alignment
2019 Vector newDs = (importDs) ? new Vector() : null; // used to create
2020 // minimum dataset set
2022 for (int i = 0; i < sequences.length; i++)
2026 newDs.addElement(null);
2028 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2030 if (importDs && ds != null)
2032 if (!newDs.contains(ds))
2034 newDs.setElementAt(ds, i);
2035 ds = new Sequence(ds);
2036 // update with new dataset sequence
2037 sequences[i].setDatasetSequence(ds);
2041 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2046 // copy and derive new dataset sequence
2047 sequences[i] = sequences[i].deriveSequence();
2048 alignment.getDataset().addSequence(
2049 sequences[i].getDatasetSequence());
2050 // TODO: avoid creation of duplicate dataset sequences with a
2051 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2053 alignment.addSequence(sequences[i]); // merges dataset
2057 newDs.clear(); // tidy up
2059 if (alignment.getAlignmentAnnotation() != null)
2061 for (AlignmentAnnotation alan : alignment
2062 .getAlignmentAnnotation())
2064 if (alan.graphGroup > fgroup)
2066 fgroup = alan.graphGroup;
2070 if (pastedal.getAlignmentAnnotation() != null)
2072 // Add any annotation attached to alignment.
2073 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2074 for (int i = 0; i < alann.length; i++)
2076 annotationAdded = true;
2077 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2079 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2080 if (newann.graphGroup > -1)
2082 if (newGraphGroups.size() <= newann.graphGroup
2083 || newGraphGroups.get(newann.graphGroup) == null)
2085 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2087 newGraphGroups.add(q, null);
2089 newGraphGroups.set(newann.graphGroup, new Integer(
2092 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2096 newann.padAnnotation(alwidth);
2097 alignment.addAnnotation(newann);
2107 addHistoryItem(new EditCommand(
2108 MessageManager.getString("label.add_sequences"),
2109 Action.PASTE, sequences, 0, alignment.getWidth(), alignment));
2111 // Add any annotations attached to sequences
2112 for (int i = 0; i < sequences.length; i++)
2114 if (sequences[i].getAnnotation() != null)
2116 AlignmentAnnotation newann;
2117 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2119 annotationAdded = true;
2120 newann = sequences[i].getAnnotation()[a];
2121 newann.adjustForAlignment();
2122 newann.padAnnotation(alwidth);
2123 if (newann.graphGroup > -1)
2125 if (newann.graphGroup > -1)
2127 if (newGraphGroups.size() <= newann.graphGroup
2128 || newGraphGroups.get(newann.graphGroup) == null)
2130 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2132 newGraphGroups.add(q, null);
2134 newGraphGroups.set(newann.graphGroup, new Integer(
2137 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2141 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2146 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2153 // propagate alignment changed.
2154 viewport.setEndSeq(alignment.getHeight());
2155 if (annotationAdded)
2157 // Duplicate sequence annotation in all views.
2158 AlignmentI[] alview = this.getViewAlignments();
2159 for (int i = 0; i < sequences.length; i++)
2161 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2166 for (int avnum = 0; avnum < alview.length; avnum++)
2168 if (alview[avnum] != alignment)
2170 // duplicate in a view other than the one with input focus
2171 int avwidth = alview[avnum].getWidth() + 1;
2172 // this relies on sann being preserved after we
2173 // modify the sequence's annotation array for each duplication
2174 for (int a = 0; a < sann.length; a++)
2176 AlignmentAnnotation newann = new AlignmentAnnotation(
2178 sequences[i].addAlignmentAnnotation(newann);
2179 newann.padAnnotation(avwidth);
2180 alview[avnum].addAnnotation(newann); // annotation was
2181 // duplicated earlier
2182 // TODO JAL-1145 graphGroups are not updated for sequence
2183 // annotation added to several views. This may cause
2185 alview[avnum].setAnnotationIndex(newann, a);
2190 buildSortByAnnotationScoresMenu();
2192 viewport.firePropertyChange("alignment", null,
2193 alignment.getSequences());
2194 if (alignPanels != null)
2196 for (AlignmentPanel ap : alignPanels)
2198 ap.validateAnnotationDimensions(false);
2203 alignPanel.validateAnnotationDimensions(false);
2209 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2211 String newtitle = new String("Copied sequences");
2213 if (Desktop.jalviewClipboard != null
2214 && Desktop.jalviewClipboard[2] != null)
2216 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2217 for (int[] region : hc)
2219 af.viewport.hideColumns(region[0], region[1]);
2223 // >>>This is a fix for the moment, until a better solution is
2225 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2227 alignPanel.getSeqPanel().seqCanvas
2228 .getFeatureRenderer());
2230 // TODO: maintain provenance of an alignment, rather than just make the
2231 // title a concatenation of operations.
2234 if (title.startsWith("Copied sequences"))
2240 newtitle = newtitle.concat("- from " + title);
2245 newtitle = new String("Pasted sequences");
2248 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2253 } catch (Exception ex)
2255 ex.printStackTrace();
2256 System.out.println("Exception whilst pasting: " + ex);
2257 // could be anything being pasted in here
2263 protected void expand_newalign(ActionEvent e)
2267 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2268 .getAlignment(), -1);
2269 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2271 String newtitle = new String("Flanking alignment");
2273 if (Desktop.jalviewClipboard != null
2274 && Desktop.jalviewClipboard[2] != null)
2276 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2277 for (int region[] : hc)
2279 af.viewport.hideColumns(region[0], region[1]);
2283 // >>>This is a fix for the moment, until a better solution is
2285 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2287 alignPanel.getSeqPanel().seqCanvas
2288 .getFeatureRenderer());
2290 // TODO: maintain provenance of an alignment, rather than just make the
2291 // title a concatenation of operations.
2293 if (title.startsWith("Copied sequences"))
2299 newtitle = newtitle.concat("- from " + title);
2303 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2305 } catch (Exception ex)
2307 ex.printStackTrace();
2308 System.out.println("Exception whilst pasting: " + ex);
2309 // could be anything being pasted in here
2310 } catch (OutOfMemoryError oom)
2312 new OOMWarning("Viewing flanking region of alignment", oom);
2323 protected void cut_actionPerformed(ActionEvent e)
2325 copy_actionPerformed(null);
2326 delete_actionPerformed(null);
2336 protected void delete_actionPerformed(ActionEvent evt)
2339 SequenceGroup sg = viewport.getSelectionGroup();
2346 * If the cut affects all sequences, warn, remove highlighted columns
2348 if (sg.getSize() == viewport.getAlignment().getHeight())
2350 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes()) + 1) == viewport
2351 .getAlignment().getWidth()) ? true : false;
2352 if (isEntireAlignWidth)
2354 int confirm = JvOptionPane.showConfirmDialog(this,
2355 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2356 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2357 JvOptionPane.OK_CANCEL_OPTION);
2359 if (confirm == JvOptionPane.CANCEL_OPTION
2360 || confirm == JvOptionPane.CLOSED_OPTION)
2365 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2366 sg.getEndRes() + 1);
2368 SequenceI[] cut = sg.getSequences()
2369 .toArray(new SequenceI[sg.getSize()]);
2371 addHistoryItem(new EditCommand(
2372 MessageManager.getString("label.cut_sequences"), Action.CUT,
2373 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2374 viewport.getAlignment()));
2376 viewport.setSelectionGroup(null);
2377 viewport.sendSelection();
2378 viewport.getAlignment().deleteGroup(sg);
2380 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2382 if (viewport.getAlignment().getHeight() < 1)
2386 this.setClosed(true);
2387 } catch (Exception ex)
2400 protected void deleteGroups_actionPerformed(ActionEvent e)
2402 if (avc.deleteGroups())
2404 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2405 alignPanel.updateAnnotation();
2406 alignPanel.paintAlignment(true);
2417 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2419 SequenceGroup sg = new SequenceGroup();
2421 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2423 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2426 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2427 viewport.setSelectionGroup(sg);
2428 viewport.sendSelection();
2429 // JAL-2034 - should delegate to
2430 // alignPanel to decide if overview needs
2432 alignPanel.paintAlignment(false);
2433 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2443 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2445 if (viewport.cursorMode)
2447 alignPanel.getSeqPanel().keyboardNo1 = null;
2448 alignPanel.getSeqPanel().keyboardNo2 = null;
2450 viewport.setSelectionGroup(null);
2451 viewport.getColumnSelection().clear();
2452 viewport.setSelectionGroup(null);
2453 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2454 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2455 // JAL-2034 - should delegate to
2456 // alignPanel to decide if overview needs
2458 alignPanel.paintAlignment(false);
2459 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2460 viewport.sendSelection();
2470 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2472 SequenceGroup sg = viewport.getSelectionGroup();
2476 selectAllSequenceMenuItem_actionPerformed(null);
2481 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2483 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2485 // JAL-2034 - should delegate to
2486 // alignPanel to decide if overview needs
2489 alignPanel.paintAlignment(true);
2490 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2491 viewport.sendSelection();
2495 public void invertColSel_actionPerformed(ActionEvent e)
2497 viewport.invertColumnSelection();
2498 alignPanel.paintAlignment(true);
2499 viewport.sendSelection();
2509 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2511 trimAlignment(true);
2521 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2523 trimAlignment(false);
2526 void trimAlignment(boolean trimLeft)
2528 ColumnSelection colSel = viewport.getColumnSelection();
2531 if (!colSel.isEmpty())
2535 column = colSel.getMin();
2539 column = colSel.getMax();
2543 if (viewport.getSelectionGroup() != null)
2545 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2546 viewport.getHiddenRepSequences());
2550 seqs = viewport.getAlignment().getSequencesArray();
2553 TrimRegionCommand trimRegion;
2556 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2557 column, viewport.getAlignment());
2558 viewport.setStartRes(0);
2562 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2563 column, viewport.getAlignment());
2566 statusBar.setText(MessageManager.formatMessage(
2567 "label.removed_columns",
2568 new String[] { Integer.valueOf(trimRegion.getSize())
2571 addHistoryItem(trimRegion);
2573 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2575 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2576 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2578 viewport.getAlignment().deleteGroup(sg);
2582 viewport.firePropertyChange("alignment", null, viewport
2583 .getAlignment().getSequences());
2594 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2596 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2599 if (viewport.getSelectionGroup() != null)
2601 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2602 viewport.getHiddenRepSequences());
2603 start = viewport.getSelectionGroup().getStartRes();
2604 end = viewport.getSelectionGroup().getEndRes();
2608 seqs = viewport.getAlignment().getSequencesArray();
2611 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2612 "Remove Gapped Columns", seqs, start, end,
2613 viewport.getAlignment());
2615 addHistoryItem(removeGapCols);
2617 statusBar.setText(MessageManager.formatMessage(
2618 "label.removed_empty_columns",
2619 new Object[] { Integer.valueOf(removeGapCols.getSize())
2622 // This is to maintain viewport position on first residue
2623 // of first sequence
2624 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2625 int startRes = seq.findPosition(viewport.startRes);
2626 // ShiftList shifts;
2627 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2628 // edit.alColumnChanges=shifts.getInverse();
2629 // if (viewport.hasHiddenColumns)
2630 // viewport.getColumnSelection().compensateForEdits(shifts);
2631 viewport.setStartRes(seq.findIndex(startRes) - 1);
2632 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2644 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2646 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2649 if (viewport.getSelectionGroup() != null)
2651 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2652 viewport.getHiddenRepSequences());
2653 start = viewport.getSelectionGroup().getStartRes();
2654 end = viewport.getSelectionGroup().getEndRes();
2658 seqs = viewport.getAlignment().getSequencesArray();
2661 // This is to maintain viewport position on first residue
2662 // of first sequence
2663 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2664 int startRes = seq.findPosition(viewport.startRes);
2666 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2667 viewport.getAlignment()));
2669 viewport.setStartRes(seq.findIndex(startRes) - 1);
2671 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2683 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2685 viewport.setPadGaps(padGapsMenuitem.isSelected());
2686 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2697 public void findMenuItem_actionPerformed(ActionEvent e)
2703 * Create a new view of the current alignment.
2706 public void newView_actionPerformed(ActionEvent e)
2708 newView(null, true);
2712 * Creates and shows a new view of the current alignment.
2715 * title of newly created view; if null, one will be generated
2716 * @param copyAnnotation
2717 * if true then duplicate all annnotation, groups and settings
2718 * @return new alignment panel, already displayed.
2720 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2723 * Create a new AlignmentPanel (with its own, new Viewport)
2725 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2727 if (!copyAnnotation)
2730 * remove all groups and annotation except for the automatic stuff
2732 newap.av.getAlignment().deleteAllGroups();
2733 newap.av.getAlignment().deleteAllAnnotations(false);
2736 newap.av.setGatherViewsHere(false);
2738 if (viewport.viewName == null)
2740 viewport.viewName = MessageManager
2741 .getString("label.view_name_original");
2745 * Views share the same edits undo and redo stacks
2747 newap.av.setHistoryList(viewport.getHistoryList());
2748 newap.av.setRedoList(viewport.getRedoList());
2751 * Views share the same mappings; need to deregister any new mappings
2752 * created by copyAlignPanel, and register the new reference to the shared
2755 newap.av.replaceMappings(viewport.getAlignment());
2757 newap.av.viewName = getNewViewName(viewTitle);
2759 addAlignmentPanel(newap, true);
2760 newap.alignmentChanged();
2762 if (alignPanels.size() == 2)
2764 viewport.setGatherViewsHere(true);
2766 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2771 * Make a new name for the view, ensuring it is unique within the current
2772 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2773 * these now use viewId. Unique view names are still desirable for usability.)
2778 protected String getNewViewName(String viewTitle)
2780 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2781 boolean addFirstIndex = false;
2782 if (viewTitle == null || viewTitle.trim().length() == 0)
2784 viewTitle = MessageManager.getString("action.view");
2785 addFirstIndex = true;
2789 index = 1;// we count from 1 if given a specific name
2791 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2793 List<Component> comps = PaintRefresher.components.get(viewport
2794 .getSequenceSetId());
2796 List<String> existingNames = getExistingViewNames(comps);
2798 while (existingNames.contains(newViewName))
2800 newViewName = viewTitle + " " + (++index);
2806 * Returns a list of distinct view names found in the given list of
2807 * components. View names are held on the viewport of an AlignmentPanel.
2812 protected List<String> getExistingViewNames(List<Component> comps)
2814 List<String> existingNames = new ArrayList<String>();
2815 for (Component comp : comps)
2817 if (comp instanceof AlignmentPanel)
2819 AlignmentPanel ap = (AlignmentPanel) comp;
2820 if (!existingNames.contains(ap.av.viewName))
2822 existingNames.add(ap.av.viewName);
2826 return existingNames;
2830 * Explode tabbed views into separate windows.
2833 public void expandViews_actionPerformed(ActionEvent e)
2835 Desktop.explodeViews(this);
2839 * Gather views in separate windows back into a tabbed presentation.
2842 public void gatherViews_actionPerformed(ActionEvent e)
2844 Desktop.instance.gatherViews(this);
2854 public void font_actionPerformed(ActionEvent e)
2856 new FontChooser(alignPanel);
2866 protected void seqLimit_actionPerformed(ActionEvent e)
2868 viewport.setShowJVSuffix(seqLimits.isSelected());
2870 alignPanel.getIdPanel().getIdCanvas()
2871 .setPreferredSize(alignPanel.calculateIdWidth());
2872 alignPanel.paintAlignment(true);
2876 public void idRightAlign_actionPerformed(ActionEvent e)
2878 viewport.setRightAlignIds(idRightAlign.isSelected());
2879 alignPanel.paintAlignment(true);
2883 public void centreColumnLabels_actionPerformed(ActionEvent e)
2885 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2886 alignPanel.paintAlignment(true);
2892 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2895 protected void followHighlight_actionPerformed()
2898 * Set the 'follow' flag on the Viewport (and scroll to position if now
2901 final boolean state = this.followHighlightMenuItem.getState();
2902 viewport.setFollowHighlight(state);
2905 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2916 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2918 viewport.setColourText(colourTextMenuItem.isSelected());
2919 alignPanel.paintAlignment(true);
2929 public void wrapMenuItem_actionPerformed(ActionEvent e)
2931 scaleAbove.setVisible(wrapMenuItem.isSelected());
2932 scaleLeft.setVisible(wrapMenuItem.isSelected());
2933 scaleRight.setVisible(wrapMenuItem.isSelected());
2934 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2935 alignPanel.updateLayout();
2939 public void showAllSeqs_actionPerformed(ActionEvent e)
2941 viewport.showAllHiddenSeqs();
2945 public void showAllColumns_actionPerformed(ActionEvent e)
2947 viewport.showAllHiddenColumns();
2949 viewport.sendSelection();
2953 public void hideSelSequences_actionPerformed(ActionEvent e)
2955 viewport.hideAllSelectedSeqs();
2956 // alignPanel.paintAlignment(true);
2960 * called by key handler and the hide all/show all menu items
2965 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2968 boolean hide = false;
2969 SequenceGroup sg = viewport.getSelectionGroup();
2970 if (!toggleSeqs && !toggleCols)
2972 // Hide everything by the current selection - this is a hack - we do the
2973 // invert and then hide
2974 // first check that there will be visible columns after the invert.
2975 if (viewport.hasSelectedColumns()
2976 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2979 // now invert the sequence set, if required - empty selection implies
2980 // that no hiding is required.
2983 invertSequenceMenuItem_actionPerformed(null);
2984 sg = viewport.getSelectionGroup();
2988 viewport.expandColSelection(sg, true);
2989 // finally invert the column selection and get the new sequence
2991 invertColSel_actionPerformed(null);
2998 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3000 hideSelSequences_actionPerformed(null);
3003 else if (!(toggleCols && viewport.hasSelectedColumns()))
3005 showAllSeqs_actionPerformed(null);
3011 if (viewport.hasSelectedColumns())
3013 hideSelColumns_actionPerformed(null);
3016 viewport.setSelectionGroup(sg);
3021 showAllColumns_actionPerformed(null);
3030 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3031 * event.ActionEvent)
3034 public void hideAllButSelection_actionPerformed(ActionEvent e)
3036 toggleHiddenRegions(false, false);
3037 viewport.sendSelection();
3044 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3048 public void hideAllSelection_actionPerformed(ActionEvent e)
3050 SequenceGroup sg = viewport.getSelectionGroup();
3051 viewport.expandColSelection(sg, false);
3052 viewport.hideAllSelectedSeqs();
3053 viewport.hideSelectedColumns();
3054 alignPanel.paintAlignment(true);
3055 viewport.sendSelection();
3062 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3066 public void showAllhidden_actionPerformed(ActionEvent e)
3068 viewport.showAllHiddenColumns();
3069 viewport.showAllHiddenSeqs();
3070 alignPanel.paintAlignment(true);
3071 viewport.sendSelection();
3075 public void hideSelColumns_actionPerformed(ActionEvent e)
3077 viewport.hideSelectedColumns();
3078 alignPanel.paintAlignment(true);
3079 viewport.sendSelection();
3083 public void hiddenMarkers_actionPerformed(ActionEvent e)
3085 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3096 protected void scaleAbove_actionPerformed(ActionEvent e)
3098 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3099 alignPanel.paintAlignment(true);
3109 protected void scaleLeft_actionPerformed(ActionEvent e)
3111 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3112 alignPanel.paintAlignment(true);
3122 protected void scaleRight_actionPerformed(ActionEvent e)
3124 viewport.setScaleRightWrapped(scaleRight.isSelected());
3125 alignPanel.paintAlignment(true);
3135 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3137 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3138 alignPanel.paintAlignment(true);
3148 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3150 viewport.setShowText(viewTextMenuItem.isSelected());
3151 alignPanel.paintAlignment(true);
3161 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3163 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3164 alignPanel.paintAlignment(true);
3167 public FeatureSettings featureSettings;
3170 public FeatureSettingsControllerI getFeatureSettingsUI()
3172 return featureSettings;
3176 public void featureSettings_actionPerformed(ActionEvent e)
3178 if (featureSettings != null)
3180 featureSettings.close();
3181 featureSettings = null;
3183 if (!showSeqFeatures.isSelected())
3185 // make sure features are actually displayed
3186 showSeqFeatures.setSelected(true);
3187 showSeqFeatures_actionPerformed(null);
3189 featureSettings = new FeatureSettings(this);
3193 * Set or clear 'Show Sequence Features'
3199 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3201 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3202 alignPanel.paintAlignment(true);
3203 if (alignPanel.getOverviewPanel() != null)
3205 alignPanel.getOverviewPanel().updateOverviewImage();
3210 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3211 * the annotations panel as a whole.
3213 * The options to show/hide all annotations should be enabled when the panel
3214 * is shown, and disabled when the panel is hidden.
3219 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3221 final boolean setVisible = annotationPanelMenuItem.isSelected();
3222 viewport.setShowAnnotation(setVisible);
3223 this.showAllSeqAnnotations.setEnabled(setVisible);
3224 this.hideAllSeqAnnotations.setEnabled(setVisible);
3225 this.showAllAlAnnotations.setEnabled(setVisible);
3226 this.hideAllAlAnnotations.setEnabled(setVisible);
3227 alignPanel.updateLayout();
3231 public void alignmentProperties()
3233 JEditorPane editPane = new JEditorPane("text/html", "");
3234 editPane.setEditable(false);
3235 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3237 editPane.setText(MessageManager.formatMessage("label.html_content",
3238 new Object[] { contents.toString() }));
3239 JInternalFrame frame = new JInternalFrame();
3240 frame.getContentPane().add(new JScrollPane(editPane));
3242 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3243 "label.alignment_properties", new Object[] { getTitle() }),
3254 public void overviewMenuItem_actionPerformed(ActionEvent e)
3256 if (alignPanel.overviewPanel != null)
3261 JInternalFrame frame = new JInternalFrame();
3262 OverviewPanel overview = new OverviewPanel(alignPanel);
3263 frame.setContentPane(overview);
3264 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3265 "label.overview_params", new Object[] { this.getTitle() }),
3266 frame.getWidth(), frame.getHeight());
3268 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3269 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3272 public void internalFrameClosed(
3273 javax.swing.event.InternalFrameEvent evt)
3275 alignPanel.setOverviewPanel(null);
3279 alignPanel.setOverviewPanel(overview);
3283 public void textColour_actionPerformed()
3285 new TextColourChooser().chooseColour(alignPanel, null);
3289 * public void covariationColour_actionPerformed() {
3291 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3295 public void annotationColour_actionPerformed()
3297 new AnnotationColourChooser(viewport, alignPanel);
3301 public void annotationColumn_actionPerformed(ActionEvent e)
3303 new AnnotationColumnChooser(viewport, alignPanel);
3307 * Action on the user checking or unchecking the option to apply the selected
3308 * colour scheme to all groups. If unchecked, groups may have their own
3309 * independent colour schemes.
3314 public void applyToAllGroups_actionPerformed(boolean selected)
3316 viewport.setColourAppliesToAllGroups(selected);
3320 * Action on user selecting a colour from the colour menu
3323 * the name (not the menu item label!) of the colour scheme
3326 public void changeColour_actionPerformed(String name)
3329 * 'User Defined' opens a panel to configure or load a
3330 * user-defined colour scheme
3332 if (ResidueColourScheme.USER_DEFINED.equals(name))
3334 new UserDefinedColours(alignPanel, null);
3339 * otherwise set the chosen colour scheme (or null for 'None')
3341 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3342 viewport.getAlignment(), viewport.getHiddenRepSequences());
3347 * Actions on setting or changing the alignment colour scheme
3352 public void changeColour(ColourSchemeI cs)
3354 // TODO: pull up to controller method
3357 ColourMenuHelper.setColourSelected(colourMenu, cs.getSchemeName());
3360 viewport.setGlobalColourScheme(cs);
3362 alignPanel.paintAlignment(true);
3366 * Show the PID threshold slider panel
3369 protected void modifyPID_actionPerformed()
3371 SliderPanel.setPIDSliderSource(alignPanel,
3372 viewport.getResidueShading(), alignPanel.getViewName());
3373 SliderPanel.showPIDSlider();
3377 * Show the Conservation slider panel
3380 protected void modifyConservation_actionPerformed()
3382 SliderPanel.setConservationSlider(alignPanel,
3383 viewport.getResidueShading(), alignPanel.getViewName());
3384 SliderPanel.showConservationSlider();
3388 * Action on selecting or deselecting (Colour) By Conservation
3391 public void conservationMenuItem_actionPerformed(boolean selected)
3393 modifyConservation.setEnabled(selected);
3394 viewport.setConservationSelected(selected);
3395 viewport.getResidueShading().setConservationApplied(selected);
3397 changeColour(viewport.getGlobalColourScheme());
3400 modifyConservation_actionPerformed();
3404 SliderPanel.hideConservationSlider();
3409 * Action on selecting or deselecting (Colour) Above PID Threshold
3412 public void abovePIDThreshold_actionPerformed(boolean selected)
3414 modifyPID.setEnabled(selected);
3415 viewport.setAbovePIDThreshold(selected);
3418 viewport.getResidueShading().setThreshold(0,
3419 viewport.isIgnoreGapsConsensus());
3422 changeColour(viewport.getGlobalColourScheme());
3425 modifyPID_actionPerformed();
3429 SliderPanel.hidePIDSlider();
3440 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3442 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3443 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3444 .getAlignment().getSequenceAt(0), null);
3445 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3446 viewport.getAlignment()));
3447 alignPanel.paintAlignment(true);
3457 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3459 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3460 AlignmentSorter.sortByID(viewport.getAlignment());
3461 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3462 viewport.getAlignment()));
3463 alignPanel.paintAlignment(true);
3473 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3475 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3476 AlignmentSorter.sortByLength(viewport.getAlignment());
3477 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3478 viewport.getAlignment()));
3479 alignPanel.paintAlignment(true);
3489 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3491 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3492 AlignmentSorter.sortByGroup(viewport.getAlignment());
3493 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3494 viewport.getAlignment()));
3496 alignPanel.paintAlignment(true);
3506 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3508 new RedundancyPanel(alignPanel, this);
3518 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3520 if ((viewport.getSelectionGroup() == null)
3521 || (viewport.getSelectionGroup().getSize() < 2))
3523 JvOptionPane.showInternalMessageDialog(this, MessageManager
3524 .getString("label.you_must_select_least_two_sequences"),
3525 MessageManager.getString("label.invalid_selection"),
3526 JvOptionPane.WARNING_MESSAGE);
3530 JInternalFrame frame = new JInternalFrame();
3531 frame.setContentPane(new PairwiseAlignPanel(viewport));
3532 Desktop.addInternalFrame(frame,
3533 MessageManager.getString("action.pairwise_alignment"), 600,
3545 public void PCAMenuItem_actionPerformed(ActionEvent e)
3547 if (((viewport.getSelectionGroup() != null)
3548 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3549 .getSelectionGroup().getSize() > 0))
3550 || (viewport.getAlignment().getHeight() < 4))
3553 .showInternalMessageDialog(
3556 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3558 .getString("label.sequence_selection_insufficient"),
3559 JvOptionPane.WARNING_MESSAGE);
3564 new PCAPanel(alignPanel);
3568 public void autoCalculate_actionPerformed(ActionEvent e)
3570 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3571 if (viewport.autoCalculateConsensus)
3573 viewport.firePropertyChange("alignment", null, viewport
3574 .getAlignment().getSequences());
3579 public void sortByTreeOption_actionPerformed(ActionEvent e)
3581 viewport.sortByTree = sortByTree.isSelected();
3585 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3587 viewport.followSelection = listenToViewSelections.isSelected();
3600 void newTreePanel(String type, String pwType, String title)
3604 if (viewport.getSelectionGroup() != null
3605 && viewport.getSelectionGroup().getSize() > 0)
3607 if (viewport.getSelectionGroup().getSize() < 3)
3613 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3615 .getString("label.not_enough_sequences"),
3616 JvOptionPane.WARNING_MESSAGE);
3620 SequenceGroup sg = viewport.getSelectionGroup();
3622 /* Decide if the selection is a column region */
3623 for (SequenceI _s : sg.getSequences())
3625 if (_s.getLength() < sg.getEndRes())
3631 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3633 .getString("label.sequences_selection_not_aligned"),
3634 JvOptionPane.WARNING_MESSAGE);
3640 title = title + " on region";
3641 tp = new TreePanel(alignPanel, type, pwType);
3645 // are the visible sequences aligned?
3646 if (!viewport.getAlignment().isAligned(false))
3652 .getString("label.sequences_must_be_aligned_before_creating_tree"),
3654 .getString("label.sequences_not_aligned"),
3655 JvOptionPane.WARNING_MESSAGE);
3660 if (viewport.getAlignment().getHeight() < 2)
3665 tp = new TreePanel(alignPanel, type, pwType);
3670 if (viewport.viewName != null)
3672 title += viewport.viewName + " of ";
3675 title += this.title;
3677 Desktop.addInternalFrame(tp, title, 600, 500);
3688 public void addSortByOrderMenuItem(String title,
3689 final AlignmentOrder order)
3691 final JMenuItem item = new JMenuItem(MessageManager.formatMessage(
3692 "action.by_title_param", new Object[] { title }));
3694 item.addActionListener(new java.awt.event.ActionListener()
3697 public void actionPerformed(ActionEvent e)
3699 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3701 // TODO: JBPNote - have to map order entries to curent SequenceI
3703 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3705 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
3708 alignPanel.paintAlignment(true);
3714 * Add a new sort by annotation score menu item
3717 * the menu to add the option to
3719 * the label used to retrieve scores for each sequence on the
3722 public void addSortByAnnotScoreMenuItem(JMenu sort,
3723 final String scoreLabel)
3725 final JMenuItem item = new JMenuItem(scoreLabel);
3727 item.addActionListener(new java.awt.event.ActionListener()
3730 public void actionPerformed(ActionEvent e)
3732 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3733 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3734 viewport.getAlignment());// ,viewport.getSelectionGroup());
3735 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3736 viewport.getAlignment()));
3737 alignPanel.paintAlignment(true);
3743 * last hash for alignment's annotation array - used to minimise cost of
3746 protected int _annotationScoreVectorHash;
3749 * search the alignment and rebuild the sort by annotation score submenu the
3750 * last alignment annotation vector hash is stored to minimize cost of
3751 * rebuilding in subsequence calls.
3755 public void buildSortByAnnotationScoresMenu()
3757 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3762 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
3764 sortByAnnotScore.removeAll();
3765 // almost certainly a quicker way to do this - but we keep it simple
3766 Hashtable scoreSorts = new Hashtable();
3767 AlignmentAnnotation aann[];
3768 for (SequenceI sqa : viewport.getAlignment().getSequences())
3770 aann = sqa.getAnnotation();
3771 for (int i = 0; aann != null && i < aann.length; i++)
3773 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3775 scoreSorts.put(aann[i].label, aann[i].label);
3779 Enumeration labels = scoreSorts.keys();
3780 while (labels.hasMoreElements())
3782 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3783 (String) labels.nextElement());
3785 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3788 _annotationScoreVectorHash = viewport.getAlignment()
3789 .getAlignmentAnnotation().hashCode();
3794 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3795 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3796 * call. Listeners are added to remove the menu item when the treePanel is
3797 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3801 public void buildTreeSortMenu()
3803 sortByTreeMenu.removeAll();
3805 List<Component> comps = PaintRefresher.components.get(viewport
3806 .getSequenceSetId());
3807 List<TreePanel> treePanels = new ArrayList<TreePanel>();
3808 for (Component comp : comps)
3810 if (comp instanceof TreePanel)
3812 treePanels.add((TreePanel) comp);
3816 if (treePanels.size() < 1)
3818 sortByTreeMenu.setVisible(false);
3822 sortByTreeMenu.setVisible(true);
3824 for (final TreePanel tp : treePanels)
3826 final JMenuItem item = new JMenuItem(tp.getTitle());
3827 item.addActionListener(new java.awt.event.ActionListener()
3830 public void actionPerformed(ActionEvent e)
3832 tp.sortByTree_actionPerformed();
3833 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3838 sortByTreeMenu.add(item);
3842 public boolean sortBy(AlignmentOrder alorder, String undoname)
3844 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3845 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3846 if (undoname != null)
3848 addHistoryItem(new OrderCommand(undoname, oldOrder,
3849 viewport.getAlignment()));
3851 alignPanel.paintAlignment(true);
3856 * Work out whether the whole set of sequences or just the selected set will
3857 * be submitted for multiple alignment.
3860 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3862 // Now, check we have enough sequences
3863 AlignmentView msa = null;
3865 if ((viewport.getSelectionGroup() != null)
3866 && (viewport.getSelectionGroup().getSize() > 1))
3868 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3869 // some common interface!
3871 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3872 * SequenceI[sz = seqs.getSize(false)];
3874 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3875 * seqs.getSequenceAt(i); }
3877 msa = viewport.getAlignmentView(true);
3879 else if (viewport.getSelectionGroup() != null
3880 && viewport.getSelectionGroup().getSize() == 1)
3882 int option = JvOptionPane.showConfirmDialog(this,
3883 MessageManager.getString("warn.oneseq_msainput_selection"),
3884 MessageManager.getString("label.invalid_selection"),
3885 JvOptionPane.OK_CANCEL_OPTION);
3886 if (option == JvOptionPane.OK_OPTION)
3888 msa = viewport.getAlignmentView(false);
3893 msa = viewport.getAlignmentView(false);
3899 * Decides what is submitted to a secondary structure prediction service: the
3900 * first sequence in the alignment, or in the current selection, or, if the
3901 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3902 * region or the whole alignment. (where the first sequence in the set is the
3903 * one that the prediction will be for).
3905 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3907 AlignmentView seqs = null;
3909 if ((viewport.getSelectionGroup() != null)
3910 && (viewport.getSelectionGroup().getSize() > 0))
3912 seqs = viewport.getAlignmentView(true);
3916 seqs = viewport.getAlignmentView(false);
3918 // limit sequences - JBPNote in future - could spawn multiple prediction
3920 // TODO: viewport.getAlignment().isAligned is a global state - the local
3921 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3922 if (!viewport.getAlignment().isAligned(false))
3924 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3925 // TODO: if seqs.getSequences().length>1 then should really have warned
3939 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3941 // Pick the tree file
3942 JalviewFileChooser chooser = new JalviewFileChooser(
3943 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3944 chooser.setFileView(new JalviewFileView());
3945 chooser.setDialogTitle(MessageManager
3946 .getString("label.select_newick_like_tree_file"));
3947 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
3949 int value = chooser.showOpenDialog(null);
3951 if (value == JalviewFileChooser.APPROVE_OPTION)
3953 String choice = chooser.getSelectedFile().getPath();
3954 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
3955 jalview.io.NewickFile fin = null;
3958 fin = new NewickFile(choice, DataSourceType.FILE);
3959 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
3960 } catch (Exception ex)
3967 .getString("label.problem_reading_tree_file"),
3968 JvOptionPane.WARNING_MESSAGE);
3969 ex.printStackTrace();
3971 if (fin != null && fin.hasWarningMessage())
3973 JvOptionPane.showMessageDialog(Desktop.desktop, fin
3974 .getWarningMessage(), MessageManager
3975 .getString("label.possible_problem_with_tree_file"),
3976 JvOptionPane.WARNING_MESSAGE);
3981 public TreePanel ShowNewickTree(NewickFile nf, String title)
3983 return ShowNewickTree(nf, title, 600, 500, 4, 5);
3986 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
3987 int h, int x, int y)
3989 return ShowNewickTree(nf, title, null, w, h, x, y);
3993 * Add a treeviewer for the tree extracted from a newick file object to the
3994 * current alignment view
4001 * Associated alignment input data (or null)
4010 * @return TreePanel handle
4012 public TreePanel ShowNewickTree(NewickFile nf, String title,
4013 AlignmentView input, int w, int h, int x, int y)
4015 TreePanel tp = null;
4021 if (nf.getTree() != null)
4023 tp = new TreePanel(alignPanel, NJTree.FROM_FILE, title, nf, input);
4029 tp.setLocation(x, y);
4032 Desktop.addInternalFrame(tp, title, w, h);
4034 } catch (Exception ex)
4036 ex.printStackTrace();
4042 private boolean buildingMenu = false;
4045 * Generates menu items and listener event actions for web service clients
4048 public void BuildWebServiceMenu()
4050 while (buildingMenu)
4054 System.err.println("Waiting for building menu to finish.");
4056 } catch (Exception e)
4060 final AlignFrame me = this;
4061 buildingMenu = true;
4062 new Thread(new Runnable()
4067 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4070 // System.err.println("Building ws menu again "
4071 // + Thread.currentThread());
4072 // TODO: add support for context dependent disabling of services based
4074 // alignment and current selection
4075 // TODO: add additional serviceHandle parameter to specify abstract
4077 // class independently of AbstractName
4078 // TODO: add in rediscovery GUI function to restart discoverer
4079 // TODO: group services by location as well as function and/or
4081 // object broker mechanism.
4082 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4083 final IProgressIndicator af = me;
4086 * do not i18n these strings - they are hard-coded in class
4087 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4088 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4090 final JMenu msawsmenu = new JMenu("Alignment");
4091 final JMenu secstrmenu = new JMenu(
4092 "Secondary Structure Prediction");
4093 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4094 final JMenu analymenu = new JMenu("Analysis");
4095 final JMenu dismenu = new JMenu("Protein Disorder");
4096 // JAL-940 - only show secondary structure prediction services from
4097 // the legacy server
4098 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4100 Discoverer.services != null && (Discoverer.services.size() > 0))
4102 // TODO: refactor to allow list of AbstractName/Handler bindings to
4104 // stored or retrieved from elsewhere
4105 // No MSAWS used any more:
4106 // Vector msaws = null; // (Vector)
4107 // Discoverer.services.get("MsaWS");
4108 Vector secstrpr = (Vector) Discoverer.services
4110 if (secstrpr != null)
4112 // Add any secondary structure prediction services
4113 for (int i = 0, j = secstrpr.size(); i < j; i++)
4115 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4117 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4118 .getServiceClient(sh);
4119 int p = secstrmenu.getItemCount();
4120 impl.attachWSMenuEntry(secstrmenu, me);
4121 int q = secstrmenu.getItemCount();
4122 for (int litm = p; litm < q; litm++)
4124 legacyItems.add(secstrmenu.getItem(litm));
4130 // Add all submenus in the order they should appear on the web
4132 wsmenu.add(msawsmenu);
4133 wsmenu.add(secstrmenu);
4134 wsmenu.add(dismenu);
4135 wsmenu.add(analymenu);
4136 // No search services yet
4137 // wsmenu.add(seqsrchmenu);
4139 javax.swing.SwingUtilities.invokeLater(new Runnable()
4146 webService.removeAll();
4147 // first, add discovered services onto the webservices menu
4148 if (wsmenu.size() > 0)
4150 for (int i = 0, j = wsmenu.size(); i < j; i++)
4152 webService.add(wsmenu.get(i));
4157 webService.add(me.webServiceNoServices);
4159 // TODO: move into separate menu builder class.
4160 boolean new_sspred = false;
4161 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4163 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4164 if (jws2servs != null)
4166 if (jws2servs.hasServices())
4168 jws2servs.attachWSMenuEntry(webService, me);
4169 for (Jws2Instance sv : jws2servs.getServices())
4171 if (sv.description.toLowerCase().contains("jpred"))
4173 for (JMenuItem jmi : legacyItems)
4175 jmi.setVisible(false);
4181 if (jws2servs.isRunning())
4183 JMenuItem tm = new JMenuItem(
4184 "Still discovering JABA Services");
4185 tm.setEnabled(false);
4190 build_urlServiceMenu(me.webService);
4191 build_fetchdbmenu(webService);
4192 for (JMenu item : wsmenu)
4194 if (item.getItemCount() == 0)
4196 item.setEnabled(false);
4200 item.setEnabled(true);
4203 } catch (Exception e)
4206 .debug("Exception during web service menu building process.",
4211 } catch (Exception e)
4214 buildingMenu = false;
4221 * construct any groupURL type service menu entries.
4225 private void build_urlServiceMenu(JMenu webService)
4227 // TODO: remove this code when 2.7 is released
4228 // DEBUG - alignmentView
4230 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4231 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4233 * @Override public void actionPerformed(ActionEvent e) {
4234 * jalview.datamodel.AlignmentView
4235 * .testSelectionViews(af.viewport.getAlignment(),
4236 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4238 * }); webService.add(testAlView);
4240 // TODO: refactor to RestClient discoverer and merge menu entries for
4241 // rest-style services with other types of analysis/calculation service
4242 // SHmmr test client - still being implemented.
4243 // DEBUG - alignmentView
4245 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4248 client.attachWSMenuEntry(
4249 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4255 * Searches the alignment sequences for xRefs and builds the Show
4256 * Cross-References menu (formerly called Show Products), with database
4257 * sources for which cross-references are found (protein sources for a
4258 * nucleotide alignment and vice versa)
4260 * @return true if Show Cross-references menu should be enabled
4262 public boolean canShowProducts()
4264 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4265 AlignmentI dataset = viewport.getAlignment().getDataset();
4267 showProducts.removeAll();
4268 final boolean dna = viewport.getAlignment().isNucleotide();
4270 if (seqs == null || seqs.length == 0)
4272 // nothing to see here.
4276 boolean showp = false;
4279 List<String> ptypes = new CrossRef(seqs, dataset)
4280 .findXrefSourcesForSequences(dna);
4282 for (final String source : ptypes)
4285 final AlignFrame af = this;
4286 JMenuItem xtype = new JMenuItem(source);
4287 xtype.addActionListener(new ActionListener()
4290 public void actionPerformed(ActionEvent e)
4292 showProductsFor(af.viewport.getSequenceSelection(), dna, source);
4295 showProducts.add(xtype);
4297 showProducts.setVisible(showp);
4298 showProducts.setEnabled(showp);
4299 } catch (Exception e)
4302 .warn("canShowProducts threw an exception - please report to help@jalview.org",
4310 * Finds and displays cross-references for the selected sequences (protein
4311 * products for nucleotide sequences, dna coding sequences for peptides).
4314 * the sequences to show cross-references for
4316 * true if from a nucleotide alignment (so showing proteins)
4318 * the database to show cross-references for
4320 protected void showProductsFor(final SequenceI[] sel,
4321 final boolean _odna, final String source)
4323 new Thread(CrossRefAction.showProductsFor(sel, _odna, source, this))
4328 * Construct and display a new frame containing the translation of this
4329 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4332 public void showTranslation_actionPerformed(ActionEvent e)
4334 AlignmentI al = null;
4337 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4339 al = dna.translateCdna();
4340 } catch (Exception ex)
4342 jalview.bin.Cache.log.error(
4343 "Exception during translation. Please report this !", ex);
4344 final String msg = MessageManager
4345 .getString("label.error_when_translating_sequences_submit_bug_report");
4346 final String errorTitle = MessageManager
4347 .getString("label.implementation_error")
4348 + MessageManager.getString("label.translation_failed");
4349 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4350 JvOptionPane.ERROR_MESSAGE);
4353 if (al == null || al.getHeight() == 0)
4355 final String msg = MessageManager
4356 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4357 final String errorTitle = MessageManager
4358 .getString("label.translation_failed");
4359 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4360 JvOptionPane.WARNING_MESSAGE);
4364 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4365 af.setFileFormat(this.currentFileFormat);
4366 final String newTitle = MessageManager.formatMessage(
4367 "label.translation_of_params",
4368 new Object[] { this.getTitle() });
4369 af.setTitle(newTitle);
4370 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4372 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4373 viewport.openSplitFrame(af, new Alignment(seqs));
4377 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4384 * Set the file format
4388 public void setFileFormat(FileFormatI format)
4390 this.currentFileFormat = format;
4394 * Try to load a features file onto the alignment.
4397 * contents or path to retrieve file
4399 * access mode of file (see jalview.io.AlignFile)
4400 * @return true if features file was parsed correctly.
4402 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4404 return avc.parseFeaturesFile(file, sourceType,
4405 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4410 public void refreshFeatureUI(boolean enableIfNecessary)
4412 // note - currently this is only still here rather than in the controller
4413 // because of the featureSettings hard reference that is yet to be
4415 if (enableIfNecessary)
4417 viewport.setShowSequenceFeatures(true);
4418 showSeqFeatures.setSelected(true);
4424 public void dragEnter(DropTargetDragEvent evt)
4429 public void dragExit(DropTargetEvent evt)
4434 public void dragOver(DropTargetDragEvent evt)
4439 public void dropActionChanged(DropTargetDragEvent evt)
4444 public void drop(DropTargetDropEvent evt)
4446 // JAL-1552 - acceptDrop required before getTransferable call for
4447 // Java's Transferable for native dnd
4448 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4449 Transferable t = evt.getTransferable();
4450 List<String> files = new ArrayList<String>();
4451 List<DataSourceType> protocols = new ArrayList<DataSourceType>();
4455 Desktop.transferFromDropTarget(files, protocols, evt, t);
4456 } catch (Exception e)
4458 e.printStackTrace();
4464 // check to see if any of these files have names matching sequences in
4466 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4467 .getAlignment().getSequencesArray());
4469 * Object[] { String,SequenceI}
4471 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
4472 ArrayList<String> filesnotmatched = new ArrayList<String>();
4473 for (int i = 0; i < files.size(); i++)
4475 String file = files.get(i).toString();
4477 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4478 if (protocol == DataSourceType.FILE)
4480 File fl = new File(file);
4481 pdbfn = fl.getName();
4483 else if (protocol == DataSourceType.URL)
4485 URL url = new URL(file);
4486 pdbfn = url.getFile();
4488 if (pdbfn.length() > 0)
4490 // attempt to find a match in the alignment
4491 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4492 int l = 0, c = pdbfn.indexOf(".");
4493 while (mtch == null && c != -1)
4498 } while ((c = pdbfn.indexOf(".", l)) > l);
4501 pdbfn = pdbfn.substring(0, l);
4503 mtch = idm.findAllIdMatches(pdbfn);
4507 FileFormatI type = null;
4510 type = new IdentifyFile().identify(file, protocol);
4511 } catch (Exception ex)
4515 if (type != null && type.isStructureFile())
4517 filesmatched.add(new Object[] { file, protocol, mtch });
4521 // File wasn't named like one of the sequences or wasn't a PDB file.
4522 filesnotmatched.add(file);
4526 if (filesmatched.size() > 0)
4528 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4534 "label.automatically_associate_structure_files_with_sequences_same_name",
4535 new Object[] { Integer
4541 .getString("label.automatically_associate_structure_files_by_name"),
4542 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION)
4545 for (Object[] fm : filesmatched)
4547 // try and associate
4548 // TODO: may want to set a standard ID naming formalism for
4549 // associating PDB files which have no IDs.
4550 for (SequenceI toassoc : (SequenceI[]) fm[2])
4552 PDBEntry pe = new AssociatePdbFileWithSeq()
4553 .associatePdbWithSeq((String) fm[0],
4554 (DataSourceType) fm[1], toassoc, false,
4558 System.err.println("Associated file : "
4559 + ((String) fm[0]) + " with "
4560 + toassoc.getDisplayId(true));
4564 alignPanel.paintAlignment(true);
4568 if (filesnotmatched.size() > 0)
4571 && (Cache.getDefault(
4572 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JvOptionPane
4578 "label.ignore_unmatched_dropped_files_info",
4579 new Object[] { Integer
4586 .getString("label.ignore_unmatched_dropped_files"),
4587 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4591 for (String fn : filesnotmatched)
4593 loadJalviewDataFile(fn, null, null, null);
4597 } catch (Exception ex)
4599 ex.printStackTrace();
4605 * Attempt to load a "dropped" file or URL string, by testing in turn for
4607 * <li>an Annotation file</li>
4608 * <li>a JNet file</li>
4609 * <li>a features file</li>
4610 * <li>else try to interpret as an alignment file</li>
4614 * either a filename or a URL string.
4616 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4617 FileFormatI format, SequenceI assocSeq)
4621 if (sourceType == null)
4623 sourceType = FormatAdapter.checkProtocol(file);
4625 // if the file isn't identified, or not positively identified as some
4626 // other filetype (PFAM is default unidentified alignment file type) then
4627 // try to parse as annotation.
4628 boolean isAnnotation = (format == null || FileFormat.Pfam
4629 .equals(format)) ? new AnnotationFile()
4630 .annotateAlignmentView(viewport, file, sourceType) : false;
4634 // first see if its a T-COFFEE score file
4635 TCoffeeScoreFile tcf = null;
4638 tcf = new TCoffeeScoreFile(file, sourceType);
4641 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4644 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
4645 isAnnotation = true;
4647 .setText(MessageManager
4648 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
4652 // some problem - if no warning its probable that the ID matching
4653 // process didn't work
4657 tcf.getWarningMessage() == null ? MessageManager
4658 .getString("label.check_file_matches_sequence_ids_alignment")
4659 : tcf.getWarningMessage(),
4661 .getString("label.problem_reading_tcoffee_score_file"),
4662 JvOptionPane.WARNING_MESSAGE);
4669 } catch (Exception x)
4672 .debug("Exception when processing data source as T-COFFEE score file",
4678 // try to see if its a JNet 'concise' style annotation file *before*
4680 // try to parse it as a features file
4683 format = new IdentifyFile().identify(file, sourceType);
4685 if (FileFormat.ScoreMatrix == format)
4687 ScoreMatrixFile sm = new ScoreMatrixFile(new FileParse(file,
4690 // todo: i18n this message
4692 .setText(MessageManager.formatMessage(
4693 "label.successfully_loaded_matrix",
4694 sm.getMatrixName()));
4696 else if (FileFormat.Jnet.equals(format))
4698 JPredFile predictions = new JPredFile(file, sourceType);
4699 new JnetAnnotationMaker();
4700 JnetAnnotationMaker.add_annotation(predictions,
4701 viewport.getAlignment(), 0, false);
4702 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
4703 viewport.getAlignment().setSeqrep(repseq);
4704 ColumnSelection cs = new ColumnSelection();
4705 cs.hideInsertionsFor(repseq);
4706 viewport.setColumnSelection(cs);
4707 isAnnotation = true;
4709 // else if (IdentifyFile.FeaturesFile.equals(format))
4710 else if (FileFormat.Features.equals(format))
4712 if (parseFeaturesFile(file, sourceType))
4714 alignPanel.paintAlignment(true);
4719 new FileLoader().LoadFile(viewport, file, sourceType, format);
4726 alignPanel.adjustAnnotationHeight();
4727 viewport.updateSequenceIdColours();
4728 buildSortByAnnotationScoresMenu();
4729 alignPanel.paintAlignment(true);
4731 } catch (Exception ex)
4733 ex.printStackTrace();
4734 } catch (OutOfMemoryError oom)
4739 } catch (Exception x)
4744 + (sourceType != null ? (sourceType == DataSourceType.PASTE ? "from clipboard."
4745 : "using " + sourceType + " from " + file)
4747 + (format != null ? "(parsing as '" + format
4748 + "' file)" : ""), oom, Desktop.desktop);
4753 * Method invoked by the ChangeListener on the tabbed pane, in other words
4754 * when a different tabbed pane is selected by the user or programmatically.
4757 public void tabSelectionChanged(int index)
4761 alignPanel = alignPanels.get(index);
4762 viewport = alignPanel.av;
4763 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4764 setMenusFromViewport(viewport);
4768 * 'focus' any colour slider that is open to the selected viewport
4770 if (viewport.getConservationSelected())
4772 SliderPanel.setConservationSlider(alignPanel,
4773 viewport.getResidueShading(), alignPanel.getViewName());
4777 SliderPanel.hideConservationSlider();
4779 if (viewport.getAbovePIDThreshold())
4781 SliderPanel.setPIDSliderSource(alignPanel,
4782 viewport.getResidueShading(), alignPanel.getViewName());
4786 SliderPanel.hidePIDSlider();
4790 * If there is a frame linked to this one in a SplitPane, switch it to the
4791 * same view tab index. No infinite recursion of calls should happen, since
4792 * tabSelectionChanged() should not get invoked on setting the selected
4793 * index to an unchanged value. Guard against setting an invalid index
4794 * before the new view peer tab has been created.
4796 final AlignViewportI peer = viewport.getCodingComplement();
4799 AlignFrame linkedAlignFrame = ((AlignViewport) peer).getAlignPanel().alignFrame;
4800 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4802 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4808 * On right mouse click on view tab, prompt for and set new view name.
4811 public void tabbedPane_mousePressed(MouseEvent e)
4813 if (e.isPopupTrigger())
4815 String msg = MessageManager.getString("label.enter_view_name");
4816 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4817 JvOptionPane.QUESTION_MESSAGE);
4821 viewport.viewName = reply;
4822 // TODO warn if reply is in getExistingViewNames()?
4823 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4828 public AlignViewport getCurrentView()
4834 * Open the dialog for regex description parsing.
4837 protected void extractScores_actionPerformed(ActionEvent e)
4839 ParseProperties pp = new jalview.analysis.ParseProperties(
4840 viewport.getAlignment());
4841 // TODO: verify regex and introduce GUI dialog for version 2.5
4842 // if (pp.getScoresFromDescription("col", "score column ",
4843 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4845 if (pp.getScoresFromDescription("description column",
4846 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4848 buildSortByAnnotationScoresMenu();
4856 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4860 protected void showDbRefs_actionPerformed(ActionEvent e)
4862 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4868 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4872 protected void showNpFeats_actionPerformed(ActionEvent e)
4874 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4878 * find the viewport amongst the tabs in this alignment frame and close that
4883 public boolean closeView(AlignViewportI av)
4887 this.closeMenuItem_actionPerformed(false);
4890 Component[] comp = tabbedPane.getComponents();
4891 for (int i = 0; comp != null && i < comp.length; i++)
4893 if (comp[i] instanceof AlignmentPanel)
4895 if (((AlignmentPanel) comp[i]).av == av)
4898 closeView((AlignmentPanel) comp[i]);
4906 protected void build_fetchdbmenu(JMenu webService)
4908 // Temporary hack - DBRef Fetcher always top level ws entry.
4909 // TODO We probably want to store a sequence database checklist in
4910 // preferences and have checkboxes.. rather than individual sources selected
4912 final JMenu rfetch = new JMenu(
4913 MessageManager.getString("action.fetch_db_references"));
4914 rfetch.setToolTipText(MessageManager
4915 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4916 webService.add(rfetch);
4918 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4919 MessageManager.getString("option.trim_retrieved_seqs"));
4920 trimrs.setToolTipText(MessageManager
4921 .getString("label.trim_retrieved_sequences"));
4922 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
4923 trimrs.addActionListener(new ActionListener()
4926 public void actionPerformed(ActionEvent e)
4928 trimrs.setSelected(trimrs.isSelected());
4929 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
4930 Boolean.valueOf(trimrs.isSelected()).toString());
4934 JMenuItem fetchr = new JMenuItem(
4935 MessageManager.getString("label.standard_databases"));
4936 fetchr.setToolTipText(MessageManager
4937 .getString("label.fetch_embl_uniprot"));
4938 fetchr.addActionListener(new ActionListener()
4942 public void actionPerformed(ActionEvent e)
4944 new Thread(new Runnable()
4949 boolean isNucleotide = alignPanel.alignFrame.getViewport()
4950 .getAlignment().isNucleotide();
4951 DBRefFetcher dbRefFetcher = new DBRefFetcher(alignPanel.av
4952 .getSequenceSelection(), alignPanel.alignFrame, null,
4953 alignPanel.alignFrame.featureSettings, isNucleotide);
4954 dbRefFetcher.addListener(new FetchFinishedListenerI()
4957 public void finished()
4959 AlignFrame.this.setMenusForViewport();
4962 dbRefFetcher.fetchDBRefs(false);
4970 final AlignFrame me = this;
4971 new Thread(new Runnable()
4976 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
4977 .getSequenceFetcherSingleton(me);
4978 javax.swing.SwingUtilities.invokeLater(new Runnable()
4983 String[] dbclasses = sf.getOrderedSupportedSources();
4984 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
4985 // jalview.util.QuickSort.sort(otherdb, otherdb);
4986 List<DbSourceProxy> otherdb;
4987 JMenu dfetch = new JMenu();
4988 JMenu ifetch = new JMenu();
4989 JMenuItem fetchr = null;
4990 int comp = 0, icomp = 0, mcomp = 15;
4991 String mname = null;
4993 for (String dbclass : dbclasses)
4995 otherdb = sf.getSourceProxy(dbclass);
4996 // add a single entry for this class, or submenu allowing 'fetch
4998 if (otherdb == null || otherdb.size() < 1)
5002 // List<DbSourceProxy> dbs=otherdb;
5003 // otherdb=new ArrayList<DbSourceProxy>();
5004 // for (DbSourceProxy db:dbs)
5006 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5010 mname = "From " + dbclass;
5012 if (otherdb.size() == 1)
5014 final DbSourceProxy[] dassource = otherdb
5015 .toArray(new DbSourceProxy[0]);
5016 DbSourceProxy src = otherdb.get(0);
5017 fetchr = new JMenuItem(src.getDbSource());
5018 fetchr.addActionListener(new ActionListener()
5022 public void actionPerformed(ActionEvent e)
5024 new Thread(new Runnable()
5030 boolean isNucleotide = alignPanel.alignFrame
5031 .getViewport().getAlignment()
5033 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5034 alignPanel.av.getSequenceSelection(),
5035 alignPanel.alignFrame, dassource,
5036 alignPanel.alignFrame.featureSettings,
5039 .addListener(new FetchFinishedListenerI()
5042 public void finished()
5044 AlignFrame.this.setMenusForViewport();
5047 dbRefFetcher.fetchDBRefs(false);
5053 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5054 MessageManager.formatMessage(
5055 "label.fetch_retrieve_from",
5056 new Object[] { src.getDbName() })));
5062 final DbSourceProxy[] dassource = otherdb
5063 .toArray(new DbSourceProxy[0]);
5065 DbSourceProxy src = otherdb.get(0);
5066 fetchr = new JMenuItem(MessageManager.formatMessage(
5067 "label.fetch_all_param",
5068 new Object[] { src.getDbSource() }));
5069 fetchr.addActionListener(new ActionListener()
5072 public void actionPerformed(ActionEvent e)
5074 new Thread(new Runnable()
5080 boolean isNucleotide = alignPanel.alignFrame
5081 .getViewport().getAlignment()
5083 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5084 alignPanel.av.getSequenceSelection(),
5085 alignPanel.alignFrame, dassource,
5086 alignPanel.alignFrame.featureSettings,
5089 .addListener(new FetchFinishedListenerI()
5092 public void finished()
5094 AlignFrame.this.setMenusForViewport();
5097 dbRefFetcher.fetchDBRefs(false);
5103 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5104 MessageManager.formatMessage(
5105 "label.fetch_retrieve_from_all_sources",
5107 Integer.valueOf(otherdb.size())
5108 .toString(), src.getDbSource(),
5109 src.getDbName() })));
5112 // and then build the rest of the individual menus
5113 ifetch = new JMenu(MessageManager.formatMessage(
5114 "label.source_from_db_source",
5115 new Object[] { src.getDbSource() }));
5117 String imname = null;
5119 for (DbSourceProxy sproxy : otherdb)
5121 String dbname = sproxy.getDbName();
5122 String sname = dbname.length() > 5 ? dbname.substring(0,
5123 5) + "..." : dbname;
5124 String msname = dbname.length() > 10 ? dbname.substring(
5125 0, 10) + "..." : dbname;
5128 imname = MessageManager.formatMessage(
5129 "label.from_msname", new Object[] { sname });
5131 fetchr = new JMenuItem(msname);
5132 final DbSourceProxy[] dassrc = { sproxy };
5133 fetchr.addActionListener(new ActionListener()
5137 public void actionPerformed(ActionEvent e)
5139 new Thread(new Runnable()
5145 boolean isNucleotide = alignPanel.alignFrame
5146 .getViewport().getAlignment()
5148 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5149 alignPanel.av.getSequenceSelection(),
5150 alignPanel.alignFrame, dassrc,
5151 alignPanel.alignFrame.featureSettings,
5154 .addListener(new FetchFinishedListenerI()
5157 public void finished()
5159 AlignFrame.this.setMenusForViewport();
5162 dbRefFetcher.fetchDBRefs(false);
5168 fetchr.setToolTipText("<html>"
5169 + MessageManager.formatMessage(
5170 "label.fetch_retrieve_from", new Object[]
5174 if (++icomp >= mcomp || i == (otherdb.size()))
5176 ifetch.setText(MessageManager.formatMessage(
5177 "label.source_to_target", imname, sname));
5179 ifetch = new JMenu();
5187 if (comp >= mcomp || dbi >= (dbclasses.length))
5189 dfetch.setText(MessageManager.formatMessage(
5190 "label.source_to_target", mname, dbclass));
5192 dfetch = new JMenu();
5205 * Left justify the whole alignment.
5208 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5210 AlignmentI al = viewport.getAlignment();
5212 viewport.firePropertyChange("alignment", null, al);
5216 * Right justify the whole alignment.
5219 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5221 AlignmentI al = viewport.getAlignment();
5223 viewport.firePropertyChange("alignment", null, al);
5227 public void setShowSeqFeatures(boolean b)
5229 showSeqFeatures.setSelected(b);
5230 viewport.setShowSequenceFeatures(b);
5237 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5238 * awt.event.ActionEvent)
5241 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5243 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5244 alignPanel.paintAlignment(true);
5251 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5255 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5257 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5258 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5266 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5267 * .event.ActionEvent)
5270 protected void showGroupConservation_actionPerformed(ActionEvent e)
5272 viewport.setShowGroupConservation(showGroupConservation.getState());
5273 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5280 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5281 * .event.ActionEvent)
5284 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5286 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5287 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5294 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5295 * .event.ActionEvent)
5298 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5300 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5301 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5305 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5307 showSequenceLogo.setState(true);
5308 viewport.setShowSequenceLogo(true);
5309 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5310 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5314 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5316 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5323 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5324 * .event.ActionEvent)
5327 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5329 if (avc.makeGroupsFromSelection())
5331 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5332 alignPanel.updateAnnotation();
5333 alignPanel.paintAlignment(true);
5337 public void clearAlignmentSeqRep()
5339 // TODO refactor alignmentseqrep to controller
5340 if (viewport.getAlignment().hasSeqrep())
5342 viewport.getAlignment().setSeqrep(null);
5343 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5344 alignPanel.updateAnnotation();
5345 alignPanel.paintAlignment(true);
5350 protected void createGroup_actionPerformed(ActionEvent e)
5352 if (avc.createGroup())
5354 alignPanel.alignmentChanged();
5359 protected void unGroup_actionPerformed(ActionEvent e)
5363 alignPanel.alignmentChanged();
5368 * make the given alignmentPanel the currently selected tab
5370 * @param alignmentPanel
5372 public void setDisplayedView(AlignmentPanel alignmentPanel)
5374 if (!viewport.getSequenceSetId().equals(
5375 alignmentPanel.av.getSequenceSetId()))
5379 .getString("error.implementation_error_cannot_show_view_alignment_frame"));
5381 if (tabbedPane != null
5382 && tabbedPane.getTabCount() > 0
5383 && alignPanels.indexOf(alignmentPanel) != tabbedPane
5384 .getSelectedIndex())
5386 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5391 * Action on selection of menu options to Show or Hide annotations.
5394 * @param forSequences
5395 * update sequence-related annotations
5396 * @param forAlignment
5397 * update non-sequence-related annotations
5400 protected void setAnnotationsVisibility(boolean visible,
5401 boolean forSequences, boolean forAlignment)
5403 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5404 .getAlignmentAnnotation();
5409 for (AlignmentAnnotation aa : anns)
5412 * don't display non-positional annotations on an alignment
5414 if (aa.annotations == null)
5418 boolean apply = (aa.sequenceRef == null && forAlignment)
5419 || (aa.sequenceRef != null && forSequences);
5422 aa.visible = visible;
5425 alignPanel.validateAnnotationDimensions(true);
5426 alignPanel.alignmentChanged();
5430 * Store selected annotation sort order for the view and repaint.
5433 protected void sortAnnotations_actionPerformed()
5435 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5437 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5438 alignPanel.paintAlignment(true);
5443 * @return alignment panels in this alignment frame
5445 public List<? extends AlignmentViewPanel> getAlignPanels()
5447 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5451 * Open a new alignment window, with the cDNA associated with this (protein)
5452 * alignment, aligned as is the protein.
5454 protected void viewAsCdna_actionPerformed()
5456 // TODO no longer a menu action - refactor as required
5457 final AlignmentI alignment = getViewport().getAlignment();
5458 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5459 if (mappings == null)
5463 List<SequenceI> cdnaSeqs = new ArrayList<SequenceI>();
5464 for (SequenceI aaSeq : alignment.getSequences())
5466 for (AlignedCodonFrame acf : mappings)
5468 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5472 * There is a cDNA mapping for this protein sequence - add to new
5473 * alignment. It will share the same dataset sequence as other mapped
5474 * cDNA (no new mappings need to be created).
5476 final Sequence newSeq = new Sequence(dnaSeq);
5477 newSeq.setDatasetSequence(dnaSeq);
5478 cdnaSeqs.add(newSeq);
5482 if (cdnaSeqs.size() == 0)
5484 // show a warning dialog no mapped cDNA
5487 AlignmentI cdna = new Alignment(cdnaSeqs.toArray(new SequenceI[cdnaSeqs
5489 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5490 AlignFrame.DEFAULT_HEIGHT);
5491 cdna.alignAs(alignment);
5492 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5494 Desktop.addInternalFrame(alignFrame, newtitle,
5495 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
5499 * Set visibility of dna/protein complement view (available when shown in a
5505 protected void showComplement_actionPerformed(boolean show)
5507 SplitContainerI sf = getSplitViewContainer();
5510 sf.setComplementVisible(this, show);
5515 * Generate the reverse (optionally complemented) of the selected sequences,
5516 * and add them to the alignment
5519 protected void showReverse_actionPerformed(boolean complement)
5521 AlignmentI al = null;
5524 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5525 al = dna.reverseCdna(complement);
5526 viewport.addAlignment(al, "");
5527 addHistoryItem(new EditCommand(
5528 MessageManager.getString("label.add_sequences"),
5529 Action.PASTE, al.getSequencesArray(), 0, al.getWidth(),
5530 viewport.getAlignment()));
5531 } catch (Exception ex)
5533 System.err.println(ex.getMessage());
5539 * Try to run a script in the Groovy console, having first ensured that this
5540 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5541 * be targeted at this alignment.
5544 protected void runGroovy_actionPerformed()
5546 Jalview.setCurrentAlignFrame(this);
5547 groovy.ui.Console console = Desktop.getGroovyConsole();
5548 if (console != null)
5552 console.runScript();
5553 } catch (Exception ex)
5555 System.err.println((ex.toString()));
5557 .showInternalMessageDialog(Desktop.desktop, MessageManager
5558 .getString("label.couldnt_run_groovy_script"),
5560 .getString("label.groovy_support_failed"),
5561 JvOptionPane.ERROR_MESSAGE);
5566 System.err.println("Can't run Groovy script as console not found");
5571 * Hides columns containing (or not containing) a specified feature, provided
5572 * that would not leave all columns hidden
5574 * @param featureType
5575 * @param columnsContaining
5578 public boolean hideFeatureColumns(String featureType,
5579 boolean columnsContaining)
5581 boolean notForHiding = avc.markColumnsContainingFeatures(
5582 columnsContaining, false, false, featureType);
5585 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5586 false, featureType))
5588 getViewport().hideSelectedColumns();
5596 protected void selectHighlightedColumns_actionPerformed(
5597 ActionEvent actionEvent)
5599 // include key modifier check in case user selects from menu
5600 avc.markHighlightedColumns(
5601 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0,
5603 (actionEvent.getModifiers() & (ActionEvent.META_MASK | ActionEvent.CTRL_MASK)) != 0);
5607 * Rebuilds the Colour menu, including any user-defined colours which have
5608 * been loaded either on startup or during the session
5610 public void buildColourMenu()
5612 colourMenu.removeAll();
5614 colourMenu.add(applyToAllGroups);
5615 colourMenu.add(textColour);
5616 colourMenu.addSeparator();
5618 ColourMenuHelper.addMenuItems(colourMenu, this,
5619 viewport.getAlignment(), false);
5621 colourMenu.addSeparator();
5622 colourMenu.add(conservationMenuItem);
5623 colourMenu.add(modifyConservation);
5624 colourMenu.add(abovePIDThreshold);
5625 colourMenu.add(modifyPID);
5626 colourMenu.add(annotationColour);
5628 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5629 String schemeName = colourScheme == null ? null : colourScheme
5632 ColourMenuHelper.setColourSelected(colourMenu, schemeName);
5635 public void newTreePanel(String treeType, ScoreModelI sm)
5637 String scoreModelName = sm.getName();
5638 final String ttl = TreePanel.getPanelTitle(treeType, scoreModelName);
5639 newTreePanel(treeType, scoreModelName, ttl);
5643 class PrintThread extends Thread
5647 public PrintThread(AlignmentPanel ap)
5652 static PageFormat pf;
5657 PrinterJob printJob = PrinterJob.getPrinterJob();
5661 printJob.setPrintable(ap, pf);
5665 printJob.setPrintable(ap);
5668 if (printJob.printDialog())
5673 } catch (Exception PrintException)
5675 PrintException.printStackTrace();