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 java.awt.BorderLayout;
24 import java.awt.Component;
25 import java.awt.Rectangle;
26 import java.awt.Toolkit;
27 import java.awt.datatransfer.Clipboard;
28 import java.awt.datatransfer.DataFlavor;
29 import java.awt.datatransfer.StringSelection;
30 import java.awt.datatransfer.Transferable;
31 import java.awt.dnd.DnDConstants;
32 import java.awt.dnd.DropTargetDragEvent;
33 import java.awt.dnd.DropTargetDropEvent;
34 import java.awt.dnd.DropTargetEvent;
35 import java.awt.dnd.DropTargetListener;
36 import java.awt.event.ActionEvent;
37 import java.awt.event.ActionListener;
38 import java.awt.event.ItemEvent;
39 import java.awt.event.ItemListener;
40 import java.awt.event.KeyAdapter;
41 import java.awt.event.KeyEvent;
42 import java.awt.event.MouseAdapter;
43 import java.awt.event.MouseEvent;
44 import java.awt.print.PageFormat;
45 import java.awt.print.PrinterJob;
46 import java.beans.PropertyChangeEvent;
49 import java.util.ArrayList;
50 import java.util.Arrays;
51 import java.util.Deque;
52 import java.util.Enumeration;
53 import java.util.Hashtable;
54 import java.util.List;
56 import java.util.Vector;
58 import javax.swing.JCheckBoxMenuItem;
59 import javax.swing.JEditorPane;
60 import javax.swing.JInternalFrame;
61 import javax.swing.JLayeredPane;
62 import javax.swing.JMenu;
63 import javax.swing.JMenuItem;
64 import javax.swing.JOptionPane;
65 import javax.swing.JRadioButtonMenuItem;
66 import javax.swing.JScrollPane;
67 import javax.swing.SwingUtilities;
69 import jalview.analysis.AAFrequency;
70 import jalview.analysis.AlignmentSorter;
71 import jalview.analysis.AlignmentUtils;
72 import jalview.analysis.Conservation;
73 import jalview.analysis.CrossRef;
74 import jalview.analysis.Dna;
75 import jalview.analysis.ParseProperties;
76 import jalview.analysis.SequenceIdMatcher;
77 import jalview.api.AlignViewControllerGuiI;
78 import jalview.api.AlignViewControllerI;
79 import jalview.api.AlignViewportI;
80 import jalview.api.AlignmentViewPanel;
81 import jalview.api.SplitContainerI;
82 import jalview.api.ViewStyleI;
83 import jalview.api.analysis.ScoreModelI;
84 import jalview.bin.Cache;
85 import jalview.commands.CommandI;
86 import jalview.commands.EditCommand;
87 import jalview.commands.EditCommand.Action;
88 import jalview.commands.OrderCommand;
89 import jalview.commands.RemoveGapColCommand;
90 import jalview.commands.RemoveGapsCommand;
91 import jalview.commands.SlideSequencesCommand;
92 import jalview.commands.TrimRegionCommand;
93 import jalview.datamodel.AlignedCodonFrame;
94 import jalview.datamodel.Alignment;
95 import jalview.datamodel.AlignmentAnnotation;
96 import jalview.datamodel.AlignmentI;
97 import jalview.datamodel.AlignmentOrder;
98 import jalview.datamodel.AlignmentView;
99 import jalview.datamodel.ColumnSelection;
100 import jalview.datamodel.HiddenSequences;
101 import jalview.datamodel.PDBEntry;
102 import jalview.datamodel.SeqCigar;
103 import jalview.datamodel.Sequence;
104 import jalview.datamodel.SequenceGroup;
105 import jalview.datamodel.SequenceI;
106 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
107 import jalview.io.AlignmentProperties;
108 import jalview.io.AnnotationFile;
109 import jalview.io.BioJsHTMLOutput;
110 import jalview.io.FeaturesFile;
111 import jalview.io.FileLoader;
112 import jalview.io.FormatAdapter;
113 import jalview.io.HtmlSvgOutput;
114 import jalview.io.IdentifyFile;
115 import jalview.io.JalviewFileChooser;
116 import jalview.io.JalviewFileView;
117 import jalview.io.JnetAnnotationMaker;
118 import jalview.io.NewickFile;
119 import jalview.io.TCoffeeScoreFile;
120 import jalview.jbgui.GAlignFrame;
121 import jalview.schemes.Blosum62ColourScheme;
122 import jalview.schemes.BuriedColourScheme;
123 import jalview.schemes.ClustalxColourScheme;
124 import jalview.schemes.ColourSchemeI;
125 import jalview.schemes.ColourSchemeProperty;
126 import jalview.schemes.HelixColourScheme;
127 import jalview.schemes.HydrophobicColourScheme;
128 import jalview.schemes.NucleotideColourScheme;
129 import jalview.schemes.PIDColourScheme;
130 import jalview.schemes.PurinePyrimidineColourScheme;
131 import jalview.schemes.RNAHelicesColourChooser;
132 import jalview.schemes.ResidueProperties;
133 import jalview.schemes.StrandColourScheme;
134 import jalview.schemes.TCoffeeColourScheme;
135 import jalview.schemes.TaylorColourScheme;
136 import jalview.schemes.TurnColourScheme;
137 import jalview.schemes.UserColourScheme;
138 import jalview.schemes.ZappoColourScheme;
139 import jalview.structure.StructureSelectionManager;
140 import jalview.util.MessageManager;
141 import jalview.viewmodel.AlignmentViewport;
142 import jalview.ws.jws1.Discoverer;
143 import jalview.ws.jws2.Jws2Discoverer;
144 import jalview.ws.jws2.jabaws2.Jws2Instance;
145 import jalview.ws.seqfetcher.DbSourceProxy;
151 * @version $Revision$
153 public class AlignFrame extends GAlignFrame implements DropTargetListener,
154 IProgressIndicator, AlignViewControllerGuiI
157 public static final int DEFAULT_WIDTH = 700;
159 public static final int DEFAULT_HEIGHT = 500;
162 * The currently displayed panel (selected tabbed view if more than one)
164 public AlignmentPanel alignPanel;
166 AlignViewport viewport;
168 public AlignViewControllerI avc;
170 List<AlignmentPanel> alignPanels = new ArrayList<AlignmentPanel>();
173 * Last format used to load or save alignments in this window
175 String currentFileFormat = null;
178 * Current filename for this alignment
180 String fileName = null;
183 * Creates a new AlignFrame object with specific width and height.
189 public AlignFrame(AlignmentI al, int width, int height)
191 this(al, null, width, height);
195 * Creates a new AlignFrame object with specific width, height and
201 * @param sequenceSetId
203 public AlignFrame(AlignmentI al, int width, int height,
204 String sequenceSetId)
206 this(al, null, width, height, sequenceSetId);
210 * Creates a new AlignFrame object with specific width, height and
216 * @param sequenceSetId
219 public AlignFrame(AlignmentI al, int width, int height,
220 String sequenceSetId, String viewId)
222 this(al, null, width, height, sequenceSetId, viewId);
226 * new alignment window with hidden columns
230 * @param hiddenColumns
231 * ColumnSelection or null
233 * Width of alignment frame
237 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
238 int width, int height)
240 this(al, hiddenColumns, width, height, null);
244 * Create alignment frame for al with hiddenColumns, a specific width and
245 * height, and specific sequenceId
248 * @param hiddenColumns
251 * @param sequenceSetId
254 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
255 int width, int height, String sequenceSetId)
257 this(al, hiddenColumns, width, height, sequenceSetId, null);
261 * Create alignment frame for al with hiddenColumns, a specific width and
262 * height, and specific sequenceId
265 * @param hiddenColumns
268 * @param sequenceSetId
273 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
274 int width, int height, String sequenceSetId, String viewId)
276 setSize(width, height);
278 if (al.getDataset() == null)
283 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
285 alignPanel = new AlignmentPanel(this, viewport);
288 addAlignmentPanel(alignPanel, true);
293 * Make a new AlignFrame from existing alignmentPanels
300 public AlignFrame(AlignmentPanel ap)
304 addAlignmentPanel(ap, false);
309 * initalise the alignframe from the underlying viewport data and the
314 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
316 avc = new jalview.controller.AlignViewController(this, viewport,
318 if (viewport.getAlignmentConservationAnnotation() == null)
320 BLOSUM62Colour.setEnabled(false);
321 conservationMenuItem.setEnabled(false);
322 modifyConservation.setEnabled(false);
323 // PIDColour.setEnabled(false);
324 // abovePIDThreshold.setEnabled(false);
325 // modifyPID.setEnabled(false);
328 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
331 if (sortby.equals("Id"))
333 sortIDMenuItem_actionPerformed(null);
335 else if (sortby.equals("Pairwise Identity"))
337 sortPairwiseMenuItem_actionPerformed(null);
340 if (Desktop.desktop != null)
342 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
343 addServiceListeners();
344 setGUINucleotide(viewport.getAlignment().isNucleotide());
347 setMenusFromViewport(viewport);
348 buildSortByAnnotationScoresMenu();
351 if (viewport.getWrapAlignment())
353 wrapMenuItem_actionPerformed(null);
356 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
358 this.overviewMenuItem_actionPerformed(null);
363 final List<AlignmentPanel> selviews = new ArrayList<AlignmentPanel>();
364 final List<AlignmentPanel> origview = new ArrayList<AlignmentPanel>();
365 final String menuLabel = MessageManager
366 .getString("label.copy_format_from");
367 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
368 new ViewSetProvider()
372 public AlignmentPanel[] getAllAlignmentPanels()
375 origview.add(alignPanel);
376 // make an array of all alignment panels except for this one
377 List<AlignmentPanel> aps = new ArrayList<AlignmentPanel>(
378 Arrays.asList(Desktop.getAlignmentPanels(null)));
379 aps.remove(AlignFrame.this.alignPanel);
380 return aps.toArray(new AlignmentPanel[aps.size()]);
382 }, selviews, new ItemListener()
386 public void itemStateChanged(ItemEvent e)
388 if (origview.size() > 0)
390 final AlignmentPanel ap = origview.get(0);
393 * Copy the ViewStyle of the selected panel to 'this one'.
394 * Don't change value of 'scaleProteinAsCdna' unless copying
397 ViewStyleI vs = selviews.get(0).getAlignViewport()
399 boolean fromSplitFrame = selviews.get(0)
400 .getAlignViewport().getCodingComplement() != null;
403 vs.setScaleProteinAsCdna(ap.getAlignViewport()
404 .getViewStyle().isScaleProteinAsCdna());
406 ap.getAlignViewport().setViewStyle(vs);
409 * Also rescale ViewStyle of SplitFrame complement if there is
410 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
411 * the whole ViewStyle (allow cDNA protein to have different
414 AlignViewportI complement = ap.getAlignViewport()
415 .getCodingComplement();
416 if (complement != null && vs.isScaleProteinAsCdna())
418 AlignFrame af = Desktop.getAlignFrameFor(complement);
419 ((SplitFrame) af.getSplitViewContainer())
421 af.setMenusForViewport();
425 ap.setSelected(true);
426 ap.alignFrame.setMenusForViewport();
431 formatMenu.add(vsel);
436 * Change the filename and format for the alignment, and enable the 'reload'
437 * button functionality.
444 public void setFileName(String file, String format)
447 setFileFormat(format);
448 reload.setEnabled(true);
452 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
455 void addKeyListener()
457 addKeyListener(new KeyAdapter()
460 public void keyPressed(KeyEvent evt)
462 if (viewport.cursorMode
463 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
464 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
465 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
466 && Character.isDigit(evt.getKeyChar()))
468 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
471 switch (evt.getKeyCode())
474 case 27: // escape key
475 deselectAllSequenceMenuItem_actionPerformed(null);
479 case KeyEvent.VK_DOWN:
480 if (evt.isAltDown() || !viewport.cursorMode)
482 moveSelectedSequences(false);
484 if (viewport.cursorMode)
486 alignPanel.getSeqPanel().moveCursor(0, 1);
491 if (evt.isAltDown() || !viewport.cursorMode)
493 moveSelectedSequences(true);
495 if (viewport.cursorMode)
497 alignPanel.getSeqPanel().moveCursor(0, -1);
502 case KeyEvent.VK_LEFT:
503 if (evt.isAltDown() || !viewport.cursorMode)
505 slideSequences(false, alignPanel.getSeqPanel().getKeyboardNo1());
509 alignPanel.getSeqPanel().moveCursor(-1, 0);
514 case KeyEvent.VK_RIGHT:
515 if (evt.isAltDown() || !viewport.cursorMode)
517 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
521 alignPanel.getSeqPanel().moveCursor(1, 0);
525 case KeyEvent.VK_SPACE:
526 if (viewport.cursorMode)
528 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
529 || evt.isShiftDown() || evt.isAltDown());
533 // case KeyEvent.VK_A:
534 // if (viewport.cursorMode)
536 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
537 // //System.out.println("A");
541 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
542 * System.out.println("closing bracket"); } break;
544 case KeyEvent.VK_DELETE:
545 case KeyEvent.VK_BACK_SPACE:
546 if (!viewport.cursorMode)
548 cut_actionPerformed(null);
552 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
553 || evt.isShiftDown() || evt.isAltDown());
559 if (viewport.cursorMode)
561 alignPanel.getSeqPanel().setCursorRow();
565 if (viewport.cursorMode && !evt.isControlDown())
567 alignPanel.getSeqPanel().setCursorColumn();
571 if (viewport.cursorMode)
573 alignPanel.getSeqPanel().setCursorPosition();
577 case KeyEvent.VK_ENTER:
578 case KeyEvent.VK_COMMA:
579 if (viewport.cursorMode)
581 alignPanel.getSeqPanel().setCursorRowAndColumn();
586 if (viewport.cursorMode)
588 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
592 if (viewport.cursorMode)
594 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
599 viewport.cursorMode = !viewport.cursorMode;
600 statusBar.setText(MessageManager.formatMessage(
601 "label.keyboard_editing_mode", new String[]
602 { (viewport.cursorMode ? "on" : "off") }));
603 if (viewport.cursorMode)
605 alignPanel.getSeqPanel().seqCanvas.cursorX = viewport.startRes;
606 alignPanel.getSeqPanel().seqCanvas.cursorY = viewport.startSeq;
608 alignPanel.getSeqPanel().seqCanvas.repaint();
614 Help.showHelpWindow();
615 } catch (Exception ex)
617 ex.printStackTrace();
622 boolean toggleSeqs = !evt.isControlDown();
623 boolean toggleCols = !evt.isShiftDown();
624 toggleHiddenRegions(toggleSeqs, toggleCols);
627 case KeyEvent.VK_PAGE_UP:
628 if (viewport.getWrapAlignment())
630 alignPanel.scrollUp(true);
634 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
635 - viewport.endSeq + viewport.startSeq);
638 case KeyEvent.VK_PAGE_DOWN:
639 if (viewport.getWrapAlignment())
641 alignPanel.scrollUp(false);
645 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
646 + viewport.endSeq - viewport.startSeq);
653 public void keyReleased(KeyEvent evt)
655 switch (evt.getKeyCode())
657 case KeyEvent.VK_LEFT:
658 if (evt.isAltDown() || !viewport.cursorMode)
660 viewport.firePropertyChange("alignment", null, viewport
661 .getAlignment().getSequences());
665 case KeyEvent.VK_RIGHT:
666 if (evt.isAltDown() || !viewport.cursorMode)
668 viewport.firePropertyChange("alignment", null, viewport
669 .getAlignment().getSequences());
677 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
679 ap.alignFrame = this;
680 avc = new jalview.controller.AlignViewController(this, viewport,
685 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
687 int aSize = alignPanels.size();
689 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
691 if (aSize == 1 && ap.av.viewName == null)
693 this.getContentPane().add(ap, BorderLayout.CENTER);
699 setInitialTabVisible();
702 expandViews.setEnabled(true);
703 gatherViews.setEnabled(true);
704 tabbedPane.addTab(ap.av.viewName, ap);
706 ap.setVisible(false);
711 if (ap.av.isPadGaps())
713 ap.av.getAlignment().padGaps();
715 ap.av.updateConservation(ap);
716 ap.av.updateConsensus(ap);
717 ap.av.updateStrucConsensus(ap);
721 public void setInitialTabVisible()
723 expandViews.setEnabled(true);
724 gatherViews.setEnabled(true);
725 tabbedPane.setVisible(true);
726 AlignmentPanel first = alignPanels.get(0);
727 tabbedPane.addTab(first.av.viewName, first);
728 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
731 public AlignViewport getViewport()
736 /* Set up intrinsic listeners for dynamically generated GUI bits. */
737 private void addServiceListeners()
739 final java.beans.PropertyChangeListener thisListener;
740 Desktop.instance.addJalviewPropertyChangeListener("services",
741 thisListener = new java.beans.PropertyChangeListener()
744 public void propertyChange(PropertyChangeEvent evt)
746 // // System.out.println("Discoverer property change.");
747 // if (evt.getPropertyName().equals("services"))
749 SwingUtilities.invokeLater(new Runnable()
756 .println("Rebuild WS Menu for service change");
757 BuildWebServiceMenu();
764 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
767 public void internalFrameClosed(
768 javax.swing.event.InternalFrameEvent evt)
770 System.out.println("deregistering discoverer listener");
771 Desktop.instance.removeJalviewPropertyChangeListener("services",
773 closeMenuItem_actionPerformed(true);
776 // Finally, build the menu once to get current service state
777 new Thread(new Runnable()
782 BuildWebServiceMenu();
788 * Configure menu items that vary according to whether the alignment is
789 * nucleotide or protein
793 public void setGUINucleotide(boolean nucleotide)
795 showTranslation.setVisible(nucleotide);
796 conservationMenuItem.setEnabled(!nucleotide);
797 modifyConservation.setEnabled(!nucleotide);
798 showGroupConservation.setEnabled(!nucleotide);
799 rnahelicesColour.setEnabled(nucleotide);
800 purinePyrimidineColour.setEnabled(nucleotide);
801 showComplementMenuItem.setText(MessageManager
802 .getString(nucleotide ? "label.protein" : "label.nucleotide"));
803 setColourSelected(jalview.bin.Cache.getDefault(
804 nucleotide ? Preferences.DEFAULT_COLOUR_NUC
805 : Preferences.DEFAULT_COLOUR_PROT, "None"));
809 * set up menus for the current viewport. This may be called after any
810 * operation that affects the data in the current view (selection changed,
811 * etc) to update the menus to reflect the new state.
813 public void setMenusForViewport()
815 setMenusFromViewport(viewport);
819 * Need to call this method when tabs are selected for multiple views, or when
820 * loading from Jalview2XML.java
825 void setMenusFromViewport(AlignViewport av)
827 padGapsMenuitem.setSelected(av.isPadGaps());
828 colourTextMenuItem.setSelected(av.isShowColourText());
829 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
830 conservationMenuItem.setSelected(av.getConservationSelected());
831 seqLimits.setSelected(av.getShowJVSuffix());
832 idRightAlign.setSelected(av.isRightAlignIds());
833 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
834 renderGapsMenuItem.setSelected(av.isRenderGaps());
835 wrapMenuItem.setSelected(av.getWrapAlignment());
836 scaleAbove.setVisible(av.getWrapAlignment());
837 scaleLeft.setVisible(av.getWrapAlignment());
838 scaleRight.setVisible(av.getWrapAlignment());
839 annotationPanelMenuItem.setState(av.isShowAnnotation());
841 * Show/hide annotations only enabled if annotation panel is shown
843 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
844 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
845 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
846 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
847 viewBoxesMenuItem.setSelected(av.getShowBoxes());
848 viewTextMenuItem.setSelected(av.getShowText());
849 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
850 showGroupConsensus.setSelected(av.isShowGroupConsensus());
851 showGroupConservation.setSelected(av.isShowGroupConservation());
852 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
853 showSequenceLogo.setSelected(av.isShowSequenceLogo());
854 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
856 setColourSelected(ColourSchemeProperty.getColourName(av
857 .getGlobalColourScheme()));
859 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
860 hiddenMarkers.setState(av.getShowHiddenMarkers());
861 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
862 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
863 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
864 autoCalculate.setSelected(av.autoCalculateConsensus);
865 sortByTree.setSelected(av.sortByTree);
866 listenToViewSelections.setSelected(av.followSelection);
867 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
869 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
870 setShowProductsEnabled();
874 private IProgressIndicator progressBar;
879 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
882 public void setProgressBar(String message, long id)
884 progressBar.setProgressBar(message, id);
888 public void registerHandler(final long id,
889 final IProgressIndicatorHandler handler)
891 progressBar.registerHandler(id, handler);
896 * @return true if any progress bars are still active
899 public boolean operationInProgress()
901 return progressBar.operationInProgress();
905 public void setStatus(String text)
907 statusBar.setText(text);
911 * Added so Castor Mapping file can obtain Jalview Version
913 public String getVersion()
915 return jalview.bin.Cache.getProperty("VERSION");
918 public FeatureRenderer getFeatureRenderer()
920 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
924 public void fetchSequence_actionPerformed(ActionEvent e)
926 new SequenceFetcher(this);
930 public void addFromFile_actionPerformed(ActionEvent e)
932 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
936 public void reload_actionPerformed(ActionEvent e)
938 if (fileName != null)
940 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
941 // originating file's format
942 // TODO: work out how to recover feature settings for correct view(s) when
944 if (currentFileFormat.equals("Jalview"))
946 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
947 for (int i = 0; i < frames.length; i++)
949 if (frames[i] instanceof AlignFrame && frames[i] != this
950 && ((AlignFrame) frames[i]).fileName != null
951 && ((AlignFrame) frames[i]).fileName.equals(fileName))
955 frames[i].setSelected(true);
956 Desktop.instance.closeAssociatedWindows();
957 } catch (java.beans.PropertyVetoException ex)
963 Desktop.instance.closeAssociatedWindows();
965 FileLoader loader = new FileLoader();
966 String protocol = fileName.startsWith("http:") ? "URL" : "File";
967 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
971 Rectangle bounds = this.getBounds();
973 FileLoader loader = new FileLoader();
974 String protocol = fileName.startsWith("http:") ? "URL" : "File";
975 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
976 protocol, currentFileFormat);
978 newframe.setBounds(bounds);
979 if (featureSettings != null && featureSettings.isShowing())
981 final Rectangle fspos = featureSettings.frame.getBounds();
982 // TODO: need a 'show feature settings' function that takes bounds -
983 // need to refactor Desktop.addFrame
984 newframe.featureSettings_actionPerformed(null);
985 final FeatureSettings nfs = newframe.featureSettings;
986 SwingUtilities.invokeLater(new Runnable()
991 nfs.frame.setBounds(fspos);
994 this.featureSettings.close();
995 this.featureSettings = null;
997 this.closeMenuItem_actionPerformed(true);
1003 public void addFromText_actionPerformed(ActionEvent e)
1005 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
1009 public void addFromURL_actionPerformed(ActionEvent e)
1011 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1015 public void save_actionPerformed(ActionEvent e)
1017 if (fileName == null
1018 || (currentFileFormat == null || !jalview.io.FormatAdapter
1019 .isValidIOFormat(currentFileFormat, true))
1020 || fileName.startsWith("http"))
1022 saveAs_actionPerformed(null);
1026 saveAlignment(fileName, currentFileFormat);
1037 public void saveAs_actionPerformed(ActionEvent e)
1039 JalviewFileChooser chooser = new JalviewFileChooser(
1040 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
1041 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
1042 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
1043 currentFileFormat, false);
1045 chooser.setFileView(new JalviewFileView());
1046 chooser.setDialogTitle(MessageManager.getString("label.save_alignment_to_file"));
1047 chooser.setToolTipText(MessageManager.getString("action.save"));
1049 int value = chooser.showSaveDialog(this);
1051 if (value == JalviewFileChooser.APPROVE_OPTION)
1053 currentFileFormat = chooser.getSelectedFormat();
1054 while (currentFileFormat == null)
1057 .showInternalMessageDialog(
1060 .getString("label.select_file_format_before_saving"),
1062 .getString("label.file_format_not_specified"),
1063 JOptionPane.WARNING_MESSAGE);
1064 currentFileFormat = chooser.getSelectedFormat();
1065 value = chooser.showSaveDialog(this);
1066 if (value != JalviewFileChooser.APPROVE_OPTION)
1072 fileName = chooser.getSelectedFile().getPath();
1074 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
1077 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
1078 if (currentFileFormat.indexOf(" ") > -1)
1080 currentFileFormat = currentFileFormat.substring(0,
1081 currentFileFormat.indexOf(" "));
1083 saveAlignment(fileName, currentFileFormat);
1087 public boolean saveAlignment(String file, String format)
1089 boolean success = true;
1091 if (format.equalsIgnoreCase("Jalview"))
1093 String shortName = title;
1095 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1097 shortName = shortName.substring(shortName
1098 .lastIndexOf(java.io.File.separatorChar) + 1);
1101 success = new Jalview2XML().saveAlignment(this, file, shortName);
1103 statusBar.setText(MessageManager.formatMessage(
1104 "label.successfully_saved_to_file_in_format", new Object[]
1105 { fileName, format }));
1110 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1112 warningMessage("Cannot save file " + fileName + " using format "
1113 + format, "Alignment output format not supported");
1114 saveAs_actionPerformed(null);
1115 // JBPNote need to have a raise_gui flag here
1119 ExportData exportData = getAlignmentForExport();
1120 FormatAdapter f = new FormatAdapter(viewport);
1121 String output = f.formatSequences(format,
1122 exportData.getAlignment(), // class cast exceptions will
1123 // occur in the distant future
1124 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1125 f.getCacheSuffixDefault(format),
1126 viewport.getColumnSelection());
1136 java.io.PrintWriter out = new java.io.PrintWriter(
1137 new java.io.FileWriter(file));
1141 this.setTitle(file);
1142 statusBar.setText(MessageManager.formatMessage(
1143 "label.successfully_saved_to_file_in_format",
1145 { fileName, format }));
1146 } catch (Exception ex)
1149 ex.printStackTrace();
1156 JOptionPane.showInternalMessageDialog(this, MessageManager
1157 .formatMessage("label.couldnt_save_file", new Object[]
1158 { fileName }), MessageManager
1159 .getString("label.error_saving_file"),
1160 JOptionPane.WARNING_MESSAGE);
1167 private void warningMessage(String warning, String title)
1169 if (new jalview.util.Platform().isHeadless())
1171 System.err.println("Warning: " + title + "\nWarning: " + warning);
1176 JOptionPane.showInternalMessageDialog(this, warning, title,
1177 JOptionPane.WARNING_MESSAGE);
1189 protected void outputText_actionPerformed(ActionEvent e)
1192 ExportData exportData = getAlignmentForExport();
1193 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1194 cap.setForInput(null);
1198 cap.setText(new FormatAdapter(viewport).formatSequences(
1199 e.getActionCommand(),
1200 exportData.getAlignment(),
1201 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1202 viewport.getColumnSelection()));
1203 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1204 "label.alignment_output_command", new Object[]
1205 { e.getActionCommand() }), 600, 500);
1206 } catch (OutOfMemoryError oom)
1208 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1214 public ExportData getAlignmentForExport()
1216 AlignmentI alignmentToExport = null;
1217 String[] omitHidden = null;
1218 int[] alignmentStartEnd = new int[2];
1219 FeatureRenderer fr = new FeatureRenderer(this.alignPanel);
1220 viewport.setFeatureRenderer(fr);
1221 HiddenSequences hiddenSeqs = viewport.getAlignment()
1222 .getHiddenSequences();
1225 alignmentToExport = viewport.getAlignment();
1226 alignmentStartEnd = new int[]
1227 { 0, alignmentToExport.getWidth() - 1 };
1229 if (viewport.hasHiddenColumns() || hiddenSeqs.getSize() > 0)
1231 int reply = JOptionPane
1232 .showInternalConfirmDialog(
1235 .getString("label.alignment_contains_hidden_columns"),
1237 .getString("action.save_omit_hidden_columns"),
1238 JOptionPane.YES_NO_OPTION,
1239 JOptionPane.QUESTION_MESSAGE);
1241 if (reply == JOptionPane.YES_OPTION)
1243 // export only visible region
1244 omitHidden = viewport.getViewAsString(false);
1245 alignmentToExport = viewport.getAlignment();
1246 alignmentStartEnd = getStartEnd(alignmentStartEnd, viewport
1247 .getColumnSelection().getHiddenColumns());
1251 // export all region including visible
1252 alignmentToExport = hiddenSeqs.getFullAlignment();
1256 return new ExportData(alignmentToExport, omitHidden, alignmentStartEnd);
1259 private static int[] getStartEnd(int[] aligmentStartEnd,
1260 List<int[]> hiddenCols)
1262 int startPos = aligmentStartEnd[0];
1263 int endPos = aligmentStartEnd[1];
1265 int[] lowestRange = new int[2];
1266 int[] higestRange = new int[2];
1268 for (int[] hiddenCol : hiddenCols)
1270 // System.out.println("comparing : " + hiddenCol[0] + "-" + hiddenCol[1]);
1272 lowestRange = (hiddenCol[0] <= startPos) ? hiddenCol : lowestRange;
1273 higestRange = (hiddenCol[1] >= endPos) ? hiddenCol : higestRange;
1275 // System.out.println("min : " + lowestRange[0] + "-" + lowestRange[1]);
1276 // System.out.println("max : " + higestRange[0] + "-" + higestRange[1]);
1278 if (lowestRange[0] == 0 && lowestRange[1] == 0)
1280 startPos = aligmentStartEnd[0];
1284 startPos = lowestRange[1] + 1;
1287 if (higestRange[0] == 0 && higestRange[1] == 0)
1289 endPos = aligmentStartEnd[1];
1293 endPos = higestRange[0];
1296 // System.out.println("Export range : " + minPos + " - " + maxPos);
1298 { startPos, endPos };
1301 public static void main(String[] args)
1303 ArrayList<int[]> hiddenCols = new ArrayList<int[]>();
1304 hiddenCols.add(new int[]
1306 hiddenCols.add(new int[]
1308 hiddenCols.add(new int[]
1310 hiddenCols.add(new int[]
1312 hiddenCols.add(new int[]
1315 int[] x = getStartEnd(new int[]
1316 { 0, 50 }, hiddenCols);
1317 // System.out.println("Export range : " + x[0] + " - " + x[1]);
1327 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1329 // new HTMLOutput(alignPanel,
1330 // alignPanel.getSeqPanel().seqCanvas.getSequenceRenderer(),
1331 // alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
1332 new HtmlSvgOutput(null, alignPanel);
1336 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1338 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel,
1339 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
1340 bjs.exportJalviewAlignmentAsBioJsHtmlFile();
1342 public void createImageMap(File file, String image)
1344 alignPanel.makePNGImageMap(file, image);
1354 public void createPNG(File f)
1356 alignPanel.makePNG(f);
1366 public void createEPS(File f)
1368 alignPanel.makeEPS(f);
1371 public void createSVG(File f)
1373 alignPanel.makeSVG(f);
1376 public void pageSetup_actionPerformed(ActionEvent e)
1378 PrinterJob printJob = PrinterJob.getPrinterJob();
1379 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1389 public void printMenuItem_actionPerformed(ActionEvent e)
1391 // Putting in a thread avoids Swing painting problems
1392 PrintThread thread = new PrintThread(alignPanel);
1397 public void exportFeatures_actionPerformed(ActionEvent e)
1399 new AnnotationExporter().exportFeatures(alignPanel);
1403 public void exportAnnotations_actionPerformed(ActionEvent e)
1405 new AnnotationExporter().exportAnnotations(alignPanel);
1409 public void associatedData_actionPerformed(ActionEvent e)
1411 // Pick the tree file
1412 JalviewFileChooser chooser = new JalviewFileChooser(
1413 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1414 chooser.setFileView(new JalviewFileView());
1415 chooser.setDialogTitle(MessageManager
1416 .getString("label.load_jalview_annotations"));
1417 chooser.setToolTipText(MessageManager
1418 .getString("label.load_jalview_annotations"));
1420 int value = chooser.showOpenDialog(null);
1422 if (value == JalviewFileChooser.APPROVE_OPTION)
1424 String choice = chooser.getSelectedFile().getPath();
1425 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1426 loadJalviewDataFile(choice, null, null, null);
1432 * Close the current view or all views in the alignment frame. If the frame
1433 * only contains one view then the alignment will be removed from memory.
1435 * @param closeAllTabs
1438 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1440 if (alignPanels != null && alignPanels.size() < 2)
1442 closeAllTabs = true;
1447 if (alignPanels != null)
1451 if (this.isClosed())
1453 // really close all the windows - otherwise wait till
1454 // setClosed(true) is called
1455 for (int i = 0; i < alignPanels.size(); i++)
1457 AlignmentPanel ap = alignPanels.get(i);
1464 closeView(alignPanel);
1470 this.setClosed(true);
1472 } catch (Exception ex)
1474 ex.printStackTrace();
1479 * Close the specified panel and close up tabs appropriately.
1481 * @param panelToClose
1483 public void closeView(AlignmentPanel panelToClose)
1485 int index = tabbedPane.getSelectedIndex();
1486 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1487 alignPanels.remove(panelToClose);
1488 panelToClose.closePanel();
1489 panelToClose = null;
1491 tabbedPane.removeTabAt(closedindex);
1492 tabbedPane.validate();
1494 if (index > closedindex || index == tabbedPane.getTabCount())
1496 // modify currently selected tab index if necessary.
1500 this.tabSelectionChanged(index);
1506 void updateEditMenuBar()
1509 if (viewport.getHistoryList().size() > 0)
1511 undoMenuItem.setEnabled(true);
1512 CommandI command = viewport.getHistoryList().peek();
1513 undoMenuItem.setText(MessageManager.formatMessage(
1514 "label.undo_command", new Object[]
1515 { command.getDescription() }));
1519 undoMenuItem.setEnabled(false);
1520 undoMenuItem.setText(MessageManager.getString("action.undo"));
1523 if (viewport.getRedoList().size() > 0)
1525 redoMenuItem.setEnabled(true);
1527 CommandI command = viewport.getRedoList().peek();
1528 redoMenuItem.setText(MessageManager.formatMessage(
1529 "label.redo_command", new Object[]
1530 { command.getDescription() }));
1534 redoMenuItem.setEnabled(false);
1535 redoMenuItem.setText(MessageManager.getString("action.redo"));
1539 public void addHistoryItem(CommandI command)
1541 if (command.getSize() > 0)
1543 viewport.addToHistoryList(command);
1544 viewport.clearRedoList();
1545 updateEditMenuBar();
1546 viewport.updateHiddenColumns();
1547 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1548 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1549 // viewport.getColumnSelection()
1550 // .getHiddenColumns().size() > 0);
1556 * @return alignment objects for all views
1558 AlignmentI[] getViewAlignments()
1560 if (alignPanels != null)
1562 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1564 for (AlignmentPanel ap : alignPanels)
1566 als[i++] = ap.av.getAlignment();
1570 if (viewport != null)
1572 return new AlignmentI[]
1573 { viewport.getAlignment() };
1585 protected void undoMenuItem_actionPerformed(ActionEvent e)
1587 if (viewport.getHistoryList().isEmpty())
1591 CommandI command = viewport.getHistoryList().pop();
1592 viewport.addToRedoList(command);
1593 command.undoCommand(getViewAlignments());
1595 AlignmentViewport originalSource = getOriginatingSource(command);
1596 updateEditMenuBar();
1598 if (originalSource != null)
1600 if (originalSource != viewport)
1603 .warn("Implementation worry: mismatch of viewport origin for undo");
1605 originalSource.updateHiddenColumns();
1606 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1608 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1609 // viewport.getColumnSelection()
1610 // .getHiddenColumns().size() > 0);
1611 originalSource.firePropertyChange("alignment", null, originalSource
1612 .getAlignment().getSequences());
1623 protected void redoMenuItem_actionPerformed(ActionEvent e)
1625 if (viewport.getRedoList().size() < 1)
1630 CommandI command = viewport.getRedoList().pop();
1631 viewport.addToHistoryList(command);
1632 command.doCommand(getViewAlignments());
1634 AlignmentViewport originalSource = getOriginatingSource(command);
1635 updateEditMenuBar();
1637 if (originalSource != null)
1640 if (originalSource != viewport)
1643 .warn("Implementation worry: mismatch of viewport origin for redo");
1645 originalSource.updateHiddenColumns();
1646 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1648 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1649 // viewport.getColumnSelection()
1650 // .getHiddenColumns().size() > 0);
1651 originalSource.firePropertyChange("alignment", null, originalSource
1652 .getAlignment().getSequences());
1656 AlignmentViewport getOriginatingSource(CommandI command)
1658 AlignmentViewport originalSource = null;
1659 // For sequence removal and addition, we need to fire
1660 // the property change event FROM the viewport where the
1661 // original alignment was altered
1662 AlignmentI al = null;
1663 if (command instanceof EditCommand)
1665 EditCommand editCommand = (EditCommand) command;
1666 al = editCommand.getAlignment();
1667 List<Component> comps = PaintRefresher.components.get(viewport
1668 .getSequenceSetId());
1670 for (Component comp : comps)
1672 if (comp instanceof AlignmentPanel)
1674 if (al == ((AlignmentPanel) comp).av.getAlignment())
1676 originalSource = ((AlignmentPanel) comp).av;
1683 if (originalSource == null)
1685 // The original view is closed, we must validate
1686 // the current view against the closed view first
1689 PaintRefresher.validateSequences(al, viewport.getAlignment());
1692 originalSource = viewport;
1695 return originalSource;
1704 public void moveSelectedSequences(boolean up)
1706 SequenceGroup sg = viewport.getSelectionGroup();
1712 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1713 viewport.getHiddenRepSequences(), up);
1714 alignPanel.paintAlignment(true);
1717 synchronized void slideSequences(boolean right, int size)
1719 List<SequenceI> sg = new ArrayList<SequenceI>();
1720 if (viewport.cursorMode)
1722 sg.add(viewport.getAlignment().getSequenceAt(
1723 alignPanel.getSeqPanel().seqCanvas.cursorY));
1725 else if (viewport.getSelectionGroup() != null
1726 && viewport.getSelectionGroup().getSize() != viewport
1727 .getAlignment().getHeight())
1729 sg = viewport.getSelectionGroup().getSequences(
1730 viewport.getHiddenRepSequences());
1738 List<SequenceI> invertGroup = new ArrayList<SequenceI>();
1740 for (SequenceI seq : viewport.getAlignment().getSequences())
1742 if (!sg.contains(seq))
1744 invertGroup.add(seq);
1748 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1750 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1751 for (int i = 0; i < invertGroup.size(); i++)
1753 seqs2[i] = invertGroup.get(i);
1756 SlideSequencesCommand ssc;
1759 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1760 size, viewport.getGapCharacter());
1764 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1765 size, viewport.getGapCharacter());
1768 int groupAdjustment = 0;
1769 if (ssc.getGapsInsertedBegin() && right)
1771 if (viewport.cursorMode)
1773 alignPanel.getSeqPanel().moveCursor(size, 0);
1777 groupAdjustment = size;
1780 else if (!ssc.getGapsInsertedBegin() && !right)
1782 if (viewport.cursorMode)
1784 alignPanel.getSeqPanel().moveCursor(-size, 0);
1788 groupAdjustment = -size;
1792 if (groupAdjustment != 0)
1794 viewport.getSelectionGroup().setStartRes(
1795 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1796 viewport.getSelectionGroup().setEndRes(
1797 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1800 boolean appendHistoryItem = false;
1801 Deque<CommandI> historyList = viewport.getHistoryList();
1802 if (historyList != null
1803 && historyList.size() > 0
1804 && historyList.peek() instanceof SlideSequencesCommand)
1806 appendHistoryItem = ssc
1807 .appendSlideCommand((SlideSequencesCommand) historyList
1811 if (!appendHistoryItem)
1813 addHistoryItem(ssc);
1826 protected void copy_actionPerformed(ActionEvent e)
1829 if (viewport.getSelectionGroup() == null)
1833 // TODO: preserve the ordering of displayed alignment annotation in any
1834 // internal paste (particularly sequence associated annotation)
1835 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1836 String[] omitHidden = null;
1838 if (viewport.hasHiddenColumns())
1840 omitHidden = viewport.getViewAsString(true);
1843 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1846 StringSelection ss = new StringSelection(output);
1850 jalview.gui.Desktop.internalCopy = true;
1851 // Its really worth setting the clipboard contents
1852 // to empty before setting the large StringSelection!!
1853 Toolkit.getDefaultToolkit().getSystemClipboard()
1854 .setContents(new StringSelection(""), null);
1856 Toolkit.getDefaultToolkit().getSystemClipboard()
1857 .setContents(ss, Desktop.instance);
1858 } catch (OutOfMemoryError er)
1860 new OOMWarning("copying region", er);
1864 ArrayList<int[]> hiddenColumns = null;
1865 if (viewport.hasHiddenColumns())
1867 hiddenColumns = new ArrayList<int[]>();
1868 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1869 .getSelectionGroup().getEndRes();
1870 for (int[] region : viewport.getColumnSelection().getHiddenColumns())
1872 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1874 hiddenColumns.add(new int[]
1875 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1880 Desktop.jalviewClipboard = new Object[]
1881 { seqs, viewport.getAlignment().getDataset(), hiddenColumns };
1882 statusBar.setText(MessageManager.formatMessage(
1883 "label.copied_sequences_to_clipboard", new Object[]
1884 { Integer.valueOf(seqs.length).toString() }));
1894 protected void pasteNew_actionPerformed(ActionEvent e)
1906 protected void pasteThis_actionPerformed(ActionEvent e)
1912 * Paste contents of Jalview clipboard
1914 * @param newAlignment
1915 * true to paste to a new alignment, otherwise add to this.
1917 void paste(boolean newAlignment)
1919 boolean externalPaste = true;
1922 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1923 Transferable contents = c.getContents(this);
1925 if (contents == null)
1933 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1934 if (str.length() < 1)
1939 format = new IdentifyFile().Identify(str, "Paste");
1941 } catch (OutOfMemoryError er)
1943 new OOMWarning("Out of memory pasting sequences!!", er);
1947 SequenceI[] sequences;
1948 boolean annotationAdded = false;
1949 AlignmentI alignment = null;
1951 if (Desktop.jalviewClipboard != null)
1953 // The clipboard was filled from within Jalview, we must use the
1955 // And dataset from the copied alignment
1956 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1957 // be doubly sure that we create *new* sequence objects.
1958 sequences = new SequenceI[newseq.length];
1959 for (int i = 0; i < newseq.length; i++)
1961 sequences[i] = new Sequence(newseq[i]);
1963 alignment = new Alignment(sequences);
1964 externalPaste = false;
1968 // parse the clipboard as an alignment.
1969 alignment = new FormatAdapter().readFile(str, "Paste", format);
1970 sequences = alignment.getSequencesArray();
1974 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1980 if (Desktop.jalviewClipboard != null)
1982 // dataset is inherited
1983 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1987 // new dataset is constructed
1988 alignment.setDataset(null);
1990 alwidth = alignment.getWidth() + 1;
1994 AlignmentI pastedal = alignment; // preserve pasted alignment object
1995 // Add pasted sequences and dataset into existing alignment.
1996 alignment = viewport.getAlignment();
1997 alwidth = alignment.getWidth() + 1;
1998 // decide if we need to import sequences from an existing dataset
1999 boolean importDs = Desktop.jalviewClipboard != null
2000 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2001 // importDs==true instructs us to copy over new dataset sequences from
2002 // an existing alignment
2003 Vector newDs = (importDs) ? new Vector() : null; // used to create
2004 // minimum dataset set
2006 for (int i = 0; i < sequences.length; i++)
2010 newDs.addElement(null);
2012 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2014 if (importDs && ds != null)
2016 if (!newDs.contains(ds))
2018 newDs.setElementAt(ds, i);
2019 ds = new Sequence(ds);
2020 // update with new dataset sequence
2021 sequences[i].setDatasetSequence(ds);
2025 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2030 // copy and derive new dataset sequence
2031 sequences[i] = sequences[i].deriveSequence();
2032 alignment.getDataset().addSequence(
2033 sequences[i].getDatasetSequence());
2034 // TODO: avoid creation of duplicate dataset sequences with a
2035 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2037 alignment.addSequence(sequences[i]); // merges dataset
2041 newDs.clear(); // tidy up
2043 if (alignment.getAlignmentAnnotation() != null)
2045 for (AlignmentAnnotation alan : alignment
2046 .getAlignmentAnnotation())
2048 if (alan.graphGroup > fgroup)
2050 fgroup = alan.graphGroup;
2054 if (pastedal.getAlignmentAnnotation() != null)
2056 // Add any annotation attached to alignment.
2057 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2058 for (int i = 0; i < alann.length; i++)
2060 annotationAdded = true;
2061 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2063 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2064 if (newann.graphGroup > -1)
2066 if (newGraphGroups.size() <= newann.graphGroup
2067 || newGraphGroups.get(newann.graphGroup) == null)
2069 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2071 newGraphGroups.add(q, null);
2073 newGraphGroups.set(newann.graphGroup, new Integer(
2076 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2080 newann.padAnnotation(alwidth);
2081 alignment.addAnnotation(newann);
2091 addHistoryItem(new EditCommand(
2092 MessageManager.getString("label.add_sequences"),
2094 sequences, 0, alignment.getWidth(), alignment));
2096 // Add any annotations attached to sequences
2097 for (int i = 0; i < sequences.length; i++)
2099 if (sequences[i].getAnnotation() != null)
2101 AlignmentAnnotation newann;
2102 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2104 annotationAdded = true;
2105 newann = sequences[i].getAnnotation()[a];
2106 newann.adjustForAlignment();
2107 newann.padAnnotation(alwidth);
2108 if (newann.graphGroup > -1)
2110 if (newann.graphGroup > -1)
2112 if (newGraphGroups.size() <= newann.graphGroup
2113 || newGraphGroups.get(newann.graphGroup) == null)
2115 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2117 newGraphGroups.add(q, null);
2119 newGraphGroups.set(newann.graphGroup, new Integer(
2122 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2126 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2131 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2138 // propagate alignment changed.
2139 viewport.setEndSeq(alignment.getHeight());
2140 if (annotationAdded)
2142 // Duplicate sequence annotation in all views.
2143 AlignmentI[] alview = this.getViewAlignments();
2144 for (int i = 0; i < sequences.length; i++)
2146 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2151 for (int avnum = 0; avnum < alview.length; avnum++)
2153 if (alview[avnum] != alignment)
2155 // duplicate in a view other than the one with input focus
2156 int avwidth = alview[avnum].getWidth() + 1;
2157 // this relies on sann being preserved after we
2158 // modify the sequence's annotation array for each duplication
2159 for (int a = 0; a < sann.length; a++)
2161 AlignmentAnnotation newann = new AlignmentAnnotation(
2163 sequences[i].addAlignmentAnnotation(newann);
2164 newann.padAnnotation(avwidth);
2165 alview[avnum].addAnnotation(newann); // annotation was
2166 // duplicated earlier
2167 // TODO JAL-1145 graphGroups are not updated for sequence
2168 // annotation added to several views. This may cause
2170 alview[avnum].setAnnotationIndex(newann, a);
2175 buildSortByAnnotationScoresMenu();
2177 viewport.firePropertyChange("alignment", null,
2178 alignment.getSequences());
2179 if (alignPanels != null)
2181 for (AlignmentPanel ap : alignPanels)
2183 ap.validateAnnotationDimensions(false);
2188 alignPanel.validateAnnotationDimensions(false);
2194 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2196 String newtitle = new String("Copied sequences");
2198 if (Desktop.jalviewClipboard != null
2199 && Desktop.jalviewClipboard[2] != null)
2201 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2202 for (int[] region : hc)
2204 af.viewport.hideColumns(region[0], region[1]);
2208 // >>>This is a fix for the moment, until a better solution is
2210 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2212 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
2214 // TODO: maintain provenance of an alignment, rather than just make the
2215 // title a concatenation of operations.
2218 if (title.startsWith("Copied sequences"))
2224 newtitle = newtitle.concat("- from " + title);
2229 newtitle = new String("Pasted sequences");
2232 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2237 } catch (Exception ex)
2239 ex.printStackTrace();
2240 System.out.println("Exception whilst pasting: " + ex);
2241 // could be anything being pasted in here
2247 protected void expand_newalign(ActionEvent e)
2251 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2252 .getAlignment(), -1);
2253 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2255 String newtitle = new String("Flanking alignment");
2257 if (Desktop.jalviewClipboard != null
2258 && Desktop.jalviewClipboard[2] != null)
2260 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2261 for (int region[] : hc)
2263 af.viewport.hideColumns(region[0], region[1]);
2267 // >>>This is a fix for the moment, until a better solution is
2269 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2271 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
2273 // TODO: maintain provenance of an alignment, rather than just make the
2274 // title a concatenation of operations.
2276 if (title.startsWith("Copied sequences"))
2282 newtitle = newtitle.concat("- from " + title);
2286 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2288 } catch (Exception ex)
2290 ex.printStackTrace();
2291 System.out.println("Exception whilst pasting: " + ex);
2292 // could be anything being pasted in here
2293 } catch (OutOfMemoryError oom)
2295 new OOMWarning("Viewing flanking region of alignment", oom);
2306 protected void cut_actionPerformed(ActionEvent e)
2308 copy_actionPerformed(null);
2309 delete_actionPerformed(null);
2319 protected void delete_actionPerformed(ActionEvent evt)
2322 SequenceGroup sg = viewport.getSelectionGroup();
2329 * If the cut affects all sequences, warn, remove highlighted columns
2331 if (sg.getSize() == viewport.getAlignment().getHeight())
2333 int confirm = JOptionPane.showConfirmDialog(this,
2334 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2335 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2336 JOptionPane.OK_CANCEL_OPTION);
2338 if (confirm == JOptionPane.CANCEL_OPTION
2339 || confirm == JOptionPane.CLOSED_OPTION)
2343 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2344 sg.getEndRes() + 1);
2347 SequenceI[] cut = sg.getSequences()
2348 .toArray(new SequenceI[sg.getSize()]);
2350 addHistoryItem(new EditCommand(
2351 MessageManager.getString("label.cut_sequences"), Action.CUT,
2352 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2353 viewport.getAlignment()));
2355 viewport.setSelectionGroup(null);
2356 viewport.sendSelection();
2357 viewport.getAlignment().deleteGroup(sg);
2359 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2361 if (viewport.getAlignment().getHeight() < 1)
2365 this.setClosed(true);
2366 } catch (Exception ex)
2379 protected void deleteGroups_actionPerformed(ActionEvent e)
2381 if (avc.deleteGroups())
2383 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2384 alignPanel.updateAnnotation();
2385 alignPanel.paintAlignment(true);
2396 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2398 SequenceGroup sg = new SequenceGroup();
2400 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2402 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2405 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2406 viewport.setSelectionGroup(sg);
2407 viewport.sendSelection();
2408 alignPanel.paintAlignment(true);
2409 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2419 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2421 if (viewport.cursorMode)
2423 alignPanel.getSeqPanel().keyboardNo1 = null;
2424 alignPanel.getSeqPanel().keyboardNo2 = null;
2426 viewport.setSelectionGroup(null);
2427 viewport.getColumnSelection().clear();
2428 viewport.setSelectionGroup(null);
2429 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2430 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2431 alignPanel.paintAlignment(true);
2432 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2433 viewport.sendSelection();
2443 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2445 SequenceGroup sg = viewport.getSelectionGroup();
2449 selectAllSequenceMenuItem_actionPerformed(null);
2454 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2456 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2459 alignPanel.paintAlignment(true);
2460 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2461 viewport.sendSelection();
2465 public void invertColSel_actionPerformed(ActionEvent e)
2467 viewport.invertColumnSelection();
2468 alignPanel.paintAlignment(true);
2469 viewport.sendSelection();
2479 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2481 trimAlignment(true);
2491 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2493 trimAlignment(false);
2496 void trimAlignment(boolean trimLeft)
2498 ColumnSelection colSel = viewport.getColumnSelection();
2501 if (colSel.size() > 0)
2505 column = colSel.getMin();
2509 column = colSel.getMax();
2513 if (viewport.getSelectionGroup() != null)
2515 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2516 viewport.getHiddenRepSequences());
2520 seqs = viewport.getAlignment().getSequencesArray();
2523 TrimRegionCommand trimRegion;
2526 trimRegion = new TrimRegionCommand("Remove Left",
2527 TrimRegionCommand.TRIM_LEFT, seqs, column,
2528 viewport.getAlignment(), viewport.getColumnSelection(),
2529 viewport.getSelectionGroup());
2530 viewport.setStartRes(0);
2534 trimRegion = new TrimRegionCommand("Remove Right",
2535 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2536 viewport.getAlignment(), viewport.getColumnSelection(),
2537 viewport.getSelectionGroup());
2540 statusBar.setText(MessageManager.formatMessage(
2541 "label.removed_columns", new String[]
2542 { Integer.valueOf(trimRegion.getSize()).toString() }));
2544 addHistoryItem(trimRegion);
2546 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2548 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2549 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2551 viewport.getAlignment().deleteGroup(sg);
2555 viewport.firePropertyChange("alignment", null, viewport
2556 .getAlignment().getSequences());
2567 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2569 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2572 if (viewport.getSelectionGroup() != null)
2574 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2575 viewport.getHiddenRepSequences());
2576 start = viewport.getSelectionGroup().getStartRes();
2577 end = viewport.getSelectionGroup().getEndRes();
2581 seqs = viewport.getAlignment().getSequencesArray();
2584 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2585 "Remove Gapped Columns", seqs, start, end,
2586 viewport.getAlignment());
2588 addHistoryItem(removeGapCols);
2590 statusBar.setText(MessageManager.formatMessage(
2591 "label.removed_empty_columns", new Object[]
2592 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2594 // This is to maintain viewport position on first residue
2595 // of first sequence
2596 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2597 int startRes = seq.findPosition(viewport.startRes);
2598 // ShiftList shifts;
2599 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2600 // edit.alColumnChanges=shifts.getInverse();
2601 // if (viewport.hasHiddenColumns)
2602 // viewport.getColumnSelection().compensateForEdits(shifts);
2603 viewport.setStartRes(seq.findIndex(startRes) - 1);
2604 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2616 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2618 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2621 if (viewport.getSelectionGroup() != null)
2623 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2624 viewport.getHiddenRepSequences());
2625 start = viewport.getSelectionGroup().getStartRes();
2626 end = viewport.getSelectionGroup().getEndRes();
2630 seqs = viewport.getAlignment().getSequencesArray();
2633 // This is to maintain viewport position on first residue
2634 // of first sequence
2635 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2636 int startRes = seq.findPosition(viewport.startRes);
2638 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2639 viewport.getAlignment()));
2641 viewport.setStartRes(seq.findIndex(startRes) - 1);
2643 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2655 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2657 viewport.setPadGaps(padGapsMenuitem.isSelected());
2658 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2669 public void findMenuItem_actionPerformed(ActionEvent e)
2675 * Create a new view of the current alignment.
2678 public void newView_actionPerformed(ActionEvent e)
2680 newView(null, true);
2684 * Creates and shows a new view of the current alignment.
2687 * title of newly created view; if null, one will be generated
2688 * @param copyAnnotation
2689 * if true then duplicate all annnotation, groups and settings
2690 * @return new alignment panel, already displayed.
2692 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2695 * Create a new AlignmentPanel (with its own, new Viewport)
2697 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2699 if (!copyAnnotation)
2702 * remove all groups and annotation except for the automatic stuff
2704 newap.av.getAlignment().deleteAllGroups();
2705 newap.av.getAlignment().deleteAllAnnotations(false);
2708 newap.av.setGatherViewsHere(false);
2710 if (viewport.viewName == null)
2712 viewport.viewName = MessageManager
2713 .getString("label.view_name_original");
2717 * Views share the same edits, undo and redo stacks, mappings.
2719 newap.av.setHistoryList(viewport.getHistoryList());
2720 newap.av.setRedoList(viewport.getRedoList());
2721 newap.av.getAlignment().setCodonFrames(
2722 viewport.getAlignment().getCodonFrames());
2724 newap.av.viewName = getNewViewName(viewTitle);
2726 addAlignmentPanel(newap, true);
2727 newap.alignmentChanged();
2729 if (alignPanels.size() == 2)
2731 viewport.setGatherViewsHere(true);
2733 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2738 * Make a new name for the view, ensuring it is unique within the current
2739 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2740 * these now use viewId. Unique view names are still desirable for usability.)
2745 protected String getNewViewName(String viewTitle)
2747 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2748 boolean addFirstIndex = false;
2749 if (viewTitle == null || viewTitle.trim().length() == 0)
2751 viewTitle = MessageManager.getString("action.view");
2752 addFirstIndex = true;
2756 index = 1;// we count from 1 if given a specific name
2758 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2760 List<Component> comps = PaintRefresher.components.get(viewport
2761 .getSequenceSetId());
2763 List<String> existingNames = getExistingViewNames(comps);
2765 while (existingNames.contains(newViewName))
2767 newViewName = viewTitle + " " + (++index);
2773 * Returns a list of distinct view names found in the given list of
2774 * components. View names are held on the viewport of an AlignmentPanel.
2779 protected List<String> getExistingViewNames(List<Component> comps)
2781 List<String> existingNames = new ArrayList<String>();
2782 for (Component comp : comps)
2784 if (comp instanceof AlignmentPanel)
2786 AlignmentPanel ap = (AlignmentPanel) comp;
2787 if (!existingNames.contains(ap.av.viewName))
2789 existingNames.add(ap.av.viewName);
2793 return existingNames;
2797 * Explode tabbed views into separate windows.
2800 public void expandViews_actionPerformed(ActionEvent e)
2802 Desktop.instance.explodeViews(this);
2806 * Gather views in separate windows back into a tabbed presentation.
2809 public void gatherViews_actionPerformed(ActionEvent e)
2811 Desktop.instance.gatherViews(this);
2821 public void font_actionPerformed(ActionEvent e)
2823 new FontChooser(alignPanel);
2833 protected void seqLimit_actionPerformed(ActionEvent e)
2835 viewport.setShowJVSuffix(seqLimits.isSelected());
2837 alignPanel.getIdPanel().getIdCanvas().setPreferredSize(alignPanel
2838 .calculateIdWidth());
2839 alignPanel.paintAlignment(true);
2843 public void idRightAlign_actionPerformed(ActionEvent e)
2845 viewport.setRightAlignIds(idRightAlign.isSelected());
2846 alignPanel.paintAlignment(true);
2850 public void centreColumnLabels_actionPerformed(ActionEvent e)
2852 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2853 alignPanel.paintAlignment(true);
2859 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2862 protected void followHighlight_actionPerformed()
2865 * Set the 'follow' flag on the Viewport (and scroll to position if now
2868 final boolean state = this.followHighlightMenuItem.getState();
2869 viewport.setFollowHighlight(state);
2872 alignPanel.scrollToPosition(
2873 alignPanel.getSeqPanel().seqCanvas.searchResults, false);
2884 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2886 viewport.setColourText(colourTextMenuItem.isSelected());
2887 alignPanel.paintAlignment(true);
2897 public void wrapMenuItem_actionPerformed(ActionEvent e)
2899 scaleAbove.setVisible(wrapMenuItem.isSelected());
2900 scaleLeft.setVisible(wrapMenuItem.isSelected());
2901 scaleRight.setVisible(wrapMenuItem.isSelected());
2902 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2903 alignPanel.updateLayout();
2907 public void showAllSeqs_actionPerformed(ActionEvent e)
2909 viewport.showAllHiddenSeqs();
2913 public void showAllColumns_actionPerformed(ActionEvent e)
2915 viewport.showAllHiddenColumns();
2920 public void hideSelSequences_actionPerformed(ActionEvent e)
2922 viewport.hideAllSelectedSeqs();
2923 // alignPanel.paintAlignment(true);
2927 * called by key handler and the hide all/show all menu items
2932 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2935 boolean hide = false;
2936 SequenceGroup sg = viewport.getSelectionGroup();
2937 if (!toggleSeqs && !toggleCols)
2939 // Hide everything by the current selection - this is a hack - we do the
2940 // invert and then hide
2941 // first check that there will be visible columns after the invert.
2942 if ((viewport.getColumnSelection() != null
2943 && viewport.getColumnSelection().getSelected() != null && viewport
2944 .getColumnSelection().getSelected().size() > 0)
2945 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2948 // now invert the sequence set, if required - empty selection implies
2949 // that no hiding is required.
2952 invertSequenceMenuItem_actionPerformed(null);
2953 sg = viewport.getSelectionGroup();
2957 viewport.expandColSelection(sg, true);
2958 // finally invert the column selection and get the new sequence
2960 invertColSel_actionPerformed(null);
2967 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
2969 hideSelSequences_actionPerformed(null);
2972 else if (!(toggleCols && viewport.getColumnSelection().getSelected()
2975 showAllSeqs_actionPerformed(null);
2981 if (viewport.getColumnSelection().getSelected().size() > 0)
2983 hideSelColumns_actionPerformed(null);
2986 viewport.setSelectionGroup(sg);
2991 showAllColumns_actionPerformed(null);
3000 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3001 * event.ActionEvent)
3004 public void hideAllButSelection_actionPerformed(ActionEvent e)
3006 toggleHiddenRegions(false, false);
3013 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3017 public void hideAllSelection_actionPerformed(ActionEvent e)
3019 SequenceGroup sg = viewport.getSelectionGroup();
3020 viewport.expandColSelection(sg, false);
3021 viewport.hideAllSelectedSeqs();
3022 viewport.hideSelectedColumns();
3023 alignPanel.paintAlignment(true);
3030 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3034 public void showAllhidden_actionPerformed(ActionEvent e)
3036 viewport.showAllHiddenColumns();
3037 viewport.showAllHiddenSeqs();
3038 alignPanel.paintAlignment(true);
3042 public void hideSelColumns_actionPerformed(ActionEvent e)
3044 viewport.hideSelectedColumns();
3045 alignPanel.paintAlignment(true);
3049 public void hiddenMarkers_actionPerformed(ActionEvent e)
3051 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3062 protected void scaleAbove_actionPerformed(ActionEvent e)
3064 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3065 alignPanel.paintAlignment(true);
3075 protected void scaleLeft_actionPerformed(ActionEvent e)
3077 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3078 alignPanel.paintAlignment(true);
3088 protected void scaleRight_actionPerformed(ActionEvent e)
3090 viewport.setScaleRightWrapped(scaleRight.isSelected());
3091 alignPanel.paintAlignment(true);
3101 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3103 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3104 alignPanel.paintAlignment(true);
3114 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3116 viewport.setShowText(viewTextMenuItem.isSelected());
3117 alignPanel.paintAlignment(true);
3127 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3129 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3130 alignPanel.paintAlignment(true);
3133 public FeatureSettings featureSettings;
3136 public void featureSettings_actionPerformed(ActionEvent e)
3138 if (featureSettings != null)
3140 featureSettings.close();
3141 featureSettings = null;
3143 if (!showSeqFeatures.isSelected())
3145 // make sure features are actually displayed
3146 showSeqFeatures.setSelected(true);
3147 showSeqFeatures_actionPerformed(null);
3149 featureSettings = new FeatureSettings(this);
3153 * Set or clear 'Show Sequence Features'
3159 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3161 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3162 alignPanel.paintAlignment(true);
3163 if (alignPanel.getOverviewPanel() != null)
3165 alignPanel.getOverviewPanel().updateOverviewImage();
3170 * Set or clear 'Show Sequence Features'
3176 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
3178 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
3180 if (viewport.isShowSequenceFeaturesHeight())
3182 // ensure we're actually displaying features
3183 viewport.setShowSequenceFeatures(true);
3184 showSeqFeatures.setSelected(true);
3186 alignPanel.paintAlignment(true);
3187 if (alignPanel.getOverviewPanel() != null)
3189 alignPanel.getOverviewPanel().updateOverviewImage();
3194 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3195 * the annotations panel as a whole.
3197 * The options to show/hide all annotations should be enabled when the panel
3198 * is shown, and disabled when the panel is hidden.
3203 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3205 final boolean setVisible = annotationPanelMenuItem.isSelected();
3206 viewport.setShowAnnotation(setVisible);
3207 this.showAllSeqAnnotations.setEnabled(setVisible);
3208 this.hideAllSeqAnnotations.setEnabled(setVisible);
3209 this.showAllAlAnnotations.setEnabled(setVisible);
3210 this.hideAllAlAnnotations.setEnabled(setVisible);
3211 alignPanel.updateLayout();
3215 public void alignmentProperties()
3217 JEditorPane editPane = new JEditorPane("text/html", "");
3218 editPane.setEditable(false);
3219 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3221 editPane.setText(MessageManager.formatMessage("label.html_content",
3223 { contents.toString() }));
3224 JInternalFrame frame = new JInternalFrame();
3225 frame.getContentPane().add(new JScrollPane(editPane));
3227 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3228 "label.alignment_properties", new Object[]
3229 { getTitle() }), 500, 400);
3239 public void overviewMenuItem_actionPerformed(ActionEvent e)
3241 if (alignPanel.overviewPanel != null)
3246 JInternalFrame frame = new JInternalFrame();
3247 OverviewPanel overview = new OverviewPanel(alignPanel);
3248 frame.setContentPane(overview);
3249 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3250 "label.overview_params", new Object[]
3251 { this.getTitle() }), frame.getWidth(), frame.getHeight());
3253 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3254 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3257 public void internalFrameClosed(
3258 javax.swing.event.InternalFrameEvent evt)
3260 alignPanel.setOverviewPanel(null);
3264 alignPanel.setOverviewPanel(overview);
3268 public void textColour_actionPerformed(ActionEvent e)
3270 new TextColourChooser().chooseColour(alignPanel, null);
3280 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3292 public void clustalColour_actionPerformed(ActionEvent e)
3294 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3295 viewport.getHiddenRepSequences()));
3305 public void zappoColour_actionPerformed(ActionEvent e)
3307 changeColour(new ZappoColourScheme());
3317 public void taylorColour_actionPerformed(ActionEvent e)
3319 changeColour(new TaylorColourScheme());
3329 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3331 changeColour(new HydrophobicColourScheme());
3341 public void helixColour_actionPerformed(ActionEvent e)
3343 changeColour(new HelixColourScheme());
3353 public void strandColour_actionPerformed(ActionEvent e)
3355 changeColour(new StrandColourScheme());
3365 public void turnColour_actionPerformed(ActionEvent e)
3367 changeColour(new TurnColourScheme());
3377 public void buriedColour_actionPerformed(ActionEvent e)
3379 changeColour(new BuriedColourScheme());
3389 public void nucleotideColour_actionPerformed(ActionEvent e)
3391 changeColour(new NucleotideColourScheme());
3395 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3397 changeColour(new PurinePyrimidineColourScheme());
3401 * public void covariationColour_actionPerformed(ActionEvent e) {
3403 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3407 public void annotationColour_actionPerformed(ActionEvent e)
3409 new AnnotationColourChooser(viewport, alignPanel);
3413 public void annotationColumn_actionPerformed(ActionEvent e)
3415 new AnnotationColumnChooser(viewport, alignPanel);
3419 public void rnahelicesColour_actionPerformed(ActionEvent e)
3421 new RNAHelicesColourChooser(viewport, alignPanel);
3431 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3433 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3442 public void changeColour(ColourSchemeI cs)
3444 // TODO: compare with applet and pull up to model method
3449 if (viewport.getAbovePIDThreshold())
3451 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3453 cs.setThreshold(threshold, viewport.isIgnoreGapsConsensus());
3457 cs.setThreshold(0, viewport.isIgnoreGapsConsensus());
3460 if (viewport.getConservationSelected())
3463 Alignment al = (Alignment) viewport.getAlignment();
3464 Conservation c = new Conservation("All",
3465 ResidueProperties.propHash, 3, al.getSequences(), 0,
3469 c.verdict(false, viewport.getConsPercGaps());
3471 cs.setConservation(c);
3473 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3478 cs.setConservation(null);
3481 cs.setConsensus(viewport.getSequenceConsensusHash());
3484 viewport.setGlobalColourScheme(cs);
3486 if (viewport.getColourAppliesToAllGroups())
3489 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3497 if (cs instanceof ClustalxColourScheme)
3499 sg.cs = new ClustalxColourScheme(sg,
3500 viewport.getHiddenRepSequences());
3502 else if (cs instanceof UserColourScheme)
3504 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
3510 sg.cs = cs.getClass().newInstance();
3511 } catch (Exception ex)
3516 if (viewport.getAbovePIDThreshold()
3517 || cs instanceof PIDColourScheme
3518 || cs instanceof Blosum62ColourScheme)
3520 sg.cs.setThreshold(threshold, viewport.isIgnoreGapsConsensus());
3522 sg.cs.setConsensus(AAFrequency.calculate(
3523 sg.getSequences(viewport.getHiddenRepSequences()),
3524 sg.getStartRes(), sg.getEndRes() + 1));
3528 sg.cs.setThreshold(0, viewport.isIgnoreGapsConsensus());
3531 if (viewport.getConservationSelected())
3533 Conservation c = new Conservation("Group",
3534 ResidueProperties.propHash, 3, sg.getSequences(viewport
3535 .getHiddenRepSequences()), sg.getStartRes(),
3536 sg.getEndRes() + 1);
3538 c.verdict(false, viewport.getConsPercGaps());
3539 sg.cs.setConservation(c);
3543 sg.cs.setConservation(null);
3548 if (alignPanel.getOverviewPanel() != null)
3550 alignPanel.getOverviewPanel().updateOverviewImage();
3553 alignPanel.paintAlignment(true);
3563 protected void modifyPID_actionPerformed(ActionEvent e)
3565 if (viewport.getAbovePIDThreshold()
3566 && viewport.getGlobalColourScheme() != null)
3568 SliderPanel.setPIDSliderSource(alignPanel,
3569 viewport.getGlobalColourScheme(), "Background");
3570 SliderPanel.showPIDSlider();
3581 protected void modifyConservation_actionPerformed(ActionEvent e)
3583 if (viewport.getConservationSelected()
3584 && viewport.getGlobalColourScheme() != null)
3586 SliderPanel.setConservationSlider(alignPanel,
3587 viewport.getGlobalColourScheme(), "Background");
3588 SliderPanel.showConservationSlider();
3599 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3601 viewport.setConservationSelected(conservationMenuItem.isSelected());
3603 viewport.setAbovePIDThreshold(false);
3604 abovePIDThreshold.setSelected(false);
3606 changeColour(viewport.getGlobalColourScheme());
3608 modifyConservation_actionPerformed(null);
3618 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3620 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3622 conservationMenuItem.setSelected(false);
3623 viewport.setConservationSelected(false);
3625 changeColour(viewport.getGlobalColourScheme());
3627 modifyPID_actionPerformed(null);
3637 public void userDefinedColour_actionPerformed(ActionEvent e)
3639 if (e.getActionCommand().equals(
3640 MessageManager.getString("action.user_defined")))
3642 new UserDefinedColours(alignPanel, null);
3646 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3647 .getUserColourSchemes().get(e.getActionCommand());
3653 public void updateUserColourMenu()
3656 Component[] menuItems = colourMenu.getMenuComponents();
3657 int iSize = menuItems.length;
3658 for (int i = 0; i < iSize; i++)
3660 if (menuItems[i].getName() != null
3661 && menuItems[i].getName().equals("USER_DEFINED"))
3663 colourMenu.remove(menuItems[i]);
3667 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3669 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3670 .getUserColourSchemes().keys();
3672 while (userColours.hasMoreElements())
3674 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3675 userColours.nextElement().toString());
3676 radioItem.setName("USER_DEFINED");
3677 radioItem.addMouseListener(new MouseAdapter()
3680 public void mousePressed(MouseEvent evt)
3682 if (evt.isControlDown()
3683 || SwingUtilities.isRightMouseButton(evt))
3685 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3687 int option = JOptionPane.showInternalConfirmDialog(
3688 jalview.gui.Desktop.desktop,
3690 .getString("label.remove_from_default_list"),
3692 .getString("label.remove_user_defined_colour"),
3693 JOptionPane.YES_NO_OPTION);
3694 if (option == JOptionPane.YES_OPTION)
3696 jalview.gui.UserDefinedColours
3697 .removeColourFromDefaults(radioItem.getText());
3698 colourMenu.remove(radioItem);
3702 radioItem.addActionListener(new ActionListener()
3705 public void actionPerformed(ActionEvent evt)
3707 userDefinedColour_actionPerformed(evt);
3714 radioItem.addActionListener(new ActionListener()
3717 public void actionPerformed(ActionEvent evt)
3719 userDefinedColour_actionPerformed(evt);
3723 colourMenu.insert(radioItem, 15);
3724 colours.add(radioItem);
3736 public void PIDColour_actionPerformed(ActionEvent e)
3738 changeColour(new PIDColourScheme());
3748 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3750 changeColour(new Blosum62ColourScheme());
3760 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3762 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3763 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3764 .getAlignment().getSequenceAt(0), null);
3765 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3766 viewport.getAlignment()));
3767 alignPanel.paintAlignment(true);
3777 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3779 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3780 AlignmentSorter.sortByID(viewport.getAlignment());
3781 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3782 viewport.getAlignment()));
3783 alignPanel.paintAlignment(true);
3793 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3795 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3796 AlignmentSorter.sortByLength(viewport.getAlignment());
3797 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3798 viewport.getAlignment()));
3799 alignPanel.paintAlignment(true);
3809 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3811 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3812 AlignmentSorter.sortByGroup(viewport.getAlignment());
3813 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3814 viewport.getAlignment()));
3816 alignPanel.paintAlignment(true);
3826 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3828 new RedundancyPanel(alignPanel, this);
3838 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3840 if ((viewport.getSelectionGroup() == null)
3841 || (viewport.getSelectionGroup().getSize() < 2))
3843 JOptionPane.showInternalMessageDialog(this, MessageManager
3844 .getString("label.you_must_select_least_two_sequences"),
3845 MessageManager.getString("label.invalid_selection"),
3846 JOptionPane.WARNING_MESSAGE);
3850 JInternalFrame frame = new JInternalFrame();
3851 frame.setContentPane(new PairwiseAlignPanel(viewport));
3852 Desktop.addInternalFrame(frame,
3853 MessageManager.getString("action.pairwise_alignment"), 600,
3865 public void PCAMenuItem_actionPerformed(ActionEvent e)
3867 if (((viewport.getSelectionGroup() != null)
3868 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3869 .getSelectionGroup().getSize() > 0))
3870 || (viewport.getAlignment().getHeight() < 4))
3873 .showInternalMessageDialog(
3876 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3878 .getString("label.sequence_selection_insufficient"),
3879 JOptionPane.WARNING_MESSAGE);
3884 new PCAPanel(alignPanel);
3888 public void autoCalculate_actionPerformed(ActionEvent e)
3890 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3891 if (viewport.autoCalculateConsensus)
3893 viewport.firePropertyChange("alignment", null, viewport
3894 .getAlignment().getSequences());
3899 public void sortByTreeOption_actionPerformed(ActionEvent e)
3901 viewport.sortByTree = sortByTree.isSelected();
3905 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3907 viewport.followSelection = listenToViewSelections.isSelected();
3917 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3919 newTreePanel("AV", "PID", "Average distance tree using PID");
3929 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3931 newTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3941 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3943 newTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3953 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3955 newTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3968 void newTreePanel(String type, String pwType, String title)
3972 if (viewport.getSelectionGroup() != null
3973 && viewport.getSelectionGroup().getSize() > 0)
3975 if (viewport.getSelectionGroup().getSize() < 3)
3981 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3983 .getString("label.not_enough_sequences"),
3984 JOptionPane.WARNING_MESSAGE);
3988 SequenceGroup sg = viewport.getSelectionGroup();
3990 /* Decide if the selection is a column region */
3991 for (SequenceI _s : sg.getSequences())
3993 if (_s.getLength() < sg.getEndRes())
3999 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
4001 .getString("label.sequences_selection_not_aligned"),
4002 JOptionPane.WARNING_MESSAGE);
4008 title = title + " on region";
4009 tp = new TreePanel(alignPanel, type, pwType);
4013 // are the visible sequences aligned?
4014 if (!viewport.getAlignment().isAligned(false))
4020 .getString("label.sequences_must_be_aligned_before_creating_tree"),
4022 .getString("label.sequences_not_aligned"),
4023 JOptionPane.WARNING_MESSAGE);
4028 if (viewport.getAlignment().getHeight() < 2)
4033 tp = new TreePanel(alignPanel, type, pwType);
4038 if (viewport.viewName != null)
4040 title += viewport.viewName + " of ";
4043 title += this.title;
4045 Desktop.addInternalFrame(tp, title, 600, 500);
4056 public void addSortByOrderMenuItem(String title,
4057 final AlignmentOrder order)
4059 final JMenuItem item = new JMenuItem(MessageManager.formatMessage("action.by_title_param", new Object[]{title}));
4061 item.addActionListener(new java.awt.event.ActionListener()
4064 public void actionPerformed(ActionEvent e)
4066 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4068 // TODO: JBPNote - have to map order entries to curent SequenceI
4070 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4072 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
4075 alignPanel.paintAlignment(true);
4081 * Add a new sort by annotation score menu item
4084 * the menu to add the option to
4086 * the label used to retrieve scores for each sequence on the
4089 public void addSortByAnnotScoreMenuItem(JMenu sort,
4090 final String scoreLabel)
4092 final JMenuItem item = new JMenuItem(scoreLabel);
4094 item.addActionListener(new java.awt.event.ActionListener()
4097 public void actionPerformed(ActionEvent e)
4099 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4100 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4101 viewport.getAlignment());// ,viewport.getSelectionGroup());
4102 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4103 viewport.getAlignment()));
4104 alignPanel.paintAlignment(true);
4110 * last hash for alignment's annotation array - used to minimise cost of
4113 protected int _annotationScoreVectorHash;
4116 * search the alignment and rebuild the sort by annotation score submenu the
4117 * last alignment annotation vector hash is stored to minimize cost of
4118 * rebuilding in subsequence calls.
4122 public void buildSortByAnnotationScoresMenu()
4124 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4129 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4131 sortByAnnotScore.removeAll();
4132 // almost certainly a quicker way to do this - but we keep it simple
4133 Hashtable scoreSorts = new Hashtable();
4134 AlignmentAnnotation aann[];
4135 for (SequenceI sqa : viewport.getAlignment().getSequences())
4137 aann = sqa.getAnnotation();
4138 for (int i = 0; aann != null && i < aann.length; i++)
4140 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4142 scoreSorts.put(aann[i].label, aann[i].label);
4146 Enumeration labels = scoreSorts.keys();
4147 while (labels.hasMoreElements())
4149 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4150 (String) labels.nextElement());
4152 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4155 _annotationScoreVectorHash = viewport.getAlignment()
4156 .getAlignmentAnnotation().hashCode();
4161 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4162 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4163 * call. Listeners are added to remove the menu item when the treePanel is
4164 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4168 * Displayed tree window.
4170 * SortBy menu item title.
4173 public void buildTreeMenu()
4175 calculateTree.removeAll();
4176 // build the calculate menu
4178 for (final String type : new String[]
4181 String treecalcnm = MessageManager.getString("label.tree_calc_"
4182 + type.toLowerCase());
4183 for (final String pwtype : ResidueProperties.scoreMatrices.keySet())
4185 JMenuItem tm = new JMenuItem();
4186 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4187 if (sm.isProtein() == !viewport.getAlignment().isNucleotide())
4189 String smn = MessageManager.getStringOrReturn(
4190 "label.score_model_", sm.getName());
4191 final String title = MessageManager.formatMessage(
4192 "label.treecalc_title", treecalcnm, smn);
4193 tm.setText(title);//
4194 tm.addActionListener(new java.awt.event.ActionListener()
4197 public void actionPerformed(ActionEvent e)
4199 newTreePanel(type, pwtype, title);
4202 calculateTree.add(tm);
4207 sortByTreeMenu.removeAll();
4209 List<Component> comps = PaintRefresher.components.get(viewport
4210 .getSequenceSetId());
4211 List<TreePanel> treePanels = new ArrayList<TreePanel>();
4212 for (Component comp : comps)
4214 if (comp instanceof TreePanel)
4216 treePanels.add((TreePanel) comp);
4220 if (treePanels.size() < 1)
4222 sortByTreeMenu.setVisible(false);
4226 sortByTreeMenu.setVisible(true);
4228 for (final TreePanel tp : treePanels)
4230 final JMenuItem item = new JMenuItem(tp.getTitle());
4231 item.addActionListener(new java.awt.event.ActionListener()
4234 public void actionPerformed(ActionEvent e)
4236 tp.sortByTree_actionPerformed();
4237 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4242 sortByTreeMenu.add(item);
4246 public boolean sortBy(AlignmentOrder alorder, String undoname)
4248 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4249 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4250 if (undoname != null)
4252 addHistoryItem(new OrderCommand(undoname, oldOrder,
4253 viewport.getAlignment()));
4255 alignPanel.paintAlignment(true);
4260 * Work out whether the whole set of sequences or just the selected set will
4261 * be submitted for multiple alignment.
4264 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4266 // Now, check we have enough sequences
4267 AlignmentView msa = null;
4269 if ((viewport.getSelectionGroup() != null)
4270 && (viewport.getSelectionGroup().getSize() > 1))
4272 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4273 // some common interface!
4275 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4276 * SequenceI[sz = seqs.getSize(false)];
4278 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4279 * seqs.getSequenceAt(i); }
4281 msa = viewport.getAlignmentView(true);
4283 else if (viewport.getSelectionGroup() != null
4284 && viewport.getSelectionGroup().getSize() == 1)
4286 int option = JOptionPane.showConfirmDialog(this,
4287 MessageManager.getString("warn.oneseq_msainput_selection"),
4288 MessageManager.getString("label.invalid_selection"),
4289 JOptionPane.OK_CANCEL_OPTION);
4290 if (option == JOptionPane.OK_OPTION)
4292 msa = viewport.getAlignmentView(false);
4297 msa = viewport.getAlignmentView(false);
4303 * Decides what is submitted to a secondary structure prediction service: the
4304 * first sequence in the alignment, or in the current selection, or, if the
4305 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4306 * region or the whole alignment. (where the first sequence in the set is the
4307 * one that the prediction will be for).
4309 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4311 AlignmentView seqs = null;
4313 if ((viewport.getSelectionGroup() != null)
4314 && (viewport.getSelectionGroup().getSize() > 0))
4316 seqs = viewport.getAlignmentView(true);
4320 seqs = viewport.getAlignmentView(false);
4322 // limit sequences - JBPNote in future - could spawn multiple prediction
4324 // TODO: viewport.getAlignment().isAligned is a global state - the local
4325 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4326 if (!viewport.getAlignment().isAligned(false))
4328 seqs.setSequences(new SeqCigar[]
4329 { seqs.getSequences()[0] });
4330 // TODO: if seqs.getSequences().length>1 then should really have warned
4344 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4346 // Pick the tree file
4347 JalviewFileChooser chooser = new JalviewFileChooser(
4348 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4349 chooser.setFileView(new JalviewFileView());
4350 chooser.setDialogTitle(MessageManager
4351 .getString("label.select_newick_like_tree_file"));
4352 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4354 int value = chooser.showOpenDialog(null);
4356 if (value == JalviewFileChooser.APPROVE_OPTION)
4358 String choice = chooser.getSelectedFile().getPath();
4359 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4360 jalview.io.NewickFile fin = null;
4363 fin = new jalview.io.NewickFile(choice, "File");
4364 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4365 } catch (Exception ex)
4372 .getString("label.problem_reading_tree_file"),
4373 JOptionPane.WARNING_MESSAGE);
4374 ex.printStackTrace();
4376 if (fin != null && fin.hasWarningMessage())
4378 JOptionPane.showMessageDialog(Desktop.desktop, fin
4379 .getWarningMessage(), MessageManager
4380 .getString("label.possible_problem_with_tree_file"),
4381 JOptionPane.WARNING_MESSAGE);
4387 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4389 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4392 public TreePanel ShowNewickTree(NewickFile nf, String title)
4394 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4397 public TreePanel ShowNewickTree(NewickFile nf, String title,
4398 AlignmentView input)
4400 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4403 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4404 int h, int x, int y)
4406 return ShowNewickTree(nf, title, null, w, h, x, y);
4410 * Add a treeviewer for the tree extracted from a newick file object to the
4411 * current alignment view
4418 * Associated alignment input data (or null)
4427 * @return TreePanel handle
4429 public TreePanel ShowNewickTree(NewickFile nf, String title,
4430 AlignmentView input, int w, int h, int x, int y)
4432 TreePanel tp = null;
4438 if (nf.getTree() != null)
4440 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4446 tp.setLocation(x, y);
4449 Desktop.addInternalFrame(tp, title, w, h);
4451 } catch (Exception ex)
4453 ex.printStackTrace();
4459 private boolean buildingMenu = false;
4462 * Generates menu items and listener event actions for web service clients
4465 public void BuildWebServiceMenu()
4467 while (buildingMenu)
4471 System.err.println("Waiting for building menu to finish.");
4473 } catch (Exception e)
4477 final AlignFrame me = this;
4478 buildingMenu = true;
4479 new Thread(new Runnable()
4484 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4487 System.err.println("Building ws menu again "
4488 + Thread.currentThread());
4489 // TODO: add support for context dependent disabling of services based
4491 // alignment and current selection
4492 // TODO: add additional serviceHandle parameter to specify abstract
4494 // class independently of AbstractName
4495 // TODO: add in rediscovery GUI function to restart discoverer
4496 // TODO: group services by location as well as function and/or
4498 // object broker mechanism.
4499 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4500 final IProgressIndicator af = me;
4501 final JMenu msawsmenu = new JMenu("Alignment");
4502 final JMenu secstrmenu = new JMenu(
4503 "Secondary Structure Prediction");
4504 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4505 final JMenu analymenu = new JMenu("Analysis");
4506 final JMenu dismenu = new JMenu("Protein Disorder");
4507 // final JMenu msawsmenu = new
4508 // JMenu(MessageManager.getString("label.alignment"));
4509 // final JMenu secstrmenu = new
4510 // JMenu(MessageManager.getString("label.secondary_structure_prediction"));
4511 // final JMenu seqsrchmenu = new
4512 // JMenu(MessageManager.getString("label.sequence_database_search"));
4513 // final JMenu analymenu = new
4514 // JMenu(MessageManager.getString("label.analysis"));
4515 // final JMenu dismenu = new
4516 // JMenu(MessageManager.getString("label.protein_disorder"));
4517 // JAL-940 - only show secondary structure prediction services from
4518 // the legacy server
4519 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4521 Discoverer.services != null && (Discoverer.services.size() > 0))
4523 // TODO: refactor to allow list of AbstractName/Handler bindings to
4525 // stored or retrieved from elsewhere
4526 // No MSAWS used any more:
4527 // Vector msaws = null; // (Vector)
4528 // Discoverer.services.get("MsaWS");
4529 Vector secstrpr = (Vector) Discoverer.services
4531 if (secstrpr != null)
4533 // Add any secondary structure prediction services
4534 for (int i = 0, j = secstrpr.size(); i < j; i++)
4536 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4538 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4539 .getServiceClient(sh);
4540 int p = secstrmenu.getItemCount();
4541 impl.attachWSMenuEntry(secstrmenu, me);
4542 int q = secstrmenu.getItemCount();
4543 for (int litm = p; litm < q; litm++)
4545 legacyItems.add(secstrmenu.getItem(litm));
4551 // Add all submenus in the order they should appear on the web
4553 wsmenu.add(msawsmenu);
4554 wsmenu.add(secstrmenu);
4555 wsmenu.add(dismenu);
4556 wsmenu.add(analymenu);
4557 // No search services yet
4558 // wsmenu.add(seqsrchmenu);
4560 javax.swing.SwingUtilities.invokeLater(new Runnable()
4567 webService.removeAll();
4568 // first, add discovered services onto the webservices menu
4569 if (wsmenu.size() > 0)
4571 for (int i = 0, j = wsmenu.size(); i < j; i++)
4573 webService.add(wsmenu.get(i));
4578 webService.add(me.webServiceNoServices);
4580 // TODO: move into separate menu builder class.
4581 boolean new_sspred = false;
4582 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4584 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4585 if (jws2servs != null)
4587 if (jws2servs.hasServices())
4589 jws2servs.attachWSMenuEntry(webService, me);
4590 for (Jws2Instance sv : jws2servs.getServices())
4592 if (sv.description.toLowerCase().contains("jpred"))
4594 for (JMenuItem jmi : legacyItems)
4596 jmi.setVisible(false);
4602 if (jws2servs.isRunning())
4604 JMenuItem tm = new JMenuItem(
4605 "Still discovering JABA Services");
4606 tm.setEnabled(false);
4611 build_urlServiceMenu(me.webService);
4612 build_fetchdbmenu(webService);
4613 for (JMenu item : wsmenu)
4615 if (item.getItemCount() == 0)
4617 item.setEnabled(false);
4621 item.setEnabled(true);
4624 } catch (Exception e)
4627 .debug("Exception during web service menu building process.",
4632 } catch (Exception e)
4635 buildingMenu = false;
4642 * construct any groupURL type service menu entries.
4646 private void build_urlServiceMenu(JMenu webService)
4648 // TODO: remove this code when 2.7 is released
4649 // DEBUG - alignmentView
4651 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4652 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4654 * @Override public void actionPerformed(ActionEvent e) {
4655 * jalview.datamodel.AlignmentView
4656 * .testSelectionViews(af.viewport.getAlignment(),
4657 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4659 * }); webService.add(testAlView);
4661 // TODO: refactor to RestClient discoverer and merge menu entries for
4662 // rest-style services with other types of analysis/calculation service
4663 // SHmmr test client - still being implemented.
4664 // DEBUG - alignmentView
4666 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4669 client.attachWSMenuEntry(
4670 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4676 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
4677 * chooser = new JalviewFileChooser(jalview.bin.Cache.
4678 * getProperty("LAST_DIRECTORY"));
4680 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
4681 * to Vamsas file"); chooser.setToolTipText("Export");
4683 * int value = chooser.showSaveDialog(this);
4685 * if (value == JalviewFileChooser.APPROVE_OPTION) {
4686 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
4687 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
4688 * chooser.getSelectedFile().getAbsolutePath(), this); } }
4691 * prototype of an automatically enabled/disabled analysis function
4694 protected void setShowProductsEnabled()
4696 SequenceI[] selection = viewport.getSequenceSelection();
4697 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
4698 viewport.getAlignment().getDataset()))
4700 showProducts.setEnabled(true);
4705 showProducts.setEnabled(false);
4710 * search selection for sequence xRef products and build the show products
4715 * @return true if showProducts menu should be enabled.
4717 public boolean canShowProducts(SequenceI[] selection,
4718 boolean isRegionSelection, Alignment dataset)
4720 boolean showp = false;
4723 showProducts.removeAll();
4724 final boolean dna = viewport.getAlignment().isNucleotide();
4725 final Alignment ds = dataset;
4726 String[] ptypes = (selection == null || selection.length == 0) ? null
4727 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4729 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4730 // selection, dataset, true);
4731 final SequenceI[] sel = selection;
4732 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4735 final boolean isRegSel = isRegionSelection;
4736 final AlignFrame af = this;
4737 final String source = ptypes[t];
4738 JMenuItem xtype = new JMenuItem(ptypes[t]);
4739 xtype.addActionListener(new ActionListener()
4743 public void actionPerformed(ActionEvent e)
4745 // TODO: new thread for this call with vis-delay
4746 af.showProductsFor(af.viewport.getSequenceSelection(),
4747 isRegSel, dna, source);
4751 showProducts.add(xtype);
4753 showProducts.setVisible(showp);
4754 showProducts.setEnabled(showp);
4755 } catch (Exception e)
4757 jalview.bin.Cache.log
4758 .warn("canTranslate threw an exception - please report to help@jalview.org",
4765 protected void showProductsFor(final SequenceI[] sel,
4766 final boolean isRegSel, final boolean dna, final String source)
4768 Runnable foo = new Runnable()
4774 final long sttime = System.currentTimeMillis();
4775 AlignFrame.this.setProgressBar(MessageManager.formatMessage(
4776 "status.searching_for_sequences_from", new Object[]
4777 { source }), sttime);
4780 // update our local dataset reference
4781 Alignment ds = AlignFrame.this.getViewport().getAlignment()
4783 Alignment prods = CrossRef
4784 .findXrefSequences(sel, dna, source, ds);
4787 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4788 for (int s = 0; s < sprods.length; s++)
4790 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4791 if (ds.getSequences() == null
4792 || !ds.getSequences().contains(
4793 sprods[s].getDatasetSequence()))
4795 ds.addSequence(sprods[s].getDatasetSequence());
4797 sprods[s].updatePDBIds();
4799 Alignment al = new Alignment(sprods);
4803 * Copy dna-to-protein mappings to new alignment
4805 // TODO 1: no mappings are set up for EMBL product
4806 // TODO 2: if they were, should add them to protein alignment, not
4808 Set<AlignedCodonFrame> cf = prods.getCodonFrames();
4809 for (AlignedCodonFrame acf : cf)
4811 al.addCodonFrame(acf);
4813 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4815 String newtitle = "" + ((dna) ? "Proteins" : "Nucleotides")
4816 + " for " + ((isRegSel) ? "selected region of " : "")
4818 naf.setTitle(newtitle);
4820 // temporary flag until SplitFrame is released
4821 boolean asSplitFrame = Cache.getDefault(
4822 Preferences.ENABLE_SPLIT_FRAME, false);
4826 * Make a copy of this alignment (sharing the same dataset
4827 * sequences). If we are DNA, drop introns and update mappings
4829 AlignmentI copyAlignment = null;
4830 final SequenceI[] sequenceSelection = AlignFrame.this.viewport
4831 .getSequenceSelection();
4834 copyAlignment = AlignmentUtils.makeExonAlignment(
4835 sequenceSelection, cf);
4836 al.getCodonFrames().clear();
4837 al.getCodonFrames().addAll(cf);
4838 final StructureSelectionManager ssm = StructureSelectionManager
4839 .getStructureSelectionManager(Desktop.instance);
4840 ssm.addMappings(cf);
4844 copyAlignment = new Alignment(new Alignment(
4845 sequenceSelection));
4847 AlignFrame copyThis = new AlignFrame(copyAlignment,
4848 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
4849 copyThis.setTitle(AlignFrame.this.getTitle());
4850 // SplitFrame with dna above, protein below
4851 SplitFrame sf = new SplitFrame(dna ? copyThis : naf,
4852 dna ? naf : copyThis);
4853 naf.setVisible(true);
4854 copyThis.setVisible(true);
4855 String linkedTitle = MessageManager
4856 .getString("label.linked_view_title");
4857 Desktop.addInternalFrame(sf, linkedTitle, -1, -1);
4861 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4867 System.err.println("No Sequences generated for xRef type "
4870 } catch (Exception e)
4872 jalview.bin.Cache.log.error(
4873 "Exception when finding crossreferences", e);
4874 } catch (OutOfMemoryError e)
4876 new OOMWarning("whilst fetching crossreferences", e);
4879 jalview.bin.Cache.log.error("Error when finding crossreferences",
4882 AlignFrame.this.setProgressBar(MessageManager.formatMessage(
4883 "status.finished_searching_for_sequences_from",
4890 Thread frunner = new Thread(foo);
4894 public boolean canShowTranslationProducts(SequenceI[] selection,
4895 AlignmentI alignment)
4900 return (jalview.analysis.Dna.canTranslate(selection,
4901 viewport.getViewAsVisibleContigs(true)));
4902 } catch (Exception e)
4904 jalview.bin.Cache.log
4905 .warn("canTranslate threw an exception - please report to help@jalview.org",
4912 * Construct and display a new frame containing the translation of this
4913 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4916 public void showTranslation_actionPerformed(ActionEvent e)
4918 AlignmentI al = null;
4921 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4923 al = dna.translateCdna();
4924 } catch (Exception ex)
4926 jalview.bin.Cache.log.error(
4927 "Exception during translation. Please report this !", ex);
4928 final String msg = MessageManager
4929 .getString("label.error_when_translating_sequences_submit_bug_report");
4930 final String title = MessageManager
4931 .getString("label.implementation_error")
4932 + MessageManager.getString("translation_failed");
4933 JOptionPane.showMessageDialog(Desktop.desktop, msg, title,
4934 JOptionPane.ERROR_MESSAGE);
4937 if (al == null || al.getHeight() == 0)
4939 final String msg = MessageManager
4940 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4941 final String title = MessageManager
4942 .getString("label.translation_failed");
4943 JOptionPane.showMessageDialog(Desktop.desktop, msg, title,
4944 JOptionPane.WARNING_MESSAGE);
4948 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4949 af.setFileFormat(this.currentFileFormat);
4950 final String newTitle = MessageManager.formatMessage(
4951 "label.translation_of_params", new Object[]
4952 { this.getTitle() });
4953 af.setTitle(newTitle);
4954 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, false))
4956 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4957 viewport.openSplitFrame(af, new Alignment(seqs),
4958 al.getCodonFrames());
4962 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4969 * Set the file format
4973 public void setFileFormat(String fileFormat)
4975 this.currentFileFormat = fileFormat;
4979 * Try to load a features file onto the alignment.
4982 * contents or path to retrieve file
4984 * access mode of file (see jalview.io.AlignFile)
4985 * @return true if features file was parsed corectly.
4987 public boolean parseFeaturesFile(String file, String type)
4989 boolean featuresFile = false;
4992 featuresFile = new FeaturesFile(file, type).parse(viewport
4993 .getAlignment().getDataset(), alignPanel.getSeqPanel().seqCanvas
4994 .getFeatureRenderer().getFeatureColours(), false,
4995 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4996 } catch (Exception ex)
4998 ex.printStackTrace();
5003 viewport.setShowSequenceFeatures(true);
5004 showSeqFeatures.setSelected(true);
5005 if (alignPanel.getSeqPanel().seqCanvas.fr != null)
5007 // update the min/max ranges where necessary
5008 alignPanel.getSeqPanel().seqCanvas.fr.findAllFeatures(true);
5010 if (featureSettings != null)
5012 featureSettings.setTableData();
5014 alignPanel.paintAlignment(true);
5017 return featuresFile;
5021 public void dragEnter(DropTargetDragEvent evt)
5026 public void dragExit(DropTargetEvent evt)
5031 public void dragOver(DropTargetDragEvent evt)
5036 public void dropActionChanged(DropTargetDragEvent evt)
5041 public void drop(DropTargetDropEvent evt)
5043 Transferable t = evt.getTransferable();
5044 java.util.List files = null;
5048 DataFlavor uriListFlavor = new DataFlavor(
5049 "text/uri-list;class=java.lang.String");
5050 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
5052 // Works on Windows and MacOSX
5053 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
5054 files = (java.util.List) t
5055 .getTransferData(DataFlavor.javaFileListFlavor);
5057 else if (t.isDataFlavorSupported(uriListFlavor))
5059 // This is used by Unix drag system
5060 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
5061 String data = (String) t.getTransferData(uriListFlavor);
5062 files = new java.util.ArrayList(1);
5063 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
5064 data, "\r\n"); st.hasMoreTokens();)
5066 String s = st.nextToken();
5067 if (s.startsWith("#"))
5069 // the line is a comment (as per the RFC 2483)
5073 java.net.URI uri = new java.net.URI(s);
5074 // check to see if we can handle this kind of URI
5075 if (uri.getScheme().toLowerCase().startsWith("http"))
5077 files.add(uri.toString());
5081 // otherwise preserve old behaviour: catch all for file objects
5082 java.io.File file = new java.io.File(uri);
5083 files.add(file.toString());
5087 } catch (Exception e)
5089 e.printStackTrace();
5095 // check to see if any of these files have names matching sequences in
5097 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5098 .getAlignment().getSequencesArray());
5100 * Object[] { String,SequenceI}
5102 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
5103 ArrayList<String> filesnotmatched = new ArrayList<String>();
5104 for (int i = 0; i < files.size(); i++)
5106 String file = files.get(i).toString();
5108 String protocol = FormatAdapter.checkProtocol(file);
5109 if (protocol == jalview.io.FormatAdapter.FILE)
5111 File fl = new File(file);
5112 pdbfn = fl.getName();
5114 else if (protocol == jalview.io.FormatAdapter.URL)
5116 URL url = new URL(file);
5117 pdbfn = url.getFile();
5119 if (pdbfn.length() > 0)
5121 // attempt to find a match in the alignment
5122 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5123 int l = 0, c = pdbfn.indexOf(".");
5124 while (mtch == null && c != -1)
5129 } while ((c = pdbfn.indexOf(".", l)) > l);
5132 pdbfn = pdbfn.substring(0, l);
5134 mtch = idm.findAllIdMatches(pdbfn);
5141 type = new IdentifyFile().Identify(file, protocol);
5142 } catch (Exception ex)
5148 if (type.equalsIgnoreCase("PDB"))
5150 filesmatched.add(new Object[]
5151 { file, protocol, mtch });
5156 // File wasn't named like one of the sequences or wasn't a PDB file.
5157 filesnotmatched.add(file);
5161 if (filesmatched.size() > 0)
5163 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
5169 "label.automatically_associate_pdb_files_with_sequences_same_name",
5176 .getString("label.automatically_associate_pdb_files_by_name"),
5177 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
5180 for (Object[] fm : filesmatched)
5182 // try and associate
5183 // TODO: may want to set a standard ID naming formalism for
5184 // associating PDB files which have no IDs.
5185 for (SequenceI toassoc : (SequenceI[]) fm[2])
5187 PDBEntry pe = new AssociatePdbFileWithSeq()
5188 .associatePdbWithSeq((String) fm[0],
5189 (String) fm[1], toassoc, false,
5193 System.err.println("Associated file : "
5194 + ((String) fm[0]) + " with "
5195 + toassoc.getDisplayId(true));
5199 alignPanel.paintAlignment(true);
5203 if (filesnotmatched.size() > 0)
5206 && (Cache.getDefault(
5207 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
5210 "<html>"+MessageManager
5212 "label.ignore_unmatched_dropped_files_info",
5217 .toString() })+"</html>",
5219 .getString("label.ignore_unmatched_dropped_files"),
5220 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
5224 for (String fn : filesnotmatched)
5226 loadJalviewDataFile(fn, null, null, null);
5230 } catch (Exception ex)
5232 ex.printStackTrace();
5238 * Attempt to load a "dropped" file or URL string: First by testing whether
5239 * it's and Annotation file, then a JNet file, and finally a features file. If
5240 * all are false then the user may have dropped an alignment file onto this
5244 * either a filename or a URL string.
5246 public void loadJalviewDataFile(String file, String protocol,
5247 String format, SequenceI assocSeq)
5251 if (protocol == null)
5253 protocol = jalview.io.FormatAdapter.checkProtocol(file);
5255 // if the file isn't identified, or not positively identified as some
5256 // other filetype (PFAM is default unidentified alignment file type) then
5257 // try to parse as annotation.
5258 boolean isAnnotation = (format == null || format
5259 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
5260 .annotateAlignmentView(viewport, file, protocol)
5265 // first see if its a T-COFFEE score file
5266 TCoffeeScoreFile tcf = null;
5269 tcf = new TCoffeeScoreFile(file, protocol);
5272 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5274 tcoffeeColour.setEnabled(true);
5275 tcoffeeColour.setSelected(true);
5276 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5277 isAnnotation = true;
5279 .setText(MessageManager
5280 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5284 // some problem - if no warning its probable that the ID matching
5285 // process didn't work
5289 tcf.getWarningMessage() == null ? MessageManager
5290 .getString("label.check_file_matches_sequence_ids_alignment")
5291 : tcf.getWarningMessage(),
5293 .getString("label.problem_reading_tcoffee_score_file"),
5294 JOptionPane.WARNING_MESSAGE);
5301 } catch (Exception x)
5304 .debug("Exception when processing data source as T-COFFEE score file",
5310 // try to see if its a JNet 'concise' style annotation file *before*
5312 // try to parse it as a features file
5315 format = new IdentifyFile().Identify(file, protocol);
5317 if (format.equalsIgnoreCase("JnetFile"))
5319 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5321 new JnetAnnotationMaker();
5322 JnetAnnotationMaker.add_annotation(predictions,
5323 viewport.getAlignment(), 0, false);
5324 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
5325 viewport.getAlignment().setSeqrep(repseq);
5326 ColumnSelection cs = new ColumnSelection();
5327 cs.hideInsertionsFor(repseq);
5328 viewport.setColumnSelection(cs);
5329 isAnnotation = true;
5334 * if (format.equalsIgnoreCase("PDB")) {
5336 * String pdbfn = ""; // try to match up filename with sequence id
5337 * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
5338 * new File(file); pdbfn = fl.getName(); } else if (protocol ==
5339 * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
5340 * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
5341 * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5342 * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
5343 * // attempt to find a match in the alignment SequenceI mtch =
5344 * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
5345 * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
5346 * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
5347 * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
5348 * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
5349 * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
5350 * { System.err.println("Associated file : " + file + " with " +
5351 * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
5352 * TODO: maybe need to load as normal otherwise return; } }
5354 // try to parse it as a features file
5355 boolean isGroupsFile = parseFeaturesFile(file, protocol);
5356 // if it wasn't a features file then we just treat it as a general
5357 // alignment file to load into the current view.
5360 new FileLoader().LoadFile(viewport, file, protocol, format);
5364 alignPanel.paintAlignment(true);
5372 alignPanel.adjustAnnotationHeight();
5373 viewport.updateSequenceIdColours();
5374 buildSortByAnnotationScoresMenu();
5375 alignPanel.paintAlignment(true);
5377 } catch (Exception ex)
5379 ex.printStackTrace();
5380 } catch (OutOfMemoryError oom)
5385 } catch (Exception x)
5391 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5392 : "using " + protocol + " from " + file)
5394 + (format != null ? "(parsing as '" + format
5395 + "' file)" : ""), oom, Desktop.desktop);
5400 * Method invoked by the ChangeListener on the tabbed pane, in other words
5401 * when a different tabbed pane is selected by the user or programmatically.
5404 public void tabSelectionChanged(int index)
5408 alignPanel = alignPanels.get(index);
5409 viewport = alignPanel.av;
5410 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5411 setMenusFromViewport(viewport);
5415 * If there is a frame linked to this one in a SplitPane, switch it to the
5416 * same view tab index. No infinite recursion of calls should happen, since
5417 * tabSelectionChanged() should not get invoked on setting the selected
5418 * index to an unchanged value. Guard against setting an invalid index
5419 * before the new view peer tab has been created.
5421 final AlignViewportI peer = viewport.getCodingComplement();
5424 AlignFrame linkedAlignFrame = ((AlignViewport) peer).getAlignPanel().alignFrame;
5425 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5427 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5433 * On right mouse click on view tab, prompt for and set new view name.
5436 public void tabbedPane_mousePressed(MouseEvent e)
5438 if (SwingUtilities.isRightMouseButton(e))
5440 String msg = MessageManager.getString("label.enter_view_name");
5441 String reply = JOptionPane.showInternalInputDialog(this, msg, msg,
5442 JOptionPane.QUESTION_MESSAGE);
5446 viewport.viewName = reply;
5447 // TODO warn if reply is in getExistingViewNames()?
5448 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5453 public AlignViewport getCurrentView()
5459 * Open the dialog for regex description parsing.
5462 protected void extractScores_actionPerformed(ActionEvent e)
5464 ParseProperties pp = new jalview.analysis.ParseProperties(
5465 viewport.getAlignment());
5466 // TODO: verify regex and introduce GUI dialog for version 2.5
5467 // if (pp.getScoresFromDescription("col", "score column ",
5468 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5470 if (pp.getScoresFromDescription("description column",
5471 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5473 buildSortByAnnotationScoresMenu();
5481 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5485 protected void showDbRefs_actionPerformed(ActionEvent e)
5487 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5493 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5497 protected void showNpFeats_actionPerformed(ActionEvent e)
5499 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5503 * find the viewport amongst the tabs in this alignment frame and close that
5508 public boolean closeView(AlignViewportI av)
5512 this.closeMenuItem_actionPerformed(false);
5515 Component[] comp = tabbedPane.getComponents();
5516 for (int i = 0; comp != null && i < comp.length; i++)
5518 if (comp[i] instanceof AlignmentPanel)
5520 if (((AlignmentPanel) comp[i]).av == av)
5523 closeView((AlignmentPanel) comp[i]);
5531 protected void build_fetchdbmenu(JMenu webService)
5533 // Temporary hack - DBRef Fetcher always top level ws entry.
5534 // TODO We probably want to store a sequence database checklist in
5535 // preferences and have checkboxes.. rather than individual sources selected
5537 final JMenu rfetch = new JMenu(
5538 MessageManager.getString("action.fetch_db_references"));
5539 rfetch.setToolTipText(MessageManager
5540 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5541 webService.add(rfetch);
5543 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5544 MessageManager.getString("option.trim_retrieved_seqs"));
5545 trimrs.setToolTipText(MessageManager
5546 .getString("label.trim_retrieved_sequences"));
5547 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5548 trimrs.addActionListener(new ActionListener()
5551 public void actionPerformed(ActionEvent e)
5553 trimrs.setSelected(trimrs.isSelected());
5554 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5555 Boolean.valueOf(trimrs.isSelected()).toString());
5559 JMenuItem fetchr = new JMenuItem(
5560 MessageManager.getString("label.standard_databases"));
5561 fetchr.setToolTipText(MessageManager
5562 .getString("label.fetch_embl_uniprot"));
5563 fetchr.addActionListener(new ActionListener()
5567 public void actionPerformed(ActionEvent e)
5569 new Thread(new Runnable()
5575 new jalview.ws.DBRefFetcher(alignPanel.av
5576 .getSequenceSelection(), alignPanel.alignFrame)
5577 .fetchDBRefs(false);
5585 final AlignFrame me = this;
5586 new Thread(new Runnable()
5591 final jalview.ws.SequenceFetcher sf = SequenceFetcher
5592 .getSequenceFetcherSingleton(me);
5593 javax.swing.SwingUtilities.invokeLater(new Runnable()
5598 String[] dbclasses = sf.getOrderedSupportedSources();
5599 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5600 // jalview.util.QuickSort.sort(otherdb, otherdb);
5601 List<DbSourceProxy> otherdb;
5602 JMenu dfetch = new JMenu();
5603 JMenu ifetch = new JMenu();
5604 JMenuItem fetchr = null;
5605 int comp = 0, icomp = 0, mcomp = 15;
5606 String mname = null;
5608 for (String dbclass : dbclasses)
5610 otherdb = sf.getSourceProxy(dbclass);
5611 // add a single entry for this class, or submenu allowing 'fetch
5613 if (otherdb == null || otherdb.size() < 1)
5617 // List<DbSourceProxy> dbs=otherdb;
5618 // otherdb=new ArrayList<DbSourceProxy>();
5619 // for (DbSourceProxy db:dbs)
5621 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5625 mname = "From " + dbclass;
5627 if (otherdb.size() == 1)
5629 final DbSourceProxy[] dassource = otherdb
5630 .toArray(new DbSourceProxy[0]);
5631 DbSourceProxy src = otherdb.get(0);
5632 fetchr = new JMenuItem(src.getDbSource());
5633 fetchr.addActionListener(new ActionListener()
5637 public void actionPerformed(ActionEvent e)
5639 new Thread(new Runnable()
5645 new jalview.ws.DBRefFetcher(alignPanel.av
5646 .getSequenceSelection(),
5647 alignPanel.alignFrame, dassource)
5648 .fetchDBRefs(false);
5654 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from", new Object[]{src.getDbName()})));
5660 final DbSourceProxy[] dassource = otherdb
5661 .toArray(new DbSourceProxy[0]);
5663 DbSourceProxy src = otherdb.get(0);
5664 fetchr = new JMenuItem(MessageManager.formatMessage(
5665 "label.fetch_all_param", new Object[]
5666 { src.getDbSource() }));
5667 fetchr.addActionListener(new ActionListener()
5670 public void actionPerformed(ActionEvent e)
5672 new Thread(new Runnable()
5678 new jalview.ws.DBRefFetcher(alignPanel.av
5679 .getSequenceSelection(),
5680 alignPanel.alignFrame, dassource)
5681 .fetchDBRefs(false);
5687 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from_all_sources", new Object[]{Integer.valueOf(otherdb.size()).toString(), src.getDbSource(), src.getDbName()})));
5690 // and then build the rest of the individual menus
5691 ifetch = new JMenu(MessageManager.formatMessage("label.source_from_db_source", new Object[]{src.getDbSource()}));
5693 String imname = null;
5695 for (DbSourceProxy sproxy : otherdb)
5697 String dbname = sproxy.getDbName();
5698 String sname = dbname.length() > 5 ? dbname.substring(0,
5699 5) + "..." : dbname;
5700 String msname = dbname.length() > 10 ? dbname.substring(
5701 0, 10) + "..." : dbname;
5704 imname = MessageManager.formatMessage("label.from_msname", new Object[]{sname});
5706 fetchr = new JMenuItem(msname);
5707 final DbSourceProxy[] dassrc =
5709 fetchr.addActionListener(new ActionListener()
5713 public void actionPerformed(ActionEvent e)
5715 new Thread(new Runnable()
5721 new jalview.ws.DBRefFetcher(alignPanel.av
5722 .getSequenceSelection(),
5723 alignPanel.alignFrame, dassrc)
5724 .fetchDBRefs(false);
5730 fetchr.setToolTipText("<html>"
5731 + MessageManager.formatMessage("label.fetch_retrieve_from", new Object[]{dbname}));
5734 if (++icomp >= mcomp || i == (otherdb.size()))
5736 ifetch.setText(MessageManager.formatMessage(
5737 "label.source_to_target", imname, sname));
5739 ifetch = new JMenu();
5747 if (comp >= mcomp || dbi >= (dbclasses.length))
5749 dfetch.setText(MessageManager.formatMessage(
5750 "label.source_to_target", mname, dbclass));
5752 dfetch = new JMenu();
5765 * Left justify the whole alignment.
5768 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5770 AlignmentI al = viewport.getAlignment();
5772 viewport.firePropertyChange("alignment", null, al);
5776 * Right justify the whole alignment.
5779 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5781 AlignmentI al = viewport.getAlignment();
5783 viewport.firePropertyChange("alignment", null, al);
5786 public void setShowSeqFeatures(boolean b)
5788 showSeqFeatures.setSelected(b);
5789 viewport.setShowSequenceFeatures(b);
5796 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5797 * awt.event.ActionEvent)
5800 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5802 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5803 alignPanel.paintAlignment(true);
5810 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5814 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5816 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5817 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5825 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5826 * .event.ActionEvent)
5829 protected void showGroupConservation_actionPerformed(ActionEvent e)
5831 viewport.setShowGroupConservation(showGroupConservation.getState());
5832 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5839 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5840 * .event.ActionEvent)
5843 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5845 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5846 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5853 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5854 * .event.ActionEvent)
5857 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5859 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5860 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5864 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5866 showSequenceLogo.setState(true);
5867 viewport.setShowSequenceLogo(true);
5868 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5869 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5873 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5875 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5882 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5883 * .event.ActionEvent)
5886 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5888 if (avc.makeGroupsFromSelection())
5890 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5891 alignPanel.updateAnnotation();
5892 alignPanel.paintAlignment(true);
5895 public void clearAlignmentSeqRep()
5897 // TODO refactor alignmentseqrep to controller
5898 if (viewport.getAlignment().hasSeqrep()) {
5899 viewport.getAlignment().setSeqrep(null);
5900 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5901 alignPanel.updateAnnotation();
5902 alignPanel.paintAlignment(true);
5907 protected void createGroup_actionPerformed(ActionEvent e)
5909 if (avc.createGroup())
5911 alignPanel.alignmentChanged();
5916 protected void unGroup_actionPerformed(ActionEvent e)
5920 alignPanel.alignmentChanged();
5925 * make the given alignmentPanel the currently selected tab
5927 * @param alignmentPanel
5929 public void setDisplayedView(AlignmentPanel alignmentPanel)
5931 if (!viewport.getSequenceSetId().equals(
5932 alignmentPanel.av.getSequenceSetId()))
5934 throw new Error(MessageManager.getString("error.implementation_error_cannot_show_view_alignment_frame"));
5936 if (tabbedPane != null
5937 && tabbedPane.getTabCount() > 0
5938 && alignPanels.indexOf(alignmentPanel) != tabbedPane
5939 .getSelectedIndex())
5941 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5946 * Action on selection of menu options to Show or Hide annotations.
5949 * @param forSequences
5950 * update sequence-related annotations
5951 * @param forAlignment
5952 * update non-sequence-related annotations
5955 protected void setAnnotationsVisibility(boolean visible,
5956 boolean forSequences, boolean forAlignment)
5958 for (AlignmentAnnotation aa : alignPanel.getAlignment()
5959 .getAlignmentAnnotation())
5962 * don't display non-positional annotations on an alignment
5964 if (aa.annotations == null)
5968 boolean apply = (aa.sequenceRef == null && forAlignment)
5969 || (aa.sequenceRef != null && forSequences);
5972 aa.visible = visible;
5975 alignPanel.validateAnnotationDimensions(false);
5976 alignPanel.alignmentChanged();
5980 * Store selected annotation sort order for the view and repaint.
5983 protected void sortAnnotations_actionPerformed()
5985 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5987 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5988 alignPanel.paintAlignment(true);
5993 * @return alignment panels in this alignment frame
5995 public List<? extends AlignmentViewPanel> getAlignPanels()
5997 return alignPanels == null ? Arrays.asList(alignPanel)
6002 * Open a new alignment window, with the cDNA associated with this (protein)
6003 * alignment, aligned as is the protein.
6005 protected void viewAsCdna_actionPerformed()
6007 // TODO no longer a menu action - refactor as required
6008 final AlignmentI alignment = getViewport().getAlignment();
6009 Set<AlignedCodonFrame> mappings = alignment.getCodonFrames();
6010 if (mappings == null)
6014 List<SequenceI> cdnaSeqs = new ArrayList<SequenceI>();
6015 for (SequenceI aaSeq : alignment.getSequences()) {
6016 for (AlignedCodonFrame acf : mappings) {
6017 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
6021 * There is a cDNA mapping for this protein sequence - add to new
6022 * alignment. It will share the same dataset sequence as other mapped
6023 * cDNA (no new mappings need to be created).
6025 final Sequence newSeq = new Sequence(dnaSeq);
6026 newSeq.setDatasetSequence(dnaSeq);
6027 cdnaSeqs.add(newSeq);
6031 if (cdnaSeqs.size() == 0)
6033 // show a warning dialog no mapped cDNA
6036 AlignmentI cdna = new Alignment(cdnaSeqs.toArray(new SequenceI[cdnaSeqs
6038 AlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
6039 AlignFrame.DEFAULT_HEIGHT);
6040 cdna.alignAs(alignment);
6041 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
6043 Desktop.addInternalFrame(alignFrame, newtitle,
6044 AlignFrame.DEFAULT_WIDTH,
6045 AlignFrame.DEFAULT_HEIGHT);
6049 * Set visibility of dna/protein complement view (available when shown in a
6055 protected void showComplement_actionPerformed(boolean show)
6057 SplitContainerI sf = getSplitViewContainer();
6059 sf.setComplementVisible(this, show);
6063 public class ExportData
6065 private AlignmentI alignment;
6067 private String[] omitHidden;
6069 private int[] startEnd;
6071 public ExportData(AlignmentI align, String[] ommit, int[] startEnd)
6073 this.alignment = align;
6074 this.omitHidden = ommit;
6075 this.startEnd = startEnd;
6078 public AlignmentI getAlignment()
6083 public void setAlignment(AlignmentI alignment)
6085 this.alignment = alignment;
6088 public String[] getOmitHidden()
6093 public void setOmitHidden(String[] omitHidden)
6095 this.omitHidden = omitHidden;
6098 public int[] getStartEndPostions()
6103 public void setStartEndPostions(int[] startEnd)
6105 this.startEnd = startEnd;
6110 public void hideColumns(List<int[]> colsToHide)
6112 for (int[] colRange : colsToHide)
6114 viewport.hideColumns(colRange[0], colRange[1]);
6120 public void syncHiddenSequences()
6122 AlignmentI al = viewport.getAlignment();
6123 HiddenSequences hiddenSeqs = al.getHiddenSequences();
6124 for (SequenceI seq : al.getSequencesArray())
6128 hiddenSeqs.hideSequence(seq);
6134 class PrintThread extends Thread
6138 public PrintThread(AlignmentPanel ap)
6143 static PageFormat pf;
6148 PrinterJob printJob = PrinterJob.getPrinterJob();
6152 printJob.setPrintable(ap, pf);
6156 printJob.setPrintable(ap);
6159 if (printJob.printDialog())
6164 } catch (Exception PrintException)
6166 PrintException.printStackTrace();