2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AlignmentSorter;
24 import jalview.analysis.AlignmentUtils;
25 import jalview.analysis.CrossRef;
26 import jalview.analysis.Dna;
27 import jalview.analysis.ParseProperties;
28 import jalview.analysis.SequenceIdMatcher;
29 import jalview.api.AlignExportSettingI;
30 import jalview.api.AlignViewControllerGuiI;
31 import jalview.api.AlignViewControllerI;
32 import jalview.api.AlignViewportI;
33 import jalview.api.AlignmentViewPanel;
34 import jalview.api.FeatureSettingsControllerI;
35 import jalview.api.FeatureSettingsModelI;
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.DBRefSource;
58 import jalview.datamodel.HiddenSequences;
59 import jalview.datamodel.PDBEntry;
60 import jalview.datamodel.SeqCigar;
61 import jalview.datamodel.Sequence;
62 import jalview.datamodel.SequenceGroup;
63 import jalview.datamodel.SequenceI;
64 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
65 import jalview.io.AlignmentProperties;
66 import jalview.io.AnnotationFile;
67 import jalview.io.BioJsHTMLOutput;
68 import jalview.io.FileLoader;
69 import jalview.io.FormatAdapter;
70 import jalview.io.HtmlSvgOutput;
71 import jalview.io.IdentifyFile;
72 import jalview.io.JalviewFileChooser;
73 import jalview.io.JalviewFileView;
74 import jalview.io.JnetAnnotationMaker;
75 import jalview.io.NewickFile;
76 import jalview.io.TCoffeeScoreFile;
77 import jalview.jbgui.GAlignFrame;
78 import jalview.schemes.Blosum62ColourScheme;
79 import jalview.schemes.BuriedColourScheme;
80 import jalview.schemes.ClustalxColourScheme;
81 import jalview.schemes.ColourSchemeI;
82 import jalview.schemes.ColourSchemeProperty;
83 import jalview.schemes.HelixColourScheme;
84 import jalview.schemes.HydrophobicColourScheme;
85 import jalview.schemes.NucleotideColourScheme;
86 import jalview.schemes.PIDColourScheme;
87 import jalview.schemes.PurinePyrimidineColourScheme;
88 import jalview.schemes.RNAHelicesColourChooser;
89 import jalview.schemes.ResidueProperties;
90 import jalview.schemes.StrandColourScheme;
91 import jalview.schemes.TCoffeeColourScheme;
92 import jalview.schemes.TaylorColourScheme;
93 import jalview.schemes.TurnColourScheme;
94 import jalview.schemes.UserColourScheme;
95 import jalview.schemes.ZappoColourScheme;
96 import jalview.structure.StructureSelectionManager;
97 import jalview.util.MessageManager;
98 import jalview.viewmodel.AlignmentViewport;
99 import jalview.ws.SequenceFetcher;
100 import jalview.ws.jws1.Discoverer;
101 import jalview.ws.jws2.Jws2Discoverer;
102 import jalview.ws.jws2.jabaws2.Jws2Instance;
103 import jalview.ws.seqfetcher.ASequenceFetcher;
104 import jalview.ws.seqfetcher.DbSourceProxy;
106 import java.awt.BorderLayout;
107 import java.awt.Component;
108 import java.awt.Rectangle;
109 import java.awt.Toolkit;
110 import java.awt.datatransfer.Clipboard;
111 import java.awt.datatransfer.DataFlavor;
112 import java.awt.datatransfer.StringSelection;
113 import java.awt.datatransfer.Transferable;
114 import java.awt.dnd.DnDConstants;
115 import java.awt.dnd.DropTargetDragEvent;
116 import java.awt.dnd.DropTargetDropEvent;
117 import java.awt.dnd.DropTargetEvent;
118 import java.awt.dnd.DropTargetListener;
119 import java.awt.event.ActionEvent;
120 import java.awt.event.ActionListener;
121 import java.awt.event.ItemEvent;
122 import java.awt.event.ItemListener;
123 import java.awt.event.KeyAdapter;
124 import java.awt.event.KeyEvent;
125 import java.awt.event.MouseAdapter;
126 import java.awt.event.MouseEvent;
127 import java.awt.print.PageFormat;
128 import java.awt.print.PrinterJob;
129 import java.beans.PropertyChangeEvent;
132 import java.util.ArrayList;
133 import java.util.Arrays;
134 import java.util.Deque;
135 import java.util.Enumeration;
136 import java.util.Hashtable;
137 import java.util.List;
138 import java.util.Vector;
140 import javax.swing.JCheckBoxMenuItem;
141 import javax.swing.JEditorPane;
142 import javax.swing.JInternalFrame;
143 import javax.swing.JLayeredPane;
144 import javax.swing.JMenu;
145 import javax.swing.JMenuItem;
146 import javax.swing.JOptionPane;
147 import javax.swing.JRadioButtonMenuItem;
148 import javax.swing.JScrollPane;
149 import javax.swing.SwingUtilities;
155 * @version $Revision$
157 public class AlignFrame extends GAlignFrame implements DropTargetListener,
158 IProgressIndicator, AlignViewControllerGuiI
161 public static final int DEFAULT_WIDTH = 700;
163 public static final int DEFAULT_HEIGHT = 500;
166 * The currently displayed panel (selected tabbed view if more than one)
168 public AlignmentPanel alignPanel;
170 AlignViewport viewport;
172 public AlignViewControllerI avc;
174 List<AlignmentPanel> alignPanels = new ArrayList<AlignmentPanel>();
177 * Last format used to load or save alignments in this window
179 String currentFileFormat = null;
182 * Current filename for this alignment
184 String fileName = null;
187 * Creates a new AlignFrame object with specific width and height.
193 public AlignFrame(AlignmentI al, int width, int height)
195 this(al, null, width, height);
199 * Creates a new AlignFrame object with specific width, height and
205 * @param sequenceSetId
207 public AlignFrame(AlignmentI al, int width, int height,
208 String sequenceSetId)
210 this(al, null, width, height, sequenceSetId);
214 * Creates a new AlignFrame object with specific width, height and
220 * @param sequenceSetId
223 public AlignFrame(AlignmentI al, int width, int height,
224 String sequenceSetId, String viewId)
226 this(al, null, width, height, sequenceSetId, viewId);
230 * new alignment window with hidden columns
234 * @param hiddenColumns
235 * ColumnSelection or null
237 * Width of alignment frame
241 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
242 int width, int height)
244 this(al, hiddenColumns, width, height, null);
248 * Create alignment frame for al with hiddenColumns, a specific width and
249 * height, and specific sequenceId
252 * @param hiddenColumns
255 * @param sequenceSetId
258 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
259 int width, int height, String sequenceSetId)
261 this(al, hiddenColumns, width, height, sequenceSetId, null);
265 * Create alignment frame for al with hiddenColumns, a specific width and
266 * height, and specific sequenceId
269 * @param hiddenColumns
272 * @param sequenceSetId
277 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
278 int width, int height, String sequenceSetId, String viewId)
280 setSize(width, height);
282 if (al.getDataset() == null)
287 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
289 alignPanel = new AlignmentPanel(this, viewport);
291 addAlignmentPanel(alignPanel, true);
295 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
296 ColumnSelection hiddenColumns, int width, int height)
298 setSize(width, height);
300 if (al.getDataset() == null)
305 viewport = new AlignViewport(al, hiddenColumns);
307 if (hiddenSeqs != null && hiddenSeqs.length > 0)
309 viewport.hideSequence(hiddenSeqs);
311 alignPanel = new AlignmentPanel(this, viewport);
312 addAlignmentPanel(alignPanel, true);
317 * Make a new AlignFrame from existing alignmentPanels
324 public AlignFrame(AlignmentPanel ap)
328 addAlignmentPanel(ap, false);
333 * initalise the alignframe from the underlying viewport data and the
338 if (!Jalview.isHeadlessMode())
340 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
343 avc = new jalview.controller.AlignViewController(this, viewport,
345 if (viewport.getAlignmentConservationAnnotation() == null)
347 BLOSUM62Colour.setEnabled(false);
348 conservationMenuItem.setEnabled(false);
349 modifyConservation.setEnabled(false);
350 // PIDColour.setEnabled(false);
351 // abovePIDThreshold.setEnabled(false);
352 // modifyPID.setEnabled(false);
355 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
358 if (sortby.equals("Id"))
360 sortIDMenuItem_actionPerformed(null);
362 else if (sortby.equals("Pairwise Identity"))
364 sortPairwiseMenuItem_actionPerformed(null);
367 if (Desktop.desktop != null)
369 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
370 addServiceListeners();
371 setGUINucleotide(viewport.getAlignment().isNucleotide());
375 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
377 setMenusFromViewport(viewport);
378 buildSortByAnnotationScoresMenu();
381 if (viewport.getWrapAlignment())
383 wrapMenuItem_actionPerformed(null);
386 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
388 this.overviewMenuItem_actionPerformed(null);
393 final List<AlignmentPanel> selviews = new ArrayList<AlignmentPanel>();
394 final List<AlignmentPanel> origview = new ArrayList<AlignmentPanel>();
395 final String menuLabel = MessageManager
396 .getString("label.copy_format_from");
397 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
398 new ViewSetProvider()
402 public AlignmentPanel[] getAllAlignmentPanels()
405 origview.add(alignPanel);
406 // make an array of all alignment panels except for this one
407 List<AlignmentPanel> aps = new ArrayList<AlignmentPanel>(
408 Arrays.asList(Desktop.getAlignmentPanels(null)));
409 aps.remove(AlignFrame.this.alignPanel);
410 return aps.toArray(new AlignmentPanel[aps.size()]);
412 }, selviews, new ItemListener()
416 public void itemStateChanged(ItemEvent e)
418 if (origview.size() > 0)
420 final AlignmentPanel ap = origview.get(0);
423 * Copy the ViewStyle of the selected panel to 'this one'.
424 * Don't change value of 'scaleProteinAsCdna' unless copying
427 ViewStyleI vs = selviews.get(0).getAlignViewport()
429 boolean fromSplitFrame = selviews.get(0)
430 .getAlignViewport().getCodingComplement() != null;
433 vs.setScaleProteinAsCdna(ap.getAlignViewport()
434 .getViewStyle().isScaleProteinAsCdna());
436 ap.getAlignViewport().setViewStyle(vs);
439 * Also rescale ViewStyle of SplitFrame complement if there is
440 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
441 * the whole ViewStyle (allow cDNA protein to have different
444 AlignViewportI complement = ap.getAlignViewport()
445 .getCodingComplement();
446 if (complement != null && vs.isScaleProteinAsCdna())
448 AlignFrame af = Desktop.getAlignFrameFor(complement);
449 ((SplitFrame) af.getSplitViewContainer())
451 af.setMenusForViewport();
455 ap.setSelected(true);
456 ap.alignFrame.setMenusForViewport();
461 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
462 .indexOf("devel") > -1
463 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
464 .indexOf("test") > -1)
466 formatMenu.add(vsel);
472 * Change the filename and format for the alignment, and enable the 'reload'
473 * button functionality.
480 public void setFileName(String file, String format)
483 setFileFormat(format);
484 reload.setEnabled(true);
488 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
491 void addKeyListener()
493 addKeyListener(new KeyAdapter()
496 public void keyPressed(KeyEvent evt)
498 if (viewport.cursorMode
499 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
500 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
501 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
502 && Character.isDigit(evt.getKeyChar()))
504 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
507 switch (evt.getKeyCode())
510 case 27: // escape key
511 deselectAllSequenceMenuItem_actionPerformed(null);
515 case KeyEvent.VK_DOWN:
516 if (evt.isAltDown() || !viewport.cursorMode)
518 moveSelectedSequences(false);
520 if (viewport.cursorMode)
522 alignPanel.getSeqPanel().moveCursor(0, 1);
527 if (evt.isAltDown() || !viewport.cursorMode)
529 moveSelectedSequences(true);
531 if (viewport.cursorMode)
533 alignPanel.getSeqPanel().moveCursor(0, -1);
538 case KeyEvent.VK_LEFT:
539 if (evt.isAltDown() || !viewport.cursorMode)
541 slideSequences(false, alignPanel.getSeqPanel().getKeyboardNo1());
545 alignPanel.getSeqPanel().moveCursor(-1, 0);
550 case KeyEvent.VK_RIGHT:
551 if (evt.isAltDown() || !viewport.cursorMode)
553 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
557 alignPanel.getSeqPanel().moveCursor(1, 0);
561 case KeyEvent.VK_SPACE:
562 if (viewport.cursorMode)
564 alignPanel.getSeqPanel().insertGapAtCursor(
565 evt.isControlDown() || evt.isShiftDown()
570 // case KeyEvent.VK_A:
571 // if (viewport.cursorMode)
573 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
574 // //System.out.println("A");
578 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
579 * System.out.println("closing bracket"); } break;
581 case KeyEvent.VK_DELETE:
582 case KeyEvent.VK_BACK_SPACE:
583 if (!viewport.cursorMode)
585 cut_actionPerformed(null);
589 alignPanel.getSeqPanel().deleteGapAtCursor(
590 evt.isControlDown() || evt.isShiftDown()
597 if (viewport.cursorMode)
599 alignPanel.getSeqPanel().setCursorRow();
603 if (viewport.cursorMode && !evt.isControlDown())
605 alignPanel.getSeqPanel().setCursorColumn();
609 if (viewport.cursorMode)
611 alignPanel.getSeqPanel().setCursorPosition();
615 case KeyEvent.VK_ENTER:
616 case KeyEvent.VK_COMMA:
617 if (viewport.cursorMode)
619 alignPanel.getSeqPanel().setCursorRowAndColumn();
624 if (viewport.cursorMode)
626 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
630 if (viewport.cursorMode)
632 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
637 viewport.cursorMode = !viewport.cursorMode;
638 statusBar.setText(MessageManager.formatMessage(
639 "label.keyboard_editing_mode",
640 new String[] { (viewport.cursorMode ? "on" : "off") }));
641 if (viewport.cursorMode)
643 alignPanel.getSeqPanel().seqCanvas.cursorX = viewport.startRes;
644 alignPanel.getSeqPanel().seqCanvas.cursorY = viewport.startSeq;
646 alignPanel.getSeqPanel().seqCanvas.repaint();
652 Help.showHelpWindow();
653 } catch (Exception ex)
655 ex.printStackTrace();
660 boolean toggleSeqs = !evt.isControlDown();
661 boolean toggleCols = !evt.isShiftDown();
662 toggleHiddenRegions(toggleSeqs, toggleCols);
665 case KeyEvent.VK_PAGE_UP:
666 if (viewport.getWrapAlignment())
668 alignPanel.scrollUp(true);
672 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
673 - viewport.endSeq + viewport.startSeq);
676 case KeyEvent.VK_PAGE_DOWN:
677 if (viewport.getWrapAlignment())
679 alignPanel.scrollUp(false);
683 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
684 + viewport.endSeq - viewport.startSeq);
691 public void keyReleased(KeyEvent evt)
693 switch (evt.getKeyCode())
695 case KeyEvent.VK_LEFT:
696 if (evt.isAltDown() || !viewport.cursorMode)
698 viewport.firePropertyChange("alignment", null, viewport
699 .getAlignment().getSequences());
703 case KeyEvent.VK_RIGHT:
704 if (evt.isAltDown() || !viewport.cursorMode)
706 viewport.firePropertyChange("alignment", null, viewport
707 .getAlignment().getSequences());
715 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
717 ap.alignFrame = this;
718 avc = new jalview.controller.AlignViewController(this, viewport,
723 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
725 int aSize = alignPanels.size();
727 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
729 if (aSize == 1 && ap.av.viewName == null)
731 this.getContentPane().add(ap, BorderLayout.CENTER);
737 setInitialTabVisible();
740 expandViews.setEnabled(true);
741 gatherViews.setEnabled(true);
742 tabbedPane.addTab(ap.av.viewName, ap);
744 ap.setVisible(false);
749 if (ap.av.isPadGaps())
751 ap.av.getAlignment().padGaps();
753 ap.av.updateConservation(ap);
754 ap.av.updateConsensus(ap);
755 ap.av.updateStrucConsensus(ap);
759 public void setInitialTabVisible()
761 expandViews.setEnabled(true);
762 gatherViews.setEnabled(true);
763 tabbedPane.setVisible(true);
764 AlignmentPanel first = alignPanels.get(0);
765 tabbedPane.addTab(first.av.viewName, first);
766 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
769 public AlignViewport getViewport()
774 /* Set up intrinsic listeners for dynamically generated GUI bits. */
775 private void addServiceListeners()
777 final java.beans.PropertyChangeListener thisListener;
778 Desktop.instance.addJalviewPropertyChangeListener("services",
779 thisListener = new java.beans.PropertyChangeListener()
782 public void propertyChange(PropertyChangeEvent evt)
784 // // System.out.println("Discoverer property change.");
785 // if (evt.getPropertyName().equals("services"))
787 SwingUtilities.invokeLater(new Runnable()
794 .println("Rebuild WS Menu for service change");
795 BuildWebServiceMenu();
802 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
805 public void internalFrameClosed(
806 javax.swing.event.InternalFrameEvent evt)
808 // System.out.println("deregistering discoverer listener");
809 Desktop.instance.removeJalviewPropertyChangeListener("services",
811 closeMenuItem_actionPerformed(true);
814 // Finally, build the menu once to get current service state
815 new Thread(new Runnable()
820 BuildWebServiceMenu();
826 * Configure menu items that vary according to whether the alignment is
827 * nucleotide or protein
831 public void setGUINucleotide(boolean nucleotide)
833 showTranslation.setVisible(nucleotide);
834 showReverse.setVisible(nucleotide);
835 showReverseComplement.setVisible(nucleotide);
836 conservationMenuItem.setEnabled(!nucleotide);
837 modifyConservation.setEnabled(!nucleotide);
838 showGroupConservation.setEnabled(!nucleotide);
839 rnahelicesColour.setEnabled(nucleotide);
840 purinePyrimidineColour.setEnabled(nucleotide);
841 showComplementMenuItem.setText(MessageManager
842 .getString(nucleotide ? "label.protein" : "label.nucleotide"));
843 setColourSelected(jalview.bin.Cache.getDefault(
844 nucleotide ? Preferences.DEFAULT_COLOUR_NUC
845 : Preferences.DEFAULT_COLOUR_PROT, "None"));
849 * set up menus for the current viewport. This may be called after any
850 * operation that affects the data in the current view (selection changed,
851 * etc) to update the menus to reflect the new state.
854 public void setMenusForViewport()
856 setMenusFromViewport(viewport);
860 * Need to call this method when tabs are selected for multiple views, or when
861 * loading from Jalview2XML.java
866 void setMenusFromViewport(AlignViewport av)
868 padGapsMenuitem.setSelected(av.isPadGaps());
869 colourTextMenuItem.setSelected(av.isShowColourText());
870 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
871 conservationMenuItem.setSelected(av.getConservationSelected());
872 seqLimits.setSelected(av.getShowJVSuffix());
873 idRightAlign.setSelected(av.isRightAlignIds());
874 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
875 renderGapsMenuItem.setSelected(av.isRenderGaps());
876 wrapMenuItem.setSelected(av.getWrapAlignment());
877 scaleAbove.setVisible(av.getWrapAlignment());
878 scaleLeft.setVisible(av.getWrapAlignment());
879 scaleRight.setVisible(av.getWrapAlignment());
880 annotationPanelMenuItem.setState(av.isShowAnnotation());
882 * Show/hide annotations only enabled if annotation panel is shown
884 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
885 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
886 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
887 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
888 viewBoxesMenuItem.setSelected(av.getShowBoxes());
889 viewTextMenuItem.setSelected(av.getShowText());
890 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
891 showGroupConsensus.setSelected(av.isShowGroupConsensus());
892 showGroupConservation.setSelected(av.isShowGroupConservation());
893 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
894 showSequenceLogo.setSelected(av.isShowSequenceLogo());
895 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
897 setColourSelected(ColourSchemeProperty.getColourName(av
898 .getGlobalColourScheme()));
900 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
901 hiddenMarkers.setState(av.getShowHiddenMarkers());
902 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
903 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
904 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
905 autoCalculate.setSelected(av.autoCalculateConsensus);
906 sortByTree.setSelected(av.sortByTree);
907 listenToViewSelections.setSelected(av.followSelection);
908 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
910 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
912 showProducts.setEnabled(canShowProducts());
917 private IProgressIndicator progressBar;
922 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
925 public void setProgressBar(String message, long id)
927 progressBar.setProgressBar(message, id);
931 public void registerHandler(final long id,
932 final IProgressIndicatorHandler handler)
934 progressBar.registerHandler(id, handler);
939 * @return true if any progress bars are still active
942 public boolean operationInProgress()
944 return progressBar.operationInProgress();
948 public void setStatus(String text)
950 statusBar.setText(text);
954 * Added so Castor Mapping file can obtain Jalview Version
956 public String getVersion()
958 return jalview.bin.Cache.getProperty("VERSION");
961 public FeatureRenderer getFeatureRenderer()
963 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
967 public void fetchSequence_actionPerformed(ActionEvent e)
969 new jalview.gui.SequenceFetcher(this);
973 public void addFromFile_actionPerformed(ActionEvent e)
975 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
979 public void reload_actionPerformed(ActionEvent e)
981 if (fileName != null)
983 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
984 // originating file's format
985 // TODO: work out how to recover feature settings for correct view(s) when
987 if (currentFileFormat.equals("Jalview"))
989 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
990 for (int i = 0; i < frames.length; i++)
992 if (frames[i] instanceof AlignFrame && frames[i] != this
993 && ((AlignFrame) frames[i]).fileName != null
994 && ((AlignFrame) frames[i]).fileName.equals(fileName))
998 frames[i].setSelected(true);
999 Desktop.instance.closeAssociatedWindows();
1000 } catch (java.beans.PropertyVetoException ex)
1006 Desktop.instance.closeAssociatedWindows();
1008 FileLoader loader = new FileLoader();
1009 String protocol = fileName.startsWith("http:") ? "URL" : "File";
1010 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1014 Rectangle bounds = this.getBounds();
1016 FileLoader loader = new FileLoader();
1017 String protocol = fileName.startsWith("http:") ? "URL" : "File";
1018 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1019 protocol, currentFileFormat);
1021 newframe.setBounds(bounds);
1022 if (featureSettings != null && featureSettings.isShowing())
1024 final Rectangle fspos = featureSettings.frame.getBounds();
1025 // TODO: need a 'show feature settings' function that takes bounds -
1026 // need to refactor Desktop.addFrame
1027 newframe.featureSettings_actionPerformed(null);
1028 final FeatureSettings nfs = newframe.featureSettings;
1029 SwingUtilities.invokeLater(new Runnable()
1034 nfs.frame.setBounds(fspos);
1037 this.featureSettings.close();
1038 this.featureSettings = null;
1040 this.closeMenuItem_actionPerformed(true);
1046 public void addFromText_actionPerformed(ActionEvent e)
1048 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport
1053 public void addFromURL_actionPerformed(ActionEvent e)
1055 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1059 public void save_actionPerformed(ActionEvent e)
1061 if (fileName == null
1062 || (currentFileFormat == null || !jalview.io.FormatAdapter
1063 .isValidIOFormat(currentFileFormat, true))
1064 || fileName.startsWith("http"))
1066 saveAs_actionPerformed(null);
1070 saveAlignment(fileName, currentFileFormat);
1081 public void saveAs_actionPerformed(ActionEvent e)
1083 JalviewFileChooser chooser = new JalviewFileChooser(
1084 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
1085 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
1086 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
1087 currentFileFormat, false);
1089 chooser.setFileView(new JalviewFileView());
1090 chooser.setDialogTitle(MessageManager
1091 .getString("label.save_alignment_to_file"));
1092 chooser.setToolTipText(MessageManager.getString("action.save"));
1094 int value = chooser.showSaveDialog(this);
1096 if (value == JalviewFileChooser.APPROVE_OPTION)
1098 currentFileFormat = chooser.getSelectedFormat();
1099 while (currentFileFormat == null)
1102 .showInternalMessageDialog(
1105 .getString("label.select_file_format_before_saving"),
1107 .getString("label.file_format_not_specified"),
1108 JOptionPane.WARNING_MESSAGE);
1109 currentFileFormat = chooser.getSelectedFormat();
1110 value = chooser.showSaveDialog(this);
1111 if (value != JalviewFileChooser.APPROVE_OPTION)
1117 fileName = chooser.getSelectedFile().getPath();
1119 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
1122 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
1123 if (currentFileFormat.indexOf(" ") > -1)
1125 currentFileFormat = currentFileFormat.substring(0,
1126 currentFileFormat.indexOf(" "));
1128 saveAlignment(fileName, currentFileFormat);
1132 public boolean saveAlignment(String file, String format)
1134 boolean success = true;
1136 if (format.equalsIgnoreCase("Jalview"))
1138 String shortName = title;
1140 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1142 shortName = shortName.substring(shortName
1143 .lastIndexOf(java.io.File.separatorChar) + 1);
1146 success = new Jalview2XML().saveAlignment(this, file, shortName);
1148 statusBar.setText(MessageManager.formatMessage(
1149 "label.successfully_saved_to_file_in_format", new Object[] {
1150 fileName, format }));
1155 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1157 warningMessage("Cannot save file " + fileName + " using format "
1158 + format, "Alignment output format not supported");
1159 if (!Jalview.isHeadlessMode())
1161 saveAs_actionPerformed(null);
1166 AlignmentExportData exportData = getAlignmentForExport(format,
1168 if (exportData.getSettings().isCancelled())
1172 FormatAdapter f = new FormatAdapter(alignPanel,
1173 exportData.getSettings());
1174 String output = f.formatSequences(
1176 exportData.getAlignment(), // class cast exceptions will
1177 // occur in the distant future
1178 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1179 f.getCacheSuffixDefault(format),
1180 viewport.getColumnSelection());
1190 java.io.PrintWriter out = new java.io.PrintWriter(
1191 new java.io.FileWriter(file));
1195 this.setTitle(file);
1196 statusBar.setText(MessageManager.formatMessage(
1197 "label.successfully_saved_to_file_in_format",
1198 new Object[] { fileName, format }));
1199 } catch (Exception ex)
1202 ex.printStackTrace();
1209 JOptionPane.showInternalMessageDialog(this, MessageManager
1210 .formatMessage("label.couldnt_save_file",
1211 new Object[] { fileName }), MessageManager
1212 .getString("label.error_saving_file"),
1213 JOptionPane.WARNING_MESSAGE);
1219 private void warningMessage(String warning, String title)
1221 if (new jalview.util.Platform().isHeadless())
1223 System.err.println("Warning: " + title + "\nWarning: " + warning);
1228 JOptionPane.showInternalMessageDialog(this, warning, title,
1229 JOptionPane.WARNING_MESSAGE);
1241 protected void outputText_actionPerformed(ActionEvent e)
1244 AlignmentExportData exportData = getAlignmentForExport(
1245 e.getActionCommand(), viewport, null);
1246 if (exportData.getSettings().isCancelled())
1250 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1251 cap.setForInput(null);
1254 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1255 .formatSequences(e.getActionCommand(),
1256 exportData.getAlignment(),
1257 exportData.getOmitHidden(),
1258 exportData.getStartEndPostions(),
1259 viewport.getColumnSelection()));
1260 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1261 "label.alignment_output_command",
1262 new Object[] { e.getActionCommand() }), 600, 500);
1263 } catch (OutOfMemoryError oom)
1265 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1271 public static AlignmentExportData getAlignmentForExport(
1272 String exportFormat, AlignViewportI viewport,
1273 AlignExportSettingI exportSettings)
1275 AlignmentI alignmentToExport = null;
1276 AlignExportSettingI settings = exportSettings;
1277 String[] omitHidden = null;
1278 int[] alignmentStartEnd = new int[2];
1280 HiddenSequences hiddenSeqs = viewport.getAlignment()
1281 .getHiddenSequences();
1283 alignmentToExport = viewport.getAlignment();
1284 alignmentStartEnd = new int[] { 0, alignmentToExport.getWidth() - 1 };
1286 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1287 if (settings == null)
1289 settings = new AlignExportSettings(hasHiddenSeqs,
1290 viewport.hasHiddenColumns(), exportFormat);
1292 // settings.isExportAnnotations();
1294 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1296 omitHidden = viewport.getViewAsString(false);
1299 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1301 alignmentToExport = hiddenSeqs.getFullAlignment();
1305 alignmentToExport = viewport.getAlignment();
1306 alignmentStartEnd = getStartEnd(alignmentStartEnd, viewport
1307 .getColumnSelection().getHiddenColumns());
1309 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1310 omitHidden, alignmentStartEnd, settings);
1314 public static int[] getStartEnd(int[] aligmentStartEnd,
1315 List<int[]> hiddenCols)
1317 int startPos = aligmentStartEnd[0];
1318 int endPos = aligmentStartEnd[1];
1320 int[] lowestRange = new int[] { -1, -1 };
1321 int[] higestRange = new int[] { -1, -1 };
1323 for (int[] hiddenCol : hiddenCols)
1325 lowestRange = (hiddenCol[0] <= startPos) ? hiddenCol : lowestRange;
1326 higestRange = (hiddenCol[1] >= endPos) ? hiddenCol : higestRange;
1329 if (lowestRange[0] == -1 && lowestRange[1] == -1)
1331 startPos = aligmentStartEnd[0];
1335 startPos = lowestRange[1] + 1;
1338 if (higestRange[0] == -1 && higestRange[1] == -1)
1340 endPos = aligmentStartEnd[1];
1344 endPos = higestRange[0] - 1;
1347 // System.out.println("Export range : " + startPos + " - " + endPos);
1348 return new int[] { startPos, endPos };
1351 public static void main(String[] args)
1353 ArrayList<int[]> hiddenCols = new ArrayList<int[]>();
1354 hiddenCols.add(new int[] { 0, 0 });
1355 hiddenCols.add(new int[] { 6, 9 });
1356 hiddenCols.add(new int[] { 11, 12 });
1357 hiddenCols.add(new int[] { 33, 33 });
1358 hiddenCols.add(new int[] { 50, 50 });
1360 int[] x = getStartEnd(new int[] { 0, 50 }, hiddenCols);
1361 // System.out.println("Export range : " + x[0] + " - " + x[1]);
1371 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1373 new HtmlSvgOutput(null, alignPanel);
1377 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1379 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel, this);
1380 bjs.exportJalviewAlignmentAsBioJsHtmlFile();
1383 public void createImageMap(File file, String image)
1385 alignPanel.makePNGImageMap(file, image);
1395 public void createPNG(File f)
1397 alignPanel.makePNG(f);
1407 public void createEPS(File f)
1409 alignPanel.makeEPS(f);
1413 public void createSVG(File f)
1415 alignPanel.makeSVG(f);
1419 public void pageSetup_actionPerformed(ActionEvent e)
1421 PrinterJob printJob = PrinterJob.getPrinterJob();
1422 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1432 public void printMenuItem_actionPerformed(ActionEvent e)
1434 // Putting in a thread avoids Swing painting problems
1435 PrintThread thread = new PrintThread(alignPanel);
1440 public void exportFeatures_actionPerformed(ActionEvent e)
1442 new AnnotationExporter().exportFeatures(alignPanel);
1446 public void exportAnnotations_actionPerformed(ActionEvent e)
1448 new AnnotationExporter().exportAnnotations(alignPanel);
1452 public void associatedData_actionPerformed(ActionEvent e)
1454 // Pick the tree file
1455 JalviewFileChooser chooser = new JalviewFileChooser(
1456 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1457 chooser.setFileView(new JalviewFileView());
1458 chooser.setDialogTitle(MessageManager
1459 .getString("label.load_jalview_annotations"));
1460 chooser.setToolTipText(MessageManager
1461 .getString("label.load_jalview_annotations"));
1463 int value = chooser.showOpenDialog(null);
1465 if (value == JalviewFileChooser.APPROVE_OPTION)
1467 String choice = chooser.getSelectedFile().getPath();
1468 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1469 loadJalviewDataFile(choice, null, null, null);
1475 * Close the current view or all views in the alignment frame. If the frame
1476 * only contains one view then the alignment will be removed from memory.
1478 * @param closeAllTabs
1481 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1483 if (alignPanels != null && alignPanels.size() < 2)
1485 closeAllTabs = true;
1490 if (alignPanels != null)
1494 if (this.isClosed())
1496 // really close all the windows - otherwise wait till
1497 // setClosed(true) is called
1498 for (int i = 0; i < alignPanels.size(); i++)
1500 AlignmentPanel ap = alignPanels.get(i);
1507 closeView(alignPanel);
1514 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1515 * be called recursively, with the frame now in 'closed' state
1517 this.setClosed(true);
1519 } catch (Exception ex)
1521 ex.printStackTrace();
1526 * Close the specified panel and close up tabs appropriately.
1528 * @param panelToClose
1530 public void closeView(AlignmentPanel panelToClose)
1532 int index = tabbedPane.getSelectedIndex();
1533 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1534 alignPanels.remove(panelToClose);
1535 panelToClose.closePanel();
1536 panelToClose = null;
1538 tabbedPane.removeTabAt(closedindex);
1539 tabbedPane.validate();
1541 if (index > closedindex || index == tabbedPane.getTabCount())
1543 // modify currently selected tab index if necessary.
1547 this.tabSelectionChanged(index);
1553 void updateEditMenuBar()
1556 if (viewport.getHistoryList().size() > 0)
1558 undoMenuItem.setEnabled(true);
1559 CommandI command = viewport.getHistoryList().peek();
1560 undoMenuItem.setText(MessageManager.formatMessage(
1561 "label.undo_command",
1562 new Object[] { command.getDescription() }));
1566 undoMenuItem.setEnabled(false);
1567 undoMenuItem.setText(MessageManager.getString("action.undo"));
1570 if (viewport.getRedoList().size() > 0)
1572 redoMenuItem.setEnabled(true);
1574 CommandI command = viewport.getRedoList().peek();
1575 redoMenuItem.setText(MessageManager.formatMessage(
1576 "label.redo_command",
1577 new Object[] { command.getDescription() }));
1581 redoMenuItem.setEnabled(false);
1582 redoMenuItem.setText(MessageManager.getString("action.redo"));
1587 public void addHistoryItem(CommandI command)
1589 if (command.getSize() > 0)
1591 viewport.addToHistoryList(command);
1592 viewport.clearRedoList();
1593 updateEditMenuBar();
1594 viewport.updateHiddenColumns();
1595 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1596 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1597 // viewport.getColumnSelection()
1598 // .getHiddenColumns().size() > 0);
1604 * @return alignment objects for all views
1606 AlignmentI[] getViewAlignments()
1608 if (alignPanels != null)
1610 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1612 for (AlignmentPanel ap : alignPanels)
1614 als[i++] = ap.av.getAlignment();
1618 if (viewport != null)
1620 return new AlignmentI[] { viewport.getAlignment() };
1632 protected void undoMenuItem_actionPerformed(ActionEvent e)
1634 if (viewport.getHistoryList().isEmpty())
1638 CommandI command = viewport.getHistoryList().pop();
1639 viewport.addToRedoList(command);
1640 command.undoCommand(getViewAlignments());
1642 AlignmentViewport originalSource = getOriginatingSource(command);
1643 updateEditMenuBar();
1645 if (originalSource != null)
1647 if (originalSource != viewport)
1650 .warn("Implementation worry: mismatch of viewport origin for undo");
1652 originalSource.updateHiddenColumns();
1653 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1655 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1656 // viewport.getColumnSelection()
1657 // .getHiddenColumns().size() > 0);
1658 originalSource.firePropertyChange("alignment", null, originalSource
1659 .getAlignment().getSequences());
1670 protected void redoMenuItem_actionPerformed(ActionEvent e)
1672 if (viewport.getRedoList().size() < 1)
1677 CommandI command = viewport.getRedoList().pop();
1678 viewport.addToHistoryList(command);
1679 command.doCommand(getViewAlignments());
1681 AlignmentViewport originalSource = getOriginatingSource(command);
1682 updateEditMenuBar();
1684 if (originalSource != null)
1687 if (originalSource != viewport)
1690 .warn("Implementation worry: mismatch of viewport origin for redo");
1692 originalSource.updateHiddenColumns();
1693 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1695 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1696 // viewport.getColumnSelection()
1697 // .getHiddenColumns().size() > 0);
1698 originalSource.firePropertyChange("alignment", null, originalSource
1699 .getAlignment().getSequences());
1703 AlignmentViewport getOriginatingSource(CommandI command)
1705 AlignmentViewport originalSource = null;
1706 // For sequence removal and addition, we need to fire
1707 // the property change event FROM the viewport where the
1708 // original alignment was altered
1709 AlignmentI al = null;
1710 if (command instanceof EditCommand)
1712 EditCommand editCommand = (EditCommand) command;
1713 al = editCommand.getAlignment();
1714 List<Component> comps = PaintRefresher.components.get(viewport
1715 .getSequenceSetId());
1717 for (Component comp : comps)
1719 if (comp instanceof AlignmentPanel)
1721 if (al == ((AlignmentPanel) comp).av.getAlignment())
1723 originalSource = ((AlignmentPanel) comp).av;
1730 if (originalSource == null)
1732 // The original view is closed, we must validate
1733 // the current view against the closed view first
1736 PaintRefresher.validateSequences(al, viewport.getAlignment());
1739 originalSource = viewport;
1742 return originalSource;
1751 public void moveSelectedSequences(boolean up)
1753 SequenceGroup sg = viewport.getSelectionGroup();
1759 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1760 viewport.getHiddenRepSequences(), up);
1761 alignPanel.paintAlignment(true);
1764 synchronized void slideSequences(boolean right, int size)
1766 List<SequenceI> sg = new ArrayList<SequenceI>();
1767 if (viewport.cursorMode)
1769 sg.add(viewport.getAlignment().getSequenceAt(
1770 alignPanel.getSeqPanel().seqCanvas.cursorY));
1772 else if (viewport.getSelectionGroup() != null
1773 && viewport.getSelectionGroup().getSize() != viewport
1774 .getAlignment().getHeight())
1776 sg = viewport.getSelectionGroup().getSequences(
1777 viewport.getHiddenRepSequences());
1785 List<SequenceI> invertGroup = new ArrayList<SequenceI>();
1787 for (SequenceI seq : viewport.getAlignment().getSequences())
1789 if (!sg.contains(seq))
1791 invertGroup.add(seq);
1795 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1797 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1798 for (int i = 0; i < invertGroup.size(); i++)
1800 seqs2[i] = invertGroup.get(i);
1803 SlideSequencesCommand ssc;
1806 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1807 size, viewport.getGapCharacter());
1811 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1812 size, viewport.getGapCharacter());
1815 int groupAdjustment = 0;
1816 if (ssc.getGapsInsertedBegin() && right)
1818 if (viewport.cursorMode)
1820 alignPanel.getSeqPanel().moveCursor(size, 0);
1824 groupAdjustment = size;
1827 else if (!ssc.getGapsInsertedBegin() && !right)
1829 if (viewport.cursorMode)
1831 alignPanel.getSeqPanel().moveCursor(-size, 0);
1835 groupAdjustment = -size;
1839 if (groupAdjustment != 0)
1841 viewport.getSelectionGroup().setStartRes(
1842 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1843 viewport.getSelectionGroup().setEndRes(
1844 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1848 * just extend the last slide command if compatible; but not if in
1849 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1851 boolean appendHistoryItem = false;
1852 Deque<CommandI> historyList = viewport.getHistoryList();
1853 boolean inSplitFrame = getSplitViewContainer() != null;
1854 if (!inSplitFrame && historyList != null && historyList.size() > 0
1855 && historyList.peek() instanceof SlideSequencesCommand)
1857 appendHistoryItem = ssc
1858 .appendSlideCommand((SlideSequencesCommand) historyList
1862 if (!appendHistoryItem)
1864 addHistoryItem(ssc);
1877 protected void copy_actionPerformed(ActionEvent e)
1880 if (viewport.getSelectionGroup() == null)
1884 // TODO: preserve the ordering of displayed alignment annotation in any
1885 // internal paste (particularly sequence associated annotation)
1886 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1887 String[] omitHidden = null;
1889 if (viewport.hasHiddenColumns())
1891 omitHidden = viewport.getViewAsString(true);
1894 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1897 StringSelection ss = new StringSelection(output);
1901 jalview.gui.Desktop.internalCopy = true;
1902 // Its really worth setting the clipboard contents
1903 // to empty before setting the large StringSelection!!
1904 Toolkit.getDefaultToolkit().getSystemClipboard()
1905 .setContents(new StringSelection(""), null);
1907 Toolkit.getDefaultToolkit().getSystemClipboard()
1908 .setContents(ss, Desktop.instance);
1909 } catch (OutOfMemoryError er)
1911 new OOMWarning("copying region", er);
1915 ArrayList<int[]> hiddenColumns = null;
1916 if (viewport.hasHiddenColumns())
1918 hiddenColumns = new ArrayList<int[]>();
1919 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1920 .getSelectionGroup().getEndRes();
1921 for (int[] region : viewport.getColumnSelection().getHiddenColumns())
1923 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1925 hiddenColumns.add(new int[] { region[0] - hiddenOffset,
1926 region[1] - hiddenOffset });
1931 Desktop.jalviewClipboard = new Object[] { seqs,
1932 viewport.getAlignment().getDataset(), hiddenColumns };
1933 statusBar.setText(MessageManager.formatMessage(
1934 "label.copied_sequences_to_clipboard", new Object[] { Integer
1935 .valueOf(seqs.length).toString() }));
1945 protected void pasteNew_actionPerformed(ActionEvent e)
1957 protected void pasteThis_actionPerformed(ActionEvent e)
1963 * Paste contents of Jalview clipboard
1965 * @param newAlignment
1966 * true to paste to a new alignment, otherwise add to this.
1968 void paste(boolean newAlignment)
1970 boolean externalPaste = true;
1973 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1974 Transferable contents = c.getContents(this);
1976 if (contents == null)
1984 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1985 if (str.length() < 1)
1990 format = new IdentifyFile().identify(str, "Paste");
1992 } catch (OutOfMemoryError er)
1994 new OOMWarning("Out of memory pasting sequences!!", er);
1998 SequenceI[] sequences;
1999 boolean annotationAdded = false;
2000 AlignmentI alignment = null;
2002 if (Desktop.jalviewClipboard != null)
2004 // The clipboard was filled from within Jalview, we must use the
2006 // And dataset from the copied alignment
2007 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2008 // be doubly sure that we create *new* sequence objects.
2009 sequences = new SequenceI[newseq.length];
2010 for (int i = 0; i < newseq.length; i++)
2012 sequences[i] = new Sequence(newseq[i]);
2014 alignment = new Alignment(sequences);
2015 externalPaste = false;
2019 // parse the clipboard as an alignment.
2020 alignment = new FormatAdapter().readFile(str, "Paste", format);
2021 sequences = alignment.getSequencesArray();
2025 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
2031 if (Desktop.jalviewClipboard != null)
2033 // dataset is inherited
2034 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2038 // new dataset is constructed
2039 alignment.setDataset(null);
2041 alwidth = alignment.getWidth() + 1;
2045 AlignmentI pastedal = alignment; // preserve pasted alignment object
2046 // Add pasted sequences and dataset into existing alignment.
2047 alignment = viewport.getAlignment();
2048 alwidth = alignment.getWidth() + 1;
2049 // decide if we need to import sequences from an existing dataset
2050 boolean importDs = Desktop.jalviewClipboard != null
2051 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2052 // importDs==true instructs us to copy over new dataset sequences from
2053 // an existing alignment
2054 Vector newDs = (importDs) ? new Vector() : null; // used to create
2055 // minimum dataset set
2057 for (int i = 0; i < sequences.length; i++)
2061 newDs.addElement(null);
2063 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2065 if (importDs && ds != null)
2067 if (!newDs.contains(ds))
2069 newDs.setElementAt(ds, i);
2070 ds = new Sequence(ds);
2071 // update with new dataset sequence
2072 sequences[i].setDatasetSequence(ds);
2076 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2081 // copy and derive new dataset sequence
2082 sequences[i] = sequences[i].deriveSequence();
2083 alignment.getDataset().addSequence(
2084 sequences[i].getDatasetSequence());
2085 // TODO: avoid creation of duplicate dataset sequences with a
2086 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2088 alignment.addSequence(sequences[i]); // merges dataset
2092 newDs.clear(); // tidy up
2094 if (alignment.getAlignmentAnnotation() != null)
2096 for (AlignmentAnnotation alan : alignment
2097 .getAlignmentAnnotation())
2099 if (alan.graphGroup > fgroup)
2101 fgroup = alan.graphGroup;
2105 if (pastedal.getAlignmentAnnotation() != null)
2107 // Add any annotation attached to alignment.
2108 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2109 for (int i = 0; i < alann.length; i++)
2111 annotationAdded = true;
2112 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2114 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2115 if (newann.graphGroup > -1)
2117 if (newGraphGroups.size() <= newann.graphGroup
2118 || newGraphGroups.get(newann.graphGroup) == null)
2120 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2122 newGraphGroups.add(q, null);
2124 newGraphGroups.set(newann.graphGroup, new Integer(
2127 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2131 newann.padAnnotation(alwidth);
2132 alignment.addAnnotation(newann);
2142 addHistoryItem(new EditCommand(
2143 MessageManager.getString("label.add_sequences"),
2144 Action.PASTE, sequences, 0, alignment.getWidth(), alignment));
2146 // Add any annotations attached to sequences
2147 for (int i = 0; i < sequences.length; i++)
2149 if (sequences[i].getAnnotation() != null)
2151 AlignmentAnnotation newann;
2152 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2154 annotationAdded = true;
2155 newann = sequences[i].getAnnotation()[a];
2156 newann.adjustForAlignment();
2157 newann.padAnnotation(alwidth);
2158 if (newann.graphGroup > -1)
2160 if (newann.graphGroup > -1)
2162 if (newGraphGroups.size() <= newann.graphGroup
2163 || newGraphGroups.get(newann.graphGroup) == null)
2165 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2167 newGraphGroups.add(q, null);
2169 newGraphGroups.set(newann.graphGroup, new Integer(
2172 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2176 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2181 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2188 // propagate alignment changed.
2189 viewport.setEndSeq(alignment.getHeight());
2190 if (annotationAdded)
2192 // Duplicate sequence annotation in all views.
2193 AlignmentI[] alview = this.getViewAlignments();
2194 for (int i = 0; i < sequences.length; i++)
2196 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2201 for (int avnum = 0; avnum < alview.length; avnum++)
2203 if (alview[avnum] != alignment)
2205 // duplicate in a view other than the one with input focus
2206 int avwidth = alview[avnum].getWidth() + 1;
2207 // this relies on sann being preserved after we
2208 // modify the sequence's annotation array for each duplication
2209 for (int a = 0; a < sann.length; a++)
2211 AlignmentAnnotation newann = new AlignmentAnnotation(
2213 sequences[i].addAlignmentAnnotation(newann);
2214 newann.padAnnotation(avwidth);
2215 alview[avnum].addAnnotation(newann); // annotation was
2216 // duplicated earlier
2217 // TODO JAL-1145 graphGroups are not updated for sequence
2218 // annotation added to several views. This may cause
2220 alview[avnum].setAnnotationIndex(newann, a);
2225 buildSortByAnnotationScoresMenu();
2227 viewport.firePropertyChange("alignment", null,
2228 alignment.getSequences());
2229 if (alignPanels != null)
2231 for (AlignmentPanel ap : alignPanels)
2233 ap.validateAnnotationDimensions(false);
2238 alignPanel.validateAnnotationDimensions(false);
2244 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2246 String newtitle = new String("Copied sequences");
2248 if (Desktop.jalviewClipboard != null
2249 && Desktop.jalviewClipboard[2] != null)
2251 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2252 for (int[] region : hc)
2254 af.viewport.hideColumns(region[0], region[1]);
2258 // >>>This is a fix for the moment, until a better solution is
2260 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2262 alignPanel.getSeqPanel().seqCanvas
2263 .getFeatureRenderer());
2265 // TODO: maintain provenance of an alignment, rather than just make the
2266 // title a concatenation of operations.
2269 if (title.startsWith("Copied sequences"))
2275 newtitle = newtitle.concat("- from " + title);
2280 newtitle = new String("Pasted sequences");
2283 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2288 } catch (Exception ex)
2290 ex.printStackTrace();
2291 System.out.println("Exception whilst pasting: " + ex);
2292 // could be anything being pasted in here
2298 protected void expand_newalign(ActionEvent e)
2302 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2303 .getAlignment(), -1);
2304 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2306 String newtitle = new String("Flanking alignment");
2308 if (Desktop.jalviewClipboard != null
2309 && Desktop.jalviewClipboard[2] != null)
2311 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2312 for (int region[] : hc)
2314 af.viewport.hideColumns(region[0], region[1]);
2318 // >>>This is a fix for the moment, until a better solution is
2320 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2322 alignPanel.getSeqPanel().seqCanvas
2323 .getFeatureRenderer());
2325 // TODO: maintain provenance of an alignment, rather than just make the
2326 // title a concatenation of operations.
2328 if (title.startsWith("Copied sequences"))
2334 newtitle = newtitle.concat("- from " + title);
2338 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2340 } catch (Exception ex)
2342 ex.printStackTrace();
2343 System.out.println("Exception whilst pasting: " + ex);
2344 // could be anything being pasted in here
2345 } catch (OutOfMemoryError oom)
2347 new OOMWarning("Viewing flanking region of alignment", oom);
2358 protected void cut_actionPerformed(ActionEvent e)
2360 copy_actionPerformed(null);
2361 delete_actionPerformed(null);
2371 protected void delete_actionPerformed(ActionEvent evt)
2374 SequenceGroup sg = viewport.getSelectionGroup();
2381 * If the cut affects all sequences, warn, remove highlighted columns
2383 if (sg.getSize() == viewport.getAlignment().getHeight())
2385 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes()) + 1) == viewport
2386 .getAlignment().getWidth()) ? true : false;
2387 if (isEntireAlignWidth)
2389 int confirm = JOptionPane.showConfirmDialog(this,
2390 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2391 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2392 JOptionPane.OK_CANCEL_OPTION);
2394 if (confirm == JOptionPane.CANCEL_OPTION
2395 || confirm == JOptionPane.CLOSED_OPTION)
2400 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2401 sg.getEndRes() + 1);
2403 SequenceI[] cut = sg.getSequences()
2404 .toArray(new SequenceI[sg.getSize()]);
2406 addHistoryItem(new EditCommand(
2407 MessageManager.getString("label.cut_sequences"), Action.CUT,
2408 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2409 viewport.getAlignment()));
2411 viewport.setSelectionGroup(null);
2412 viewport.sendSelection();
2413 viewport.getAlignment().deleteGroup(sg);
2415 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2417 if (viewport.getAlignment().getHeight() < 1)
2421 this.setClosed(true);
2422 } catch (Exception ex)
2435 protected void deleteGroups_actionPerformed(ActionEvent e)
2437 if (avc.deleteGroups())
2439 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2440 alignPanel.updateAnnotation();
2441 alignPanel.paintAlignment(true);
2452 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2454 SequenceGroup sg = new SequenceGroup();
2456 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2458 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2461 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2462 viewport.setSelectionGroup(sg);
2463 viewport.sendSelection();
2464 // JAL-2034 - should delegate to
2465 // alignPanel to decide if overview needs
2467 alignPanel.paintAlignment(false);
2468 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2478 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2480 if (viewport.cursorMode)
2482 alignPanel.getSeqPanel().keyboardNo1 = null;
2483 alignPanel.getSeqPanel().keyboardNo2 = null;
2485 viewport.setSelectionGroup(null);
2486 viewport.getColumnSelection().clear();
2487 viewport.setSelectionGroup(null);
2488 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2489 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2490 // JAL-2034 - should delegate to
2491 // alignPanel to decide if overview needs
2493 alignPanel.paintAlignment(false);
2494 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2495 viewport.sendSelection();
2505 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2507 SequenceGroup sg = viewport.getSelectionGroup();
2511 selectAllSequenceMenuItem_actionPerformed(null);
2516 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2518 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2520 // JAL-2034 - should delegate to
2521 // alignPanel to decide if overview needs
2524 alignPanel.paintAlignment(true);
2525 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2526 viewport.sendSelection();
2530 public void invertColSel_actionPerformed(ActionEvent e)
2532 viewport.invertColumnSelection();
2533 alignPanel.paintAlignment(true);
2534 viewport.sendSelection();
2544 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2546 trimAlignment(true);
2556 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2558 trimAlignment(false);
2561 void trimAlignment(boolean trimLeft)
2563 ColumnSelection colSel = viewport.getColumnSelection();
2566 if (!colSel.isEmpty())
2570 column = colSel.getMin();
2574 column = colSel.getMax();
2578 if (viewport.getSelectionGroup() != null)
2580 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2581 viewport.getHiddenRepSequences());
2585 seqs = viewport.getAlignment().getSequencesArray();
2588 TrimRegionCommand trimRegion;
2591 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2592 column, viewport.getAlignment());
2593 viewport.setStartRes(0);
2597 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2598 column, viewport.getAlignment());
2601 statusBar.setText(MessageManager.formatMessage(
2602 "label.removed_columns",
2603 new String[] { Integer.valueOf(trimRegion.getSize())
2606 addHistoryItem(trimRegion);
2608 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2610 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2611 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2613 viewport.getAlignment().deleteGroup(sg);
2617 viewport.firePropertyChange("alignment", null, viewport
2618 .getAlignment().getSequences());
2629 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2631 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2634 if (viewport.getSelectionGroup() != null)
2636 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2637 viewport.getHiddenRepSequences());
2638 start = viewport.getSelectionGroup().getStartRes();
2639 end = viewport.getSelectionGroup().getEndRes();
2643 seqs = viewport.getAlignment().getSequencesArray();
2646 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2647 "Remove Gapped Columns", seqs, start, end,
2648 viewport.getAlignment());
2650 addHistoryItem(removeGapCols);
2652 statusBar.setText(MessageManager.formatMessage(
2653 "label.removed_empty_columns",
2654 new Object[] { Integer.valueOf(removeGapCols.getSize())
2657 // This is to maintain viewport position on first residue
2658 // of first sequence
2659 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2660 int startRes = seq.findPosition(viewport.startRes);
2661 // ShiftList shifts;
2662 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2663 // edit.alColumnChanges=shifts.getInverse();
2664 // if (viewport.hasHiddenColumns)
2665 // viewport.getColumnSelection().compensateForEdits(shifts);
2666 viewport.setStartRes(seq.findIndex(startRes) - 1);
2667 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2679 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2681 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2684 if (viewport.getSelectionGroup() != null)
2686 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2687 viewport.getHiddenRepSequences());
2688 start = viewport.getSelectionGroup().getStartRes();
2689 end = viewport.getSelectionGroup().getEndRes();
2693 seqs = viewport.getAlignment().getSequencesArray();
2696 // This is to maintain viewport position on first residue
2697 // of first sequence
2698 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2699 int startRes = seq.findPosition(viewport.startRes);
2701 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2702 viewport.getAlignment()));
2704 viewport.setStartRes(seq.findIndex(startRes) - 1);
2706 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2718 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2720 viewport.setPadGaps(padGapsMenuitem.isSelected());
2721 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2732 public void findMenuItem_actionPerformed(ActionEvent e)
2738 * Create a new view of the current alignment.
2741 public void newView_actionPerformed(ActionEvent e)
2743 newView(null, true);
2747 * Creates and shows a new view of the current alignment.
2750 * title of newly created view; if null, one will be generated
2751 * @param copyAnnotation
2752 * if true then duplicate all annnotation, groups and settings
2753 * @return new alignment panel, already displayed.
2755 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2758 * Create a new AlignmentPanel (with its own, new Viewport)
2760 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2762 if (!copyAnnotation)
2765 * remove all groups and annotation except for the automatic stuff
2767 newap.av.getAlignment().deleteAllGroups();
2768 newap.av.getAlignment().deleteAllAnnotations(false);
2771 newap.av.setGatherViewsHere(false);
2773 if (viewport.viewName == null)
2775 viewport.viewName = MessageManager
2776 .getString("label.view_name_original");
2780 * Views share the same edits undo and redo stacks
2782 newap.av.setHistoryList(viewport.getHistoryList());
2783 newap.av.setRedoList(viewport.getRedoList());
2786 * Views share the same mappings; need to deregister any new mappings
2787 * created by copyAlignPanel, and register the new reference to the shared
2790 newap.av.replaceMappings(viewport.getAlignment());
2792 newap.av.viewName = getNewViewName(viewTitle);
2794 addAlignmentPanel(newap, true);
2795 newap.alignmentChanged();
2797 if (alignPanels.size() == 2)
2799 viewport.setGatherViewsHere(true);
2801 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2806 * Make a new name for the view, ensuring it is unique within the current
2807 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2808 * these now use viewId. Unique view names are still desirable for usability.)
2813 protected String getNewViewName(String viewTitle)
2815 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2816 boolean addFirstIndex = false;
2817 if (viewTitle == null || viewTitle.trim().length() == 0)
2819 viewTitle = MessageManager.getString("action.view");
2820 addFirstIndex = true;
2824 index = 1;// we count from 1 if given a specific name
2826 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2828 List<Component> comps = PaintRefresher.components.get(viewport
2829 .getSequenceSetId());
2831 List<String> existingNames = getExistingViewNames(comps);
2833 while (existingNames.contains(newViewName))
2835 newViewName = viewTitle + " " + (++index);
2841 * Returns a list of distinct view names found in the given list of
2842 * components. View names are held on the viewport of an AlignmentPanel.
2847 protected List<String> getExistingViewNames(List<Component> comps)
2849 List<String> existingNames = new ArrayList<String>();
2850 for (Component comp : comps)
2852 if (comp instanceof AlignmentPanel)
2854 AlignmentPanel ap = (AlignmentPanel) comp;
2855 if (!existingNames.contains(ap.av.viewName))
2857 existingNames.add(ap.av.viewName);
2861 return existingNames;
2865 * Explode tabbed views into separate windows.
2868 public void expandViews_actionPerformed(ActionEvent e)
2870 Desktop.instance.explodeViews(this);
2874 * Gather views in separate windows back into a tabbed presentation.
2877 public void gatherViews_actionPerformed(ActionEvent e)
2879 Desktop.instance.gatherViews(this);
2889 public void font_actionPerformed(ActionEvent e)
2891 new FontChooser(alignPanel);
2901 protected void seqLimit_actionPerformed(ActionEvent e)
2903 viewport.setShowJVSuffix(seqLimits.isSelected());
2905 alignPanel.getIdPanel().getIdCanvas()
2906 .setPreferredSize(alignPanel.calculateIdWidth());
2907 alignPanel.paintAlignment(true);
2911 public void idRightAlign_actionPerformed(ActionEvent e)
2913 viewport.setRightAlignIds(idRightAlign.isSelected());
2914 alignPanel.paintAlignment(true);
2918 public void centreColumnLabels_actionPerformed(ActionEvent e)
2920 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2921 alignPanel.paintAlignment(true);
2927 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2930 protected void followHighlight_actionPerformed()
2933 * Set the 'follow' flag on the Viewport (and scroll to position if now
2936 final boolean state = this.followHighlightMenuItem.getState();
2937 viewport.setFollowHighlight(state);
2940 alignPanel.scrollToPosition(
2941 alignPanel.getSeqPanel().seqCanvas.searchResults, false);
2952 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2954 viewport.setColourText(colourTextMenuItem.isSelected());
2955 alignPanel.paintAlignment(true);
2965 public void wrapMenuItem_actionPerformed(ActionEvent e)
2967 scaleAbove.setVisible(wrapMenuItem.isSelected());
2968 scaleLeft.setVisible(wrapMenuItem.isSelected());
2969 scaleRight.setVisible(wrapMenuItem.isSelected());
2970 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2971 alignPanel.updateLayout();
2975 public void showAllSeqs_actionPerformed(ActionEvent e)
2977 viewport.showAllHiddenSeqs();
2981 public void showAllColumns_actionPerformed(ActionEvent e)
2983 viewport.showAllHiddenColumns();
2985 viewport.sendSelection();
2989 public void hideSelSequences_actionPerformed(ActionEvent e)
2991 viewport.hideAllSelectedSeqs();
2992 // alignPanel.paintAlignment(true);
2996 * called by key handler and the hide all/show all menu items
3001 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3004 boolean hide = false;
3005 SequenceGroup sg = viewport.getSelectionGroup();
3006 if (!toggleSeqs && !toggleCols)
3008 // Hide everything by the current selection - this is a hack - we do the
3009 // invert and then hide
3010 // first check that there will be visible columns after the invert.
3011 if ((viewport.getColumnSelection() != null
3012 && viewport.getColumnSelection().getSelected() != null && viewport
3013 .getColumnSelection().getSelected().size() > 0)
3014 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
3017 // now invert the sequence set, if required - empty selection implies
3018 // that no hiding is required.
3021 invertSequenceMenuItem_actionPerformed(null);
3022 sg = viewport.getSelectionGroup();
3026 viewport.expandColSelection(sg, true);
3027 // finally invert the column selection and get the new sequence
3029 invertColSel_actionPerformed(null);
3036 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3038 hideSelSequences_actionPerformed(null);
3041 else if (!(toggleCols && viewport.getColumnSelection().getSelected()
3044 showAllSeqs_actionPerformed(null);
3050 if (viewport.getColumnSelection().getSelected().size() > 0)
3052 hideSelColumns_actionPerformed(null);
3055 viewport.setSelectionGroup(sg);
3060 showAllColumns_actionPerformed(null);
3069 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3070 * event.ActionEvent)
3073 public void hideAllButSelection_actionPerformed(ActionEvent e)
3075 toggleHiddenRegions(false, false);
3076 viewport.sendSelection();
3083 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3087 public void hideAllSelection_actionPerformed(ActionEvent e)
3089 SequenceGroup sg = viewport.getSelectionGroup();
3090 viewport.expandColSelection(sg, false);
3091 viewport.hideAllSelectedSeqs();
3092 viewport.hideSelectedColumns();
3093 alignPanel.paintAlignment(true);
3094 viewport.sendSelection();
3101 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3105 public void showAllhidden_actionPerformed(ActionEvent e)
3107 viewport.showAllHiddenColumns();
3108 viewport.showAllHiddenSeqs();
3109 alignPanel.paintAlignment(true);
3110 viewport.sendSelection();
3114 public void hideSelColumns_actionPerformed(ActionEvent e)
3116 viewport.hideSelectedColumns();
3117 alignPanel.paintAlignment(true);
3118 viewport.sendSelection();
3122 public void hiddenMarkers_actionPerformed(ActionEvent e)
3124 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3135 protected void scaleAbove_actionPerformed(ActionEvent e)
3137 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3138 alignPanel.paintAlignment(true);
3148 protected void scaleLeft_actionPerformed(ActionEvent e)
3150 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3151 alignPanel.paintAlignment(true);
3161 protected void scaleRight_actionPerformed(ActionEvent e)
3163 viewport.setScaleRightWrapped(scaleRight.isSelected());
3164 alignPanel.paintAlignment(true);
3174 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3176 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3177 alignPanel.paintAlignment(true);
3187 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3189 viewport.setShowText(viewTextMenuItem.isSelected());
3190 alignPanel.paintAlignment(true);
3200 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3202 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3203 alignPanel.paintAlignment(true);
3206 public FeatureSettings featureSettings;
3209 public FeatureSettingsControllerI getFeatureSettingsUI()
3211 return featureSettings;
3215 public void featureSettings_actionPerformed(ActionEvent e)
3217 if (featureSettings != null)
3219 featureSettings.close();
3220 featureSettings = null;
3222 if (!showSeqFeatures.isSelected())
3224 // make sure features are actually displayed
3225 showSeqFeatures.setSelected(true);
3226 showSeqFeatures_actionPerformed(null);
3228 featureSettings = new FeatureSettings(this);
3232 * Set or clear 'Show Sequence Features'
3238 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3240 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3241 alignPanel.paintAlignment(true);
3242 if (alignPanel.getOverviewPanel() != null)
3244 alignPanel.getOverviewPanel().updateOverviewImage();
3249 * Set or clear 'Show Sequence Features'
3255 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
3257 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
3259 if (viewport.isShowSequenceFeaturesHeight())
3261 // ensure we're actually displaying features
3262 viewport.setShowSequenceFeatures(true);
3263 showSeqFeatures.setSelected(true);
3265 alignPanel.paintAlignment(true);
3266 if (alignPanel.getOverviewPanel() != null)
3268 alignPanel.getOverviewPanel().updateOverviewImage();
3273 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3274 * the annotations panel as a whole.
3276 * The options to show/hide all annotations should be enabled when the panel
3277 * is shown, and disabled when the panel is hidden.
3282 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3284 final boolean setVisible = annotationPanelMenuItem.isSelected();
3285 viewport.setShowAnnotation(setVisible);
3286 this.showAllSeqAnnotations.setEnabled(setVisible);
3287 this.hideAllSeqAnnotations.setEnabled(setVisible);
3288 this.showAllAlAnnotations.setEnabled(setVisible);
3289 this.hideAllAlAnnotations.setEnabled(setVisible);
3290 alignPanel.updateLayout();
3294 public void alignmentProperties()
3296 JEditorPane editPane = new JEditorPane("text/html", "");
3297 editPane.setEditable(false);
3298 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3300 editPane.setText(MessageManager.formatMessage("label.html_content",
3301 new Object[] { contents.toString() }));
3302 JInternalFrame frame = new JInternalFrame();
3303 frame.getContentPane().add(new JScrollPane(editPane));
3305 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3306 "label.alignment_properties", new Object[] { getTitle() }),
3317 public void overviewMenuItem_actionPerformed(ActionEvent e)
3319 if (alignPanel.overviewPanel != null)
3324 JInternalFrame frame = new JInternalFrame();
3325 OverviewPanel overview = new OverviewPanel(alignPanel);
3326 frame.setContentPane(overview);
3327 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3328 "label.overview_params", new Object[] { this.getTitle() }),
3329 frame.getWidth(), frame.getHeight());
3331 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3332 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3335 public void internalFrameClosed(
3336 javax.swing.event.InternalFrameEvent evt)
3338 alignPanel.setOverviewPanel(null);
3342 alignPanel.setOverviewPanel(overview);
3346 public void textColour_actionPerformed(ActionEvent e)
3348 new TextColourChooser().chooseColour(alignPanel, null);
3358 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3370 public void clustalColour_actionPerformed(ActionEvent e)
3372 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3373 viewport.getHiddenRepSequences()));
3383 public void zappoColour_actionPerformed(ActionEvent e)
3385 changeColour(new ZappoColourScheme());
3395 public void taylorColour_actionPerformed(ActionEvent e)
3397 changeColour(new TaylorColourScheme());
3407 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3409 changeColour(new HydrophobicColourScheme());
3419 public void helixColour_actionPerformed(ActionEvent e)
3421 changeColour(new HelixColourScheme());
3431 public void strandColour_actionPerformed(ActionEvent e)
3433 changeColour(new StrandColourScheme());
3443 public void turnColour_actionPerformed(ActionEvent e)
3445 changeColour(new TurnColourScheme());
3455 public void buriedColour_actionPerformed(ActionEvent e)
3457 changeColour(new BuriedColourScheme());
3467 public void nucleotideColour_actionPerformed(ActionEvent e)
3469 changeColour(new NucleotideColourScheme());
3473 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3475 changeColour(new PurinePyrimidineColourScheme());
3479 * public void covariationColour_actionPerformed(ActionEvent e) {
3481 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3485 public void annotationColour_actionPerformed(ActionEvent e)
3487 new AnnotationColourChooser(viewport, alignPanel);
3491 public void annotationColumn_actionPerformed(ActionEvent e)
3493 new AnnotationColumnChooser(viewport, alignPanel);
3497 public void rnahelicesColour_actionPerformed(ActionEvent e)
3499 new RNAHelicesColourChooser(viewport, alignPanel);
3509 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3511 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3521 public void changeColour(ColourSchemeI cs)
3523 // TODO: pull up to controller method
3527 // Make sure viewport is up to date w.r.t. any sliders
3528 if (viewport.getAbovePIDThreshold())
3530 int threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3532 viewport.setThreshold(threshold);
3535 if (viewport.getConservationSelected())
3537 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3540 if (cs instanceof TCoffeeColourScheme)
3542 tcoffeeColour.setEnabled(true);
3543 tcoffeeColour.setSelected(true);
3547 viewport.setGlobalColourScheme(cs);
3549 alignPanel.paintAlignment(true);
3559 protected void modifyPID_actionPerformed(ActionEvent e)
3561 if (viewport.getAbovePIDThreshold()
3562 && viewport.getGlobalColourScheme() != null)
3564 SliderPanel.setPIDSliderSource(alignPanel,
3565 viewport.getGlobalColourScheme(), "Background");
3566 SliderPanel.showPIDSlider();
3577 protected void modifyConservation_actionPerformed(ActionEvent e)
3579 if (viewport.getConservationSelected()
3580 && viewport.getGlobalColourScheme() != null)
3582 SliderPanel.setConservationSlider(alignPanel,
3583 viewport.getGlobalColourScheme(), "Background");
3584 SliderPanel.showConservationSlider();
3595 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3597 viewport.setConservationSelected(conservationMenuItem.isSelected());
3599 viewport.setAbovePIDThreshold(false);
3600 abovePIDThreshold.setSelected(false);
3602 changeColour(viewport.getGlobalColourScheme());
3604 modifyConservation_actionPerformed(null);
3614 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3616 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3618 conservationMenuItem.setSelected(false);
3619 viewport.setConservationSelected(false);
3621 changeColour(viewport.getGlobalColourScheme());
3623 modifyPID_actionPerformed(null);
3633 public void userDefinedColour_actionPerformed(ActionEvent e)
3635 if (e.getActionCommand().equals(
3636 MessageManager.getString("action.user_defined")))
3638 new UserDefinedColours(alignPanel, null);
3642 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3643 .getUserColourSchemes().get(e.getActionCommand());
3649 public void updateUserColourMenu()
3652 Component[] menuItems = colourMenu.getMenuComponents();
3653 int iSize = menuItems.length;
3654 for (int i = 0; i < iSize; i++)
3656 if (menuItems[i].getName() != null
3657 && menuItems[i].getName().equals("USER_DEFINED"))
3659 colourMenu.remove(menuItems[i]);
3663 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3665 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3666 .getUserColourSchemes().keys();
3668 while (userColours.hasMoreElements())
3670 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3671 userColours.nextElement().toString());
3672 radioItem.setName("USER_DEFINED");
3673 radioItem.addMouseListener(new MouseAdapter()
3676 public void mousePressed(MouseEvent evt)
3678 if (evt.isControlDown()
3679 || SwingUtilities.isRightMouseButton(evt))
3681 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3683 int option = JOptionPane.showInternalConfirmDialog(
3684 jalview.gui.Desktop.desktop,
3686 .getString("label.remove_from_default_list"),
3688 .getString("label.remove_user_defined_colour"),
3689 JOptionPane.YES_NO_OPTION);
3690 if (option == JOptionPane.YES_OPTION)
3692 jalview.gui.UserDefinedColours
3693 .removeColourFromDefaults(radioItem.getText());
3694 colourMenu.remove(radioItem);
3698 radioItem.addActionListener(new ActionListener()
3701 public void actionPerformed(ActionEvent evt)
3703 userDefinedColour_actionPerformed(evt);
3710 radioItem.addActionListener(new ActionListener()
3713 public void actionPerformed(ActionEvent evt)
3715 userDefinedColour_actionPerformed(evt);
3719 colourMenu.insert(radioItem, 15);
3720 colours.add(radioItem);
3732 public void PIDColour_actionPerformed(ActionEvent e)
3734 changeColour(new PIDColourScheme());
3744 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3746 changeColour(new Blosum62ColourScheme());
3756 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3758 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3759 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3760 .getAlignment().getSequenceAt(0), null);
3761 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3762 viewport.getAlignment()));
3763 alignPanel.paintAlignment(true);
3773 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3775 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3776 AlignmentSorter.sortByID(viewport.getAlignment());
3777 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3778 viewport.getAlignment()));
3779 alignPanel.paintAlignment(true);
3789 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3791 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3792 AlignmentSorter.sortByLength(viewport.getAlignment());
3793 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3794 viewport.getAlignment()));
3795 alignPanel.paintAlignment(true);
3805 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3807 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3808 AlignmentSorter.sortByGroup(viewport.getAlignment());
3809 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3810 viewport.getAlignment()));
3812 alignPanel.paintAlignment(true);
3822 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3824 new RedundancyPanel(alignPanel, this);
3834 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3836 if ((viewport.getSelectionGroup() == null)
3837 || (viewport.getSelectionGroup().getSize() < 2))
3839 JOptionPane.showInternalMessageDialog(this, MessageManager
3840 .getString("label.you_must_select_least_two_sequences"),
3841 MessageManager.getString("label.invalid_selection"),
3842 JOptionPane.WARNING_MESSAGE);
3846 JInternalFrame frame = new JInternalFrame();
3847 frame.setContentPane(new PairwiseAlignPanel(viewport));
3848 Desktop.addInternalFrame(frame,
3849 MessageManager.getString("action.pairwise_alignment"), 600,
3861 public void PCAMenuItem_actionPerformed(ActionEvent e)
3863 if (((viewport.getSelectionGroup() != null)
3864 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3865 .getSelectionGroup().getSize() > 0))
3866 || (viewport.getAlignment().getHeight() < 4))
3869 .showInternalMessageDialog(
3872 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3874 .getString("label.sequence_selection_insufficient"),
3875 JOptionPane.WARNING_MESSAGE);
3880 new PCAPanel(alignPanel);
3884 public void autoCalculate_actionPerformed(ActionEvent e)
3886 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3887 if (viewport.autoCalculateConsensus)
3889 viewport.firePropertyChange("alignment", null, viewport
3890 .getAlignment().getSequences());
3895 public void sortByTreeOption_actionPerformed(ActionEvent e)
3897 viewport.sortByTree = sortByTree.isSelected();
3901 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3903 viewport.followSelection = listenToViewSelections.isSelected();
3913 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3915 newTreePanel("AV", "PID", "Average distance tree using PID");
3925 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3927 newTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3937 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3939 newTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3949 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3951 newTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3964 void newTreePanel(String type, String pwType, String title)
3968 if (viewport.getSelectionGroup() != null
3969 && viewport.getSelectionGroup().getSize() > 0)
3971 if (viewport.getSelectionGroup().getSize() < 3)
3977 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3979 .getString("label.not_enough_sequences"),
3980 JOptionPane.WARNING_MESSAGE);
3984 SequenceGroup sg = viewport.getSelectionGroup();
3986 /* Decide if the selection is a column region */
3987 for (SequenceI _s : sg.getSequences())
3989 if (_s.getLength() < sg.getEndRes())
3995 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3997 .getString("label.sequences_selection_not_aligned"),
3998 JOptionPane.WARNING_MESSAGE);
4004 title = title + " on region";
4005 tp = new TreePanel(alignPanel, type, pwType);
4009 // are the visible sequences aligned?
4010 if (!viewport.getAlignment().isAligned(false))
4016 .getString("label.sequences_must_be_aligned_before_creating_tree"),
4018 .getString("label.sequences_not_aligned"),
4019 JOptionPane.WARNING_MESSAGE);
4024 if (viewport.getAlignment().getHeight() < 2)
4029 tp = new TreePanel(alignPanel, type, pwType);
4034 if (viewport.viewName != null)
4036 title += viewport.viewName + " of ";
4039 title += this.title;
4041 Desktop.addInternalFrame(tp, title, 600, 500);
4052 public void addSortByOrderMenuItem(String title,
4053 final AlignmentOrder order)
4055 final JMenuItem item = new JMenuItem(MessageManager.formatMessage(
4056 "action.by_title_param", new Object[] { title }));
4058 item.addActionListener(new java.awt.event.ActionListener()
4061 public void actionPerformed(ActionEvent e)
4063 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4065 // TODO: JBPNote - have to map order entries to curent SequenceI
4067 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4069 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
4072 alignPanel.paintAlignment(true);
4078 * Add a new sort by annotation score menu item
4081 * the menu to add the option to
4083 * the label used to retrieve scores for each sequence on the
4086 public void addSortByAnnotScoreMenuItem(JMenu sort,
4087 final String scoreLabel)
4089 final JMenuItem item = new JMenuItem(scoreLabel);
4091 item.addActionListener(new java.awt.event.ActionListener()
4094 public void actionPerformed(ActionEvent e)
4096 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4097 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4098 viewport.getAlignment());// ,viewport.getSelectionGroup());
4099 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4100 viewport.getAlignment()));
4101 alignPanel.paintAlignment(true);
4107 * last hash for alignment's annotation array - used to minimise cost of
4110 protected int _annotationScoreVectorHash;
4113 * search the alignment and rebuild the sort by annotation score submenu the
4114 * last alignment annotation vector hash is stored to minimize cost of
4115 * rebuilding in subsequence calls.
4119 public void buildSortByAnnotationScoresMenu()
4121 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4126 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4128 sortByAnnotScore.removeAll();
4129 // almost certainly a quicker way to do this - but we keep it simple
4130 Hashtable scoreSorts = new Hashtable();
4131 AlignmentAnnotation aann[];
4132 for (SequenceI sqa : viewport.getAlignment().getSequences())
4134 aann = sqa.getAnnotation();
4135 for (int i = 0; aann != null && i < aann.length; i++)
4137 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4139 scoreSorts.put(aann[i].label, aann[i].label);
4143 Enumeration labels = scoreSorts.keys();
4144 while (labels.hasMoreElements())
4146 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4147 (String) labels.nextElement());
4149 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4152 _annotationScoreVectorHash = viewport.getAlignment()
4153 .getAlignmentAnnotation().hashCode();
4158 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4159 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4160 * call. Listeners are added to remove the menu item when the treePanel is
4161 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4165 * Displayed tree window.
4167 * SortBy menu item title.
4170 public void buildTreeMenu()
4172 calculateTree.removeAll();
4173 // build the calculate menu
4175 for (final String type : new String[] { "NJ", "AV" })
4177 String treecalcnm = MessageManager.getString("label.tree_calc_"
4178 + type.toLowerCase());
4179 for (final String pwtype : ResidueProperties.scoreMatrices.keySet())
4181 JMenuItem tm = new JMenuItem();
4182 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4183 if (sm.isProtein() == !viewport.getAlignment().isNucleotide())
4185 String smn = MessageManager.getStringOrReturn(
4186 "label.score_model_", sm.getName());
4187 final String title = MessageManager.formatMessage(
4188 "label.treecalc_title", treecalcnm, smn);
4189 tm.setText(title);//
4190 tm.addActionListener(new java.awt.event.ActionListener()
4193 public void actionPerformed(ActionEvent e)
4195 newTreePanel(type, pwtype, title);
4198 calculateTree.add(tm);
4203 sortByTreeMenu.removeAll();
4205 List<Component> comps = PaintRefresher.components.get(viewport
4206 .getSequenceSetId());
4207 List<TreePanel> treePanels = new ArrayList<TreePanel>();
4208 for (Component comp : comps)
4210 if (comp instanceof TreePanel)
4212 treePanels.add((TreePanel) comp);
4216 if (treePanels.size() < 1)
4218 sortByTreeMenu.setVisible(false);
4222 sortByTreeMenu.setVisible(true);
4224 for (final TreePanel tp : treePanels)
4226 final JMenuItem item = new JMenuItem(tp.getTitle());
4227 item.addActionListener(new java.awt.event.ActionListener()
4230 public void actionPerformed(ActionEvent e)
4232 tp.sortByTree_actionPerformed();
4233 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4238 sortByTreeMenu.add(item);
4242 public boolean sortBy(AlignmentOrder alorder, String undoname)
4244 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4245 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4246 if (undoname != null)
4248 addHistoryItem(new OrderCommand(undoname, oldOrder,
4249 viewport.getAlignment()));
4251 alignPanel.paintAlignment(true);
4256 * Work out whether the whole set of sequences or just the selected set will
4257 * be submitted for multiple alignment.
4260 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4262 // Now, check we have enough sequences
4263 AlignmentView msa = null;
4265 if ((viewport.getSelectionGroup() != null)
4266 && (viewport.getSelectionGroup().getSize() > 1))
4268 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4269 // some common interface!
4271 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4272 * SequenceI[sz = seqs.getSize(false)];
4274 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4275 * seqs.getSequenceAt(i); }
4277 msa = viewport.getAlignmentView(true);
4279 else if (viewport.getSelectionGroup() != null
4280 && viewport.getSelectionGroup().getSize() == 1)
4282 int option = JOptionPane.showConfirmDialog(this,
4283 MessageManager.getString("warn.oneseq_msainput_selection"),
4284 MessageManager.getString("label.invalid_selection"),
4285 JOptionPane.OK_CANCEL_OPTION);
4286 if (option == JOptionPane.OK_OPTION)
4288 msa = viewport.getAlignmentView(false);
4293 msa = viewport.getAlignmentView(false);
4299 * Decides what is submitted to a secondary structure prediction service: the
4300 * first sequence in the alignment, or in the current selection, or, if the
4301 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4302 * region or the whole alignment. (where the first sequence in the set is the
4303 * one that the prediction will be for).
4305 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4307 AlignmentView seqs = null;
4309 if ((viewport.getSelectionGroup() != null)
4310 && (viewport.getSelectionGroup().getSize() > 0))
4312 seqs = viewport.getAlignmentView(true);
4316 seqs = viewport.getAlignmentView(false);
4318 // limit sequences - JBPNote in future - could spawn multiple prediction
4320 // TODO: viewport.getAlignment().isAligned is a global state - the local
4321 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4322 if (!viewport.getAlignment().isAligned(false))
4324 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4325 // TODO: if seqs.getSequences().length>1 then should really have warned
4339 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4341 // Pick the tree file
4342 JalviewFileChooser chooser = new JalviewFileChooser(
4343 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4344 chooser.setFileView(new JalviewFileView());
4345 chooser.setDialogTitle(MessageManager
4346 .getString("label.select_newick_like_tree_file"));
4347 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4349 int value = chooser.showOpenDialog(null);
4351 if (value == JalviewFileChooser.APPROVE_OPTION)
4353 String choice = chooser.getSelectedFile().getPath();
4354 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4355 jalview.io.NewickFile fin = null;
4358 fin = new jalview.io.NewickFile(choice, "File");
4359 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4360 } catch (Exception ex)
4367 .getString("label.problem_reading_tree_file"),
4368 JOptionPane.WARNING_MESSAGE);
4369 ex.printStackTrace();
4371 if (fin != null && fin.hasWarningMessage())
4373 JOptionPane.showMessageDialog(Desktop.desktop, fin
4374 .getWarningMessage(), MessageManager
4375 .getString("label.possible_problem_with_tree_file"),
4376 JOptionPane.WARNING_MESSAGE);
4382 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4384 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4387 public TreePanel ShowNewickTree(NewickFile nf, String title)
4389 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4392 public TreePanel ShowNewickTree(NewickFile nf, String title,
4393 AlignmentView input)
4395 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4398 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4399 int h, int x, int y)
4401 return ShowNewickTree(nf, title, null, w, h, x, y);
4405 * Add a treeviewer for the tree extracted from a newick file object to the
4406 * current alignment view
4413 * Associated alignment input data (or null)
4422 * @return TreePanel handle
4424 public TreePanel ShowNewickTree(NewickFile nf, String title,
4425 AlignmentView input, int w, int h, int x, int y)
4427 TreePanel tp = null;
4433 if (nf.getTree() != null)
4435 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4441 tp.setLocation(x, y);
4444 Desktop.addInternalFrame(tp, title, w, h);
4446 } catch (Exception ex)
4448 ex.printStackTrace();
4454 private boolean buildingMenu = false;
4457 * Generates menu items and listener event actions for web service clients
4460 public void BuildWebServiceMenu()
4462 while (buildingMenu)
4466 System.err.println("Waiting for building menu to finish.");
4468 } catch (Exception e)
4472 final AlignFrame me = this;
4473 buildingMenu = true;
4474 new Thread(new Runnable()
4479 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4482 // System.err.println("Building ws menu again "
4483 // + Thread.currentThread());
4484 // TODO: add support for context dependent disabling of services based
4486 // alignment and current selection
4487 // TODO: add additional serviceHandle parameter to specify abstract
4489 // class independently of AbstractName
4490 // TODO: add in rediscovery GUI function to restart discoverer
4491 // TODO: group services by location as well as function and/or
4493 // object broker mechanism.
4494 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4495 final IProgressIndicator af = me;
4496 final JMenu msawsmenu = new JMenu("Alignment");
4497 final JMenu secstrmenu = new JMenu(
4498 "Secondary Structure Prediction");
4499 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4500 final JMenu analymenu = new JMenu("Analysis");
4501 final JMenu dismenu = new JMenu("Protein Disorder");
4502 // final JMenu msawsmenu = new
4503 // JMenu(MessageManager.getString("label.alignment"));
4504 // final JMenu secstrmenu = new
4505 // JMenu(MessageManager.getString("label.secondary_structure_prediction"));
4506 // final JMenu seqsrchmenu = new
4507 // JMenu(MessageManager.getString("label.sequence_database_search"));
4508 // final JMenu analymenu = new
4509 // JMenu(MessageManager.getString("label.analysis"));
4510 // final JMenu dismenu = new
4511 // JMenu(MessageManager.getString("label.protein_disorder"));
4512 // JAL-940 - only show secondary structure prediction services from
4513 // the legacy server
4514 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4516 Discoverer.services != null && (Discoverer.services.size() > 0))
4518 // TODO: refactor to allow list of AbstractName/Handler bindings to
4520 // stored or retrieved from elsewhere
4521 // No MSAWS used any more:
4522 // Vector msaws = null; // (Vector)
4523 // Discoverer.services.get("MsaWS");
4524 Vector secstrpr = (Vector) Discoverer.services
4526 if (secstrpr != null)
4528 // Add any secondary structure prediction services
4529 for (int i = 0, j = secstrpr.size(); i < j; i++)
4531 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4533 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4534 .getServiceClient(sh);
4535 int p = secstrmenu.getItemCount();
4536 impl.attachWSMenuEntry(secstrmenu, me);
4537 int q = secstrmenu.getItemCount();
4538 for (int litm = p; litm < q; litm++)
4540 legacyItems.add(secstrmenu.getItem(litm));
4546 // Add all submenus in the order they should appear on the web
4548 wsmenu.add(msawsmenu);
4549 wsmenu.add(secstrmenu);
4550 wsmenu.add(dismenu);
4551 wsmenu.add(analymenu);
4552 // No search services yet
4553 // wsmenu.add(seqsrchmenu);
4555 javax.swing.SwingUtilities.invokeLater(new Runnable()
4562 webService.removeAll();
4563 // first, add discovered services onto the webservices menu
4564 if (wsmenu.size() > 0)
4566 for (int i = 0, j = wsmenu.size(); i < j; i++)
4568 webService.add(wsmenu.get(i));
4573 webService.add(me.webServiceNoServices);
4575 // TODO: move into separate menu builder class.
4576 boolean new_sspred = false;
4577 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4579 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4580 if (jws2servs != null)
4582 if (jws2servs.hasServices())
4584 jws2servs.attachWSMenuEntry(webService, me);
4585 for (Jws2Instance sv : jws2servs.getServices())
4587 if (sv.description.toLowerCase().contains("jpred"))
4589 for (JMenuItem jmi : legacyItems)
4591 jmi.setVisible(false);
4597 if (jws2servs.isRunning())
4599 JMenuItem tm = new JMenuItem(
4600 "Still discovering JABA Services");
4601 tm.setEnabled(false);
4606 build_urlServiceMenu(me.webService);
4607 build_fetchdbmenu(webService);
4608 for (JMenu item : wsmenu)
4610 if (item.getItemCount() == 0)
4612 item.setEnabled(false);
4616 item.setEnabled(true);
4619 } catch (Exception e)
4622 .debug("Exception during web service menu building process.",
4627 } catch (Exception e)
4630 buildingMenu = false;
4637 * construct any groupURL type service menu entries.
4641 private void build_urlServiceMenu(JMenu webService)
4643 // TODO: remove this code when 2.7 is released
4644 // DEBUG - alignmentView
4646 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4647 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4649 * @Override public void actionPerformed(ActionEvent e) {
4650 * jalview.datamodel.AlignmentView
4651 * .testSelectionViews(af.viewport.getAlignment(),
4652 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4654 * }); webService.add(testAlView);
4656 // TODO: refactor to RestClient discoverer and merge menu entries for
4657 // rest-style services with other types of analysis/calculation service
4658 // SHmmr test client - still being implemented.
4659 // DEBUG - alignmentView
4661 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4664 client.attachWSMenuEntry(
4665 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4671 * Searches selected sequences for xRef products and builds the Show
4672 * Cross-References menu (formerly called Show Products)
4674 * @return true if Show Cross-references menu should be enabled.
4676 public boolean canShowProducts()
4678 SequenceI[] selection = viewport.getSequenceSelection();
4679 AlignmentI dataset = viewport.getAlignment().getDataset();
4680 boolean showp = false;
4683 showProducts.removeAll();
4684 final boolean dna = viewport.getAlignment().isNucleotide();
4685 String[] ptypes = (selection == null || selection.length == 0) ? null
4686 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4688 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4691 final AlignFrame af = this;
4692 final String source = ptypes[t];
4693 JMenuItem xtype = new JMenuItem(ptypes[t]);
4694 xtype.addActionListener(new ActionListener()
4698 public void actionPerformed(ActionEvent e)
4700 showProductsFor(af.viewport.getSequenceSelection(), dna, source);
4704 showProducts.add(xtype);
4706 showProducts.setVisible(showp);
4707 showProducts.setEnabled(showp);
4708 } catch (Exception e)
4710 jalview.bin.Cache.log
4711 .warn("canShowProducts threw an exception - please report to help@jalview.org",
4718 protected void showProductsFor(final SequenceI[] sel, final boolean dna,
4719 final String source)
4721 Runnable foo = new Runnable()
4727 final long sttime = System.currentTimeMillis();
4728 AlignFrame.this.setProgressBar(MessageManager.formatMessage(
4729 "status.searching_for_sequences_from",
4730 new Object[] { source }), sttime);
4734 * 'peer' sequences are any to add to this alignment, for example
4735 * alternative protein products for my protein's gene
4737 List<SequenceI> addedPeers = new ArrayList<SequenceI>();
4738 AlignmentI alignment = AlignFrame.this.getViewport()
4740 Alignment xrefs = CrossRef.findXrefSequences(sel, dna, source,
4741 alignment, addedPeers);
4745 * figure out colour scheme if any to apply to features
4747 ASequenceFetcher sftch = new SequenceFetcher();
4748 List<DbSourceProxy> proxies = sftch.getSourceProxy(source);
4749 FeatureSettingsModelI featureColourScheme = null;
4750 for (DbSourceProxy proxy : proxies)
4752 FeatureSettingsModelI preferredColours = proxy
4753 .getFeatureColourScheme();
4754 if (preferredColours != null)
4756 featureColourScheme = preferredColours;
4760 AlignmentI al = makeCrossReferencesAlignment(
4761 alignment.getDataset(), xrefs);
4763 AlignFrame newFrame = new AlignFrame(al, DEFAULT_WIDTH,
4765 String newtitle = String.format("%s %s %s",
4766 MessageManager.getString(dna ? "label.proteins"
4767 : "label.nucleotides"), MessageManager
4768 .getString("label.for"), getTitle());
4769 newFrame.setTitle(newtitle);
4771 boolean asSplitFrame = Cache.getDefault(
4772 Preferences.ENABLE_SPLIT_FRAME, true);
4776 * Make a copy of this alignment (sharing the same dataset
4777 * sequences). If we are DNA, drop introns and update mappings
4779 AlignmentI copyAlignment = null;
4780 final SequenceI[] sequenceSelection = AlignFrame.this.viewport
4781 .getSequenceSelection();
4782 List<AlignedCodonFrame> cf = xrefs.getCodonFrames();
4785 copyAlignment = AlignmentUtils.makeCdsAlignment(
4786 sequenceSelection, cf, alignment);
4787 if (copyAlignment.getHeight() == 0)
4789 System.err.println("Failed to make CDS alignment");
4791 al.getCodonFrames().clear();
4792 al.getCodonFrames().addAll(cf);
4796 copyAlignment = new Alignment(new Alignment(
4797 sequenceSelection));
4798 copyAlignment.getCodonFrames().addAll(cf);
4800 copyAlignment.setGapCharacter(AlignFrame.this.viewport
4801 .getGapCharacter());
4802 StructureSelectionManager ssm = StructureSelectionManager
4803 .getStructureSelectionManager(Desktop.instance);
4804 ssm.registerMappings(cf);
4807 * add in any extra 'peer' sequences discovered
4808 * (e.g. alternative protein products)
4810 for (SequenceI peer : addedPeers)
4812 copyAlignment.addSequence(peer);
4815 if (copyAlignment.getHeight() > 0)
4818 * align protein to dna
4820 // FIXME what if the dna is not aligned :-O
4823 al.alignAs(copyAlignment);
4828 * align cdna to protein - currently only if
4829 * fetching and aligning Ensembl transcripts!
4831 if (DBRefSource.ENSEMBL.equalsIgnoreCase(source))
4833 copyAlignment.alignAs(al);
4837 AlignFrame copyThis = new AlignFrame(copyAlignment,
4838 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
4839 copyThis.setTitle(AlignFrame.this.getTitle());
4841 boolean showSequenceFeatures = viewport
4842 .isShowSequenceFeatures();
4843 newFrame.setShowSeqFeatures(showSequenceFeatures);
4844 copyThis.setShowSeqFeatures(showSequenceFeatures);
4845 FeatureRenderer myFeatureStyling = alignPanel.getSeqPanel().seqCanvas
4846 .getFeatureRenderer();
4849 * copy feature rendering settings to split frame
4851 newFrame.alignPanel.getSeqPanel().seqCanvas
4852 .getFeatureRenderer().transferSettings(
4854 copyThis.alignPanel.getSeqPanel().seqCanvas
4855 .getFeatureRenderer().transferSettings(
4859 * apply 'database source' feature configuration
4862 // TODO is this the feature colouring for the original
4863 // alignment or the fetched xrefs? either could be Ensembl
4864 newFrame.getViewport().applyFeaturesStyle(
4865 featureColourScheme);
4866 copyThis.getViewport().applyFeaturesStyle(
4867 featureColourScheme);
4869 SplitFrame sf = new SplitFrame(dna ? copyThis : newFrame,
4870 dna ? newFrame : copyThis);
4871 newFrame.setVisible(true);
4872 copyThis.setVisible(true);
4873 String linkedTitle = MessageManager
4874 .getString("label.linked_view_title");
4875 Desktop.addInternalFrame(sf, linkedTitle, -1, -1);
4881 Desktop.addInternalFrame(newFrame, newtitle, DEFAULT_WIDTH,
4887 System.err.println("No Sequences generated for xRef type "
4890 } catch (Exception e)
4892 jalview.bin.Cache.log.error(
4893 "Exception when finding crossreferences", e);
4894 } catch (OutOfMemoryError e)
4896 new OOMWarning("whilst fetching crossreferences", e);
4899 jalview.bin.Cache.log.error("Error when finding crossreferences",
4902 AlignFrame.this.setProgressBar(MessageManager.formatMessage(
4903 "status.finished_searching_for_sequences_from",
4904 new Object[] { source }), sttime);
4908 * Makes an alignment containing the given sequences. If this is of the
4909 * same type as the given dataset (nucleotide/protein), then the new
4910 * alignment shares the same dataset, and its dataset sequences are added
4911 * to it. Otherwise a new dataset sequence is created for the
4918 protected AlignmentI makeCrossReferencesAlignment(AlignmentI dataset,
4921 boolean sameType = dataset.isNucleotide() == seqs.isNucleotide();
4923 SequenceI[] sprods = new SequenceI[seqs.getHeight()];
4924 for (int s = 0; s < sprods.length; s++)
4926 sprods[s] = (seqs.getSequenceAt(s)).deriveSequence();
4929 if (dataset.getSequences() == null
4930 || !dataset.getSequences().contains(
4931 sprods[s].getDatasetSequence()))
4933 dataset.addSequence(sprods[s].getDatasetSequence());
4936 sprods[s].updatePDBIds();
4938 Alignment al = new Alignment(sprods);
4941 al.setDataset((Alignment) dataset);
4945 al.createDatasetAlignment();
4951 Thread frunner = new Thread(foo);
4955 public boolean canShowTranslationProducts(SequenceI[] selection,
4956 AlignmentI alignment)
4961 return (jalview.analysis.Dna.canTranslate(selection,
4962 viewport.getViewAsVisibleContigs(true)));
4963 } catch (Exception e)
4965 jalview.bin.Cache.log
4966 .warn("canTranslate threw an exception - please report to help@jalview.org",
4973 * Construct and display a new frame containing the translation of this
4974 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4977 public void showTranslation_actionPerformed(ActionEvent e)
4979 AlignmentI al = null;
4982 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4984 al = dna.translateCdna();
4985 } catch (Exception ex)
4987 jalview.bin.Cache.log.error(
4988 "Exception during translation. Please report this !", ex);
4989 final String msg = MessageManager
4990 .getString("label.error_when_translating_sequences_submit_bug_report");
4991 final String errorTitle = MessageManager
4992 .getString("label.implementation_error")
4993 + MessageManager.getString("translation_failed");
4994 JOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4995 JOptionPane.ERROR_MESSAGE);
4998 if (al == null || al.getHeight() == 0)
5000 final String msg = MessageManager
5001 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
5002 final String errorTitle = MessageManager
5003 .getString("label.translation_failed");
5004 JOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
5005 JOptionPane.WARNING_MESSAGE);
5009 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
5010 af.setFileFormat(this.currentFileFormat);
5011 final String newTitle = MessageManager.formatMessage(
5012 "label.translation_of_params",
5013 new Object[] { this.getTitle() });
5014 af.setTitle(newTitle);
5015 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
5017 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
5018 viewport.openSplitFrame(af, new Alignment(seqs));
5022 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
5029 * Set the file format
5033 public void setFileFormat(String fileFormat)
5035 this.currentFileFormat = fileFormat;
5039 * Try to load a features file onto the alignment.
5042 * contents or path to retrieve file
5044 * access mode of file (see jalview.io.AlignFile)
5045 * @return true if features file was parsed correctly.
5047 public boolean parseFeaturesFile(String file, String type)
5049 return avc.parseFeaturesFile(file, type,
5050 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
5055 public void refreshFeatureUI(boolean enableIfNecessary)
5057 // note - currently this is only still here rather than in the controller
5058 // because of the featureSettings hard reference that is yet to be
5060 if (enableIfNecessary)
5062 viewport.setShowSequenceFeatures(true);
5063 showSeqFeatures.setSelected(true);
5069 public void dragEnter(DropTargetDragEvent evt)
5074 public void dragExit(DropTargetEvent evt)
5079 public void dragOver(DropTargetDragEvent evt)
5084 public void dropActionChanged(DropTargetDragEvent evt)
5089 public void drop(DropTargetDropEvent evt)
5091 Transferable t = evt.getTransferable();
5092 java.util.List files = null;
5096 DataFlavor uriListFlavor = new DataFlavor(
5097 "text/uri-list;class=java.lang.String");
5098 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
5100 // Works on Windows and MacOSX
5101 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
5102 files = (java.util.List) t
5103 .getTransferData(DataFlavor.javaFileListFlavor);
5105 else if (t.isDataFlavorSupported(uriListFlavor))
5107 // This is used by Unix drag system
5108 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
5109 String data = (String) t.getTransferData(uriListFlavor);
5110 files = new java.util.ArrayList(1);
5111 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
5112 data, "\r\n"); st.hasMoreTokens();)
5114 String s = st.nextToken();
5115 if (s.startsWith("#"))
5117 // the line is a comment (as per the RFC 2483)
5121 java.net.URI uri = new java.net.URI(s);
5122 // check to see if we can handle this kind of URI
5123 if (uri.getScheme().toLowerCase().startsWith("http"))
5125 files.add(uri.toString());
5129 // otherwise preserve old behaviour: catch all for file objects
5130 java.io.File file = new java.io.File(uri);
5131 files.add(file.toString());
5135 } catch (Exception e)
5137 e.printStackTrace();
5143 // check to see if any of these files have names matching sequences in
5145 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5146 .getAlignment().getSequencesArray());
5148 * Object[] { String,SequenceI}
5150 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
5151 ArrayList<String> filesnotmatched = new ArrayList<String>();
5152 for (int i = 0; i < files.size(); i++)
5154 String file = files.get(i).toString();
5156 String protocol = FormatAdapter.checkProtocol(file);
5157 if (protocol == jalview.io.FormatAdapter.FILE)
5159 File fl = new File(file);
5160 pdbfn = fl.getName();
5162 else if (protocol == jalview.io.FormatAdapter.URL)
5164 URL url = new URL(file);
5165 pdbfn = url.getFile();
5167 if (pdbfn.length() > 0)
5169 // attempt to find a match in the alignment
5170 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5171 int l = 0, c = pdbfn.indexOf(".");
5172 while (mtch == null && c != -1)
5177 } while ((c = pdbfn.indexOf(".", l)) > l);
5180 pdbfn = pdbfn.substring(0, l);
5182 mtch = idm.findAllIdMatches(pdbfn);
5189 type = new IdentifyFile().identify(file, protocol);
5190 } catch (Exception ex)
5196 if (type.equalsIgnoreCase("PDB"))
5198 filesmatched.add(new Object[] { file, protocol, mtch });
5203 // File wasn't named like one of the sequences or wasn't a PDB file.
5204 filesnotmatched.add(file);
5208 if (filesmatched.size() > 0)
5210 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
5216 "label.automatically_associate_pdb_files_with_sequences_same_name",
5217 new Object[] { Integer
5223 .getString("label.automatically_associate_pdb_files_by_name"),
5224 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
5227 for (Object[] fm : filesmatched)
5229 // try and associate
5230 // TODO: may want to set a standard ID naming formalism for
5231 // associating PDB files which have no IDs.
5232 for (SequenceI toassoc : (SequenceI[]) fm[2])
5234 PDBEntry pe = new AssociatePdbFileWithSeq()
5235 .associatePdbWithSeq((String) fm[0],
5236 (String) fm[1], toassoc, false,
5240 System.err.println("Associated file : "
5241 + ((String) fm[0]) + " with "
5242 + toassoc.getDisplayId(true));
5246 alignPanel.paintAlignment(true);
5250 if (filesnotmatched.size() > 0)
5253 && (Cache.getDefault(
5254 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
5260 "label.ignore_unmatched_dropped_files_info",
5261 new Object[] { Integer
5268 .getString("label.ignore_unmatched_dropped_files"),
5269 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
5273 for (String fn : filesnotmatched)
5275 loadJalviewDataFile(fn, null, null, null);
5279 } catch (Exception ex)
5281 ex.printStackTrace();
5287 * Attempt to load a "dropped" file or URL string: First by testing whether
5288 * it's an Annotation file, then a JNet file, and finally a features file. If
5289 * all are false then the user may have dropped an alignment file onto this
5293 * either a filename or a URL string.
5295 public void loadJalviewDataFile(String file, String protocol,
5296 String format, SequenceI assocSeq)
5300 if (protocol == null)
5302 protocol = FormatAdapter.checkProtocol(file);
5304 // if the file isn't identified, or not positively identified as some
5305 // other filetype (PFAM is default unidentified alignment file type) then
5306 // try to parse as annotation.
5307 boolean isAnnotation = (format == null || format
5308 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
5309 .annotateAlignmentView(viewport, file, protocol) : false;
5313 // first see if its a T-COFFEE score file
5314 TCoffeeScoreFile tcf = null;
5317 tcf = new TCoffeeScoreFile(file, protocol);
5320 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5322 tcoffeeColour.setEnabled(true);
5323 tcoffeeColour.setSelected(true);
5324 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5325 isAnnotation = true;
5327 .setText(MessageManager
5328 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5332 // some problem - if no warning its probable that the ID matching
5333 // process didn't work
5337 tcf.getWarningMessage() == null ? MessageManager
5338 .getString("label.check_file_matches_sequence_ids_alignment")
5339 : tcf.getWarningMessage(),
5341 .getString("label.problem_reading_tcoffee_score_file"),
5342 JOptionPane.WARNING_MESSAGE);
5349 } catch (Exception x)
5352 .debug("Exception when processing data source as T-COFFEE score file",
5358 // try to see if its a JNet 'concise' style annotation file *before*
5360 // try to parse it as a features file
5363 format = new IdentifyFile().identify(file, protocol);
5365 if (format.equalsIgnoreCase("JnetFile"))
5367 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5369 new JnetAnnotationMaker();
5370 JnetAnnotationMaker.add_annotation(predictions,
5371 viewport.getAlignment(), 0, false);
5372 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
5373 viewport.getAlignment().setSeqrep(repseq);
5374 ColumnSelection cs = new ColumnSelection();
5375 cs.hideInsertionsFor(repseq);
5376 viewport.setColumnSelection(cs);
5377 isAnnotation = true;
5379 else if (IdentifyFile.FeaturesFile.equals(format))
5381 if (parseFeaturesFile(file, protocol))
5383 alignPanel.paintAlignment(true);
5388 new FileLoader().LoadFile(viewport, file, protocol, format);
5395 alignPanel.adjustAnnotationHeight();
5396 viewport.updateSequenceIdColours();
5397 buildSortByAnnotationScoresMenu();
5398 alignPanel.paintAlignment(true);
5400 } catch (Exception ex)
5402 ex.printStackTrace();
5403 } catch (OutOfMemoryError oom)
5408 } catch (Exception x)
5413 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5414 : "using " + protocol + " from " + file)
5416 + (format != null ? "(parsing as '" + format
5417 + "' file)" : ""), oom, Desktop.desktop);
5422 * Method invoked by the ChangeListener on the tabbed pane, in other words
5423 * when a different tabbed pane is selected by the user or programmatically.
5426 public void tabSelectionChanged(int index)
5430 alignPanel = alignPanels.get(index);
5431 viewport = alignPanel.av;
5432 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5433 setMenusFromViewport(viewport);
5437 * If there is a frame linked to this one in a SplitPane, switch it to the
5438 * same view tab index. No infinite recursion of calls should happen, since
5439 * tabSelectionChanged() should not get invoked on setting the selected
5440 * index to an unchanged value. Guard against setting an invalid index
5441 * before the new view peer tab has been created.
5443 final AlignViewportI peer = viewport.getCodingComplement();
5446 AlignFrame linkedAlignFrame = ((AlignViewport) peer).getAlignPanel().alignFrame;
5447 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5449 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5455 * On right mouse click on view tab, prompt for and set new view name.
5458 public void tabbedPane_mousePressed(MouseEvent e)
5460 if (SwingUtilities.isRightMouseButton(e))
5462 String msg = MessageManager.getString("label.enter_view_name");
5463 String reply = JOptionPane.showInternalInputDialog(this, msg, msg,
5464 JOptionPane.QUESTION_MESSAGE);
5468 viewport.viewName = reply;
5469 // TODO warn if reply is in getExistingViewNames()?
5470 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5475 public AlignViewport getCurrentView()
5481 * Open the dialog for regex description parsing.
5484 protected void extractScores_actionPerformed(ActionEvent e)
5486 ParseProperties pp = new jalview.analysis.ParseProperties(
5487 viewport.getAlignment());
5488 // TODO: verify regex and introduce GUI dialog for version 2.5
5489 // if (pp.getScoresFromDescription("col", "score column ",
5490 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5492 if (pp.getScoresFromDescription("description column",
5493 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5495 buildSortByAnnotationScoresMenu();
5503 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5507 protected void showDbRefs_actionPerformed(ActionEvent e)
5509 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5515 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5519 protected void showNpFeats_actionPerformed(ActionEvent e)
5521 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5525 * find the viewport amongst the tabs in this alignment frame and close that
5530 public boolean closeView(AlignViewportI av)
5534 this.closeMenuItem_actionPerformed(false);
5537 Component[] comp = tabbedPane.getComponents();
5538 for (int i = 0; comp != null && i < comp.length; i++)
5540 if (comp[i] instanceof AlignmentPanel)
5542 if (((AlignmentPanel) comp[i]).av == av)
5545 closeView((AlignmentPanel) comp[i]);
5553 protected void build_fetchdbmenu(JMenu webService)
5555 // Temporary hack - DBRef Fetcher always top level ws entry.
5556 // TODO We probably want to store a sequence database checklist in
5557 // preferences and have checkboxes.. rather than individual sources selected
5559 final JMenu rfetch = new JMenu(
5560 MessageManager.getString("action.fetch_db_references"));
5561 rfetch.setToolTipText(MessageManager
5562 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5563 webService.add(rfetch);
5565 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5566 MessageManager.getString("option.trim_retrieved_seqs"));
5567 trimrs.setToolTipText(MessageManager
5568 .getString("label.trim_retrieved_sequences"));
5569 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5570 trimrs.addActionListener(new ActionListener()
5573 public void actionPerformed(ActionEvent e)
5575 trimrs.setSelected(trimrs.isSelected());
5576 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5577 Boolean.valueOf(trimrs.isSelected()).toString());
5581 JMenuItem fetchr = new JMenuItem(
5582 MessageManager.getString("label.standard_databases"));
5583 fetchr.setToolTipText(MessageManager
5584 .getString("label.fetch_embl_uniprot"));
5585 fetchr.addActionListener(new ActionListener()
5589 public void actionPerformed(ActionEvent e)
5591 new Thread(new Runnable()
5597 boolean isNuclueotide = alignPanel.alignFrame.getViewport()
5598 .getAlignment().isNucleotide();
5599 new jalview.ws.DBRefFetcher(alignPanel.av
5600 .getSequenceSelection(), alignPanel.alignFrame, null,
5601 alignPanel.alignFrame.featureSettings, isNuclueotide)
5602 .fetchDBRefs(false);
5610 final AlignFrame me = this;
5611 new Thread(new Runnable()
5616 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5617 .getSequenceFetcherSingleton(me);
5618 javax.swing.SwingUtilities.invokeLater(new Runnable()
5623 String[] dbclasses = sf.getOrderedSupportedSources();
5624 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5625 // jalview.util.QuickSort.sort(otherdb, otherdb);
5626 List<DbSourceProxy> otherdb;
5627 JMenu dfetch = new JMenu();
5628 JMenu ifetch = new JMenu();
5629 JMenuItem fetchr = null;
5630 int comp = 0, icomp = 0, mcomp = 15;
5631 String mname = null;
5633 for (String dbclass : dbclasses)
5635 otherdb = sf.getSourceProxy(dbclass);
5636 // add a single entry for this class, or submenu allowing 'fetch
5638 if (otherdb == null || otherdb.size() < 1)
5642 // List<DbSourceProxy> dbs=otherdb;
5643 // otherdb=new ArrayList<DbSourceProxy>();
5644 // for (DbSourceProxy db:dbs)
5646 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5650 mname = "From " + dbclass;
5652 if (otherdb.size() == 1)
5654 final DbSourceProxy[] dassource = otherdb
5655 .toArray(new DbSourceProxy[0]);
5656 DbSourceProxy src = otherdb.get(0);
5657 fetchr = new JMenuItem(src.getDbSource());
5658 fetchr.addActionListener(new ActionListener()
5662 public void actionPerformed(ActionEvent e)
5664 new Thread(new Runnable()
5670 boolean isNuclueotide = alignPanel.alignFrame
5671 .getViewport().getAlignment()
5673 new jalview.ws.DBRefFetcher(alignPanel.av
5674 .getSequenceSelection(),
5675 alignPanel.alignFrame, dassource,
5676 alignPanel.alignFrame.featureSettings,
5677 isNuclueotide).fetchDBRefs(false);
5683 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5684 MessageManager.formatMessage(
5685 "label.fetch_retrieve_from",
5686 new Object[] { src.getDbName() })));
5692 final DbSourceProxy[] dassource = otherdb
5693 .toArray(new DbSourceProxy[0]);
5695 DbSourceProxy src = otherdb.get(0);
5696 fetchr = new JMenuItem(MessageManager.formatMessage(
5697 "label.fetch_all_param",
5698 new Object[] { src.getDbSource() }));
5699 fetchr.addActionListener(new ActionListener()
5702 public void actionPerformed(ActionEvent e)
5704 new Thread(new Runnable()
5710 boolean isNuclueotide = alignPanel.alignFrame
5711 .getViewport().getAlignment()
5713 new jalview.ws.DBRefFetcher(alignPanel.av
5714 .getSequenceSelection(),
5715 alignPanel.alignFrame, dassource,
5716 alignPanel.alignFrame.featureSettings,
5717 isNuclueotide).fetchDBRefs(false);
5723 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5724 MessageManager.formatMessage(
5725 "label.fetch_retrieve_from_all_sources",
5727 Integer.valueOf(otherdb.size())
5728 .toString(), src.getDbSource(),
5729 src.getDbName() })));
5732 // and then build the rest of the individual menus
5733 ifetch = new JMenu(MessageManager.formatMessage(
5734 "label.source_from_db_source",
5735 new Object[] { src.getDbSource() }));
5737 String imname = null;
5739 for (DbSourceProxy sproxy : otherdb)
5741 String dbname = sproxy.getDbName();
5742 String sname = dbname.length() > 5 ? dbname.substring(0,
5743 5) + "..." : dbname;
5744 String msname = dbname.length() > 10 ? dbname.substring(
5745 0, 10) + "..." : dbname;
5748 imname = MessageManager.formatMessage(
5749 "label.from_msname", new Object[] { sname });
5751 fetchr = new JMenuItem(msname);
5752 final DbSourceProxy[] dassrc = { sproxy };
5753 fetchr.addActionListener(new ActionListener()
5757 public void actionPerformed(ActionEvent e)
5759 new Thread(new Runnable()
5765 boolean isNuclueotide = alignPanel.alignFrame
5766 .getViewport().getAlignment()
5768 new jalview.ws.DBRefFetcher(alignPanel.av
5769 .getSequenceSelection(),
5770 alignPanel.alignFrame, dassrc,
5771 alignPanel.alignFrame.featureSettings,
5772 isNuclueotide).fetchDBRefs(false);
5778 fetchr.setToolTipText("<html>"
5779 + MessageManager.formatMessage(
5780 "label.fetch_retrieve_from", new Object[]
5784 if (++icomp >= mcomp || i == (otherdb.size()))
5786 ifetch.setText(MessageManager.formatMessage(
5787 "label.source_to_target", imname, sname));
5789 ifetch = new JMenu();
5797 if (comp >= mcomp || dbi >= (dbclasses.length))
5799 dfetch.setText(MessageManager.formatMessage(
5800 "label.source_to_target", mname, dbclass));
5802 dfetch = new JMenu();
5815 * Left justify the whole alignment.
5818 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5820 AlignmentI al = viewport.getAlignment();
5822 viewport.firePropertyChange("alignment", null, al);
5826 * Right justify the whole alignment.
5829 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5831 AlignmentI al = viewport.getAlignment();
5833 viewport.firePropertyChange("alignment", null, al);
5837 public void setShowSeqFeatures(boolean b)
5839 showSeqFeatures.setSelected(b);
5840 viewport.setShowSequenceFeatures(b);
5847 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5848 * awt.event.ActionEvent)
5851 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5853 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5854 alignPanel.paintAlignment(true);
5861 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5865 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5867 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5868 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5876 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5877 * .event.ActionEvent)
5880 protected void showGroupConservation_actionPerformed(ActionEvent e)
5882 viewport.setShowGroupConservation(showGroupConservation.getState());
5883 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5890 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5891 * .event.ActionEvent)
5894 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5896 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5897 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5904 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5905 * .event.ActionEvent)
5908 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5910 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5911 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5915 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5917 showSequenceLogo.setState(true);
5918 viewport.setShowSequenceLogo(true);
5919 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5920 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5924 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5926 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5933 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5934 * .event.ActionEvent)
5937 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5939 if (avc.makeGroupsFromSelection())
5941 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5942 alignPanel.updateAnnotation();
5943 alignPanel.paintAlignment(true);
5947 public void clearAlignmentSeqRep()
5949 // TODO refactor alignmentseqrep to controller
5950 if (viewport.getAlignment().hasSeqrep())
5952 viewport.getAlignment().setSeqrep(null);
5953 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5954 alignPanel.updateAnnotation();
5955 alignPanel.paintAlignment(true);
5960 protected void createGroup_actionPerformed(ActionEvent e)
5962 if (avc.createGroup())
5964 alignPanel.alignmentChanged();
5969 protected void unGroup_actionPerformed(ActionEvent e)
5973 alignPanel.alignmentChanged();
5978 * make the given alignmentPanel the currently selected tab
5980 * @param alignmentPanel
5982 public void setDisplayedView(AlignmentPanel alignmentPanel)
5984 if (!viewport.getSequenceSetId().equals(
5985 alignmentPanel.av.getSequenceSetId()))
5989 .getString("error.implementation_error_cannot_show_view_alignment_frame"));
5991 if (tabbedPane != null
5992 && tabbedPane.getTabCount() > 0
5993 && alignPanels.indexOf(alignmentPanel) != tabbedPane
5994 .getSelectedIndex())
5996 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
6001 * Action on selection of menu options to Show or Hide annotations.
6004 * @param forSequences
6005 * update sequence-related annotations
6006 * @param forAlignment
6007 * update non-sequence-related annotations
6010 protected void setAnnotationsVisibility(boolean visible,
6011 boolean forSequences, boolean forAlignment)
6013 for (AlignmentAnnotation aa : alignPanel.getAlignment()
6014 .getAlignmentAnnotation())
6017 * don't display non-positional annotations on an alignment
6019 if (aa.annotations == null)
6023 boolean apply = (aa.sequenceRef == null && forAlignment)
6024 || (aa.sequenceRef != null && forSequences);
6027 aa.visible = visible;
6030 alignPanel.validateAnnotationDimensions(true);
6031 alignPanel.alignmentChanged();
6035 * Store selected annotation sort order for the view and repaint.
6038 protected void sortAnnotations_actionPerformed()
6040 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
6042 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
6043 alignPanel.paintAlignment(true);
6048 * @return alignment panels in this alignment frame
6050 public List<? extends AlignmentViewPanel> getAlignPanels()
6052 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
6056 * Open a new alignment window, with the cDNA associated with this (protein)
6057 * alignment, aligned as is the protein.
6059 protected void viewAsCdna_actionPerformed()
6061 // TODO no longer a menu action - refactor as required
6062 final AlignmentI alignment = getViewport().getAlignment();
6063 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
6064 if (mappings == null)
6068 List<SequenceI> cdnaSeqs = new ArrayList<SequenceI>();
6069 for (SequenceI aaSeq : alignment.getSequences())
6071 for (AlignedCodonFrame acf : mappings)
6073 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
6077 * There is a cDNA mapping for this protein sequence - add to new
6078 * alignment. It will share the same dataset sequence as other mapped
6079 * cDNA (no new mappings need to be created).
6081 final Sequence newSeq = new Sequence(dnaSeq);
6082 newSeq.setDatasetSequence(dnaSeq);
6083 cdnaSeqs.add(newSeq);
6087 if (cdnaSeqs.size() == 0)
6089 // show a warning dialog no mapped cDNA
6092 AlignmentI cdna = new Alignment(cdnaSeqs.toArray(new SequenceI[cdnaSeqs
6094 AlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
6095 AlignFrame.DEFAULT_HEIGHT);
6096 cdna.alignAs(alignment);
6097 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
6099 Desktop.addInternalFrame(alignFrame, newtitle,
6100 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
6104 * Set visibility of dna/protein complement view (available when shown in a
6110 protected void showComplement_actionPerformed(boolean show)
6112 SplitContainerI sf = getSplitViewContainer();
6115 sf.setComplementVisible(this, show);
6120 * Generate the reverse (optionally complemented) of the selected sequences,
6121 * and add them to the alignment
6124 protected void showReverse_actionPerformed(boolean complement)
6126 AlignmentI al = null;
6129 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
6131 al = dna.reverseCdna(complement);
6132 viewport.addAlignment(al, "");
6133 } catch (Exception ex)
6135 System.err.println(ex.getMessage());
6141 class PrintThread extends Thread
6145 public PrintThread(AlignmentPanel ap)
6150 static PageFormat pf;
6155 PrinterJob printJob = PrinterJob.getPrinterJob();
6159 printJob.setPrintable(ap, pf);
6163 printJob.setPrintable(ap);
6166 if (printJob.printDialog())
6171 } catch (Exception PrintException)
6173 PrintException.printStackTrace();