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.AAFrequency;
24 import jalview.analysis.AlignmentSorter;
25 import jalview.analysis.AlignmentUtils;
26 import jalview.analysis.Conservation;
27 import jalview.analysis.CrossRef;
28 import jalview.analysis.Dna;
29 import jalview.analysis.ParseProperties;
30 import jalview.analysis.SequenceIdMatcher;
31 import jalview.api.AlignViewControllerGuiI;
32 import jalview.api.AlignViewControllerI;
33 import jalview.api.AlignViewportI;
34 import jalview.api.AlignmentViewPanel;
35 import jalview.api.FeatureSettingsControllerI;
36 import jalview.api.SplitContainerI;
37 import jalview.api.ViewStyleI;
38 import jalview.api.analysis.ScoreModelI;
39 import jalview.bin.Cache;
40 import jalview.commands.CommandI;
41 import jalview.commands.EditCommand;
42 import jalview.commands.EditCommand.Action;
43 import jalview.commands.OrderCommand;
44 import jalview.commands.RemoveGapColCommand;
45 import jalview.commands.RemoveGapsCommand;
46 import jalview.commands.SlideSequencesCommand;
47 import jalview.commands.TrimRegionCommand;
48 import jalview.datamodel.AlignedCodonFrame;
49 import jalview.datamodel.Alignment;
50 import jalview.datamodel.AlignmentAnnotation;
51 import jalview.datamodel.AlignmentExportData;
52 import jalview.datamodel.AlignmentI;
53 import jalview.datamodel.AlignmentOrder;
54 import jalview.datamodel.AlignmentView;
55 import jalview.datamodel.ColumnSelection;
56 import jalview.datamodel.HiddenSequences;
57 import jalview.datamodel.PDBEntry;
58 import jalview.datamodel.SeqCigar;
59 import jalview.datamodel.Sequence;
60 import jalview.datamodel.SequenceGroup;
61 import jalview.datamodel.SequenceI;
62 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
63 import jalview.io.AlignmentProperties;
64 import jalview.io.AnnotationFile;
65 import jalview.io.BioJsHTMLOutput;
66 import jalview.io.FileLoader;
67 import jalview.io.FormatAdapter;
68 import jalview.io.HtmlSvgOutput;
69 import jalview.io.IdentifyFile;
70 import jalview.io.JalviewFileChooser;
71 import jalview.io.JalviewFileView;
72 import jalview.io.JnetAnnotationMaker;
73 import jalview.io.NewickFile;
74 import jalview.io.TCoffeeScoreFile;
75 import jalview.jbgui.GAlignFrame;
76 import jalview.schemes.Blosum62ColourScheme;
77 import jalview.schemes.BuriedColourScheme;
78 import jalview.schemes.ClustalxColourScheme;
79 import jalview.schemes.ColourSchemeI;
80 import jalview.schemes.ColourSchemeProperty;
81 import jalview.schemes.HelixColourScheme;
82 import jalview.schemes.HydrophobicColourScheme;
83 import jalview.schemes.NucleotideColourScheme;
84 import jalview.schemes.PIDColourScheme;
85 import jalview.schemes.PurinePyrimidineColourScheme;
86 import jalview.schemes.RNAHelicesColourChooser;
87 import jalview.schemes.ResidueProperties;
88 import jalview.schemes.StrandColourScheme;
89 import jalview.schemes.TCoffeeColourScheme;
90 import jalview.schemes.TaylorColourScheme;
91 import jalview.schemes.TurnColourScheme;
92 import jalview.schemes.UserColourScheme;
93 import jalview.schemes.ZappoColourScheme;
94 import jalview.structure.StructureSelectionManager;
95 import jalview.util.MessageManager;
96 import jalview.viewmodel.AlignmentViewport;
97 import jalview.ws.jws1.Discoverer;
98 import jalview.ws.jws2.Jws2Discoverer;
99 import jalview.ws.jws2.jabaws2.Jws2Instance;
100 import jalview.ws.seqfetcher.DbSourceProxy;
102 import java.awt.BorderLayout;
103 import java.awt.Component;
104 import java.awt.Rectangle;
105 import java.awt.Toolkit;
106 import java.awt.datatransfer.Clipboard;
107 import java.awt.datatransfer.DataFlavor;
108 import java.awt.datatransfer.StringSelection;
109 import java.awt.datatransfer.Transferable;
110 import java.awt.dnd.DnDConstants;
111 import java.awt.dnd.DropTargetDragEvent;
112 import java.awt.dnd.DropTargetDropEvent;
113 import java.awt.dnd.DropTargetEvent;
114 import java.awt.dnd.DropTargetListener;
115 import java.awt.event.ActionEvent;
116 import java.awt.event.ActionListener;
117 import java.awt.event.ItemEvent;
118 import java.awt.event.ItemListener;
119 import java.awt.event.KeyAdapter;
120 import java.awt.event.KeyEvent;
121 import java.awt.event.MouseAdapter;
122 import java.awt.event.MouseEvent;
123 import java.awt.print.PageFormat;
124 import java.awt.print.PrinterJob;
125 import java.beans.PropertyChangeEvent;
128 import java.util.ArrayList;
129 import java.util.Arrays;
130 import java.util.Deque;
131 import java.util.Enumeration;
132 import java.util.Hashtable;
133 import java.util.List;
134 import java.util.Set;
135 import java.util.Vector;
137 import javax.swing.JCheckBoxMenuItem;
138 import javax.swing.JEditorPane;
139 import javax.swing.JInternalFrame;
140 import javax.swing.JLayeredPane;
141 import javax.swing.JMenu;
142 import javax.swing.JMenuItem;
143 import javax.swing.JOptionPane;
144 import javax.swing.JRadioButtonMenuItem;
145 import javax.swing.JScrollPane;
146 import javax.swing.SwingUtilities;
152 * @version $Revision$
154 public class AlignFrame extends GAlignFrame implements DropTargetListener,
155 IProgressIndicator, AlignViewControllerGuiI
158 public static final int DEFAULT_WIDTH = 700;
160 public static final int DEFAULT_HEIGHT = 500;
163 * The currently displayed panel (selected tabbed view if more than one)
165 public AlignmentPanel alignPanel;
167 AlignViewport viewport;
169 public AlignViewControllerI avc;
171 List<AlignmentPanel> alignPanels = new ArrayList<AlignmentPanel>();
174 * Last format used to load or save alignments in this window
176 String currentFileFormat = null;
179 * Current filename for this alignment
181 String fileName = null;
184 * Creates a new AlignFrame object with specific width and height.
190 public AlignFrame(AlignmentI al, int width, int height)
192 this(al, null, width, height);
196 * Creates a new AlignFrame object with specific width, height and
202 * @param sequenceSetId
204 public AlignFrame(AlignmentI al, int width, int height,
205 String sequenceSetId)
207 this(al, null, width, height, sequenceSetId);
211 * Creates a new AlignFrame object with specific width, height and
217 * @param sequenceSetId
220 public AlignFrame(AlignmentI al, int width, int height,
221 String sequenceSetId, String viewId)
223 this(al, null, width, height, sequenceSetId, viewId);
227 * new alignment window with hidden columns
231 * @param hiddenColumns
232 * ColumnSelection or null
234 * Width of alignment frame
238 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
239 int width, int height)
241 this(al, hiddenColumns, width, height, null);
246 * Create alignment frame for al with hiddenColumns, a specific width and
247 * height, and specific sequenceId
250 * @param hiddenColumns
253 * @param sequenceSetId
256 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
257 int width, int height, String sequenceSetId)
259 this(al, hiddenColumns, width, height, sequenceSetId, null);
263 * Create alignment frame for al with hiddenColumns, a specific width and
264 * height, and specific sequenceId
267 * @param hiddenColumns
270 * @param sequenceSetId
275 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
276 int width, int height, String sequenceSetId, String viewId)
278 setSize(width, height);
280 if (al.getDataset() == null)
285 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
287 alignPanel = new AlignmentPanel(this, viewport);
290 addAlignmentPanel(alignPanel, true);
294 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
295 ColumnSelection hiddenColumns, int width, int height)
297 setSize(width, height);
299 if (al.getDataset() == null)
304 viewport = new AlignViewport(al, hiddenColumns);
306 if (hiddenSeqs != null && hiddenSeqs.length > 0)
308 viewport.hideSequence(hiddenSeqs);
310 alignPanel = new AlignmentPanel(this, viewport);
311 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 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
340 avc = new jalview.controller.AlignViewController(this, viewport,
342 if (viewport.getAlignmentConservationAnnotation() == null)
344 BLOSUM62Colour.setEnabled(false);
345 conservationMenuItem.setEnabled(false);
346 modifyConservation.setEnabled(false);
347 // PIDColour.setEnabled(false);
348 // abovePIDThreshold.setEnabled(false);
349 // modifyPID.setEnabled(false);
352 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
355 if (sortby.equals("Id"))
357 sortIDMenuItem_actionPerformed(null);
359 else if (sortby.equals("Pairwise Identity"))
361 sortPairwiseMenuItem_actionPerformed(null);
364 if (Desktop.desktop != null)
366 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
367 addServiceListeners();
368 setGUINucleotide(viewport.getAlignment().isNucleotide());
371 setMenusFromViewport(viewport);
372 buildSortByAnnotationScoresMenu();
375 if (viewport.getWrapAlignment())
377 wrapMenuItem_actionPerformed(null);
380 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
382 this.overviewMenuItem_actionPerformed(null);
387 final List<AlignmentPanel> selviews = new ArrayList<AlignmentPanel>();
388 final List<AlignmentPanel> origview = new ArrayList<AlignmentPanel>();
389 final String menuLabel = MessageManager
390 .getString("label.copy_format_from");
391 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
392 new ViewSetProvider()
396 public AlignmentPanel[] getAllAlignmentPanels()
399 origview.add(alignPanel);
400 // make an array of all alignment panels except for this one
401 List<AlignmentPanel> aps = new ArrayList<AlignmentPanel>(
402 Arrays.asList(Desktop.getAlignmentPanels(null)));
403 aps.remove(AlignFrame.this.alignPanel);
404 return aps.toArray(new AlignmentPanel[aps.size()]);
406 }, selviews, new ItemListener()
410 public void itemStateChanged(ItemEvent e)
412 if (origview.size() > 0)
414 final AlignmentPanel ap = origview.get(0);
417 * Copy the ViewStyle of the selected panel to 'this one'.
418 * Don't change value of 'scaleProteinAsCdna' unless copying
421 ViewStyleI vs = selviews.get(0).getAlignViewport()
423 boolean fromSplitFrame = selviews.get(0)
424 .getAlignViewport().getCodingComplement() != null;
427 vs.setScaleProteinAsCdna(ap.getAlignViewport()
428 .getViewStyle().isScaleProteinAsCdna());
430 ap.getAlignViewport().setViewStyle(vs);
433 * Also rescale ViewStyle of SplitFrame complement if there is
434 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
435 * the whole ViewStyle (allow cDNA protein to have different
438 AlignViewportI complement = ap.getAlignViewport()
439 .getCodingComplement();
440 if (complement != null && vs.isScaleProteinAsCdna())
442 AlignFrame af = Desktop.getAlignFrameFor(complement);
443 ((SplitFrame) af.getSplitViewContainer())
445 af.setMenusForViewport();
449 ap.setSelected(true);
450 ap.alignFrame.setMenusForViewport();
455 formatMenu.add(vsel);
460 * Change the filename and format for the alignment, and enable the 'reload'
461 * button functionality.
468 public void setFileName(String file, String format)
471 setFileFormat(format);
472 reload.setEnabled(true);
476 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
479 void addKeyListener()
481 addKeyListener(new KeyAdapter()
484 public void keyPressed(KeyEvent evt)
486 if (viewport.cursorMode
487 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
488 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
489 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
490 && Character.isDigit(evt.getKeyChar()))
492 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
495 switch (evt.getKeyCode())
498 case 27: // escape key
499 deselectAllSequenceMenuItem_actionPerformed(null);
503 case KeyEvent.VK_DOWN:
504 if (evt.isAltDown() || !viewport.cursorMode)
506 moveSelectedSequences(false);
508 if (viewport.cursorMode)
510 alignPanel.getSeqPanel().moveCursor(0, 1);
515 if (evt.isAltDown() || !viewport.cursorMode)
517 moveSelectedSequences(true);
519 if (viewport.cursorMode)
521 alignPanel.getSeqPanel().moveCursor(0, -1);
526 case KeyEvent.VK_LEFT:
527 if (evt.isAltDown() || !viewport.cursorMode)
529 slideSequences(false, alignPanel.getSeqPanel().getKeyboardNo1());
533 alignPanel.getSeqPanel().moveCursor(-1, 0);
538 case KeyEvent.VK_RIGHT:
539 if (evt.isAltDown() || !viewport.cursorMode)
541 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
545 alignPanel.getSeqPanel().moveCursor(1, 0);
549 case KeyEvent.VK_SPACE:
550 if (viewport.cursorMode)
552 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
553 || evt.isShiftDown() || evt.isAltDown());
557 // case KeyEvent.VK_A:
558 // if (viewport.cursorMode)
560 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
561 // //System.out.println("A");
565 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
566 * System.out.println("closing bracket"); } break;
568 case KeyEvent.VK_DELETE:
569 case KeyEvent.VK_BACK_SPACE:
570 if (!viewport.cursorMode)
572 cut_actionPerformed(null);
576 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
577 || evt.isShiftDown() || evt.isAltDown());
583 if (viewport.cursorMode)
585 alignPanel.getSeqPanel().setCursorRow();
589 if (viewport.cursorMode && !evt.isControlDown())
591 alignPanel.getSeqPanel().setCursorColumn();
595 if (viewport.cursorMode)
597 alignPanel.getSeqPanel().setCursorPosition();
601 case KeyEvent.VK_ENTER:
602 case KeyEvent.VK_COMMA:
603 if (viewport.cursorMode)
605 alignPanel.getSeqPanel().setCursorRowAndColumn();
610 if (viewport.cursorMode)
612 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
616 if (viewport.cursorMode)
618 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
623 viewport.cursorMode = !viewport.cursorMode;
624 statusBar.setText(MessageManager.formatMessage(
625 "label.keyboard_editing_mode", new String[]
626 { (viewport.cursorMode ? "on" : "off") }));
627 if (viewport.cursorMode)
629 alignPanel.getSeqPanel().seqCanvas.cursorX = viewport.startRes;
630 alignPanel.getSeqPanel().seqCanvas.cursorY = viewport.startSeq;
632 alignPanel.getSeqPanel().seqCanvas.repaint();
638 Help.showHelpWindow();
639 } catch (Exception ex)
641 ex.printStackTrace();
646 boolean toggleSeqs = !evt.isControlDown();
647 boolean toggleCols = !evt.isShiftDown();
648 toggleHiddenRegions(toggleSeqs, toggleCols);
651 case KeyEvent.VK_PAGE_UP:
652 if (viewport.getWrapAlignment())
654 alignPanel.scrollUp(true);
658 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
659 - viewport.endSeq + viewport.startSeq);
662 case KeyEvent.VK_PAGE_DOWN:
663 if (viewport.getWrapAlignment())
665 alignPanel.scrollUp(false);
669 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
670 + viewport.endSeq - viewport.startSeq);
677 public void keyReleased(KeyEvent evt)
679 switch (evt.getKeyCode())
681 case KeyEvent.VK_LEFT:
682 if (evt.isAltDown() || !viewport.cursorMode)
684 viewport.firePropertyChange("alignment", null, viewport
685 .getAlignment().getSequences());
689 case KeyEvent.VK_RIGHT:
690 if (evt.isAltDown() || !viewport.cursorMode)
692 viewport.firePropertyChange("alignment", null, viewport
693 .getAlignment().getSequences());
701 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
703 ap.alignFrame = this;
704 avc = new jalview.controller.AlignViewController(this, viewport,
709 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
711 int aSize = alignPanels.size();
713 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
715 if (aSize == 1 && ap.av.viewName == null)
717 this.getContentPane().add(ap, BorderLayout.CENTER);
723 setInitialTabVisible();
726 expandViews.setEnabled(true);
727 gatherViews.setEnabled(true);
728 tabbedPane.addTab(ap.av.viewName, ap);
730 ap.setVisible(false);
735 if (ap.av.isPadGaps())
737 ap.av.getAlignment().padGaps();
739 ap.av.updateConservation(ap);
740 ap.av.updateConsensus(ap);
741 ap.av.updateStrucConsensus(ap);
745 public void setInitialTabVisible()
747 expandViews.setEnabled(true);
748 gatherViews.setEnabled(true);
749 tabbedPane.setVisible(true);
750 AlignmentPanel first = alignPanels.get(0);
751 tabbedPane.addTab(first.av.viewName, first);
752 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
755 public AlignViewport getViewport()
760 /* Set up intrinsic listeners for dynamically generated GUI bits. */
761 private void addServiceListeners()
763 final java.beans.PropertyChangeListener thisListener;
764 Desktop.instance.addJalviewPropertyChangeListener("services",
765 thisListener = new java.beans.PropertyChangeListener()
768 public void propertyChange(PropertyChangeEvent evt)
770 // // System.out.println("Discoverer property change.");
771 // if (evt.getPropertyName().equals("services"))
773 SwingUtilities.invokeLater(new Runnable()
780 .println("Rebuild WS Menu for service change");
781 BuildWebServiceMenu();
788 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
791 public void internalFrameClosed(
792 javax.swing.event.InternalFrameEvent evt)
794 System.out.println("deregistering discoverer listener");
795 Desktop.instance.removeJalviewPropertyChangeListener("services",
797 closeMenuItem_actionPerformed(true);
800 // Finally, build the menu once to get current service state
801 new Thread(new Runnable()
806 BuildWebServiceMenu();
812 * Configure menu items that vary according to whether the alignment is
813 * nucleotide or protein
817 public void setGUINucleotide(boolean nucleotide)
819 showTranslation.setVisible(nucleotide);
820 conservationMenuItem.setEnabled(!nucleotide);
821 modifyConservation.setEnabled(!nucleotide);
822 showGroupConservation.setEnabled(!nucleotide);
823 rnahelicesColour.setEnabled(nucleotide);
824 purinePyrimidineColour.setEnabled(nucleotide);
825 showComplementMenuItem.setText(MessageManager
826 .getString(nucleotide ? "label.protein" : "label.nucleotide"));
827 setColourSelected(jalview.bin.Cache.getDefault(
828 nucleotide ? Preferences.DEFAULT_COLOUR_NUC
829 : Preferences.DEFAULT_COLOUR_PROT, "None"));
833 * set up menus for the current viewport. This may be called after any
834 * operation that affects the data in the current view (selection changed,
835 * etc) to update the menus to reflect the new state.
837 public void setMenusForViewport()
839 setMenusFromViewport(viewport);
843 * Need to call this method when tabs are selected for multiple views, or when
844 * loading from Jalview2XML.java
849 void setMenusFromViewport(AlignViewport av)
851 padGapsMenuitem.setSelected(av.isPadGaps());
852 colourTextMenuItem.setSelected(av.isShowColourText());
853 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
854 conservationMenuItem.setSelected(av.getConservationSelected());
855 seqLimits.setSelected(av.getShowJVSuffix());
856 idRightAlign.setSelected(av.isRightAlignIds());
857 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
858 renderGapsMenuItem.setSelected(av.isRenderGaps());
859 wrapMenuItem.setSelected(av.getWrapAlignment());
860 scaleAbove.setVisible(av.getWrapAlignment());
861 scaleLeft.setVisible(av.getWrapAlignment());
862 scaleRight.setVisible(av.getWrapAlignment());
863 annotationPanelMenuItem.setState(av.isShowAnnotation());
865 * Show/hide annotations only enabled if annotation panel is shown
867 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
868 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
869 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
870 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
871 viewBoxesMenuItem.setSelected(av.getShowBoxes());
872 viewTextMenuItem.setSelected(av.getShowText());
873 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
874 showGroupConsensus.setSelected(av.isShowGroupConsensus());
875 showGroupConservation.setSelected(av.isShowGroupConservation());
876 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
877 showSequenceLogo.setSelected(av.isShowSequenceLogo());
878 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
880 setColourSelected(ColourSchemeProperty.getColourName(av
881 .getGlobalColourScheme()));
883 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
884 hiddenMarkers.setState(av.getShowHiddenMarkers());
885 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
886 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
887 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
888 autoCalculate.setSelected(av.autoCalculateConsensus);
889 sortByTree.setSelected(av.sortByTree);
890 listenToViewSelections.setSelected(av.followSelection);
891 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
893 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
894 setShowProductsEnabled();
898 private IProgressIndicator progressBar;
903 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
906 public void setProgressBar(String message, long id)
908 progressBar.setProgressBar(message, id);
912 public void registerHandler(final long id,
913 final IProgressIndicatorHandler handler)
915 progressBar.registerHandler(id, handler);
920 * @return true if any progress bars are still active
923 public boolean operationInProgress()
925 return progressBar.operationInProgress();
929 public void setStatus(String text)
931 statusBar.setText(text);
935 * Added so Castor Mapping file can obtain Jalview Version
937 public String getVersion()
939 return jalview.bin.Cache.getProperty("VERSION");
942 public FeatureRenderer getFeatureRenderer()
944 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
948 public void fetchSequence_actionPerformed(ActionEvent e)
950 new SequenceFetcher(this);
954 public void addFromFile_actionPerformed(ActionEvent e)
956 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
960 public void reload_actionPerformed(ActionEvent e)
962 if (fileName != null)
964 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
965 // originating file's format
966 // TODO: work out how to recover feature settings for correct view(s) when
968 if (currentFileFormat.equals("Jalview"))
970 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
971 for (int i = 0; i < frames.length; i++)
973 if (frames[i] instanceof AlignFrame && frames[i] != this
974 && ((AlignFrame) frames[i]).fileName != null
975 && ((AlignFrame) frames[i]).fileName.equals(fileName))
979 frames[i].setSelected(true);
980 Desktop.instance.closeAssociatedWindows();
981 } catch (java.beans.PropertyVetoException ex)
987 Desktop.instance.closeAssociatedWindows();
989 FileLoader loader = new FileLoader();
990 String protocol = fileName.startsWith("http:") ? "URL" : "File";
991 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
995 Rectangle bounds = this.getBounds();
997 FileLoader loader = new FileLoader();
998 String protocol = fileName.startsWith("http:") ? "URL" : "File";
999 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1000 protocol, currentFileFormat);
1002 newframe.setBounds(bounds);
1003 if (featureSettings != null && featureSettings.isShowing())
1005 final Rectangle fspos = featureSettings.frame.getBounds();
1006 // TODO: need a 'show feature settings' function that takes bounds -
1007 // need to refactor Desktop.addFrame
1008 newframe.featureSettings_actionPerformed(null);
1009 final FeatureSettings nfs = newframe.featureSettings;
1010 SwingUtilities.invokeLater(new Runnable()
1015 nfs.frame.setBounds(fspos);
1018 this.featureSettings.close();
1019 this.featureSettings = null;
1021 this.closeMenuItem_actionPerformed(true);
1027 public void addFromText_actionPerformed(ActionEvent e)
1029 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
1033 public void addFromURL_actionPerformed(ActionEvent e)
1035 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1039 public void save_actionPerformed(ActionEvent e)
1041 if (fileName == null
1042 || (currentFileFormat == null || !jalview.io.FormatAdapter
1043 .isValidIOFormat(currentFileFormat, true))
1044 || fileName.startsWith("http"))
1046 saveAs_actionPerformed(null);
1050 saveAlignment(fileName, currentFileFormat);
1061 public void saveAs_actionPerformed(ActionEvent e)
1063 JalviewFileChooser chooser = new JalviewFileChooser(
1064 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
1065 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
1066 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
1067 currentFileFormat, false);
1069 chooser.setFileView(new JalviewFileView());
1070 chooser.setDialogTitle(MessageManager.getString("label.save_alignment_to_file"));
1071 chooser.setToolTipText(MessageManager.getString("action.save"));
1073 int value = chooser.showSaveDialog(this);
1075 if (value == JalviewFileChooser.APPROVE_OPTION)
1077 currentFileFormat = chooser.getSelectedFormat();
1078 while (currentFileFormat == null)
1081 .showInternalMessageDialog(
1084 .getString("label.select_file_format_before_saving"),
1086 .getString("label.file_format_not_specified"),
1087 JOptionPane.WARNING_MESSAGE);
1088 currentFileFormat = chooser.getSelectedFormat();
1089 value = chooser.showSaveDialog(this);
1090 if (value != JalviewFileChooser.APPROVE_OPTION)
1096 fileName = chooser.getSelectedFile().getPath();
1098 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
1101 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
1102 if (currentFileFormat.indexOf(" ") > -1)
1104 currentFileFormat = currentFileFormat.substring(0,
1105 currentFileFormat.indexOf(" "));
1107 saveAlignment(fileName, currentFileFormat);
1111 public boolean saveAlignment(String file, String format)
1113 boolean success = true;
1115 if (format.equalsIgnoreCase("Jalview"))
1117 String shortName = title;
1119 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1121 shortName = shortName.substring(shortName
1122 .lastIndexOf(java.io.File.separatorChar) + 1);
1125 success = new Jalview2XML().saveAlignment(this, file, shortName);
1127 statusBar.setText(MessageManager.formatMessage(
1128 "label.successfully_saved_to_file_in_format", new Object[]
1129 { fileName, format }));
1134 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1136 warningMessage("Cannot save file " + fileName + " using format "
1137 + format, "Alignment output format not supported");
1138 saveAs_actionPerformed(null);
1139 // JBPNote need to have a raise_gui flag here
1143 AlignmentExportData exportData = getAlignmentForExport(format, viewport);
1144 if (exportData.getSettings().isCancelled())
1148 FormatAdapter f = new FormatAdapter(alignPanel,
1149 exportData.getSettings());
1150 String output = f.formatSequences(format,
1151 exportData.getAlignment(), // class cast exceptions will
1152 // occur in the distant future
1153 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1154 f.getCacheSuffixDefault(format),
1155 viewport.getColumnSelection());
1165 java.io.PrintWriter out = new java.io.PrintWriter(
1166 new java.io.FileWriter(file));
1170 this.setTitle(file);
1171 statusBar.setText(MessageManager.formatMessage(
1172 "label.successfully_saved_to_file_in_format",
1174 { fileName, format }));
1175 } catch (Exception ex)
1178 ex.printStackTrace();
1185 JOptionPane.showInternalMessageDialog(this, MessageManager
1186 .formatMessage("label.couldnt_save_file", new Object[]
1187 { fileName }), MessageManager
1188 .getString("label.error_saving_file"),
1189 JOptionPane.WARNING_MESSAGE);
1196 private void warningMessage(String warning, String title)
1198 if (new jalview.util.Platform().isHeadless())
1200 System.err.println("Warning: " + title + "\nWarning: " + warning);
1205 JOptionPane.showInternalMessageDialog(this, warning, title,
1206 JOptionPane.WARNING_MESSAGE);
1218 protected void outputText_actionPerformed(ActionEvent e)
1221 AlignmentExportData exportData = getAlignmentForExport(
1222 e.getActionCommand(), viewport);
1223 if (exportData.getSettings().isCancelled())
1227 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1228 cap.setForInput(null);
1231 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1233 e.getActionCommand(),
1234 exportData.getAlignment(),
1235 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1236 viewport.getColumnSelection()));
1237 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1238 "label.alignment_output_command", new Object[]
1239 { e.getActionCommand() }), 600, 500);
1240 } catch (OutOfMemoryError oom)
1242 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1248 public static AlignmentExportData getAlignmentForExport(String exportFomat,
1249 AlignViewportI viewport)
1251 AlignmentI alignmentToExport = null;
1252 String[] omitHidden = null;
1253 int[] alignmentStartEnd = new int[2];
1255 HiddenSequences hiddenSeqs = viewport.getAlignment()
1256 .getHiddenSequences();
1259 alignmentToExport = viewport.getAlignment();
1260 alignmentStartEnd = new int[]
1261 { 0, alignmentToExport.getWidth() - 1 };
1263 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1264 AlignExportSettings settings = new AlignExportSettings(hasHiddenSeqs,
1265 viewport.hasHiddenColumns(), exportFomat);
1266 settings.isExportAnnotations();
1268 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1270 omitHidden = viewport.getViewAsString(false);
1273 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1275 alignmentToExport = hiddenSeqs.getFullAlignment();
1279 alignmentToExport = viewport.getAlignment();
1280 alignmentStartEnd = getStartEnd(alignmentStartEnd, viewport
1281 .getColumnSelection().getHiddenColumns());
1283 AlignmentExportData ed = new AlignmentExportData(alignmentToExport, omitHidden, alignmentStartEnd,
1288 private static int[] getStartEnd(int[] aligmentStartEnd,
1289 List<int[]> hiddenCols)
1291 int startPos = aligmentStartEnd[0];
1292 int endPos = aligmentStartEnd[1];
1294 int[] lowestRange = new int[2];
1295 int[] higestRange = new int[2];
1297 for (int[] hiddenCol : hiddenCols)
1299 // System.out.println("comparing : " + hiddenCol[0] + "-" + hiddenCol[1]);
1301 lowestRange = (hiddenCol[0] <= startPos) ? hiddenCol : lowestRange;
1302 higestRange = (hiddenCol[1] >= endPos) ? hiddenCol : higestRange;
1304 // System.out.println("min : " + lowestRange[0] + "-" + lowestRange[1]);
1305 // System.out.println("max : " + higestRange[0] + "-" + higestRange[1]);
1307 if (lowestRange[0] == 0 && lowestRange[1] == 0)
1309 startPos = aligmentStartEnd[0];
1313 startPos = lowestRange[1] + 1;
1316 if (higestRange[0] == 0 && higestRange[1] == 0)
1318 endPos = aligmentStartEnd[1];
1322 endPos = higestRange[0];
1325 // System.out.println("Export range : " + minPos + " - " + maxPos);
1327 { startPos, endPos };
1330 public static void main(String[] args)
1332 ArrayList<int[]> hiddenCols = new ArrayList<int[]>();
1333 hiddenCols.add(new int[]
1335 hiddenCols.add(new int[]
1337 hiddenCols.add(new int[]
1339 hiddenCols.add(new int[]
1341 hiddenCols.add(new int[]
1344 int[] x = getStartEnd(new int[]
1345 { 0, 50 }, hiddenCols);
1346 // System.out.println("Export range : " + x[0] + " - " + x[1]);
1356 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1358 new HtmlSvgOutput(null, alignPanel);
1362 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1364 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1365 bjs.exportJalviewAlignmentAsBioJsHtmlFile();
1367 public void createImageMap(File file, String image)
1369 alignPanel.makePNGImageMap(file, image);
1379 public void createPNG(File f)
1381 alignPanel.makePNG(f);
1391 public void createEPS(File f)
1393 alignPanel.makeEPS(f);
1396 public void createSVG(File f)
1398 alignPanel.makeSVG(f);
1401 public void pageSetup_actionPerformed(ActionEvent e)
1403 PrinterJob printJob = PrinterJob.getPrinterJob();
1404 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1414 public void printMenuItem_actionPerformed(ActionEvent e)
1416 // Putting in a thread avoids Swing painting problems
1417 PrintThread thread = new PrintThread(alignPanel);
1422 public void exportFeatures_actionPerformed(ActionEvent e)
1424 new AnnotationExporter().exportFeatures(alignPanel);
1428 public void exportAnnotations_actionPerformed(ActionEvent e)
1430 new AnnotationExporter().exportAnnotations(alignPanel);
1434 public void associatedData_actionPerformed(ActionEvent e)
1436 // Pick the tree file
1437 JalviewFileChooser chooser = new JalviewFileChooser(
1438 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1439 chooser.setFileView(new JalviewFileView());
1440 chooser.setDialogTitle(MessageManager
1441 .getString("label.load_jalview_annotations"));
1442 chooser.setToolTipText(MessageManager
1443 .getString("label.load_jalview_annotations"));
1445 int value = chooser.showOpenDialog(null);
1447 if (value == JalviewFileChooser.APPROVE_OPTION)
1449 String choice = chooser.getSelectedFile().getPath();
1450 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1451 loadJalviewDataFile(choice, null, null, null);
1457 * Close the current view or all views in the alignment frame. If the frame
1458 * only contains one view then the alignment will be removed from memory.
1460 * @param closeAllTabs
1463 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1465 if (alignPanels != null && alignPanels.size() < 2)
1467 closeAllTabs = true;
1472 if (alignPanels != null)
1476 if (this.isClosed())
1478 // really close all the windows - otherwise wait till
1479 // setClosed(true) is called
1480 for (int i = 0; i < alignPanels.size(); i++)
1482 AlignmentPanel ap = alignPanels.get(i);
1489 closeView(alignPanel);
1495 this.setClosed(true);
1497 } catch (Exception ex)
1499 ex.printStackTrace();
1504 * Close the specified panel and close up tabs appropriately.
1506 * @param panelToClose
1508 public void closeView(AlignmentPanel panelToClose)
1510 int index = tabbedPane.getSelectedIndex();
1511 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1512 alignPanels.remove(panelToClose);
1513 panelToClose.closePanel();
1514 panelToClose = null;
1516 tabbedPane.removeTabAt(closedindex);
1517 tabbedPane.validate();
1519 if (index > closedindex || index == tabbedPane.getTabCount())
1521 // modify currently selected tab index if necessary.
1525 this.tabSelectionChanged(index);
1531 void updateEditMenuBar()
1534 if (viewport.getHistoryList().size() > 0)
1536 undoMenuItem.setEnabled(true);
1537 CommandI command = viewport.getHistoryList().peek();
1538 undoMenuItem.setText(MessageManager.formatMessage(
1539 "label.undo_command", new Object[]
1540 { command.getDescription() }));
1544 undoMenuItem.setEnabled(false);
1545 undoMenuItem.setText(MessageManager.getString("action.undo"));
1548 if (viewport.getRedoList().size() > 0)
1550 redoMenuItem.setEnabled(true);
1552 CommandI command = viewport.getRedoList().peek();
1553 redoMenuItem.setText(MessageManager.formatMessage(
1554 "label.redo_command", new Object[]
1555 { command.getDescription() }));
1559 redoMenuItem.setEnabled(false);
1560 redoMenuItem.setText(MessageManager.getString("action.redo"));
1564 public void addHistoryItem(CommandI command)
1566 if (command.getSize() > 0)
1568 viewport.addToHistoryList(command);
1569 viewport.clearRedoList();
1570 updateEditMenuBar();
1571 viewport.updateHiddenColumns();
1572 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1573 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1574 // viewport.getColumnSelection()
1575 // .getHiddenColumns().size() > 0);
1581 * @return alignment objects for all views
1583 AlignmentI[] getViewAlignments()
1585 if (alignPanels != null)
1587 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1589 for (AlignmentPanel ap : alignPanels)
1591 als[i++] = ap.av.getAlignment();
1595 if (viewport != null)
1597 return new AlignmentI[]
1598 { viewport.getAlignment() };
1610 protected void undoMenuItem_actionPerformed(ActionEvent e)
1612 if (viewport.getHistoryList().isEmpty())
1616 CommandI command = viewport.getHistoryList().pop();
1617 viewport.addToRedoList(command);
1618 command.undoCommand(getViewAlignments());
1620 AlignmentViewport originalSource = getOriginatingSource(command);
1621 updateEditMenuBar();
1623 if (originalSource != null)
1625 if (originalSource != viewport)
1628 .warn("Implementation worry: mismatch of viewport origin for undo");
1630 originalSource.updateHiddenColumns();
1631 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1633 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1634 // viewport.getColumnSelection()
1635 // .getHiddenColumns().size() > 0);
1636 originalSource.firePropertyChange("alignment", null, originalSource
1637 .getAlignment().getSequences());
1648 protected void redoMenuItem_actionPerformed(ActionEvent e)
1650 if (viewport.getRedoList().size() < 1)
1655 CommandI command = viewport.getRedoList().pop();
1656 viewport.addToHistoryList(command);
1657 command.doCommand(getViewAlignments());
1659 AlignmentViewport originalSource = getOriginatingSource(command);
1660 updateEditMenuBar();
1662 if (originalSource != null)
1665 if (originalSource != viewport)
1668 .warn("Implementation worry: mismatch of viewport origin for redo");
1670 originalSource.updateHiddenColumns();
1671 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1673 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1674 // viewport.getColumnSelection()
1675 // .getHiddenColumns().size() > 0);
1676 originalSource.firePropertyChange("alignment", null, originalSource
1677 .getAlignment().getSequences());
1681 AlignmentViewport getOriginatingSource(CommandI command)
1683 AlignmentViewport originalSource = null;
1684 // For sequence removal and addition, we need to fire
1685 // the property change event FROM the viewport where the
1686 // original alignment was altered
1687 AlignmentI al = null;
1688 if (command instanceof EditCommand)
1690 EditCommand editCommand = (EditCommand) command;
1691 al = editCommand.getAlignment();
1692 List<Component> comps = PaintRefresher.components.get(viewport
1693 .getSequenceSetId());
1695 for (Component comp : comps)
1697 if (comp instanceof AlignmentPanel)
1699 if (al == ((AlignmentPanel) comp).av.getAlignment())
1701 originalSource = ((AlignmentPanel) comp).av;
1708 if (originalSource == null)
1710 // The original view is closed, we must validate
1711 // the current view against the closed view first
1714 PaintRefresher.validateSequences(al, viewport.getAlignment());
1717 originalSource = viewport;
1720 return originalSource;
1729 public void moveSelectedSequences(boolean up)
1731 SequenceGroup sg = viewport.getSelectionGroup();
1737 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1738 viewport.getHiddenRepSequences(), up);
1739 alignPanel.paintAlignment(true);
1742 synchronized void slideSequences(boolean right, int size)
1744 List<SequenceI> sg = new ArrayList<SequenceI>();
1745 if (viewport.cursorMode)
1747 sg.add(viewport.getAlignment().getSequenceAt(
1748 alignPanel.getSeqPanel().seqCanvas.cursorY));
1750 else if (viewport.getSelectionGroup() != null
1751 && viewport.getSelectionGroup().getSize() != viewport
1752 .getAlignment().getHeight())
1754 sg = viewport.getSelectionGroup().getSequences(
1755 viewport.getHiddenRepSequences());
1763 List<SequenceI> invertGroup = new ArrayList<SequenceI>();
1765 for (SequenceI seq : viewport.getAlignment().getSequences())
1767 if (!sg.contains(seq))
1769 invertGroup.add(seq);
1773 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1775 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1776 for (int i = 0; i < invertGroup.size(); i++)
1778 seqs2[i] = invertGroup.get(i);
1781 SlideSequencesCommand ssc;
1784 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1785 size, viewport.getGapCharacter());
1789 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1790 size, viewport.getGapCharacter());
1793 int groupAdjustment = 0;
1794 if (ssc.getGapsInsertedBegin() && right)
1796 if (viewport.cursorMode)
1798 alignPanel.getSeqPanel().moveCursor(size, 0);
1802 groupAdjustment = size;
1805 else if (!ssc.getGapsInsertedBegin() && !right)
1807 if (viewport.cursorMode)
1809 alignPanel.getSeqPanel().moveCursor(-size, 0);
1813 groupAdjustment = -size;
1817 if (groupAdjustment != 0)
1819 viewport.getSelectionGroup().setStartRes(
1820 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1821 viewport.getSelectionGroup().setEndRes(
1822 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1826 * just extend the last slide command if compatible; but not if in
1827 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1829 boolean appendHistoryItem = false;
1830 Deque<CommandI> historyList = viewport.getHistoryList();
1831 boolean inSplitFrame = getSplitViewContainer() != null;
1832 if (!inSplitFrame && historyList != null
1833 && historyList.size() > 0
1834 && historyList.peek() instanceof SlideSequencesCommand)
1836 appendHistoryItem = ssc
1837 .appendSlideCommand((SlideSequencesCommand) historyList
1841 if (!appendHistoryItem)
1843 addHistoryItem(ssc);
1856 protected void copy_actionPerformed(ActionEvent e)
1859 if (viewport.getSelectionGroup() == null)
1863 // TODO: preserve the ordering of displayed alignment annotation in any
1864 // internal paste (particularly sequence associated annotation)
1865 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1866 String[] omitHidden = null;
1868 if (viewport.hasHiddenColumns())
1870 omitHidden = viewport.getViewAsString(true);
1873 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1876 StringSelection ss = new StringSelection(output);
1880 jalview.gui.Desktop.internalCopy = true;
1881 // Its really worth setting the clipboard contents
1882 // to empty before setting the large StringSelection!!
1883 Toolkit.getDefaultToolkit().getSystemClipboard()
1884 .setContents(new StringSelection(""), null);
1886 Toolkit.getDefaultToolkit().getSystemClipboard()
1887 .setContents(ss, Desktop.instance);
1888 } catch (OutOfMemoryError er)
1890 new OOMWarning("copying region", er);
1894 ArrayList<int[]> hiddenColumns = null;
1895 if (viewport.hasHiddenColumns())
1897 hiddenColumns = new ArrayList<int[]>();
1898 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1899 .getSelectionGroup().getEndRes();
1900 for (int[] region : viewport.getColumnSelection().getHiddenColumns())
1902 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1904 hiddenColumns.add(new int[]
1905 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1910 Desktop.jalviewClipboard = new Object[]
1911 { seqs, viewport.getAlignment().getDataset(), hiddenColumns };
1912 statusBar.setText(MessageManager.formatMessage(
1913 "label.copied_sequences_to_clipboard", new Object[]
1914 { Integer.valueOf(seqs.length).toString() }));
1924 protected void pasteNew_actionPerformed(ActionEvent e)
1936 protected void pasteThis_actionPerformed(ActionEvent e)
1942 * Paste contents of Jalview clipboard
1944 * @param newAlignment
1945 * true to paste to a new alignment, otherwise add to this.
1947 void paste(boolean newAlignment)
1949 boolean externalPaste = true;
1952 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1953 Transferable contents = c.getContents(this);
1955 if (contents == null)
1963 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1964 if (str.length() < 1)
1969 format = new IdentifyFile().Identify(str, "Paste");
1971 } catch (OutOfMemoryError er)
1973 new OOMWarning("Out of memory pasting sequences!!", er);
1977 SequenceI[] sequences;
1978 boolean annotationAdded = false;
1979 AlignmentI alignment = null;
1981 if (Desktop.jalviewClipboard != null)
1983 // The clipboard was filled from within Jalview, we must use the
1985 // And dataset from the copied alignment
1986 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1987 // be doubly sure that we create *new* sequence objects.
1988 sequences = new SequenceI[newseq.length];
1989 for (int i = 0; i < newseq.length; i++)
1991 sequences[i] = new Sequence(newseq[i]);
1993 alignment = new Alignment(sequences);
1994 externalPaste = false;
1998 // parse the clipboard as an alignment.
1999 alignment = new FormatAdapter().readFile(str, "Paste", format);
2000 sequences = alignment.getSequencesArray();
2004 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
2010 if (Desktop.jalviewClipboard != null)
2012 // dataset is inherited
2013 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2017 // new dataset is constructed
2018 alignment.setDataset(null);
2020 alwidth = alignment.getWidth() + 1;
2024 AlignmentI pastedal = alignment; // preserve pasted alignment object
2025 // Add pasted sequences and dataset into existing alignment.
2026 alignment = viewport.getAlignment();
2027 alwidth = alignment.getWidth() + 1;
2028 // decide if we need to import sequences from an existing dataset
2029 boolean importDs = Desktop.jalviewClipboard != null
2030 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2031 // importDs==true instructs us to copy over new dataset sequences from
2032 // an existing alignment
2033 Vector newDs = (importDs) ? new Vector() : null; // used to create
2034 // minimum dataset set
2036 for (int i = 0; i < sequences.length; i++)
2040 newDs.addElement(null);
2042 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2044 if (importDs && ds != null)
2046 if (!newDs.contains(ds))
2048 newDs.setElementAt(ds, i);
2049 ds = new Sequence(ds);
2050 // update with new dataset sequence
2051 sequences[i].setDatasetSequence(ds);
2055 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2060 // copy and derive new dataset sequence
2061 sequences[i] = sequences[i].deriveSequence();
2062 alignment.getDataset().addSequence(
2063 sequences[i].getDatasetSequence());
2064 // TODO: avoid creation of duplicate dataset sequences with a
2065 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2067 alignment.addSequence(sequences[i]); // merges dataset
2071 newDs.clear(); // tidy up
2073 if (alignment.getAlignmentAnnotation() != null)
2075 for (AlignmentAnnotation alan : alignment
2076 .getAlignmentAnnotation())
2078 if (alan.graphGroup > fgroup)
2080 fgroup = alan.graphGroup;
2084 if (pastedal.getAlignmentAnnotation() != null)
2086 // Add any annotation attached to alignment.
2087 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2088 for (int i = 0; i < alann.length; i++)
2090 annotationAdded = true;
2091 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2093 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2094 if (newann.graphGroup > -1)
2096 if (newGraphGroups.size() <= newann.graphGroup
2097 || newGraphGroups.get(newann.graphGroup) == null)
2099 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2101 newGraphGroups.add(q, null);
2103 newGraphGroups.set(newann.graphGroup, new Integer(
2106 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2110 newann.padAnnotation(alwidth);
2111 alignment.addAnnotation(newann);
2121 addHistoryItem(new EditCommand(
2122 MessageManager.getString("label.add_sequences"),
2124 sequences, 0, alignment.getWidth(), alignment));
2126 // Add any annotations attached to sequences
2127 for (int i = 0; i < sequences.length; i++)
2129 if (sequences[i].getAnnotation() != null)
2131 AlignmentAnnotation newann;
2132 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2134 annotationAdded = true;
2135 newann = sequences[i].getAnnotation()[a];
2136 newann.adjustForAlignment();
2137 newann.padAnnotation(alwidth);
2138 if (newann.graphGroup > -1)
2140 if (newann.graphGroup > -1)
2142 if (newGraphGroups.size() <= newann.graphGroup
2143 || newGraphGroups.get(newann.graphGroup) == null)
2145 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2147 newGraphGroups.add(q, null);
2149 newGraphGroups.set(newann.graphGroup, new Integer(
2152 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2156 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2161 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2168 // propagate alignment changed.
2169 viewport.setEndSeq(alignment.getHeight());
2170 if (annotationAdded)
2172 // Duplicate sequence annotation in all views.
2173 AlignmentI[] alview = this.getViewAlignments();
2174 for (int i = 0; i < sequences.length; i++)
2176 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2181 for (int avnum = 0; avnum < alview.length; avnum++)
2183 if (alview[avnum] != alignment)
2185 // duplicate in a view other than the one with input focus
2186 int avwidth = alview[avnum].getWidth() + 1;
2187 // this relies on sann being preserved after we
2188 // modify the sequence's annotation array for each duplication
2189 for (int a = 0; a < sann.length; a++)
2191 AlignmentAnnotation newann = new AlignmentAnnotation(
2193 sequences[i].addAlignmentAnnotation(newann);
2194 newann.padAnnotation(avwidth);
2195 alview[avnum].addAnnotation(newann); // annotation was
2196 // duplicated earlier
2197 // TODO JAL-1145 graphGroups are not updated for sequence
2198 // annotation added to several views. This may cause
2200 alview[avnum].setAnnotationIndex(newann, a);
2205 buildSortByAnnotationScoresMenu();
2207 viewport.firePropertyChange("alignment", null,
2208 alignment.getSequences());
2209 if (alignPanels != null)
2211 for (AlignmentPanel ap : alignPanels)
2213 ap.validateAnnotationDimensions(false);
2218 alignPanel.validateAnnotationDimensions(false);
2224 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2226 String newtitle = new String("Copied sequences");
2228 if (Desktop.jalviewClipboard != null
2229 && Desktop.jalviewClipboard[2] != null)
2231 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2232 for (int[] region : hc)
2234 af.viewport.hideColumns(region[0], region[1]);
2238 // >>>This is a fix for the moment, until a better solution is
2240 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2242 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
2244 // TODO: maintain provenance of an alignment, rather than just make the
2245 // title a concatenation of operations.
2248 if (title.startsWith("Copied sequences"))
2254 newtitle = newtitle.concat("- from " + title);
2259 newtitle = new String("Pasted sequences");
2262 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2267 } catch (Exception ex)
2269 ex.printStackTrace();
2270 System.out.println("Exception whilst pasting: " + ex);
2271 // could be anything being pasted in here
2277 protected void expand_newalign(ActionEvent e)
2281 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2282 .getAlignment(), -1);
2283 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2285 String newtitle = new String("Flanking alignment");
2287 if (Desktop.jalviewClipboard != null
2288 && Desktop.jalviewClipboard[2] != null)
2290 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2291 for (int region[] : hc)
2293 af.viewport.hideColumns(region[0], region[1]);
2297 // >>>This is a fix for the moment, until a better solution is
2299 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2301 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
2303 // TODO: maintain provenance of an alignment, rather than just make the
2304 // title a concatenation of operations.
2306 if (title.startsWith("Copied sequences"))
2312 newtitle = newtitle.concat("- from " + title);
2316 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2318 } catch (Exception ex)
2320 ex.printStackTrace();
2321 System.out.println("Exception whilst pasting: " + ex);
2322 // could be anything being pasted in here
2323 } catch (OutOfMemoryError oom)
2325 new OOMWarning("Viewing flanking region of alignment", oom);
2336 protected void cut_actionPerformed(ActionEvent e)
2338 copy_actionPerformed(null);
2339 delete_actionPerformed(null);
2349 protected void delete_actionPerformed(ActionEvent evt)
2352 SequenceGroup sg = viewport.getSelectionGroup();
2359 * If the cut affects all sequences, warn, remove highlighted columns
2361 if (sg.getSize() == viewport.getAlignment().getHeight())
2363 int confirm = JOptionPane.showConfirmDialog(this,
2364 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2365 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2366 JOptionPane.OK_CANCEL_OPTION);
2368 if (confirm == JOptionPane.CANCEL_OPTION
2369 || confirm == JOptionPane.CLOSED_OPTION)
2373 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2374 sg.getEndRes() + 1);
2377 SequenceI[] cut = sg.getSequences()
2378 .toArray(new SequenceI[sg.getSize()]);
2380 addHistoryItem(new EditCommand(
2381 MessageManager.getString("label.cut_sequences"), Action.CUT,
2382 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2383 viewport.getAlignment()));
2385 viewport.setSelectionGroup(null);
2386 viewport.sendSelection();
2387 viewport.getAlignment().deleteGroup(sg);
2389 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2391 if (viewport.getAlignment().getHeight() < 1)
2395 this.setClosed(true);
2396 } catch (Exception ex)
2409 protected void deleteGroups_actionPerformed(ActionEvent e)
2411 if (avc.deleteGroups())
2413 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2414 alignPanel.updateAnnotation();
2415 alignPanel.paintAlignment(true);
2426 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2428 SequenceGroup sg = new SequenceGroup();
2430 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2432 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2435 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2436 viewport.setSelectionGroup(sg);
2437 viewport.sendSelection();
2438 alignPanel.paintAlignment(true);
2439 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2449 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2451 if (viewport.cursorMode)
2453 alignPanel.getSeqPanel().keyboardNo1 = null;
2454 alignPanel.getSeqPanel().keyboardNo2 = null;
2456 viewport.setSelectionGroup(null);
2457 viewport.getColumnSelection().clear();
2458 viewport.setSelectionGroup(null);
2459 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2460 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2461 alignPanel.paintAlignment(true);
2462 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2463 viewport.sendSelection();
2473 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2475 SequenceGroup sg = viewport.getSelectionGroup();
2479 selectAllSequenceMenuItem_actionPerformed(null);
2484 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2486 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2489 alignPanel.paintAlignment(true);
2490 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2491 viewport.sendSelection();
2495 public void invertColSel_actionPerformed(ActionEvent e)
2497 viewport.invertColumnSelection();
2498 alignPanel.paintAlignment(true);
2499 viewport.sendSelection();
2509 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2511 trimAlignment(true);
2521 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2523 trimAlignment(false);
2526 void trimAlignment(boolean trimLeft)
2528 ColumnSelection colSel = viewport.getColumnSelection();
2531 if (colSel.size() > 0)
2535 column = colSel.getMin();
2539 column = colSel.getMax();
2543 if (viewport.getSelectionGroup() != null)
2545 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2546 viewport.getHiddenRepSequences());
2550 seqs = viewport.getAlignment().getSequencesArray();
2553 TrimRegionCommand trimRegion;
2556 trimRegion = new TrimRegionCommand("Remove Left",
2557 TrimRegionCommand.TRIM_LEFT, seqs, column,
2558 viewport.getAlignment(), viewport.getColumnSelection(),
2559 viewport.getSelectionGroup());
2560 viewport.setStartRes(0);
2564 trimRegion = new TrimRegionCommand("Remove Right",
2565 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2566 viewport.getAlignment(), viewport.getColumnSelection(),
2567 viewport.getSelectionGroup());
2570 statusBar.setText(MessageManager.formatMessage(
2571 "label.removed_columns", new String[]
2572 { Integer.valueOf(trimRegion.getSize()).toString() }));
2574 addHistoryItem(trimRegion);
2576 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2578 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2579 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2581 viewport.getAlignment().deleteGroup(sg);
2585 viewport.firePropertyChange("alignment", null, viewport
2586 .getAlignment().getSequences());
2597 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2599 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2602 if (viewport.getSelectionGroup() != null)
2604 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2605 viewport.getHiddenRepSequences());
2606 start = viewport.getSelectionGroup().getStartRes();
2607 end = viewport.getSelectionGroup().getEndRes();
2611 seqs = viewport.getAlignment().getSequencesArray();
2614 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2615 "Remove Gapped Columns", seqs, start, end,
2616 viewport.getAlignment());
2618 addHistoryItem(removeGapCols);
2620 statusBar.setText(MessageManager.formatMessage(
2621 "label.removed_empty_columns", new Object[]
2622 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2624 // This is to maintain viewport position on first residue
2625 // of first sequence
2626 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2627 int startRes = seq.findPosition(viewport.startRes);
2628 // ShiftList shifts;
2629 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2630 // edit.alColumnChanges=shifts.getInverse();
2631 // if (viewport.hasHiddenColumns)
2632 // viewport.getColumnSelection().compensateForEdits(shifts);
2633 viewport.setStartRes(seq.findIndex(startRes) - 1);
2634 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2646 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2648 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2651 if (viewport.getSelectionGroup() != null)
2653 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2654 viewport.getHiddenRepSequences());
2655 start = viewport.getSelectionGroup().getStartRes();
2656 end = viewport.getSelectionGroup().getEndRes();
2660 seqs = viewport.getAlignment().getSequencesArray();
2663 // This is to maintain viewport position on first residue
2664 // of first sequence
2665 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2666 int startRes = seq.findPosition(viewport.startRes);
2668 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2669 viewport.getAlignment()));
2671 viewport.setStartRes(seq.findIndex(startRes) - 1);
2673 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2685 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2687 viewport.setPadGaps(padGapsMenuitem.isSelected());
2688 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2699 public void findMenuItem_actionPerformed(ActionEvent e)
2705 * Create a new view of the current alignment.
2708 public void newView_actionPerformed(ActionEvent e)
2710 newView(null, true);
2714 * Creates and shows a new view of the current alignment.
2717 * title of newly created view; if null, one will be generated
2718 * @param copyAnnotation
2719 * if true then duplicate all annnotation, groups and settings
2720 * @return new alignment panel, already displayed.
2722 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2725 * Create a new AlignmentPanel (with its own, new Viewport)
2727 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2729 if (!copyAnnotation)
2732 * remove all groups and annotation except for the automatic stuff
2734 newap.av.getAlignment().deleteAllGroups();
2735 newap.av.getAlignment().deleteAllAnnotations(false);
2738 newap.av.setGatherViewsHere(false);
2740 if (viewport.viewName == null)
2742 viewport.viewName = MessageManager
2743 .getString("label.view_name_original");
2747 * Views share the same edits, undo and redo stacks, mappings.
2749 newap.av.setHistoryList(viewport.getHistoryList());
2750 newap.av.setRedoList(viewport.getRedoList());
2751 newap.av.getAlignment().setCodonFrames(
2752 viewport.getAlignment().getCodonFrames());
2754 newap.av.viewName = getNewViewName(viewTitle);
2756 addAlignmentPanel(newap, true);
2757 newap.alignmentChanged();
2759 if (alignPanels.size() == 2)
2761 viewport.setGatherViewsHere(true);
2763 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2768 * Make a new name for the view, ensuring it is unique within the current
2769 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2770 * these now use viewId. Unique view names are still desirable for usability.)
2775 protected String getNewViewName(String viewTitle)
2777 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2778 boolean addFirstIndex = false;
2779 if (viewTitle == null || viewTitle.trim().length() == 0)
2781 viewTitle = MessageManager.getString("action.view");
2782 addFirstIndex = true;
2786 index = 1;// we count from 1 if given a specific name
2788 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2790 List<Component> comps = PaintRefresher.components.get(viewport
2791 .getSequenceSetId());
2793 List<String> existingNames = getExistingViewNames(comps);
2795 while (existingNames.contains(newViewName))
2797 newViewName = viewTitle + " " + (++index);
2803 * Returns a list of distinct view names found in the given list of
2804 * components. View names are held on the viewport of an AlignmentPanel.
2809 protected List<String> getExistingViewNames(List<Component> comps)
2811 List<String> existingNames = new ArrayList<String>();
2812 for (Component comp : comps)
2814 if (comp instanceof AlignmentPanel)
2816 AlignmentPanel ap = (AlignmentPanel) comp;
2817 if (!existingNames.contains(ap.av.viewName))
2819 existingNames.add(ap.av.viewName);
2823 return existingNames;
2827 * Explode tabbed views into separate windows.
2830 public void expandViews_actionPerformed(ActionEvent e)
2832 Desktop.instance.explodeViews(this);
2836 * Gather views in separate windows back into a tabbed presentation.
2839 public void gatherViews_actionPerformed(ActionEvent e)
2841 Desktop.instance.gatherViews(this);
2851 public void font_actionPerformed(ActionEvent e)
2853 new FontChooser(alignPanel);
2863 protected void seqLimit_actionPerformed(ActionEvent e)
2865 viewport.setShowJVSuffix(seqLimits.isSelected());
2867 alignPanel.getIdPanel().getIdCanvas().setPreferredSize(alignPanel
2868 .calculateIdWidth());
2869 alignPanel.paintAlignment(true);
2873 public void idRightAlign_actionPerformed(ActionEvent e)
2875 viewport.setRightAlignIds(idRightAlign.isSelected());
2876 alignPanel.paintAlignment(true);
2880 public void centreColumnLabels_actionPerformed(ActionEvent e)
2882 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2883 alignPanel.paintAlignment(true);
2889 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2892 protected void followHighlight_actionPerformed()
2895 * Set the 'follow' flag on the Viewport (and scroll to position if now
2898 final boolean state = this.followHighlightMenuItem.getState();
2899 viewport.setFollowHighlight(state);
2902 alignPanel.scrollToPosition(
2903 alignPanel.getSeqPanel().seqCanvas.searchResults, false);
2914 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2916 viewport.setColourText(colourTextMenuItem.isSelected());
2917 alignPanel.paintAlignment(true);
2927 public void wrapMenuItem_actionPerformed(ActionEvent e)
2929 scaleAbove.setVisible(wrapMenuItem.isSelected());
2930 scaleLeft.setVisible(wrapMenuItem.isSelected());
2931 scaleRight.setVisible(wrapMenuItem.isSelected());
2932 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2933 alignPanel.updateLayout();
2937 public void showAllSeqs_actionPerformed(ActionEvent e)
2939 viewport.showAllHiddenSeqs();
2943 public void showAllColumns_actionPerformed(ActionEvent e)
2945 viewport.showAllHiddenColumns();
2950 public void hideSelSequences_actionPerformed(ActionEvent e)
2952 viewport.hideAllSelectedSeqs();
2953 // alignPanel.paintAlignment(true);
2957 * called by key handler and the hide all/show all menu items
2962 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2965 boolean hide = false;
2966 SequenceGroup sg = viewport.getSelectionGroup();
2967 if (!toggleSeqs && !toggleCols)
2969 // Hide everything by the current selection - this is a hack - we do the
2970 // invert and then hide
2971 // first check that there will be visible columns after the invert.
2972 if ((viewport.getColumnSelection() != null
2973 && viewport.getColumnSelection().getSelected() != null && viewport
2974 .getColumnSelection().getSelected().size() > 0)
2975 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2978 // now invert the sequence set, if required - empty selection implies
2979 // that no hiding is required.
2982 invertSequenceMenuItem_actionPerformed(null);
2983 sg = viewport.getSelectionGroup();
2987 viewport.expandColSelection(sg, true);
2988 // finally invert the column selection and get the new sequence
2990 invertColSel_actionPerformed(null);
2997 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
2999 hideSelSequences_actionPerformed(null);
3002 else if (!(toggleCols && viewport.getColumnSelection().getSelected()
3005 showAllSeqs_actionPerformed(null);
3011 if (viewport.getColumnSelection().getSelected().size() > 0)
3013 hideSelColumns_actionPerformed(null);
3016 viewport.setSelectionGroup(sg);
3021 showAllColumns_actionPerformed(null);
3030 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3031 * event.ActionEvent)
3034 public void hideAllButSelection_actionPerformed(ActionEvent e)
3036 toggleHiddenRegions(false, false);
3043 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3047 public void hideAllSelection_actionPerformed(ActionEvent e)
3049 SequenceGroup sg = viewport.getSelectionGroup();
3050 viewport.expandColSelection(sg, false);
3051 viewport.hideAllSelectedSeqs();
3052 viewport.hideSelectedColumns();
3053 alignPanel.paintAlignment(true);
3060 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3064 public void showAllhidden_actionPerformed(ActionEvent e)
3066 viewport.showAllHiddenColumns();
3067 viewport.showAllHiddenSeqs();
3068 alignPanel.paintAlignment(true);
3072 public void hideSelColumns_actionPerformed(ActionEvent e)
3074 viewport.hideSelectedColumns();
3075 alignPanel.paintAlignment(true);
3079 public void hiddenMarkers_actionPerformed(ActionEvent e)
3081 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3092 protected void scaleAbove_actionPerformed(ActionEvent e)
3094 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3095 alignPanel.paintAlignment(true);
3105 protected void scaleLeft_actionPerformed(ActionEvent e)
3107 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3108 alignPanel.paintAlignment(true);
3118 protected void scaleRight_actionPerformed(ActionEvent e)
3120 viewport.setScaleRightWrapped(scaleRight.isSelected());
3121 alignPanel.paintAlignment(true);
3131 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3133 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3134 alignPanel.paintAlignment(true);
3144 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3146 viewport.setShowText(viewTextMenuItem.isSelected());
3147 alignPanel.paintAlignment(true);
3157 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3159 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3160 alignPanel.paintAlignment(true);
3163 public FeatureSettings featureSettings;
3166 public FeatureSettingsControllerI getFeatureSettingsUI()
3168 return featureSettings;
3172 public void featureSettings_actionPerformed(ActionEvent e)
3174 if (featureSettings != null)
3176 featureSettings.close();
3177 featureSettings = null;
3179 if (!showSeqFeatures.isSelected())
3181 // make sure features are actually displayed
3182 showSeqFeatures.setSelected(true);
3183 showSeqFeatures_actionPerformed(null);
3185 featureSettings = new FeatureSettings(this);
3189 * Set or clear 'Show Sequence Features'
3195 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3197 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3198 alignPanel.paintAlignment(true);
3199 if (alignPanel.getOverviewPanel() != null)
3201 alignPanel.getOverviewPanel().updateOverviewImage();
3206 * Set or clear 'Show Sequence Features'
3212 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
3214 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
3216 if (viewport.isShowSequenceFeaturesHeight())
3218 // ensure we're actually displaying features
3219 viewport.setShowSequenceFeatures(true);
3220 showSeqFeatures.setSelected(true);
3222 alignPanel.paintAlignment(true);
3223 if (alignPanel.getOverviewPanel() != null)
3225 alignPanel.getOverviewPanel().updateOverviewImage();
3230 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3231 * the annotations panel as a whole.
3233 * The options to show/hide all annotations should be enabled when the panel
3234 * is shown, and disabled when the panel is hidden.
3239 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3241 final boolean setVisible = annotationPanelMenuItem.isSelected();
3242 viewport.setShowAnnotation(setVisible);
3243 this.showAllSeqAnnotations.setEnabled(setVisible);
3244 this.hideAllSeqAnnotations.setEnabled(setVisible);
3245 this.showAllAlAnnotations.setEnabled(setVisible);
3246 this.hideAllAlAnnotations.setEnabled(setVisible);
3247 alignPanel.updateLayout();
3251 public void alignmentProperties()
3253 JEditorPane editPane = new JEditorPane("text/html", "");
3254 editPane.setEditable(false);
3255 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3257 editPane.setText(MessageManager.formatMessage("label.html_content",
3259 { contents.toString() }));
3260 JInternalFrame frame = new JInternalFrame();
3261 frame.getContentPane().add(new JScrollPane(editPane));
3263 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3264 "label.alignment_properties", new Object[]
3265 { getTitle() }), 500, 400);
3275 public void overviewMenuItem_actionPerformed(ActionEvent e)
3277 if (alignPanel.overviewPanel != null)
3282 JInternalFrame frame = new JInternalFrame();
3283 OverviewPanel overview = new OverviewPanel(alignPanel);
3284 frame.setContentPane(overview);
3285 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3286 "label.overview_params", new Object[]
3287 { this.getTitle() }), frame.getWidth(), frame.getHeight());
3289 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3290 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3293 public void internalFrameClosed(
3294 javax.swing.event.InternalFrameEvent evt)
3296 alignPanel.setOverviewPanel(null);
3300 alignPanel.setOverviewPanel(overview);
3304 public void textColour_actionPerformed(ActionEvent e)
3306 new TextColourChooser().chooseColour(alignPanel, null);
3316 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3328 public void clustalColour_actionPerformed(ActionEvent e)
3330 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3331 viewport.getHiddenRepSequences()));
3341 public void zappoColour_actionPerformed(ActionEvent e)
3343 changeColour(new ZappoColourScheme());
3353 public void taylorColour_actionPerformed(ActionEvent e)
3355 changeColour(new TaylorColourScheme());
3365 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3367 changeColour(new HydrophobicColourScheme());
3377 public void helixColour_actionPerformed(ActionEvent e)
3379 changeColour(new HelixColourScheme());
3389 public void strandColour_actionPerformed(ActionEvent e)
3391 changeColour(new StrandColourScheme());
3401 public void turnColour_actionPerformed(ActionEvent e)
3403 changeColour(new TurnColourScheme());
3413 public void buriedColour_actionPerformed(ActionEvent e)
3415 changeColour(new BuriedColourScheme());
3425 public void nucleotideColour_actionPerformed(ActionEvent e)
3427 changeColour(new NucleotideColourScheme());
3431 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3433 changeColour(new PurinePyrimidineColourScheme());
3437 * public void covariationColour_actionPerformed(ActionEvent e) {
3439 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3443 public void annotationColour_actionPerformed(ActionEvent e)
3445 new AnnotationColourChooser(viewport, alignPanel);
3449 public void annotationColumn_actionPerformed(ActionEvent e)
3451 new AnnotationColumnChooser(viewport, alignPanel);
3455 public void rnahelicesColour_actionPerformed(ActionEvent e)
3457 new RNAHelicesColourChooser(viewport, alignPanel);
3467 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3469 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3478 public void changeColour(ColourSchemeI cs)
3480 // TODO: compare with applet and pull up to model method
3485 if (viewport.getAbovePIDThreshold())
3487 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3489 cs.setThreshold(threshold, viewport.isIgnoreGapsConsensus());
3493 cs.setThreshold(0, viewport.isIgnoreGapsConsensus());
3496 if (viewport.getConservationSelected())
3499 Alignment al = (Alignment) viewport.getAlignment();
3500 Conservation c = new Conservation("All",
3501 ResidueProperties.propHash, 3, al.getSequences(), 0,
3505 c.verdict(false, viewport.getConsPercGaps());
3507 cs.setConservation(c);
3509 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3514 cs.setConservation(null);
3517 cs.setConsensus(viewport.getSequenceConsensusHash());
3520 viewport.setGlobalColourScheme(cs);
3522 if (viewport.getColourAppliesToAllGroups())
3525 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3533 if (cs instanceof ClustalxColourScheme)
3535 sg.cs = new ClustalxColourScheme(sg,
3536 viewport.getHiddenRepSequences());
3538 else if (cs instanceof UserColourScheme)
3540 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
3546 sg.cs = cs.getClass().newInstance();
3547 } catch (Exception ex)
3552 if (viewport.getAbovePIDThreshold()
3553 || cs instanceof PIDColourScheme
3554 || cs instanceof Blosum62ColourScheme)
3556 sg.cs.setThreshold(threshold, viewport.isIgnoreGapsConsensus());
3558 sg.cs.setConsensus(AAFrequency.calculate(
3559 sg.getSequences(viewport.getHiddenRepSequences()),
3560 sg.getStartRes(), sg.getEndRes() + 1));
3564 sg.cs.setThreshold(0, viewport.isIgnoreGapsConsensus());
3567 if (viewport.getConservationSelected())
3569 Conservation c = new Conservation("Group",
3570 ResidueProperties.propHash, 3, sg.getSequences(viewport
3571 .getHiddenRepSequences()), sg.getStartRes(),
3572 sg.getEndRes() + 1);
3574 c.verdict(false, viewport.getConsPercGaps());
3575 sg.cs.setConservation(c);
3579 sg.cs.setConservation(null);
3584 if (alignPanel.getOverviewPanel() != null)
3586 alignPanel.getOverviewPanel().updateOverviewImage();
3589 alignPanel.paintAlignment(true);
3599 protected void modifyPID_actionPerformed(ActionEvent e)
3601 if (viewport.getAbovePIDThreshold()
3602 && viewport.getGlobalColourScheme() != null)
3604 SliderPanel.setPIDSliderSource(alignPanel,
3605 viewport.getGlobalColourScheme(), "Background");
3606 SliderPanel.showPIDSlider();
3617 protected void modifyConservation_actionPerformed(ActionEvent e)
3619 if (viewport.getConservationSelected()
3620 && viewport.getGlobalColourScheme() != null)
3622 SliderPanel.setConservationSlider(alignPanel,
3623 viewport.getGlobalColourScheme(), "Background");
3624 SliderPanel.showConservationSlider();
3635 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3637 viewport.setConservationSelected(conservationMenuItem.isSelected());
3639 viewport.setAbovePIDThreshold(false);
3640 abovePIDThreshold.setSelected(false);
3642 changeColour(viewport.getGlobalColourScheme());
3644 modifyConservation_actionPerformed(null);
3654 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3656 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3658 conservationMenuItem.setSelected(false);
3659 viewport.setConservationSelected(false);
3661 changeColour(viewport.getGlobalColourScheme());
3663 modifyPID_actionPerformed(null);
3673 public void userDefinedColour_actionPerformed(ActionEvent e)
3675 if (e.getActionCommand().equals(
3676 MessageManager.getString("action.user_defined")))
3678 new UserDefinedColours(alignPanel, null);
3682 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3683 .getUserColourSchemes().get(e.getActionCommand());
3689 public void updateUserColourMenu()
3692 Component[] menuItems = colourMenu.getMenuComponents();
3693 int iSize = menuItems.length;
3694 for (int i = 0; i < iSize; i++)
3696 if (menuItems[i].getName() != null
3697 && menuItems[i].getName().equals("USER_DEFINED"))
3699 colourMenu.remove(menuItems[i]);
3703 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3705 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3706 .getUserColourSchemes().keys();
3708 while (userColours.hasMoreElements())
3710 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3711 userColours.nextElement().toString());
3712 radioItem.setName("USER_DEFINED");
3713 radioItem.addMouseListener(new MouseAdapter()
3716 public void mousePressed(MouseEvent evt)
3718 if (evt.isControlDown()
3719 || SwingUtilities.isRightMouseButton(evt))
3721 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3723 int option = JOptionPane.showInternalConfirmDialog(
3724 jalview.gui.Desktop.desktop,
3726 .getString("label.remove_from_default_list"),
3728 .getString("label.remove_user_defined_colour"),
3729 JOptionPane.YES_NO_OPTION);
3730 if (option == JOptionPane.YES_OPTION)
3732 jalview.gui.UserDefinedColours
3733 .removeColourFromDefaults(radioItem.getText());
3734 colourMenu.remove(radioItem);
3738 radioItem.addActionListener(new ActionListener()
3741 public void actionPerformed(ActionEvent evt)
3743 userDefinedColour_actionPerformed(evt);
3750 radioItem.addActionListener(new ActionListener()
3753 public void actionPerformed(ActionEvent evt)
3755 userDefinedColour_actionPerformed(evt);
3759 colourMenu.insert(radioItem, 15);
3760 colours.add(radioItem);
3772 public void PIDColour_actionPerformed(ActionEvent e)
3774 changeColour(new PIDColourScheme());
3784 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3786 changeColour(new Blosum62ColourScheme());
3796 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3798 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3799 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3800 .getAlignment().getSequenceAt(0), null);
3801 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3802 viewport.getAlignment()));
3803 alignPanel.paintAlignment(true);
3813 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3815 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3816 AlignmentSorter.sortByID(viewport.getAlignment());
3817 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3818 viewport.getAlignment()));
3819 alignPanel.paintAlignment(true);
3829 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3831 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3832 AlignmentSorter.sortByLength(viewport.getAlignment());
3833 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3834 viewport.getAlignment()));
3835 alignPanel.paintAlignment(true);
3845 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3847 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3848 AlignmentSorter.sortByGroup(viewport.getAlignment());
3849 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3850 viewport.getAlignment()));
3852 alignPanel.paintAlignment(true);
3862 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3864 new RedundancyPanel(alignPanel, this);
3874 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3876 if ((viewport.getSelectionGroup() == null)
3877 || (viewport.getSelectionGroup().getSize() < 2))
3879 JOptionPane.showInternalMessageDialog(this, MessageManager
3880 .getString("label.you_must_select_least_two_sequences"),
3881 MessageManager.getString("label.invalid_selection"),
3882 JOptionPane.WARNING_MESSAGE);
3886 JInternalFrame frame = new JInternalFrame();
3887 frame.setContentPane(new PairwiseAlignPanel(viewport));
3888 Desktop.addInternalFrame(frame,
3889 MessageManager.getString("action.pairwise_alignment"), 600,
3901 public void PCAMenuItem_actionPerformed(ActionEvent e)
3903 if (((viewport.getSelectionGroup() != null)
3904 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3905 .getSelectionGroup().getSize() > 0))
3906 || (viewport.getAlignment().getHeight() < 4))
3909 .showInternalMessageDialog(
3912 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3914 .getString("label.sequence_selection_insufficient"),
3915 JOptionPane.WARNING_MESSAGE);
3920 new PCAPanel(alignPanel);
3924 public void autoCalculate_actionPerformed(ActionEvent e)
3926 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3927 if (viewport.autoCalculateConsensus)
3929 viewport.firePropertyChange("alignment", null, viewport
3930 .getAlignment().getSequences());
3935 public void sortByTreeOption_actionPerformed(ActionEvent e)
3937 viewport.sortByTree = sortByTree.isSelected();
3941 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3943 viewport.followSelection = listenToViewSelections.isSelected();
3953 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3955 newTreePanel("AV", "PID", "Average distance tree using PID");
3965 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3967 newTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3977 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3979 newTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3989 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3991 newTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
4004 void newTreePanel(String type, String pwType, String title)
4008 if (viewport.getSelectionGroup() != null
4009 && viewport.getSelectionGroup().getSize() > 0)
4011 if (viewport.getSelectionGroup().getSize() < 3)
4017 .getString("label.you_need_more_two_sequences_selected_build_tree"),
4019 .getString("label.not_enough_sequences"),
4020 JOptionPane.WARNING_MESSAGE);
4024 SequenceGroup sg = viewport.getSelectionGroup();
4026 /* Decide if the selection is a column region */
4027 for (SequenceI _s : sg.getSequences())
4029 if (_s.getLength() < sg.getEndRes())
4035 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
4037 .getString("label.sequences_selection_not_aligned"),
4038 JOptionPane.WARNING_MESSAGE);
4044 title = title + " on region";
4045 tp = new TreePanel(alignPanel, type, pwType);
4049 // are the visible sequences aligned?
4050 if (!viewport.getAlignment().isAligned(false))
4056 .getString("label.sequences_must_be_aligned_before_creating_tree"),
4058 .getString("label.sequences_not_aligned"),
4059 JOptionPane.WARNING_MESSAGE);
4064 if (viewport.getAlignment().getHeight() < 2)
4069 tp = new TreePanel(alignPanel, type, pwType);
4074 if (viewport.viewName != null)
4076 title += viewport.viewName + " of ";
4079 title += this.title;
4081 Desktop.addInternalFrame(tp, title, 600, 500);
4092 public void addSortByOrderMenuItem(String title,
4093 final AlignmentOrder order)
4095 final JMenuItem item = new JMenuItem(MessageManager.formatMessage("action.by_title_param", new Object[]{title}));
4097 item.addActionListener(new java.awt.event.ActionListener()
4100 public void actionPerformed(ActionEvent e)
4102 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4104 // TODO: JBPNote - have to map order entries to curent SequenceI
4106 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4108 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
4111 alignPanel.paintAlignment(true);
4117 * Add a new sort by annotation score menu item
4120 * the menu to add the option to
4122 * the label used to retrieve scores for each sequence on the
4125 public void addSortByAnnotScoreMenuItem(JMenu sort,
4126 final String scoreLabel)
4128 final JMenuItem item = new JMenuItem(scoreLabel);
4130 item.addActionListener(new java.awt.event.ActionListener()
4133 public void actionPerformed(ActionEvent e)
4135 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4136 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4137 viewport.getAlignment());// ,viewport.getSelectionGroup());
4138 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4139 viewport.getAlignment()));
4140 alignPanel.paintAlignment(true);
4146 * last hash for alignment's annotation array - used to minimise cost of
4149 protected int _annotationScoreVectorHash;
4152 * search the alignment and rebuild the sort by annotation score submenu the
4153 * last alignment annotation vector hash is stored to minimize cost of
4154 * rebuilding in subsequence calls.
4158 public void buildSortByAnnotationScoresMenu()
4160 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4165 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4167 sortByAnnotScore.removeAll();
4168 // almost certainly a quicker way to do this - but we keep it simple
4169 Hashtable scoreSorts = new Hashtable();
4170 AlignmentAnnotation aann[];
4171 for (SequenceI sqa : viewport.getAlignment().getSequences())
4173 aann = sqa.getAnnotation();
4174 for (int i = 0; aann != null && i < aann.length; i++)
4176 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4178 scoreSorts.put(aann[i].label, aann[i].label);
4182 Enumeration labels = scoreSorts.keys();
4183 while (labels.hasMoreElements())
4185 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4186 (String) labels.nextElement());
4188 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4191 _annotationScoreVectorHash = viewport.getAlignment()
4192 .getAlignmentAnnotation().hashCode();
4197 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4198 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4199 * call. Listeners are added to remove the menu item when the treePanel is
4200 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4204 * Displayed tree window.
4206 * SortBy menu item title.
4209 public void buildTreeMenu()
4211 calculateTree.removeAll();
4212 // build the calculate menu
4214 for (final String type : new String[]
4217 String treecalcnm = MessageManager.getString("label.tree_calc_"
4218 + type.toLowerCase());
4219 for (final String pwtype : ResidueProperties.scoreMatrices.keySet())
4221 JMenuItem tm = new JMenuItem();
4222 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4223 if (sm.isProtein() == !viewport.getAlignment().isNucleotide())
4225 String smn = MessageManager.getStringOrReturn(
4226 "label.score_model_", sm.getName());
4227 final String title = MessageManager.formatMessage(
4228 "label.treecalc_title", treecalcnm, smn);
4229 tm.setText(title);//
4230 tm.addActionListener(new java.awt.event.ActionListener()
4233 public void actionPerformed(ActionEvent e)
4235 newTreePanel(type, pwtype, title);
4238 calculateTree.add(tm);
4243 sortByTreeMenu.removeAll();
4245 List<Component> comps = PaintRefresher.components.get(viewport
4246 .getSequenceSetId());
4247 List<TreePanel> treePanels = new ArrayList<TreePanel>();
4248 for (Component comp : comps)
4250 if (comp instanceof TreePanel)
4252 treePanels.add((TreePanel) comp);
4256 if (treePanels.size() < 1)
4258 sortByTreeMenu.setVisible(false);
4262 sortByTreeMenu.setVisible(true);
4264 for (final TreePanel tp : treePanels)
4266 final JMenuItem item = new JMenuItem(tp.getTitle());
4267 item.addActionListener(new java.awt.event.ActionListener()
4270 public void actionPerformed(ActionEvent e)
4272 tp.sortByTree_actionPerformed();
4273 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4278 sortByTreeMenu.add(item);
4282 public boolean sortBy(AlignmentOrder alorder, String undoname)
4284 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4285 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4286 if (undoname != null)
4288 addHistoryItem(new OrderCommand(undoname, oldOrder,
4289 viewport.getAlignment()));
4291 alignPanel.paintAlignment(true);
4296 * Work out whether the whole set of sequences or just the selected set will
4297 * be submitted for multiple alignment.
4300 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4302 // Now, check we have enough sequences
4303 AlignmentView msa = null;
4305 if ((viewport.getSelectionGroup() != null)
4306 && (viewport.getSelectionGroup().getSize() > 1))
4308 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4309 // some common interface!
4311 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4312 * SequenceI[sz = seqs.getSize(false)];
4314 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4315 * seqs.getSequenceAt(i); }
4317 msa = viewport.getAlignmentView(true);
4319 else if (viewport.getSelectionGroup() != null
4320 && viewport.getSelectionGroup().getSize() == 1)
4322 int option = JOptionPane.showConfirmDialog(this,
4323 MessageManager.getString("warn.oneseq_msainput_selection"),
4324 MessageManager.getString("label.invalid_selection"),
4325 JOptionPane.OK_CANCEL_OPTION);
4326 if (option == JOptionPane.OK_OPTION)
4328 msa = viewport.getAlignmentView(false);
4333 msa = viewport.getAlignmentView(false);
4339 * Decides what is submitted to a secondary structure prediction service: the
4340 * first sequence in the alignment, or in the current selection, or, if the
4341 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4342 * region or the whole alignment. (where the first sequence in the set is the
4343 * one that the prediction will be for).
4345 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4347 AlignmentView seqs = null;
4349 if ((viewport.getSelectionGroup() != null)
4350 && (viewport.getSelectionGroup().getSize() > 0))
4352 seqs = viewport.getAlignmentView(true);
4356 seqs = viewport.getAlignmentView(false);
4358 // limit sequences - JBPNote in future - could spawn multiple prediction
4360 // TODO: viewport.getAlignment().isAligned is a global state - the local
4361 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4362 if (!viewport.getAlignment().isAligned(false))
4364 seqs.setSequences(new SeqCigar[]
4365 { seqs.getSequences()[0] });
4366 // TODO: if seqs.getSequences().length>1 then should really have warned
4380 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4382 // Pick the tree file
4383 JalviewFileChooser chooser = new JalviewFileChooser(
4384 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4385 chooser.setFileView(new JalviewFileView());
4386 chooser.setDialogTitle(MessageManager
4387 .getString("label.select_newick_like_tree_file"));
4388 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4390 int value = chooser.showOpenDialog(null);
4392 if (value == JalviewFileChooser.APPROVE_OPTION)
4394 String choice = chooser.getSelectedFile().getPath();
4395 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4396 jalview.io.NewickFile fin = null;
4399 fin = new jalview.io.NewickFile(choice, "File");
4400 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4401 } catch (Exception ex)
4408 .getString("label.problem_reading_tree_file"),
4409 JOptionPane.WARNING_MESSAGE);
4410 ex.printStackTrace();
4412 if (fin != null && fin.hasWarningMessage())
4414 JOptionPane.showMessageDialog(Desktop.desktop, fin
4415 .getWarningMessage(), MessageManager
4416 .getString("label.possible_problem_with_tree_file"),
4417 JOptionPane.WARNING_MESSAGE);
4423 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4425 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4428 public TreePanel ShowNewickTree(NewickFile nf, String title)
4430 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4433 public TreePanel ShowNewickTree(NewickFile nf, String title,
4434 AlignmentView input)
4436 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4439 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4440 int h, int x, int y)
4442 return ShowNewickTree(nf, title, null, w, h, x, y);
4446 * Add a treeviewer for the tree extracted from a newick file object to the
4447 * current alignment view
4454 * Associated alignment input data (or null)
4463 * @return TreePanel handle
4465 public TreePanel ShowNewickTree(NewickFile nf, String title,
4466 AlignmentView input, int w, int h, int x, int y)
4468 TreePanel tp = null;
4474 if (nf.getTree() != null)
4476 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4482 tp.setLocation(x, y);
4485 Desktop.addInternalFrame(tp, title, w, h);
4487 } catch (Exception ex)
4489 ex.printStackTrace();
4495 private boolean buildingMenu = false;
4498 * Generates menu items and listener event actions for web service clients
4501 public void BuildWebServiceMenu()
4503 while (buildingMenu)
4507 System.err.println("Waiting for building menu to finish.");
4509 } catch (Exception e)
4513 final AlignFrame me = this;
4514 buildingMenu = true;
4515 new Thread(new Runnable()
4520 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4523 System.err.println("Building ws menu again "
4524 + Thread.currentThread());
4525 // TODO: add support for context dependent disabling of services based
4527 // alignment and current selection
4528 // TODO: add additional serviceHandle parameter to specify abstract
4530 // class independently of AbstractName
4531 // TODO: add in rediscovery GUI function to restart discoverer
4532 // TODO: group services by location as well as function and/or
4534 // object broker mechanism.
4535 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4536 final IProgressIndicator af = me;
4537 final JMenu msawsmenu = new JMenu("Alignment");
4538 final JMenu secstrmenu = new JMenu(
4539 "Secondary Structure Prediction");
4540 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4541 final JMenu analymenu = new JMenu("Analysis");
4542 final JMenu dismenu = new JMenu("Protein Disorder");
4543 // final JMenu msawsmenu = new
4544 // JMenu(MessageManager.getString("label.alignment"));
4545 // final JMenu secstrmenu = new
4546 // JMenu(MessageManager.getString("label.secondary_structure_prediction"));
4547 // final JMenu seqsrchmenu = new
4548 // JMenu(MessageManager.getString("label.sequence_database_search"));
4549 // final JMenu analymenu = new
4550 // JMenu(MessageManager.getString("label.analysis"));
4551 // final JMenu dismenu = new
4552 // JMenu(MessageManager.getString("label.protein_disorder"));
4553 // JAL-940 - only show secondary structure prediction services from
4554 // the legacy server
4555 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4557 Discoverer.services != null && (Discoverer.services.size() > 0))
4559 // TODO: refactor to allow list of AbstractName/Handler bindings to
4561 // stored or retrieved from elsewhere
4562 // No MSAWS used any more:
4563 // Vector msaws = null; // (Vector)
4564 // Discoverer.services.get("MsaWS");
4565 Vector secstrpr = (Vector) Discoverer.services
4567 if (secstrpr != null)
4569 // Add any secondary structure prediction services
4570 for (int i = 0, j = secstrpr.size(); i < j; i++)
4572 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4574 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4575 .getServiceClient(sh);
4576 int p = secstrmenu.getItemCount();
4577 impl.attachWSMenuEntry(secstrmenu, me);
4578 int q = secstrmenu.getItemCount();
4579 for (int litm = p; litm < q; litm++)
4581 legacyItems.add(secstrmenu.getItem(litm));
4587 // Add all submenus in the order they should appear on the web
4589 wsmenu.add(msawsmenu);
4590 wsmenu.add(secstrmenu);
4591 wsmenu.add(dismenu);
4592 wsmenu.add(analymenu);
4593 // No search services yet
4594 // wsmenu.add(seqsrchmenu);
4596 javax.swing.SwingUtilities.invokeLater(new Runnable()
4603 webService.removeAll();
4604 // first, add discovered services onto the webservices menu
4605 if (wsmenu.size() > 0)
4607 for (int i = 0, j = wsmenu.size(); i < j; i++)
4609 webService.add(wsmenu.get(i));
4614 webService.add(me.webServiceNoServices);
4616 // TODO: move into separate menu builder class.
4617 boolean new_sspred = false;
4618 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4620 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4621 if (jws2servs != null)
4623 if (jws2servs.hasServices())
4625 jws2servs.attachWSMenuEntry(webService, me);
4626 for (Jws2Instance sv : jws2servs.getServices())
4628 if (sv.description.toLowerCase().contains("jpred"))
4630 for (JMenuItem jmi : legacyItems)
4632 jmi.setVisible(false);
4638 if (jws2servs.isRunning())
4640 JMenuItem tm = new JMenuItem(
4641 "Still discovering JABA Services");
4642 tm.setEnabled(false);
4647 build_urlServiceMenu(me.webService);
4648 build_fetchdbmenu(webService);
4649 for (JMenu item : wsmenu)
4651 if (item.getItemCount() == 0)
4653 item.setEnabled(false);
4657 item.setEnabled(true);
4660 } catch (Exception e)
4663 .debug("Exception during web service menu building process.",
4668 } catch (Exception e)
4671 buildingMenu = false;
4678 * construct any groupURL type service menu entries.
4682 private void build_urlServiceMenu(JMenu webService)
4684 // TODO: remove this code when 2.7 is released
4685 // DEBUG - alignmentView
4687 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4688 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4690 * @Override public void actionPerformed(ActionEvent e) {
4691 * jalview.datamodel.AlignmentView
4692 * .testSelectionViews(af.viewport.getAlignment(),
4693 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4695 * }); webService.add(testAlView);
4697 // TODO: refactor to RestClient discoverer and merge menu entries for
4698 // rest-style services with other types of analysis/calculation service
4699 // SHmmr test client - still being implemented.
4700 // DEBUG - alignmentView
4702 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4705 client.attachWSMenuEntry(
4706 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4712 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
4713 * chooser = new JalviewFileChooser(jalview.bin.Cache.
4714 * getProperty("LAST_DIRECTORY"));
4716 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
4717 * to Vamsas file"); chooser.setToolTipText("Export");
4719 * int value = chooser.showSaveDialog(this);
4721 * if (value == JalviewFileChooser.APPROVE_OPTION) {
4722 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
4723 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
4724 * chooser.getSelectedFile().getAbsolutePath(), this); } }
4727 * prototype of an automatically enabled/disabled analysis function
4730 protected void setShowProductsEnabled()
4732 SequenceI[] selection = viewport.getSequenceSelection();
4733 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
4734 viewport.getAlignment().getDataset()))
4736 showProducts.setEnabled(true);
4741 showProducts.setEnabled(false);
4746 * search selection for sequence xRef products and build the show products
4751 * @return true if showProducts menu should be enabled.
4753 public boolean canShowProducts(SequenceI[] selection,
4754 boolean isRegionSelection, Alignment dataset)
4756 boolean showp = false;
4759 showProducts.removeAll();
4760 final boolean dna = viewport.getAlignment().isNucleotide();
4761 final Alignment ds = dataset;
4762 String[] ptypes = (selection == null || selection.length == 0) ? null
4763 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4765 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4766 // selection, dataset, true);
4767 final SequenceI[] sel = selection;
4768 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4771 final boolean isRegSel = isRegionSelection;
4772 final AlignFrame af = this;
4773 final String source = ptypes[t];
4774 JMenuItem xtype = new JMenuItem(ptypes[t]);
4775 xtype.addActionListener(new ActionListener()
4779 public void actionPerformed(ActionEvent e)
4781 // TODO: new thread for this call with vis-delay
4782 af.showProductsFor(af.viewport.getSequenceSelection(),
4783 isRegSel, dna, source);
4787 showProducts.add(xtype);
4789 showProducts.setVisible(showp);
4790 showProducts.setEnabled(showp);
4791 } catch (Exception e)
4793 jalview.bin.Cache.log
4794 .warn("canTranslate threw an exception - please report to help@jalview.org",
4801 protected void showProductsFor(final SequenceI[] sel,
4802 final boolean isRegSel, final boolean dna, final String source)
4804 Runnable foo = new Runnable()
4810 final long sttime = System.currentTimeMillis();
4811 AlignFrame.this.setProgressBar(MessageManager.formatMessage(
4812 "status.searching_for_sequences_from", new Object[]
4813 { source }), sttime);
4816 // update our local dataset reference
4817 Alignment ds = AlignFrame.this.getViewport().getAlignment()
4819 Alignment prods = CrossRef
4820 .findXrefSequences(sel, dna, source, ds);
4823 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4824 for (int s = 0; s < sprods.length; s++)
4826 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4827 if (ds.getSequences() == null
4828 || !ds.getSequences().contains(
4829 sprods[s].getDatasetSequence()))
4831 ds.addSequence(sprods[s].getDatasetSequence());
4833 sprods[s].updatePDBIds();
4835 Alignment al = new Alignment(sprods);
4839 * Copy dna-to-protein mappings to new alignment
4841 // TODO 1: no mappings are set up for EMBL product
4842 // TODO 2: if they were, should add them to protein alignment, not
4844 Set<AlignedCodonFrame> cf = prods.getCodonFrames();
4845 for (AlignedCodonFrame acf : cf)
4847 al.addCodonFrame(acf);
4849 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4851 String newtitle = "" + ((dna) ? "Proteins" : "Nucleotides")
4852 + " for " + ((isRegSel) ? "selected region of " : "")
4854 naf.setTitle(newtitle);
4856 // temporary flag until SplitFrame is released
4857 boolean asSplitFrame = Cache.getDefault(
4858 Preferences.ENABLE_SPLIT_FRAME, true);
4862 * Make a copy of this alignment (sharing the same dataset
4863 * sequences). If we are DNA, drop introns and update mappings
4865 AlignmentI copyAlignment = null;
4866 final SequenceI[] sequenceSelection = AlignFrame.this.viewport
4867 .getSequenceSelection();
4870 copyAlignment = AlignmentUtils.makeExonAlignment(
4871 sequenceSelection, cf);
4872 al.getCodonFrames().clear();
4873 al.getCodonFrames().addAll(cf);
4874 final StructureSelectionManager ssm = StructureSelectionManager
4875 .getStructureSelectionManager(Desktop.instance);
4876 ssm.addMappings(cf);
4880 copyAlignment = new Alignment(new Alignment(
4881 sequenceSelection));
4883 AlignFrame copyThis = new AlignFrame(copyAlignment,
4884 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
4885 copyThis.setTitle(AlignFrame.this.getTitle());
4886 // SplitFrame with dna above, protein below
4887 SplitFrame sf = new SplitFrame(dna ? copyThis : naf,
4888 dna ? naf : copyThis);
4889 naf.setVisible(true);
4890 copyThis.setVisible(true);
4891 String linkedTitle = MessageManager
4892 .getString("label.linked_view_title");
4893 Desktop.addInternalFrame(sf, linkedTitle, -1, -1);
4897 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4903 System.err.println("No Sequences generated for xRef type "
4906 } catch (Exception e)
4908 jalview.bin.Cache.log.error(
4909 "Exception when finding crossreferences", e);
4910 } catch (OutOfMemoryError e)
4912 new OOMWarning("whilst fetching crossreferences", e);
4915 jalview.bin.Cache.log.error("Error when finding crossreferences",
4918 AlignFrame.this.setProgressBar(MessageManager.formatMessage(
4919 "status.finished_searching_for_sequences_from",
4926 Thread frunner = new Thread(foo);
4930 public boolean canShowTranslationProducts(SequenceI[] selection,
4931 AlignmentI alignment)
4936 return (jalview.analysis.Dna.canTranslate(selection,
4937 viewport.getViewAsVisibleContigs(true)));
4938 } catch (Exception e)
4940 jalview.bin.Cache.log
4941 .warn("canTranslate threw an exception - please report to help@jalview.org",
4948 * Construct and display a new frame containing the translation of this
4949 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4952 public void showTranslation_actionPerformed(ActionEvent e)
4954 AlignmentI al = null;
4957 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4959 al = dna.translateCdna();
4960 } catch (Exception ex)
4962 jalview.bin.Cache.log.error(
4963 "Exception during translation. Please report this !", ex);
4964 final String msg = MessageManager
4965 .getString("label.error_when_translating_sequences_submit_bug_report");
4966 final String title = MessageManager
4967 .getString("label.implementation_error")
4968 + MessageManager.getString("translation_failed");
4969 JOptionPane.showMessageDialog(Desktop.desktop, msg, title,
4970 JOptionPane.ERROR_MESSAGE);
4973 if (al == null || al.getHeight() == 0)
4975 final String msg = MessageManager
4976 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4977 final String title = MessageManager
4978 .getString("label.translation_failed");
4979 JOptionPane.showMessageDialog(Desktop.desktop, msg, title,
4980 JOptionPane.WARNING_MESSAGE);
4984 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4985 af.setFileFormat(this.currentFileFormat);
4986 final String newTitle = MessageManager.formatMessage(
4987 "label.translation_of_params", new Object[]
4988 { this.getTitle() });
4989 af.setTitle(newTitle);
4990 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4992 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4993 viewport.openSplitFrame(af, new Alignment(seqs),
4994 al.getCodonFrames());
4998 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
5005 * Set the file format
5009 public void setFileFormat(String fileFormat)
5011 this.currentFileFormat = fileFormat;
5015 * Try to load a features file onto the alignment.
5018 * contents or path to retrieve file
5020 * access mode of file (see jalview.io.AlignFile)
5021 * @return true if features file was parsed correctly.
5023 public boolean parseFeaturesFile(String file, String type)
5025 return avc.parseFeaturesFile(file, type,
5026 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
5031 public void refreshFeatureUI(boolean enableIfNecessary)
5033 // note - currently this is only still here rather than in the controller
5034 // because of the featureSettings hard reference that is yet to be
5036 if (enableIfNecessary)
5038 viewport.setShowSequenceFeatures(true);
5039 showSeqFeatures.setSelected(true);
5045 public void dragEnter(DropTargetDragEvent evt)
5050 public void dragExit(DropTargetEvent evt)
5055 public void dragOver(DropTargetDragEvent evt)
5060 public void dropActionChanged(DropTargetDragEvent evt)
5065 public void drop(DropTargetDropEvent evt)
5067 Transferable t = evt.getTransferable();
5068 java.util.List files = null;
5072 DataFlavor uriListFlavor = new DataFlavor(
5073 "text/uri-list;class=java.lang.String");
5074 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
5076 // Works on Windows and MacOSX
5077 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
5078 files = (java.util.List) t
5079 .getTransferData(DataFlavor.javaFileListFlavor);
5081 else if (t.isDataFlavorSupported(uriListFlavor))
5083 // This is used by Unix drag system
5084 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
5085 String data = (String) t.getTransferData(uriListFlavor);
5086 files = new java.util.ArrayList(1);
5087 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
5088 data, "\r\n"); st.hasMoreTokens();)
5090 String s = st.nextToken();
5091 if (s.startsWith("#"))
5093 // the line is a comment (as per the RFC 2483)
5097 java.net.URI uri = new java.net.URI(s);
5098 // check to see if we can handle this kind of URI
5099 if (uri.getScheme().toLowerCase().startsWith("http"))
5101 files.add(uri.toString());
5105 // otherwise preserve old behaviour: catch all for file objects
5106 java.io.File file = new java.io.File(uri);
5107 files.add(file.toString());
5111 } catch (Exception e)
5113 e.printStackTrace();
5119 // check to see if any of these files have names matching sequences in
5121 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5122 .getAlignment().getSequencesArray());
5124 * Object[] { String,SequenceI}
5126 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
5127 ArrayList<String> filesnotmatched = new ArrayList<String>();
5128 for (int i = 0; i < files.size(); i++)
5130 String file = files.get(i).toString();
5132 String protocol = FormatAdapter.checkProtocol(file);
5133 if (protocol == jalview.io.FormatAdapter.FILE)
5135 File fl = new File(file);
5136 pdbfn = fl.getName();
5138 else if (protocol == jalview.io.FormatAdapter.URL)
5140 URL url = new URL(file);
5141 pdbfn = url.getFile();
5143 if (pdbfn.length() > 0)
5145 // attempt to find a match in the alignment
5146 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5147 int l = 0, c = pdbfn.indexOf(".");
5148 while (mtch == null && c != -1)
5153 } while ((c = pdbfn.indexOf(".", l)) > l);
5156 pdbfn = pdbfn.substring(0, l);
5158 mtch = idm.findAllIdMatches(pdbfn);
5165 type = new IdentifyFile().Identify(file, protocol);
5166 } catch (Exception ex)
5172 if (type.equalsIgnoreCase("PDB"))
5174 filesmatched.add(new Object[]
5175 { file, protocol, mtch });
5180 // File wasn't named like one of the sequences or wasn't a PDB file.
5181 filesnotmatched.add(file);
5185 if (filesmatched.size() > 0)
5187 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
5193 "label.automatically_associate_pdb_files_with_sequences_same_name",
5200 .getString("label.automatically_associate_pdb_files_by_name"),
5201 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
5204 for (Object[] fm : filesmatched)
5206 // try and associate
5207 // TODO: may want to set a standard ID naming formalism for
5208 // associating PDB files which have no IDs.
5209 for (SequenceI toassoc : (SequenceI[]) fm[2])
5211 PDBEntry pe = new AssociatePdbFileWithSeq()
5212 .associatePdbWithSeq((String) fm[0],
5213 (String) fm[1], toassoc, false,
5217 System.err.println("Associated file : "
5218 + ((String) fm[0]) + " with "
5219 + toassoc.getDisplayId(true));
5223 alignPanel.paintAlignment(true);
5227 if (filesnotmatched.size() > 0)
5230 && (Cache.getDefault(
5231 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
5234 "<html>"+MessageManager
5236 "label.ignore_unmatched_dropped_files_info",
5241 .toString() })+"</html>",
5243 .getString("label.ignore_unmatched_dropped_files"),
5244 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
5248 for (String fn : filesnotmatched)
5250 loadJalviewDataFile(fn, null, null, null);
5254 } catch (Exception ex)
5256 ex.printStackTrace();
5262 * Attempt to load a "dropped" file or URL string: First by testing whether
5263 * it's and Annotation file, then a JNet file, and finally a features file. If
5264 * all are false then the user may have dropped an alignment file onto this
5268 * either a filename or a URL string.
5270 public void loadJalviewDataFile(String file, String protocol,
5271 String format, SequenceI assocSeq)
5275 if (protocol == null)
5277 protocol = jalview.io.FormatAdapter.checkProtocol(file);
5279 // if the file isn't identified, or not positively identified as some
5280 // other filetype (PFAM is default unidentified alignment file type) then
5281 // try to parse as annotation.
5282 boolean isAnnotation = (format == null || format
5283 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
5284 .annotateAlignmentView(viewport, file, protocol)
5289 // first see if its a T-COFFEE score file
5290 TCoffeeScoreFile tcf = null;
5293 tcf = new TCoffeeScoreFile(file, protocol);
5296 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5298 tcoffeeColour.setEnabled(true);
5299 tcoffeeColour.setSelected(true);
5300 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5301 isAnnotation = true;
5303 .setText(MessageManager
5304 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5308 // some problem - if no warning its probable that the ID matching
5309 // process didn't work
5313 tcf.getWarningMessage() == null ? MessageManager
5314 .getString("label.check_file_matches_sequence_ids_alignment")
5315 : tcf.getWarningMessage(),
5317 .getString("label.problem_reading_tcoffee_score_file"),
5318 JOptionPane.WARNING_MESSAGE);
5325 } catch (Exception x)
5328 .debug("Exception when processing data source as T-COFFEE score file",
5334 // try to see if its a JNet 'concise' style annotation file *before*
5336 // try to parse it as a features file
5339 format = new IdentifyFile().Identify(file, protocol);
5341 if (format.equalsIgnoreCase("JnetFile"))
5343 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5345 new JnetAnnotationMaker();
5346 JnetAnnotationMaker.add_annotation(predictions,
5347 viewport.getAlignment(), 0, false);
5348 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
5349 viewport.getAlignment().setSeqrep(repseq);
5350 ColumnSelection cs = new ColumnSelection();
5351 cs.hideInsertionsFor(repseq);
5352 viewport.setColumnSelection(cs);
5353 isAnnotation = true;
5358 * if (format.equalsIgnoreCase("PDB")) {
5360 * String pdbfn = ""; // try to match up filename with sequence id
5361 * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
5362 * new File(file); pdbfn = fl.getName(); } else if (protocol ==
5363 * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
5364 * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
5365 * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5366 * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
5367 * // attempt to find a match in the alignment SequenceI mtch =
5368 * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
5369 * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
5370 * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
5371 * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
5372 * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
5373 * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
5374 * { System.err.println("Associated file : " + file + " with " +
5375 * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
5376 * TODO: maybe need to load as normal otherwise return; } }
5378 // try to parse it as a features file
5379 boolean isGroupsFile = parseFeaturesFile(file, protocol);
5380 // if it wasn't a features file then we just treat it as a general
5381 // alignment file to load into the current view.
5384 new FileLoader().LoadFile(viewport, file, protocol, format);
5388 alignPanel.paintAlignment(true);
5396 alignPanel.adjustAnnotationHeight();
5397 viewport.updateSequenceIdColours();
5398 buildSortByAnnotationScoresMenu();
5399 alignPanel.paintAlignment(true);
5401 } catch (Exception ex)
5403 ex.printStackTrace();
5404 } catch (OutOfMemoryError oom)
5409 } catch (Exception x)
5415 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5416 : "using " + protocol + " from " + file)
5418 + (format != null ? "(parsing as '" + format
5419 + "' file)" : ""), oom, Desktop.desktop);
5424 * Method invoked by the ChangeListener on the tabbed pane, in other words
5425 * when a different tabbed pane is selected by the user or programmatically.
5428 public void tabSelectionChanged(int index)
5432 alignPanel = alignPanels.get(index);
5433 viewport = alignPanel.av;
5434 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5435 setMenusFromViewport(viewport);
5439 * If there is a frame linked to this one in a SplitPane, switch it to the
5440 * same view tab index. No infinite recursion of calls should happen, since
5441 * tabSelectionChanged() should not get invoked on setting the selected
5442 * index to an unchanged value. Guard against setting an invalid index
5443 * before the new view peer tab has been created.
5445 final AlignViewportI peer = viewport.getCodingComplement();
5448 AlignFrame linkedAlignFrame = ((AlignViewport) peer).getAlignPanel().alignFrame;
5449 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5451 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5457 * On right mouse click on view tab, prompt for and set new view name.
5460 public void tabbedPane_mousePressed(MouseEvent e)
5462 if (SwingUtilities.isRightMouseButton(e))
5464 String msg = MessageManager.getString("label.enter_view_name");
5465 String reply = JOptionPane.showInternalInputDialog(this, msg, msg,
5466 JOptionPane.QUESTION_MESSAGE);
5470 viewport.viewName = reply;
5471 // TODO warn if reply is in getExistingViewNames()?
5472 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5477 public AlignViewport getCurrentView()
5483 * Open the dialog for regex description parsing.
5486 protected void extractScores_actionPerformed(ActionEvent e)
5488 ParseProperties pp = new jalview.analysis.ParseProperties(
5489 viewport.getAlignment());
5490 // TODO: verify regex and introduce GUI dialog for version 2.5
5491 // if (pp.getScoresFromDescription("col", "score column ",
5492 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5494 if (pp.getScoresFromDescription("description column",
5495 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5497 buildSortByAnnotationScoresMenu();
5505 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5509 protected void showDbRefs_actionPerformed(ActionEvent e)
5511 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5517 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5521 protected void showNpFeats_actionPerformed(ActionEvent e)
5523 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5527 * find the viewport amongst the tabs in this alignment frame and close that
5532 public boolean closeView(AlignViewportI av)
5536 this.closeMenuItem_actionPerformed(false);
5539 Component[] comp = tabbedPane.getComponents();
5540 for (int i = 0; comp != null && i < comp.length; i++)
5542 if (comp[i] instanceof AlignmentPanel)
5544 if (((AlignmentPanel) comp[i]).av == av)
5547 closeView((AlignmentPanel) comp[i]);
5555 protected void build_fetchdbmenu(JMenu webService)
5557 // Temporary hack - DBRef Fetcher always top level ws entry.
5558 // TODO We probably want to store a sequence database checklist in
5559 // preferences and have checkboxes.. rather than individual sources selected
5561 final JMenu rfetch = new JMenu(
5562 MessageManager.getString("action.fetch_db_references"));
5563 rfetch.setToolTipText(MessageManager
5564 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5565 webService.add(rfetch);
5567 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5568 MessageManager.getString("option.trim_retrieved_seqs"));
5569 trimrs.setToolTipText(MessageManager
5570 .getString("label.trim_retrieved_sequences"));
5571 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5572 trimrs.addActionListener(new ActionListener()
5575 public void actionPerformed(ActionEvent e)
5577 trimrs.setSelected(trimrs.isSelected());
5578 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5579 Boolean.valueOf(trimrs.isSelected()).toString());
5583 JMenuItem fetchr = new JMenuItem(
5584 MessageManager.getString("label.standard_databases"));
5585 fetchr.setToolTipText(MessageManager
5586 .getString("label.fetch_embl_uniprot"));
5587 fetchr.addActionListener(new ActionListener()
5591 public void actionPerformed(ActionEvent e)
5593 new Thread(new Runnable()
5599 new jalview.ws.DBRefFetcher(alignPanel.av
5600 .getSequenceSelection(), alignPanel.alignFrame)
5601 .fetchDBRefs(false);
5609 final AlignFrame me = this;
5610 new Thread(new Runnable()
5615 final jalview.ws.SequenceFetcher sf = SequenceFetcher
5616 .getSequenceFetcherSingleton(me);
5617 javax.swing.SwingUtilities.invokeLater(new Runnable()
5622 String[] dbclasses = sf.getOrderedSupportedSources();
5623 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5624 // jalview.util.QuickSort.sort(otherdb, otherdb);
5625 List<DbSourceProxy> otherdb;
5626 JMenu dfetch = new JMenu();
5627 JMenu ifetch = new JMenu();
5628 JMenuItem fetchr = null;
5629 int comp = 0, icomp = 0, mcomp = 15;
5630 String mname = null;
5632 for (String dbclass : dbclasses)
5634 otherdb = sf.getSourceProxy(dbclass);
5635 // add a single entry for this class, or submenu allowing 'fetch
5637 if (otherdb == null || otherdb.size() < 1)
5641 // List<DbSourceProxy> dbs=otherdb;
5642 // otherdb=new ArrayList<DbSourceProxy>();
5643 // for (DbSourceProxy db:dbs)
5645 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5649 mname = "From " + dbclass;
5651 if (otherdb.size() == 1)
5653 final DbSourceProxy[] dassource = otherdb
5654 .toArray(new DbSourceProxy[0]);
5655 DbSourceProxy src = otherdb.get(0);
5656 fetchr = new JMenuItem(src.getDbSource());
5657 fetchr.addActionListener(new ActionListener()
5661 public void actionPerformed(ActionEvent e)
5663 new Thread(new Runnable()
5669 new jalview.ws.DBRefFetcher(alignPanel.av
5670 .getSequenceSelection(),
5671 alignPanel.alignFrame, dassource)
5672 .fetchDBRefs(false);
5678 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from", new Object[]{src.getDbName()})));
5684 final DbSourceProxy[] dassource = otherdb
5685 .toArray(new DbSourceProxy[0]);
5687 DbSourceProxy src = otherdb.get(0);
5688 fetchr = new JMenuItem(MessageManager.formatMessage(
5689 "label.fetch_all_param", new Object[]
5690 { src.getDbSource() }));
5691 fetchr.addActionListener(new ActionListener()
5694 public void actionPerformed(ActionEvent e)
5696 new Thread(new Runnable()
5702 new jalview.ws.DBRefFetcher(alignPanel.av
5703 .getSequenceSelection(),
5704 alignPanel.alignFrame, dassource)
5705 .fetchDBRefs(false);
5711 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from_all_sources", new Object[]{Integer.valueOf(otherdb.size()).toString(), src.getDbSource(), src.getDbName()})));
5714 // and then build the rest of the individual menus
5715 ifetch = new JMenu(MessageManager.formatMessage("label.source_from_db_source", new Object[]{src.getDbSource()}));
5717 String imname = null;
5719 for (DbSourceProxy sproxy : otherdb)
5721 String dbname = sproxy.getDbName();
5722 String sname = dbname.length() > 5 ? dbname.substring(0,
5723 5) + "..." : dbname;
5724 String msname = dbname.length() > 10 ? dbname.substring(
5725 0, 10) + "..." : dbname;
5728 imname = MessageManager.formatMessage("label.from_msname", new Object[]{sname});
5730 fetchr = new JMenuItem(msname);
5731 final DbSourceProxy[] dassrc =
5733 fetchr.addActionListener(new ActionListener()
5737 public void actionPerformed(ActionEvent e)
5739 new Thread(new Runnable()
5745 new jalview.ws.DBRefFetcher(alignPanel.av
5746 .getSequenceSelection(),
5747 alignPanel.alignFrame, dassrc)
5748 .fetchDBRefs(false);
5754 fetchr.setToolTipText("<html>"
5755 + MessageManager.formatMessage("label.fetch_retrieve_from", new Object[]{dbname}));
5758 if (++icomp >= mcomp || i == (otherdb.size()))
5760 ifetch.setText(MessageManager.formatMessage(
5761 "label.source_to_target", imname, sname));
5763 ifetch = new JMenu();
5771 if (comp >= mcomp || dbi >= (dbclasses.length))
5773 dfetch.setText(MessageManager.formatMessage(
5774 "label.source_to_target", mname, dbclass));
5776 dfetch = new JMenu();
5789 * Left justify the whole alignment.
5792 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5794 AlignmentI al = viewport.getAlignment();
5796 viewport.firePropertyChange("alignment", null, al);
5800 * Right justify the whole alignment.
5803 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5805 AlignmentI al = viewport.getAlignment();
5807 viewport.firePropertyChange("alignment", null, al);
5810 public void setShowSeqFeatures(boolean b)
5812 showSeqFeatures.setSelected(b);
5813 viewport.setShowSequenceFeatures(b);
5820 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5821 * awt.event.ActionEvent)
5824 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5826 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5827 alignPanel.paintAlignment(true);
5834 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5838 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5840 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5841 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5849 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5850 * .event.ActionEvent)
5853 protected void showGroupConservation_actionPerformed(ActionEvent e)
5855 viewport.setShowGroupConservation(showGroupConservation.getState());
5856 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5863 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5864 * .event.ActionEvent)
5867 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5869 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5870 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5877 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5878 * .event.ActionEvent)
5881 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5883 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5884 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5888 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5890 showSequenceLogo.setState(true);
5891 viewport.setShowSequenceLogo(true);
5892 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5893 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5897 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5899 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5906 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5907 * .event.ActionEvent)
5910 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5912 if (avc.makeGroupsFromSelection())
5914 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5915 alignPanel.updateAnnotation();
5916 alignPanel.paintAlignment(true);
5919 public void clearAlignmentSeqRep()
5921 // TODO refactor alignmentseqrep to controller
5922 if (viewport.getAlignment().hasSeqrep()) {
5923 viewport.getAlignment().setSeqrep(null);
5924 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5925 alignPanel.updateAnnotation();
5926 alignPanel.paintAlignment(true);
5931 protected void createGroup_actionPerformed(ActionEvent e)
5933 if (avc.createGroup())
5935 alignPanel.alignmentChanged();
5940 protected void unGroup_actionPerformed(ActionEvent e)
5944 alignPanel.alignmentChanged();
5949 * make the given alignmentPanel the currently selected tab
5951 * @param alignmentPanel
5953 public void setDisplayedView(AlignmentPanel alignmentPanel)
5955 if (!viewport.getSequenceSetId().equals(
5956 alignmentPanel.av.getSequenceSetId()))
5958 throw new Error(MessageManager.getString("error.implementation_error_cannot_show_view_alignment_frame"));
5960 if (tabbedPane != null
5961 && tabbedPane.getTabCount() > 0
5962 && alignPanels.indexOf(alignmentPanel) != tabbedPane
5963 .getSelectedIndex())
5965 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5970 * Action on selection of menu options to Show or Hide annotations.
5973 * @param forSequences
5974 * update sequence-related annotations
5975 * @param forAlignment
5976 * update non-sequence-related annotations
5979 protected void setAnnotationsVisibility(boolean visible,
5980 boolean forSequences, boolean forAlignment)
5982 for (AlignmentAnnotation aa : alignPanel.getAlignment()
5983 .getAlignmentAnnotation())
5986 * don't display non-positional annotations on an alignment
5988 if (aa.annotations == null)
5992 boolean apply = (aa.sequenceRef == null && forAlignment)
5993 || (aa.sequenceRef != null && forSequences);
5996 aa.visible = visible;
5999 alignPanel.validateAnnotationDimensions(true);
6000 alignPanel.alignmentChanged();
6004 * Store selected annotation sort order for the view and repaint.
6007 protected void sortAnnotations_actionPerformed()
6009 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
6011 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
6012 alignPanel.paintAlignment(true);
6017 * @return alignment panels in this alignment frame
6019 public List<? extends AlignmentViewPanel> getAlignPanels()
6021 return alignPanels == null ? Arrays.asList(alignPanel)
6026 * Open a new alignment window, with the cDNA associated with this (protein)
6027 * alignment, aligned as is the protein.
6029 protected void viewAsCdna_actionPerformed()
6031 // TODO no longer a menu action - refactor as required
6032 final AlignmentI alignment = getViewport().getAlignment();
6033 Set<AlignedCodonFrame> mappings = alignment.getCodonFrames();
6034 if (mappings == null)
6038 List<SequenceI> cdnaSeqs = new ArrayList<SequenceI>();
6039 for (SequenceI aaSeq : alignment.getSequences()) {
6040 for (AlignedCodonFrame acf : mappings) {
6041 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
6045 * There is a cDNA mapping for this protein sequence - add to new
6046 * alignment. It will share the same dataset sequence as other mapped
6047 * cDNA (no new mappings need to be created).
6049 final Sequence newSeq = new Sequence(dnaSeq);
6050 newSeq.setDatasetSequence(dnaSeq);
6051 cdnaSeqs.add(newSeq);
6055 if (cdnaSeqs.size() == 0)
6057 // show a warning dialog no mapped cDNA
6060 AlignmentI cdna = new Alignment(cdnaSeqs.toArray(new SequenceI[cdnaSeqs
6062 AlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
6063 AlignFrame.DEFAULT_HEIGHT);
6064 cdna.alignAs(alignment);
6065 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
6067 Desktop.addInternalFrame(alignFrame, newtitle,
6068 AlignFrame.DEFAULT_WIDTH,
6069 AlignFrame.DEFAULT_HEIGHT);
6073 * Set visibility of dna/protein complement view (available when shown in a
6079 protected void showComplement_actionPerformed(boolean show)
6081 SplitContainerI sf = getSplitViewContainer();
6083 sf.setComplementVisible(this, show);
6089 class PrintThread extends Thread
6093 public PrintThread(AlignmentPanel ap)
6098 static PageFormat pf;
6103 PrinterJob printJob = PrinterJob.getPrinterJob();
6107 printJob.setPrintable(ap, pf);
6111 printJob.setPrintable(ap);
6114 if (printJob.printDialog())
6119 } catch (Exception PrintException)
6121 PrintException.printStackTrace();