2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3 * Copyright (C) 2014 The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AAFrequency;
24 import jalview.analysis.AlignmentSorter;
25 import jalview.analysis.AlignmentUtils;
26 import jalview.analysis.AlignmentUtils.MappingResult;
27 import jalview.analysis.Conservation;
28 import jalview.analysis.CrossRef;
29 import jalview.analysis.Dna;
30 import jalview.analysis.ParseProperties;
31 import jalview.analysis.SequenceIdMatcher;
32 import jalview.api.AlignViewControllerGuiI;
33 import jalview.api.AlignViewControllerI;
34 import jalview.api.AlignViewportI;
35 import jalview.api.AlignmentViewPanel;
36 import jalview.api.analysis.ScoreModelI;
37 import jalview.bin.Cache;
38 import jalview.commands.CommandI;
39 import jalview.commands.EditCommand;
40 import jalview.commands.EditCommand.Action;
41 import jalview.commands.OrderCommand;
42 import jalview.commands.RemoveGapColCommand;
43 import jalview.commands.RemoveGapsCommand;
44 import jalview.commands.SlideSequencesCommand;
45 import jalview.commands.TrimRegionCommand;
46 import jalview.datamodel.AlignedCodonFrame;
47 import jalview.datamodel.Alignment;
48 import jalview.datamodel.AlignmentAnnotation;
49 import jalview.datamodel.AlignmentI;
50 import jalview.datamodel.AlignmentOrder;
51 import jalview.datamodel.AlignmentView;
52 import jalview.datamodel.ColumnSelection;
53 import jalview.datamodel.PDBEntry;
54 import jalview.datamodel.SeqCigar;
55 import jalview.datamodel.Sequence;
56 import jalview.datamodel.SequenceGroup;
57 import jalview.datamodel.SequenceI;
58 import jalview.io.AlignmentProperties;
59 import jalview.io.AnnotationFile;
60 import jalview.io.BioJsHTMLOutput;
61 import jalview.io.FeaturesFile;
62 import jalview.io.FileLoader;
63 import jalview.io.FormatAdapter;
64 import jalview.io.HtmlSvgOutput;
65 import jalview.io.IdentifyFile;
66 import jalview.io.JalviewFileChooser;
67 import jalview.io.JalviewFileView;
68 import jalview.io.JnetAnnotationMaker;
69 import jalview.io.NewickFile;
70 import jalview.io.TCoffeeScoreFile;
71 import jalview.jbgui.GAlignFrame;
72 import jalview.schemes.Blosum62ColourScheme;
73 import jalview.schemes.BuriedColourScheme;
74 import jalview.schemes.ClustalxColourScheme;
75 import jalview.schemes.ColourSchemeI;
76 import jalview.schemes.ColourSchemeProperty;
77 import jalview.schemes.HelixColourScheme;
78 import jalview.schemes.HydrophobicColourScheme;
79 import jalview.schemes.NucleotideColourScheme;
80 import jalview.schemes.PIDColourScheme;
81 import jalview.schemes.PurinePyrimidineColourScheme;
82 import jalview.schemes.RNAHelicesColourChooser;
83 import jalview.schemes.ResidueProperties;
84 import jalview.schemes.StrandColourScheme;
85 import jalview.schemes.TCoffeeColourScheme;
86 import jalview.schemes.TaylorColourScheme;
87 import jalview.schemes.TurnColourScheme;
88 import jalview.schemes.UserColourScheme;
89 import jalview.schemes.ZappoColourScheme;
90 import jalview.structure.StructureSelectionManager;
91 import jalview.util.MessageManager;
92 import jalview.viewmodel.AlignmentViewport;
93 import jalview.ws.jws1.Discoverer;
94 import jalview.ws.jws2.Jws2Discoverer;
95 import jalview.ws.jws2.jabaws2.Jws2Instance;
96 import jalview.ws.seqfetcher.DbSourceProxy;
98 import java.awt.BorderLayout;
99 import java.awt.Component;
100 import java.awt.GridLayout;
101 import java.awt.Rectangle;
102 import java.awt.Toolkit;
103 import java.awt.datatransfer.Clipboard;
104 import java.awt.datatransfer.DataFlavor;
105 import java.awt.datatransfer.StringSelection;
106 import java.awt.datatransfer.Transferable;
107 import java.awt.dnd.DnDConstants;
108 import java.awt.dnd.DropTargetDragEvent;
109 import java.awt.dnd.DropTargetDropEvent;
110 import java.awt.dnd.DropTargetEvent;
111 import java.awt.dnd.DropTargetListener;
112 import java.awt.event.ActionEvent;
113 import java.awt.event.ActionListener;
114 import java.awt.event.KeyAdapter;
115 import java.awt.event.KeyEvent;
116 import java.awt.event.MouseAdapter;
117 import java.awt.event.MouseEvent;
118 import java.awt.print.PageFormat;
119 import java.awt.print.PrinterJob;
120 import java.beans.PropertyChangeEvent;
123 import java.util.ArrayList;
124 import java.util.Arrays;
125 import java.util.Deque;
126 import java.util.Enumeration;
127 import java.util.Hashtable;
128 import java.util.List;
129 import java.util.Set;
130 import java.util.Vector;
132 import javax.swing.JButton;
133 import javax.swing.JCheckBoxMenuItem;
134 import javax.swing.JEditorPane;
135 import javax.swing.JInternalFrame;
136 import javax.swing.JLabel;
137 import javax.swing.JLayeredPane;
138 import javax.swing.JMenu;
139 import javax.swing.JMenuItem;
140 import javax.swing.JOptionPane;
141 import javax.swing.JPanel;
142 import javax.swing.JProgressBar;
143 import javax.swing.JRadioButtonMenuItem;
144 import javax.swing.JScrollPane;
145 import javax.swing.SwingUtilities;
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 avc = new jalview.controller.AlignViewController(this, viewport,
316 if (viewport.getAlignmentConservationAnnotation() == null)
318 BLOSUM62Colour.setEnabled(false);
319 conservationMenuItem.setEnabled(false);
320 modifyConservation.setEnabled(false);
321 // PIDColour.setEnabled(false);
322 // abovePIDThreshold.setEnabled(false);
323 // modifyPID.setEnabled(false);
326 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
329 if (sortby.equals("Id"))
331 sortIDMenuItem_actionPerformed(null);
333 else if (sortby.equals("Pairwise Identity"))
335 sortPairwiseMenuItem_actionPerformed(null);
338 if (Desktop.desktop != null)
340 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
341 addServiceListeners();
342 setGUINucleotide(viewport.getAlignment().isNucleotide());
345 setMenusFromViewport(viewport);
346 buildSortByAnnotationScoresMenu();
349 if (viewport.wrapAlignment)
351 wrapMenuItem_actionPerformed(null);
354 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
356 this.overviewMenuItem_actionPerformed(null);
364 * Change the filename and format for the alignment, and enable the 'reload'
365 * button functionality.
372 public void setFileName(String file, String format)
375 currentFileFormat = format;
376 reload.setEnabled(true);
380 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
383 void addKeyListener()
385 addKeyListener(new KeyAdapter()
388 public void keyPressed(KeyEvent evt)
390 if (viewport.cursorMode
391 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
392 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
393 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
394 && Character.isDigit(evt.getKeyChar()))
396 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
399 switch (evt.getKeyCode())
402 case 27: // escape key
403 deselectAllSequenceMenuItem_actionPerformed(null);
407 case KeyEvent.VK_DOWN:
408 if (evt.isAltDown() || !viewport.cursorMode)
410 moveSelectedSequences(false);
412 if (viewport.cursorMode)
414 alignPanel.getSeqPanel().moveCursor(0, 1);
419 if (evt.isAltDown() || !viewport.cursorMode)
421 moveSelectedSequences(true);
423 if (viewport.cursorMode)
425 alignPanel.getSeqPanel().moveCursor(0, -1);
430 case KeyEvent.VK_LEFT:
431 if (evt.isAltDown() || !viewport.cursorMode)
433 slideSequences(false, alignPanel.getSeqPanel().getKeyboardNo1());
437 alignPanel.getSeqPanel().moveCursor(-1, 0);
442 case KeyEvent.VK_RIGHT:
443 if (evt.isAltDown() || !viewport.cursorMode)
445 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
449 alignPanel.getSeqPanel().moveCursor(1, 0);
453 case KeyEvent.VK_SPACE:
454 if (viewport.cursorMode)
456 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
457 || evt.isShiftDown() || evt.isAltDown());
461 // case KeyEvent.VK_A:
462 // if (viewport.cursorMode)
464 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
465 // //System.out.println("A");
469 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
470 * System.out.println("closing bracket"); } break;
472 case KeyEvent.VK_DELETE:
473 case KeyEvent.VK_BACK_SPACE:
474 if (!viewport.cursorMode)
476 cut_actionPerformed(null);
480 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
481 || evt.isShiftDown() || evt.isAltDown());
487 if (viewport.cursorMode)
489 alignPanel.getSeqPanel().setCursorRow();
493 if (viewport.cursorMode && !evt.isControlDown())
495 alignPanel.getSeqPanel().setCursorColumn();
499 if (viewport.cursorMode)
501 alignPanel.getSeqPanel().setCursorPosition();
505 case KeyEvent.VK_ENTER:
506 case KeyEvent.VK_COMMA:
507 if (viewport.cursorMode)
509 alignPanel.getSeqPanel().setCursorRowAndColumn();
514 if (viewport.cursorMode)
516 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
520 if (viewport.cursorMode)
522 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
527 viewport.cursorMode = !viewport.cursorMode;
528 statusBar.setText(MessageManager.formatMessage(
529 "label.keyboard_editing_mode", new String[]
530 { (viewport.cursorMode ? "on" : "off") }));
531 if (viewport.cursorMode)
533 alignPanel.getSeqPanel().seqCanvas.cursorX = viewport.startRes;
534 alignPanel.getSeqPanel().seqCanvas.cursorY = viewport.startSeq;
536 alignPanel.getSeqPanel().seqCanvas.repaint();
542 Help.showHelpWindow();
543 } catch (Exception ex)
545 ex.printStackTrace();
550 boolean toggleSeqs = !evt.isControlDown();
551 boolean toggleCols = !evt.isShiftDown();
552 toggleHiddenRegions(toggleSeqs, toggleCols);
555 case KeyEvent.VK_PAGE_UP:
556 if (viewport.wrapAlignment)
558 alignPanel.scrollUp(true);
562 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
563 - viewport.endSeq + viewport.startSeq);
566 case KeyEvent.VK_PAGE_DOWN:
567 if (viewport.wrapAlignment)
569 alignPanel.scrollUp(false);
573 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
574 + viewport.endSeq - viewport.startSeq);
581 public void keyReleased(KeyEvent evt)
583 switch (evt.getKeyCode())
585 case KeyEvent.VK_LEFT:
586 if (evt.isAltDown() || !viewport.cursorMode)
588 viewport.firePropertyChange("alignment", null, viewport
589 .getAlignment().getSequences());
593 case KeyEvent.VK_RIGHT:
594 if (evt.isAltDown() || !viewport.cursorMode)
596 viewport.firePropertyChange("alignment", null, viewport
597 .getAlignment().getSequences());
605 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
607 ap.alignFrame = this;
608 avc = new jalview.controller.AlignViewController(this, viewport,
613 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
615 int aSize = alignPanels.size();
617 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
619 if (aSize == 1 && ap.av.viewName == null)
621 this.getContentPane().add(ap, BorderLayout.CENTER);
627 setInitialTabVisible();
630 expandViews.setEnabled(true);
631 gatherViews.setEnabled(true);
632 tabbedPane.addTab(ap.av.viewName, ap);
634 ap.setVisible(false);
639 if (ap.av.isPadGaps())
641 ap.av.getAlignment().padGaps();
643 ap.av.updateConservation(ap);
644 ap.av.updateConsensus(ap);
645 ap.av.updateStrucConsensus(ap);
649 public void setInitialTabVisible()
651 expandViews.setEnabled(true);
652 gatherViews.setEnabled(true);
653 tabbedPane.setVisible(true);
654 AlignmentPanel first = alignPanels.get(0);
655 tabbedPane.addTab(first.av.viewName, first);
656 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
659 public AlignViewport getViewport()
664 /* Set up intrinsic listeners for dynamically generated GUI bits. */
665 private void addServiceListeners()
667 final java.beans.PropertyChangeListener thisListener;
668 Desktop.instance.addJalviewPropertyChangeListener("services",
669 thisListener = new java.beans.PropertyChangeListener()
672 public void propertyChange(PropertyChangeEvent evt)
674 // // System.out.println("Discoverer property change.");
675 // if (evt.getPropertyName().equals("services"))
677 SwingUtilities.invokeLater(new Runnable()
684 .println("Rebuild WS Menu for service change");
685 BuildWebServiceMenu();
692 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
695 public void internalFrameClosed(
696 javax.swing.event.InternalFrameEvent evt)
698 System.out.println("deregistering discoverer listener");
699 Desktop.instance.removeJalviewPropertyChangeListener("services",
701 closeMenuItem_actionPerformed(true);
704 // Finally, build the menu once to get current service state
705 new Thread(new Runnable()
710 BuildWebServiceMenu();
715 public void setGUINucleotide(boolean nucleotide)
717 showTranslation.setVisible(nucleotide);
718 cdna.setVisible(!nucleotide);
719 conservationMenuItem.setEnabled(!nucleotide);
720 modifyConservation.setEnabled(!nucleotide);
721 showGroupConservation.setEnabled(!nucleotide);
722 rnahelicesColour.setEnabled(nucleotide);
723 purinePyrimidineColour.setEnabled(nucleotide);
727 * Builds codon mappings from this (protein) alignment to any compatible
728 * nucleotide alignments. Mappings are built between sequences with the same
729 * name and compatible lengths. Also makes the cDNA alignment a
730 * CommandListener for the protein alignment so that edits are mirrored.
733 protected void linkCdna_actionPerformed()
736 int alreadyLinkedCount = 0;
737 final AlignmentI thisAlignment = this.alignPanel.getAlignment();
739 for (AlignFrame af : Desktop.getAlignFrames())
741 if (af.alignPanel != null)
743 final AlignmentI thatAlignment = af.alignPanel.getAlignment();
744 if (thatAlignment.isNucleotide())
746 MappingResult mapped = AlignmentUtils.mapProteinToCdna(
747 thisAlignment, thatAlignment);
748 if (mapped == MappingResult.AlreadyMapped)
750 alreadyLinkedCount++;
752 else if (mapped == MappingResult.Mapped)
754 final StructureSelectionManager ssm = StructureSelectionManager
755 .getStructureSelectionManager(Desktop.instance);
756 ssm.addMappings(thisAlignment.getCodonFrames());
757 // enable the next line to enable linked editing
758 // ssm.addCommandListener(af.getViewport());
765 if (linkedCount == 0 && alreadyLinkedCount == 0)
767 msg = MessageManager.getString("label.no_cdna");
769 else if (linkedCount > 0)
771 msg = MessageManager.formatMessage("label.linked_cdna", linkedCount);
775 msg = MessageManager.formatMessage("label.cdna_all_linked",
782 * Align any linked cDNA to match the alignment of this (protein) alignment.
783 * Any mapped sequence regions will be realigned, unmapped sequences are not
787 protected void alignCdna_actionPerformed()
791 final AlignmentI thisAlignment = this.alignPanel.getAlignment();
792 for (AlignFrame af : Desktop.getAlignFrames())
794 if (af.alignPanel != null)
796 final AlignmentI thatAlignment = af.alignPanel.getAlignment();
797 if (thatAlignment.isNucleotide())
799 int seqsAligned = thatAlignment.alignAs(thisAlignment);
800 seqCount += seqsAligned;
803 af.alignPanel.alignmentChanged();
809 setStatus(MessageManager.formatMessage("label.cdna_aligned", seqCount,
813 * set up menus for the current viewport. This may be called after any
814 * operation that affects the data in the current view (selection changed,
815 * etc) to update the menus to reflect the new state.
817 public void setMenusForViewport()
819 setMenusFromViewport(viewport);
823 * Need to call this method when tabs are selected for multiple views, or when
824 * loading from Jalview2XML.java
829 void setMenusFromViewport(AlignViewport av)
831 padGapsMenuitem.setSelected(av.isPadGaps());
832 colourTextMenuItem.setSelected(av.showColourText);
833 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
834 conservationMenuItem.setSelected(av.getConservationSelected());
835 seqLimits.setSelected(av.getShowJVSuffix());
836 idRightAlign.setSelected(av.isRightAlignIds());
837 centreColumnLabelsMenuItem.setState(av.centreColumnLabels);
838 renderGapsMenuItem.setSelected(av.renderGaps);
839 wrapMenuItem.setSelected(av.wrapAlignment);
840 scaleAbove.setVisible(av.wrapAlignment);
841 scaleLeft.setVisible(av.wrapAlignment);
842 scaleRight.setVisible(av.wrapAlignment);
843 annotationPanelMenuItem.setState(av.isShowAnnotation());
845 * Show/hide annotations only enabled if annotation panel is shown
847 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
848 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
849 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
850 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
851 viewBoxesMenuItem.setSelected(av.showBoxes);
852 viewTextMenuItem.setSelected(av.showText);
853 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
854 showGroupConsensus.setSelected(av.isShowGroupConsensus());
855 showGroupConservation.setSelected(av.isShowGroupConservation());
856 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
857 showSequenceLogo.setSelected(av.isShowSequenceLogo());
858 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
860 setColourSelected(ColourSchemeProperty.getColourName(av
861 .getGlobalColourScheme()));
863 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
864 hiddenMarkers.setState(av.showHiddenMarkers);
865 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
866 showNpFeatsMenuitem.setSelected(av.isShowNpFeats());
867 showDbRefsMenuitem.setSelected(av.isShowDbRefs());
868 autoCalculate.setSelected(av.autoCalculateConsensus);
869 sortByTree.setSelected(av.sortByTree);
870 listenToViewSelections.setSelected(av.followSelection);
871 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
873 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
874 setShowProductsEnabled();
878 // methods for implementing IProgressIndicator
879 // need to refactor to a reusable stub class
880 Hashtable progressBars, progressBarHandlers;
885 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
888 public void setProgressBar(String message, long id)
890 if (progressBars == null)
892 progressBars = new Hashtable();
893 progressBarHandlers = new Hashtable();
896 JPanel progressPanel;
897 Long lId = new Long(id);
898 GridLayout layout = (GridLayout) statusPanel.getLayout();
899 if (progressBars.get(lId) != null)
901 progressPanel = (JPanel) progressBars.get(new Long(id));
902 statusPanel.remove(progressPanel);
903 progressBars.remove(lId);
904 progressPanel = null;
907 statusBar.setText(message);
909 if (progressBarHandlers.contains(lId))
911 progressBarHandlers.remove(lId);
913 layout.setRows(layout.getRows() - 1);
917 progressPanel = new JPanel(new BorderLayout(10, 5));
919 JProgressBar progressBar = new JProgressBar();
920 progressBar.setIndeterminate(true);
922 progressPanel.add(new JLabel(message), BorderLayout.WEST);
923 progressPanel.add(progressBar, BorderLayout.CENTER);
925 layout.setRows(layout.getRows() + 1);
926 statusPanel.add(progressPanel);
928 progressBars.put(lId, progressPanel);
931 // setMenusForViewport();
936 public void registerHandler(final long id,
937 final IProgressIndicatorHandler handler)
939 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
941 throw new Error(MessageManager.getString("error.call_setprogressbar_before_registering_handler"));
943 progressBarHandlers.put(new Long(id), handler);
944 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
945 if (handler.canCancel())
947 JButton cancel = new JButton(
948 MessageManager.getString("action.cancel"));
949 final IProgressIndicator us = this;
950 cancel.addActionListener(new ActionListener()
954 public void actionPerformed(ActionEvent e)
956 handler.cancelActivity(id);
957 us.setProgressBar(MessageManager.formatMessage("label.cancelled_params", new Object[]{((JLabel) progressPanel.getComponent(0)).getText()}), id);
960 progressPanel.add(cancel, BorderLayout.EAST);
966 * @return true if any progress bars are still active
969 public boolean operationInProgress()
971 if (progressBars != null && progressBars.size() > 0)
979 public void setStatus(String text)
981 statusBar.setText(text);
985 * Added so Castor Mapping file can obtain Jalview Version
987 public String getVersion()
989 return jalview.bin.Cache.getProperty("VERSION");
992 public FeatureRenderer getFeatureRenderer()
994 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
998 public void fetchSequence_actionPerformed(ActionEvent e)
1000 new SequenceFetcher(this);
1004 public void addFromFile_actionPerformed(ActionEvent e)
1006 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1010 public void reload_actionPerformed(ActionEvent e)
1012 if (fileName != null)
1014 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1015 // originating file's format
1016 // TODO: work out how to recover feature settings for correct view(s) when
1017 // file is reloaded.
1018 if (currentFileFormat.equals("Jalview"))
1020 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1021 for (int i = 0; i < frames.length; i++)
1023 if (frames[i] instanceof AlignFrame && frames[i] != this
1024 && ((AlignFrame) frames[i]).fileName != null
1025 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1029 frames[i].setSelected(true);
1030 Desktop.instance.closeAssociatedWindows();
1031 } catch (java.beans.PropertyVetoException ex)
1037 Desktop.instance.closeAssociatedWindows();
1039 FileLoader loader = new FileLoader();
1040 String protocol = fileName.startsWith("http:") ? "URL" : "File";
1041 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1045 Rectangle bounds = this.getBounds();
1047 FileLoader loader = new FileLoader();
1048 String protocol = fileName.startsWith("http:") ? "URL" : "File";
1049 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1050 protocol, currentFileFormat);
1052 newframe.setBounds(bounds);
1053 if (featureSettings != null && featureSettings.isShowing())
1055 final Rectangle fspos = featureSettings.frame.getBounds();
1056 // TODO: need a 'show feature settings' function that takes bounds -
1057 // need to refactor Desktop.addFrame
1058 newframe.featureSettings_actionPerformed(null);
1059 final FeatureSettings nfs = newframe.featureSettings;
1060 SwingUtilities.invokeLater(new Runnable()
1065 nfs.frame.setBounds(fspos);
1068 this.featureSettings.close();
1069 this.featureSettings = null;
1071 this.closeMenuItem_actionPerformed(true);
1077 public void addFromText_actionPerformed(ActionEvent e)
1079 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
1083 public void addFromURL_actionPerformed(ActionEvent e)
1085 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1089 public void save_actionPerformed(ActionEvent e)
1091 if (fileName == null
1092 || (currentFileFormat == null || !jalview.io.FormatAdapter
1093 .isValidIOFormat(currentFileFormat, true))
1094 || fileName.startsWith("http"))
1096 saveAs_actionPerformed(null);
1100 saveAlignment(fileName, currentFileFormat);
1111 public void saveAs_actionPerformed(ActionEvent e)
1113 JalviewFileChooser chooser = new JalviewFileChooser(
1114 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
1115 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
1116 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
1117 currentFileFormat, false);
1119 chooser.setFileView(new JalviewFileView());
1120 chooser.setDialogTitle(MessageManager.getString("label.save_alignment_to_file"));
1121 chooser.setToolTipText(MessageManager.getString("action.save"));
1123 int value = chooser.showSaveDialog(this);
1125 if (value == JalviewFileChooser.APPROVE_OPTION)
1127 currentFileFormat = chooser.getSelectedFormat();
1128 while (currentFileFormat == null)
1131 .showInternalMessageDialog(
1134 .getString("label.select_file_format_before_saving"),
1136 .getString("label.file_format_not_specified"),
1137 JOptionPane.WARNING_MESSAGE);
1138 currentFileFormat = chooser.getSelectedFormat();
1139 value = chooser.showSaveDialog(this);
1140 if (value != JalviewFileChooser.APPROVE_OPTION)
1146 fileName = chooser.getSelectedFile().getPath();
1148 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
1151 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
1152 if (currentFileFormat.indexOf(" ") > -1)
1154 currentFileFormat = currentFileFormat.substring(0,
1155 currentFileFormat.indexOf(" "));
1157 saveAlignment(fileName, currentFileFormat);
1161 public boolean saveAlignment(String file, String format)
1163 boolean success = true;
1165 if (format.equalsIgnoreCase("Jalview"))
1167 String shortName = title;
1169 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1171 shortName = shortName.substring(shortName
1172 .lastIndexOf(java.io.File.separatorChar) + 1);
1176 * First save any linked Chimera session.
1178 Desktop.instance.saveChimeraSessions(file);
1180 success = new Jalview2XML().saveAlignment(this, file, shortName);
1182 statusBar.setText(MessageManager.formatMessage(
1183 "label.successfully_saved_to_file_in_format", new Object[]
1184 { fileName, format }));
1189 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1191 warningMessage("Cannot save file " + fileName + " using format "
1192 + format, "Alignment output format not supported");
1193 saveAs_actionPerformed(null);
1194 // JBPNote need to have a raise_gui flag here
1198 String[] omitHidden = null;
1200 if (viewport.hasHiddenColumns())
1202 int reply = JOptionPane
1203 .showInternalConfirmDialog(
1206 .getString("label.alignment_contains_hidden_columns"),
1208 .getString("action.save_omit_hidden_columns"),
1209 JOptionPane.YES_NO_OPTION,
1210 JOptionPane.QUESTION_MESSAGE);
1212 if (reply == JOptionPane.YES_OPTION)
1214 omitHidden = viewport.getViewAsString(false);
1217 FormatAdapter f = new FormatAdapter();
1218 String output = f.formatSequences(format,
1219 viewport.getAlignment(), // class cast exceptions will
1220 // occur in the distant future
1221 omitHidden, f.getCacheSuffixDefault(format),
1222 viewport.getColumnSelection());
1232 java.io.PrintWriter out = new java.io.PrintWriter(
1233 new java.io.FileWriter(file));
1237 this.setTitle(file);
1238 statusBar.setText(MessageManager.formatMessage(
1239 "label.successfully_saved_to_file_in_format",
1241 { fileName, format }));
1242 } catch (Exception ex)
1245 ex.printStackTrace();
1252 JOptionPane.showInternalMessageDialog(this, MessageManager
1253 .formatMessage("label.couldnt_save_file", new Object[]
1254 { fileName }), MessageManager
1255 .getString("label.error_saving_file"),
1256 JOptionPane.WARNING_MESSAGE);
1262 private void warningMessage(String warning, String title)
1264 if (new jalview.util.Platform().isHeadless())
1266 System.err.println("Warning: " + title + "\nWarning: " + warning);
1271 JOptionPane.showInternalMessageDialog(this, warning, title,
1272 JOptionPane.WARNING_MESSAGE);
1284 protected void outputText_actionPerformed(ActionEvent e)
1286 String[] omitHidden = null;
1288 if (viewport.hasHiddenColumns())
1290 int reply = JOptionPane
1291 .showInternalConfirmDialog(
1294 .getString("label.alignment_contains_hidden_columns"),
1296 .getString("action.save_omit_hidden_columns"),
1297 JOptionPane.YES_NO_OPTION,
1298 JOptionPane.QUESTION_MESSAGE);
1300 if (reply == JOptionPane.YES_OPTION)
1302 omitHidden = viewport.getViewAsString(false);
1306 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1307 cap.setForInput(null);
1311 cap.setText(new FormatAdapter().formatSequences(e.getActionCommand(),
1312 viewport.getAlignment(), omitHidden,
1313 viewport.getColumnSelection()));
1314 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1315 "label.alignment_output_command", new Object[]
1316 { e.getActionCommand() }), 600, 500);
1317 } catch (OutOfMemoryError oom)
1319 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1332 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1334 // new HTMLOutput(alignPanel,
1335 // alignPanel.getSeqPanel().seqCanvas.getSequenceRenderer(),
1336 // alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
1337 new HtmlSvgOutput(null, alignPanel);
1341 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1343 new BioJsHTMLOutput(alignPanel,
1344 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
1346 public void createImageMap(File file, String image)
1348 alignPanel.makePNGImageMap(file, image);
1358 public void createPNG(File f)
1360 alignPanel.makePNG(f);
1370 public void createEPS(File f)
1372 alignPanel.makeEPS(f);
1375 public void createSVG(File f)
1377 alignPanel.makeSVG(f);
1380 public void pageSetup_actionPerformed(ActionEvent e)
1382 PrinterJob printJob = PrinterJob.getPrinterJob();
1383 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1393 public void printMenuItem_actionPerformed(ActionEvent e)
1395 // Putting in a thread avoids Swing painting problems
1396 PrintThread thread = new PrintThread(alignPanel);
1401 public void exportFeatures_actionPerformed(ActionEvent e)
1403 new AnnotationExporter().exportFeatures(alignPanel);
1407 public void exportAnnotations_actionPerformed(ActionEvent e)
1409 new AnnotationExporter().exportAnnotations(alignPanel);
1413 public void associatedData_actionPerformed(ActionEvent e)
1415 // Pick the tree file
1416 JalviewFileChooser chooser = new JalviewFileChooser(
1417 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1418 chooser.setFileView(new JalviewFileView());
1419 chooser.setDialogTitle(MessageManager
1420 .getString("label.load_jalview_annotations"));
1421 chooser.setToolTipText(MessageManager
1422 .getString("label.load_jalview_annotations"));
1424 int value = chooser.showOpenDialog(null);
1426 if (value == JalviewFileChooser.APPROVE_OPTION)
1428 String choice = chooser.getSelectedFile().getPath();
1429 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1430 loadJalviewDataFile(choice, null, null, null);
1436 * Close the current view or all views in the alignment frame. If the frame
1437 * only contains one view then the alignment will be removed from memory.
1439 * @param closeAllTabs
1442 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1444 if (alignPanels != null && alignPanels.size() < 2)
1446 closeAllTabs = true;
1451 if (alignPanels != null)
1455 if (this.isClosed())
1457 // really close all the windows - otherwise wait till
1458 // setClosed(true) is called
1459 for (int i = 0; i < alignPanels.size(); i++)
1461 AlignmentPanel ap = alignPanels.get(i);
1468 closeView(alignPanel);
1474 this.setClosed(true);
1476 } catch (Exception ex)
1478 ex.printStackTrace();
1483 * Close the specified panel and close up tabs appropriately.
1485 * @param panelToClose
1487 public void closeView(AlignmentPanel panelToClose)
1489 int index = tabbedPane.getSelectedIndex();
1490 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1491 alignPanels.remove(panelToClose);
1492 panelToClose.closePanel();
1493 panelToClose = null;
1495 tabbedPane.removeTabAt(closedindex);
1496 tabbedPane.validate();
1498 if (index > closedindex || index == tabbedPane.getTabCount())
1500 // modify currently selected tab index if necessary.
1504 this.tabSelectionChanged(index);
1510 void updateEditMenuBar()
1513 if (viewport.getHistoryList().size() > 0)
1515 undoMenuItem.setEnabled(true);
1516 CommandI command = viewport.getHistoryList().peek();
1517 undoMenuItem.setText(MessageManager.formatMessage(
1518 "label.undo_command", new Object[]
1519 { command.getDescription() }));
1523 undoMenuItem.setEnabled(false);
1524 undoMenuItem.setText(MessageManager.getString("action.undo"));
1527 if (viewport.getRedoList().size() > 0)
1529 redoMenuItem.setEnabled(true);
1531 CommandI command = viewport.getRedoList().peek();
1532 redoMenuItem.setText(MessageManager.formatMessage(
1533 "label.redo_command", new Object[]
1534 { command.getDescription() }));
1538 redoMenuItem.setEnabled(false);
1539 redoMenuItem.setText(MessageManager.getString("action.redo"));
1543 public void addHistoryItem(CommandI command)
1545 if (command.getSize() > 0)
1547 viewport.addToHistoryList(command);
1548 viewport.clearRedoList();
1549 updateEditMenuBar();
1550 viewport.updateHiddenColumns();
1551 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1552 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1553 // viewport.getColumnSelection()
1554 // .getHiddenColumns().size() > 0);
1560 * @return alignment objects for all views
1562 AlignmentI[] getViewAlignments()
1564 if (alignPanels != null)
1566 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1568 for (AlignmentPanel ap : alignPanels)
1570 als[i++] = ap.av.getAlignment();
1574 if (viewport != null)
1576 return new AlignmentI[]
1577 { viewport.getAlignment() };
1589 protected void undoMenuItem_actionPerformed(ActionEvent e)
1591 if (viewport.getHistoryList().isEmpty())
1595 CommandI command = viewport.getHistoryList().pop();
1596 viewport.addToRedoList(command);
1597 command.undoCommand(getViewAlignments());
1599 AlignmentViewport originalSource = getOriginatingSource(command);
1600 updateEditMenuBar();
1602 if (originalSource != null)
1604 if (originalSource != viewport)
1607 .warn("Implementation worry: mismatch of viewport origin for undo");
1609 originalSource.updateHiddenColumns();
1610 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1612 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1613 // viewport.getColumnSelection()
1614 // .getHiddenColumns().size() > 0);
1615 originalSource.firePropertyChange("alignment", null, originalSource
1616 .getAlignment().getSequences());
1627 protected void redoMenuItem_actionPerformed(ActionEvent e)
1629 if (viewport.getRedoList().size() < 1)
1634 CommandI command = viewport.getRedoList().pop();
1635 viewport.addToHistoryList(command);
1636 command.doCommand(getViewAlignments());
1638 AlignmentViewport originalSource = getOriginatingSource(command);
1639 updateEditMenuBar();
1641 if (originalSource != null)
1644 if (originalSource != viewport)
1647 .warn("Implementation worry: mismatch of viewport origin for redo");
1649 originalSource.updateHiddenColumns();
1650 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1652 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1653 // viewport.getColumnSelection()
1654 // .getHiddenColumns().size() > 0);
1655 originalSource.firePropertyChange("alignment", null, originalSource
1656 .getAlignment().getSequences());
1660 AlignmentViewport getOriginatingSource(CommandI command)
1662 AlignmentViewport originalSource = null;
1663 // For sequence removal and addition, we need to fire
1664 // the property change event FROM the viewport where the
1665 // original alignment was altered
1666 AlignmentI al = null;
1667 if (command instanceof EditCommand)
1669 EditCommand editCommand = (EditCommand) command;
1670 al = editCommand.getAlignment();
1671 List<Component> comps = PaintRefresher.components.get(viewport
1672 .getSequenceSetId());
1674 for (Component comp : comps)
1676 if (comp instanceof AlignmentPanel)
1678 if (al == ((AlignmentPanel) comp).av.getAlignment())
1680 originalSource = ((AlignmentPanel) comp).av;
1687 if (originalSource == null)
1689 // The original view is closed, we must validate
1690 // the current view against the closed view first
1693 PaintRefresher.validateSequences(al, viewport.getAlignment());
1696 originalSource = viewport;
1699 return originalSource;
1708 public void moveSelectedSequences(boolean up)
1710 SequenceGroup sg = viewport.getSelectionGroup();
1716 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1717 viewport.getHiddenRepSequences(), up);
1718 alignPanel.paintAlignment(true);
1721 synchronized void slideSequences(boolean right, int size)
1723 List<SequenceI> sg = new ArrayList<SequenceI>();
1724 if (viewport.cursorMode)
1726 sg.add(viewport.getAlignment().getSequenceAt(
1727 alignPanel.getSeqPanel().seqCanvas.cursorY));
1729 else if (viewport.getSelectionGroup() != null
1730 && viewport.getSelectionGroup().getSize() != viewport
1731 .getAlignment().getHeight())
1733 sg = viewport.getSelectionGroup().getSequences(
1734 viewport.getHiddenRepSequences());
1742 List<SequenceI> invertGroup = new ArrayList<SequenceI>();
1744 for (SequenceI seq : viewport.getAlignment().getSequences())
1746 if (!sg.contains(seq))
1748 invertGroup.add(seq);
1752 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1754 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1755 for (int i = 0; i < invertGroup.size(); i++)
1757 seqs2[i] = invertGroup.get(i);
1760 SlideSequencesCommand ssc;
1763 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1764 size, viewport.getGapCharacter());
1768 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1769 size, viewport.getGapCharacter());
1772 int groupAdjustment = 0;
1773 if (ssc.getGapsInsertedBegin() && right)
1775 if (viewport.cursorMode)
1777 alignPanel.getSeqPanel().moveCursor(size, 0);
1781 groupAdjustment = size;
1784 else if (!ssc.getGapsInsertedBegin() && !right)
1786 if (viewport.cursorMode)
1788 alignPanel.getSeqPanel().moveCursor(-size, 0);
1792 groupAdjustment = -size;
1796 if (groupAdjustment != 0)
1798 viewport.getSelectionGroup().setStartRes(
1799 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1800 viewport.getSelectionGroup().setEndRes(
1801 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1804 boolean appendHistoryItem = false;
1805 Deque<CommandI> historyList = viewport.getHistoryList();
1806 if (historyList != null
1807 && historyList.size() > 0
1808 && historyList.peek() instanceof SlideSequencesCommand)
1810 appendHistoryItem = ssc
1811 .appendSlideCommand((SlideSequencesCommand) historyList
1815 if (!appendHistoryItem)
1817 addHistoryItem(ssc);
1830 protected void copy_actionPerformed(ActionEvent e)
1833 if (viewport.getSelectionGroup() == null)
1837 // TODO: preserve the ordering of displayed alignment annotation in any
1838 // internal paste (particularly sequence associated annotation)
1839 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1840 String[] omitHidden = null;
1842 if (viewport.hasHiddenColumns())
1844 omitHidden = viewport.getViewAsString(true);
1847 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1850 StringSelection ss = new StringSelection(output);
1854 jalview.gui.Desktop.internalCopy = true;
1855 // Its really worth setting the clipboard contents
1856 // to empty before setting the large StringSelection!!
1857 Toolkit.getDefaultToolkit().getSystemClipboard()
1858 .setContents(new StringSelection(""), null);
1860 Toolkit.getDefaultToolkit().getSystemClipboard()
1861 .setContents(ss, Desktop.instance);
1862 } catch (OutOfMemoryError er)
1864 new OOMWarning("copying region", er);
1868 ArrayList<int[]> hiddenColumns = null;
1869 if (viewport.hasHiddenColumns())
1871 hiddenColumns = new ArrayList<int[]>();
1872 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1873 .getSelectionGroup().getEndRes();
1874 for (int[] region : viewport.getColumnSelection().getHiddenColumns())
1876 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1878 hiddenColumns.add(new int[]
1879 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1884 Desktop.jalviewClipboard = new Object[]
1885 { seqs, viewport.getAlignment().getDataset(), hiddenColumns };
1886 statusBar.setText(MessageManager.formatMessage(
1887 "label.copied_sequences_to_clipboard", new Object[]
1888 { Integer.valueOf(seqs.length).toString() }));
1898 protected void pasteNew_actionPerformed(ActionEvent e)
1910 protected void pasteThis_actionPerformed(ActionEvent e)
1916 * Paste contents of Jalview clipboard
1918 * @param newAlignment
1919 * true to paste to a new alignment, otherwise add to this.
1921 void paste(boolean newAlignment)
1923 boolean externalPaste = true;
1926 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1927 Transferable contents = c.getContents(this);
1929 if (contents == null)
1937 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1938 if (str.length() < 1)
1943 format = new IdentifyFile().Identify(str, "Paste");
1945 } catch (OutOfMemoryError er)
1947 new OOMWarning("Out of memory pasting sequences!!", er);
1951 SequenceI[] sequences;
1952 boolean annotationAdded = false;
1953 AlignmentI alignment = null;
1955 if (Desktop.jalviewClipboard != null)
1957 // The clipboard was filled from within Jalview, we must use the
1959 // And dataset from the copied alignment
1960 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1961 // be doubly sure that we create *new* sequence objects.
1962 sequences = new SequenceI[newseq.length];
1963 for (int i = 0; i < newseq.length; i++)
1965 sequences[i] = new Sequence(newseq[i]);
1967 alignment = new Alignment(sequences);
1968 externalPaste = false;
1972 // parse the clipboard as an alignment.
1973 alignment = new FormatAdapter().readFile(str, "Paste", format);
1974 sequences = alignment.getSequencesArray();
1978 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1984 if (Desktop.jalviewClipboard != null)
1986 // dataset is inherited
1987 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1991 // new dataset is constructed
1992 alignment.setDataset(null);
1994 alwidth = alignment.getWidth() + 1;
1998 AlignmentI pastedal = alignment; // preserve pasted alignment object
1999 // Add pasted sequences and dataset into existing alignment.
2000 alignment = viewport.getAlignment();
2001 alwidth = alignment.getWidth() + 1;
2002 // decide if we need to import sequences from an existing dataset
2003 boolean importDs = Desktop.jalviewClipboard != null
2004 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2005 // importDs==true instructs us to copy over new dataset sequences from
2006 // an existing alignment
2007 Vector newDs = (importDs) ? new Vector() : null; // used to create
2008 // minimum dataset set
2010 for (int i = 0; i < sequences.length; i++)
2014 newDs.addElement(null);
2016 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2018 if (importDs && ds != null)
2020 if (!newDs.contains(ds))
2022 newDs.setElementAt(ds, i);
2023 ds = new Sequence(ds);
2024 // update with new dataset sequence
2025 sequences[i].setDatasetSequence(ds);
2029 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2034 // copy and derive new dataset sequence
2035 sequences[i] = sequences[i].deriveSequence();
2036 alignment.getDataset().addSequence(
2037 sequences[i].getDatasetSequence());
2038 // TODO: avoid creation of duplicate dataset sequences with a
2039 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2041 alignment.addSequence(sequences[i]); // merges dataset
2045 newDs.clear(); // tidy up
2047 if (alignment.getAlignmentAnnotation() != null)
2049 for (AlignmentAnnotation alan : alignment
2050 .getAlignmentAnnotation())
2052 if (alan.graphGroup > fgroup)
2054 fgroup = alan.graphGroup;
2058 if (pastedal.getAlignmentAnnotation() != null)
2060 // Add any annotation attached to alignment.
2061 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2062 for (int i = 0; i < alann.length; i++)
2064 annotationAdded = true;
2065 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2067 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2068 if (newann.graphGroup > -1)
2070 if (newGraphGroups.size() <= newann.graphGroup
2071 || newGraphGroups.get(newann.graphGroup) == null)
2073 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2075 newGraphGroups.add(q, null);
2077 newGraphGroups.set(newann.graphGroup, new Integer(
2080 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2084 newann.padAnnotation(alwidth);
2085 alignment.addAnnotation(newann);
2095 addHistoryItem(new EditCommand(
2096 MessageManager.getString("label.add_sequences"),
2098 sequences, 0, alignment.getWidth(), alignment));
2100 // Add any annotations attached to sequences
2101 for (int i = 0; i < sequences.length; i++)
2103 if (sequences[i].getAnnotation() != null)
2105 AlignmentAnnotation newann;
2106 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2108 annotationAdded = true;
2109 newann = sequences[i].getAnnotation()[a];
2110 newann.adjustForAlignment();
2111 newann.padAnnotation(alwidth);
2112 if (newann.graphGroup > -1)
2114 if (newann.graphGroup > -1)
2116 if (newGraphGroups.size() <= newann.graphGroup
2117 || newGraphGroups.get(newann.graphGroup) == null)
2119 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2121 newGraphGroups.add(q, null);
2123 newGraphGroups.set(newann.graphGroup, new Integer(
2126 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2130 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2135 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2142 // propagate alignment changed.
2143 viewport.setEndSeq(alignment.getHeight());
2144 if (annotationAdded)
2146 // Duplicate sequence annotation in all views.
2147 AlignmentI[] alview = this.getViewAlignments();
2148 for (int i = 0; i < sequences.length; i++)
2150 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2155 for (int avnum = 0; avnum < alview.length; avnum++)
2157 if (alview[avnum] != alignment)
2159 // duplicate in a view other than the one with input focus
2160 int avwidth = alview[avnum].getWidth() + 1;
2161 // this relies on sann being preserved after we
2162 // modify the sequence's annotation array for each duplication
2163 for (int a = 0; a < sann.length; a++)
2165 AlignmentAnnotation newann = new AlignmentAnnotation(
2167 sequences[i].addAlignmentAnnotation(newann);
2168 newann.padAnnotation(avwidth);
2169 alview[avnum].addAnnotation(newann); // annotation was
2170 // duplicated earlier
2171 // TODO JAL-1145 graphGroups are not updated for sequence
2172 // annotation added to several views. This may cause
2174 alview[avnum].setAnnotationIndex(newann, a);
2179 buildSortByAnnotationScoresMenu();
2181 viewport.firePropertyChange("alignment", null,
2182 alignment.getSequences());
2183 if (alignPanels != null)
2185 for (AlignmentPanel ap : alignPanels)
2187 ap.validateAnnotationDimensions(false);
2192 alignPanel.validateAnnotationDimensions(false);
2198 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2200 String newtitle = new String("Copied sequences");
2202 if (Desktop.jalviewClipboard != null
2203 && Desktop.jalviewClipboard[2] != null)
2205 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2206 for (int[] region : hc)
2208 af.viewport.hideColumns(region[0], region[1]);
2212 // >>>This is a fix for the moment, until a better solution is
2214 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2216 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
2218 // TODO: maintain provenance of an alignment, rather than just make the
2219 // title a concatenation of operations.
2222 if (title.startsWith("Copied sequences"))
2228 newtitle = newtitle.concat("- from " + title);
2233 newtitle = new String("Pasted sequences");
2236 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2241 } catch (Exception ex)
2243 ex.printStackTrace();
2244 System.out.println("Exception whilst pasting: " + ex);
2245 // could be anything being pasted in here
2251 protected void expand_newalign(ActionEvent e)
2255 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2256 .getAlignment(), -1);
2257 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2259 String newtitle = new String("Flanking alignment");
2261 if (Desktop.jalviewClipboard != null
2262 && Desktop.jalviewClipboard[2] != null)
2264 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2265 for (int region[] : hc)
2267 af.viewport.hideColumns(region[0], region[1]);
2271 // >>>This is a fix for the moment, until a better solution is
2273 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2275 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
2277 // TODO: maintain provenance of an alignment, rather than just make the
2278 // title a concatenation of operations.
2280 if (title.startsWith("Copied sequences"))
2286 newtitle = newtitle.concat("- from " + title);
2290 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2292 } catch (Exception ex)
2294 ex.printStackTrace();
2295 System.out.println("Exception whilst pasting: " + ex);
2296 // could be anything being pasted in here
2297 } catch (OutOfMemoryError oom)
2299 new OOMWarning("Viewing flanking region of alignment", oom);
2310 protected void cut_actionPerformed(ActionEvent e)
2312 copy_actionPerformed(null);
2313 delete_actionPerformed(null);
2323 protected void delete_actionPerformed(ActionEvent evt)
2326 SequenceGroup sg = viewport.getSelectionGroup();
2332 List<SequenceI> seqs = new ArrayList<SequenceI>(sg.getSize());
2334 for (int i = 0; i < sg.getSize(); i++)
2336 seq = sg.getSequenceAt(i);
2340 // If the cut affects all sequences, warn, remove highlighted columns
2341 if (sg.getSize() == viewport.getAlignment().getHeight())
2343 int confirm = JOptionPane.showConfirmDialog(this,
2344 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2345 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2346 JOptionPane.OK_CANCEL_OPTION);
2348 if (confirm == JOptionPane.CANCEL_OPTION
2349 || confirm == JOptionPane.CLOSED_OPTION)
2353 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2354 sg.getEndRes() + 1);
2357 SequenceI[] cut = new SequenceI[seqs.size()];
2358 for (int i = 0; i < seqs.size(); i++)
2360 cut[i] = seqs.get(i);
2364 * //ADD HISTORY ITEM
2366 addHistoryItem(new EditCommand(
2367 MessageManager.getString("label.cut_sequences"), Action.CUT,
2368 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2369 viewport.getAlignment()));
2371 viewport.setSelectionGroup(null);
2372 viewport.sendSelection();
2373 viewport.getAlignment().deleteGroup(sg);
2375 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2377 if (viewport.getAlignment().getHeight() < 1)
2381 this.setClosed(true);
2382 } catch (Exception ex)
2395 protected void deleteGroups_actionPerformed(ActionEvent e)
2397 if (avc.deleteGroups())
2399 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2400 alignPanel.updateAnnotation();
2401 alignPanel.paintAlignment(true);
2412 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2414 SequenceGroup sg = new SequenceGroup();
2416 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2418 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2421 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2422 viewport.setSelectionGroup(sg);
2423 viewport.sendSelection();
2424 alignPanel.paintAlignment(true);
2425 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2435 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2437 if (viewport.cursorMode)
2439 alignPanel.getSeqPanel().keyboardNo1 = null;
2440 alignPanel.getSeqPanel().keyboardNo2 = null;
2442 viewport.setSelectionGroup(null);
2443 viewport.getColumnSelection().clear();
2444 viewport.setSelectionGroup(null);
2445 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2446 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2447 alignPanel.paintAlignment(true);
2448 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2449 viewport.sendSelection();
2459 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2461 SequenceGroup sg = viewport.getSelectionGroup();
2465 selectAllSequenceMenuItem_actionPerformed(null);
2470 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2472 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2475 alignPanel.paintAlignment(true);
2476 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2477 viewport.sendSelection();
2481 public void invertColSel_actionPerformed(ActionEvent e)
2483 viewport.invertColumnSelection();
2484 alignPanel.paintAlignment(true);
2485 viewport.sendSelection();
2495 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2497 trimAlignment(true);
2507 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2509 trimAlignment(false);
2512 void trimAlignment(boolean trimLeft)
2514 ColumnSelection colSel = viewport.getColumnSelection();
2517 if (colSel.size() > 0)
2521 column = colSel.getMin();
2525 column = colSel.getMax();
2529 if (viewport.getSelectionGroup() != null)
2531 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2532 viewport.getHiddenRepSequences());
2536 seqs = viewport.getAlignment().getSequencesArray();
2539 TrimRegionCommand trimRegion;
2542 trimRegion = new TrimRegionCommand("Remove Left",
2543 TrimRegionCommand.TRIM_LEFT, seqs, column,
2544 viewport.getAlignment(), viewport.getColumnSelection(),
2545 viewport.getSelectionGroup());
2546 viewport.setStartRes(0);
2550 trimRegion = new TrimRegionCommand("Remove Right",
2551 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2552 viewport.getAlignment(), viewport.getColumnSelection(),
2553 viewport.getSelectionGroup());
2556 statusBar.setText(MessageManager.formatMessage(
2557 "label.removed_columns", new String[]
2558 { Integer.valueOf(trimRegion.getSize()).toString() }));
2560 addHistoryItem(trimRegion);
2562 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2564 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2565 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2567 viewport.getAlignment().deleteGroup(sg);
2571 viewport.firePropertyChange("alignment", null, viewport
2572 .getAlignment().getSequences());
2583 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2585 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2588 if (viewport.getSelectionGroup() != null)
2590 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2591 viewport.getHiddenRepSequences());
2592 start = viewport.getSelectionGroup().getStartRes();
2593 end = viewport.getSelectionGroup().getEndRes();
2597 seqs = viewport.getAlignment().getSequencesArray();
2600 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2601 "Remove Gapped Columns", seqs, start, end,
2602 viewport.getAlignment());
2604 addHistoryItem(removeGapCols);
2606 statusBar.setText(MessageManager.formatMessage(
2607 "label.removed_empty_columns", new Object[]
2608 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2610 // This is to maintain viewport position on first residue
2611 // of first sequence
2612 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2613 int startRes = seq.findPosition(viewport.startRes);
2614 // ShiftList shifts;
2615 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2616 // edit.alColumnChanges=shifts.getInverse();
2617 // if (viewport.hasHiddenColumns)
2618 // viewport.getColumnSelection().compensateForEdits(shifts);
2619 viewport.setStartRes(seq.findIndex(startRes) - 1);
2620 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2632 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2634 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2637 if (viewport.getSelectionGroup() != null)
2639 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2640 viewport.getHiddenRepSequences());
2641 start = viewport.getSelectionGroup().getStartRes();
2642 end = viewport.getSelectionGroup().getEndRes();
2646 seqs = viewport.getAlignment().getSequencesArray();
2649 // This is to maintain viewport position on first residue
2650 // of first sequence
2651 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2652 int startRes = seq.findPosition(viewport.startRes);
2654 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2655 viewport.getAlignment()));
2657 viewport.setStartRes(seq.findIndex(startRes) - 1);
2659 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2671 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2673 viewport.setPadGaps(padGapsMenuitem.isSelected());
2674 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2685 public void findMenuItem_actionPerformed(ActionEvent e)
2691 * Create a new view of the current alignment.
2694 public void newView_actionPerformed(ActionEvent e)
2696 newView(null, true);
2700 * Creates and shows a new view of the current alignment.
2703 * title of newly created view; if null, one will be generated
2704 * @param copyAnnotation
2705 * if true then duplicate all annnotation, groups and settings
2706 * @return new alignment panel, already displayed.
2708 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2711 * Create a new AlignmentPanel (with its own, new Viewport)
2713 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2715 if (!copyAnnotation)
2718 * remove all groups and annotation except for the automatic stuff
2720 newap.av.getAlignment().deleteAllGroups();
2721 newap.av.getAlignment().deleteAllAnnotations(false);
2724 newap.av.gatherViewsHere = false;
2726 if (viewport.viewName == null)
2728 viewport.viewName = MessageManager
2729 .getString("label.view_name_original");
2733 * Views share the same edits, undo and redo stacks, mappings.
2735 newap.av.setHistoryList(viewport.getHistoryList());
2736 newap.av.setRedoList(viewport.getRedoList());
2737 newap.av.getAlignment().setCodonFrames(
2738 viewport.getAlignment().getCodonFrames());
2740 newap.av.viewName = getNewViewName(viewTitle);
2742 addAlignmentPanel(newap, true);
2743 newap.alignmentChanged();
2745 if (alignPanels.size() == 2)
2747 viewport.gatherViewsHere = true;
2749 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2754 * Make a new name for the view, ensuring it is unique within the current
2755 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2756 * these now use viewId. Unique view names are still desirable for usability.)
2761 protected String getNewViewName(String viewTitle)
2763 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2764 boolean addFirstIndex = false;
2765 if (viewTitle == null || viewTitle.trim().length() == 0)
2767 viewTitle = MessageManager.getString("action.view");
2768 addFirstIndex = true;
2772 index = 1;// we count from 1 if given a specific name
2774 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2776 List<Component> comps = PaintRefresher.components.get(viewport
2777 .getSequenceSetId());
2779 List<String> existingNames = getExistingViewNames(comps);
2781 while (existingNames.contains(newViewName))
2783 newViewName = viewTitle + " " + (++index);
2789 * Returns a list of distinct view names found in the given list of
2790 * components. View names are held on the viewport of an AlignmentPanel.
2795 protected List<String> getExistingViewNames(List<Component> comps)
2797 List<String> existingNames = new ArrayList<String>();
2798 for (Component comp : comps)
2800 if (comp instanceof AlignmentPanel)
2802 AlignmentPanel ap = (AlignmentPanel) comp;
2803 if (!existingNames.contains(ap.av.viewName))
2805 existingNames.add(ap.av.viewName);
2809 return existingNames;
2813 * Explode tabbed views into separate windows.
2816 public void expandViews_actionPerformed(ActionEvent e)
2818 Desktop.instance.explodeViews(this);
2822 * Gather views in separate windows back into a tabbed presentation.
2825 public void gatherViews_actionPerformed(ActionEvent e)
2827 Desktop.instance.gatherViews(this);
2837 public void font_actionPerformed(ActionEvent e)
2839 new FontChooser(alignPanel);
2849 protected void seqLimit_actionPerformed(ActionEvent e)
2851 viewport.setShowJVSuffix(seqLimits.isSelected());
2853 alignPanel.getIdPanel().getIdCanvas().setPreferredSize(alignPanel
2854 .calculateIdWidth());
2855 alignPanel.paintAlignment(true);
2859 public void idRightAlign_actionPerformed(ActionEvent e)
2861 viewport.setRightAlignIds(idRightAlign.isSelected());
2862 alignPanel.paintAlignment(true);
2866 public void centreColumnLabels_actionPerformed(ActionEvent e)
2868 viewport.centreColumnLabels = centreColumnLabelsMenuItem.getState();
2869 alignPanel.paintAlignment(true);
2875 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2878 protected void followHighlight_actionPerformed()
2880 if (viewport.followHighlight = this.followHighlightMenuItem.getState())
2882 alignPanel.scrollToPosition(
2883 alignPanel.getSeqPanel().seqCanvas.searchResults, false);
2894 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2896 viewport.setColourText(colourTextMenuItem.isSelected());
2897 alignPanel.paintAlignment(true);
2907 public void wrapMenuItem_actionPerformed(ActionEvent e)
2909 scaleAbove.setVisible(wrapMenuItem.isSelected());
2910 scaleLeft.setVisible(wrapMenuItem.isSelected());
2911 scaleRight.setVisible(wrapMenuItem.isSelected());
2912 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2913 alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2917 public void showAllSeqs_actionPerformed(ActionEvent e)
2919 viewport.showAllHiddenSeqs();
2923 public void showAllColumns_actionPerformed(ActionEvent e)
2925 viewport.showAllHiddenColumns();
2930 public void hideSelSequences_actionPerformed(ActionEvent e)
2932 viewport.hideAllSelectedSeqs();
2933 alignPanel.paintAlignment(true);
2937 * called by key handler and the hide all/show all menu items
2942 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2945 boolean hide = false;
2946 SequenceGroup sg = viewport.getSelectionGroup();
2947 if (!toggleSeqs && !toggleCols)
2949 // Hide everything by the current selection - this is a hack - we do the
2950 // invert and then hide
2951 // first check that there will be visible columns after the invert.
2952 if ((viewport.getColumnSelection() != null
2953 && viewport.getColumnSelection().getSelected() != null && viewport
2954 .getColumnSelection().getSelected().size() > 0)
2955 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2958 // now invert the sequence set, if required - empty selection implies
2959 // that no hiding is required.
2962 invertSequenceMenuItem_actionPerformed(null);
2963 sg = viewport.getSelectionGroup();
2967 viewport.expandColSelection(sg, true);
2968 // finally invert the column selection and get the new sequence
2970 invertColSel_actionPerformed(null);
2977 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
2979 hideSelSequences_actionPerformed(null);
2982 else if (!(toggleCols && viewport.getColumnSelection().getSelected()
2985 showAllSeqs_actionPerformed(null);
2991 if (viewport.getColumnSelection().getSelected().size() > 0)
2993 hideSelColumns_actionPerformed(null);
2996 viewport.setSelectionGroup(sg);
3001 showAllColumns_actionPerformed(null);
3010 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3011 * event.ActionEvent)
3014 public void hideAllButSelection_actionPerformed(ActionEvent e)
3016 toggleHiddenRegions(false, false);
3023 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3027 public void hideAllSelection_actionPerformed(ActionEvent e)
3029 SequenceGroup sg = viewport.getSelectionGroup();
3030 viewport.expandColSelection(sg, false);
3031 viewport.hideAllSelectedSeqs();
3032 viewport.hideSelectedColumns();
3033 alignPanel.paintAlignment(true);
3040 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3044 public void showAllhidden_actionPerformed(ActionEvent e)
3046 viewport.showAllHiddenColumns();
3047 viewport.showAllHiddenSeqs();
3048 alignPanel.paintAlignment(true);
3052 public void hideSelColumns_actionPerformed(ActionEvent e)
3054 viewport.hideSelectedColumns();
3055 alignPanel.paintAlignment(true);
3059 public void hiddenMarkers_actionPerformed(ActionEvent e)
3061 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3072 protected void scaleAbove_actionPerformed(ActionEvent e)
3074 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3075 alignPanel.paintAlignment(true);
3085 protected void scaleLeft_actionPerformed(ActionEvent e)
3087 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3088 alignPanel.paintAlignment(true);
3098 protected void scaleRight_actionPerformed(ActionEvent e)
3100 viewport.setScaleRightWrapped(scaleRight.isSelected());
3101 alignPanel.paintAlignment(true);
3111 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3113 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3114 alignPanel.paintAlignment(true);
3124 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3126 viewport.setShowText(viewTextMenuItem.isSelected());
3127 alignPanel.paintAlignment(true);
3137 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3139 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3140 alignPanel.paintAlignment(true);
3143 public FeatureSettings featureSettings;
3146 public void featureSettings_actionPerformed(ActionEvent e)
3148 if (featureSettings != null)
3150 featureSettings.close();
3151 featureSettings = null;
3153 if (!showSeqFeatures.isSelected())
3155 // make sure features are actually displayed
3156 showSeqFeatures.setSelected(true);
3157 showSeqFeatures_actionPerformed(null);
3159 featureSettings = new FeatureSettings(this);
3163 * Set or clear 'Show Sequence Features'
3169 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3171 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3172 alignPanel.paintAlignment(true);
3173 if (alignPanel.getOverviewPanel() != null)
3175 alignPanel.getOverviewPanel().updateOverviewImage();
3180 * Set or clear 'Show Sequence Features'
3186 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
3188 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
3190 if (viewport.isShowSequenceFeaturesHeight())
3192 // ensure we're actually displaying features
3193 viewport.setShowSequenceFeatures(true);
3194 showSeqFeatures.setSelected(true);
3196 alignPanel.paintAlignment(true);
3197 if (alignPanel.getOverviewPanel() != null)
3199 alignPanel.getOverviewPanel().updateOverviewImage();
3204 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3205 * the annotations panel as a whole.
3207 * The options to show/hide all annotations should be enabled when the panel
3208 * is shown, and disabled when the panel is hidden.
3213 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3215 final boolean setVisible = annotationPanelMenuItem.isSelected();
3216 viewport.setShowAnnotation(setVisible);
3217 alignPanel.setAnnotationVisible(setVisible);
3218 this.showAllSeqAnnotations.setEnabled(setVisible);
3219 this.hideAllSeqAnnotations.setEnabled(setVisible);
3220 this.showAllAlAnnotations.setEnabled(setVisible);
3221 this.hideAllAlAnnotations.setEnabled(setVisible);
3225 public void alignmentProperties()
3227 JEditorPane editPane = new JEditorPane("text/html", "");
3228 editPane.setEditable(false);
3229 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3231 editPane.setText(MessageManager.formatMessage("label.html_content",
3233 { contents.toString() }));
3234 JInternalFrame frame = new JInternalFrame();
3235 frame.getContentPane().add(new JScrollPane(editPane));
3237 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3238 "label.alignment_properties", new Object[]
3239 { getTitle() }), 500, 400);
3249 public void overviewMenuItem_actionPerformed(ActionEvent e)
3251 if (alignPanel.overviewPanel != null)
3256 JInternalFrame frame = new JInternalFrame();
3257 OverviewPanel overview = new OverviewPanel(alignPanel);
3258 frame.setContentPane(overview);
3259 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3260 "label.overview_params", new Object[]
3261 { this.getTitle() }), frame.getWidth(), frame.getHeight());
3263 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3264 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3267 public void internalFrameClosed(
3268 javax.swing.event.InternalFrameEvent evt)
3270 alignPanel.setOverviewPanel(null);
3274 alignPanel.setOverviewPanel(overview);
3278 public void textColour_actionPerformed(ActionEvent e)
3280 new TextColourChooser().chooseColour(alignPanel, null);
3290 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3302 public void clustalColour_actionPerformed(ActionEvent e)
3304 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3305 viewport.getHiddenRepSequences()));
3315 public void zappoColour_actionPerformed(ActionEvent e)
3317 changeColour(new ZappoColourScheme());
3327 public void taylorColour_actionPerformed(ActionEvent e)
3329 changeColour(new TaylorColourScheme());
3339 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3341 changeColour(new HydrophobicColourScheme());
3351 public void helixColour_actionPerformed(ActionEvent e)
3353 changeColour(new HelixColourScheme());
3363 public void strandColour_actionPerformed(ActionEvent e)
3365 changeColour(new StrandColourScheme());
3375 public void turnColour_actionPerformed(ActionEvent e)
3377 changeColour(new TurnColourScheme());
3387 public void buriedColour_actionPerformed(ActionEvent e)
3389 changeColour(new BuriedColourScheme());
3399 public void nucleotideColour_actionPerformed(ActionEvent e)
3401 changeColour(new NucleotideColourScheme());
3405 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3407 changeColour(new PurinePyrimidineColourScheme());
3411 * public void covariationColour_actionPerformed(ActionEvent e) {
3413 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3417 public void annotationColour_actionPerformed(ActionEvent e)
3419 new AnnotationColourChooser(viewport, alignPanel);
3423 public void annotationColumn_actionPerformed(ActionEvent e)
3425 new AnnotationColumnChooser(viewport, alignPanel);
3429 public void rnahelicesColour_actionPerformed(ActionEvent e)
3431 new RNAHelicesColourChooser(viewport, alignPanel);
3441 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3443 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3452 public void changeColour(ColourSchemeI cs)
3454 // TODO: compare with applet and pull up to model method
3459 if (viewport.getAbovePIDThreshold())
3461 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3463 cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3467 cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3470 if (viewport.getConservationSelected())
3473 Alignment al = (Alignment) viewport.getAlignment();
3474 Conservation c = new Conservation("All",
3475 ResidueProperties.propHash, 3, al.getSequences(), 0,
3479 c.verdict(false, viewport.getConsPercGaps());
3481 cs.setConservation(c);
3483 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3488 cs.setConservation(null);
3491 cs.setConsensus(viewport.getSequenceConsensusHash());
3494 viewport.setGlobalColourScheme(cs);
3496 if (viewport.getColourAppliesToAllGroups())
3499 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3507 if (cs instanceof ClustalxColourScheme)
3509 sg.cs = new ClustalxColourScheme(sg,
3510 viewport.getHiddenRepSequences());
3512 else if (cs instanceof UserColourScheme)
3514 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
3520 sg.cs = cs.getClass().newInstance();
3521 } catch (Exception ex)
3526 if (viewport.getAbovePIDThreshold()
3527 || cs instanceof PIDColourScheme
3528 || cs instanceof Blosum62ColourScheme)
3530 sg.cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3532 sg.cs.setConsensus(AAFrequency.calculate(
3533 sg.getSequences(viewport.getHiddenRepSequences()),
3534 sg.getStartRes(), sg.getEndRes() + 1));
3538 sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3541 if (viewport.getConservationSelected())
3543 Conservation c = new Conservation("Group",
3544 ResidueProperties.propHash, 3, sg.getSequences(viewport
3545 .getHiddenRepSequences()), sg.getStartRes(),
3546 sg.getEndRes() + 1);
3548 c.verdict(false, viewport.getConsPercGaps());
3549 sg.cs.setConservation(c);
3553 sg.cs.setConservation(null);
3558 if (alignPanel.getOverviewPanel() != null)
3560 alignPanel.getOverviewPanel().updateOverviewImage();
3563 alignPanel.paintAlignment(true);
3573 protected void modifyPID_actionPerformed(ActionEvent e)
3575 if (viewport.getAbovePIDThreshold()
3576 && viewport.getGlobalColourScheme() != null)
3578 SliderPanel.setPIDSliderSource(alignPanel,
3579 viewport.getGlobalColourScheme(), "Background");
3580 SliderPanel.showPIDSlider();
3591 protected void modifyConservation_actionPerformed(ActionEvent e)
3593 if (viewport.getConservationSelected()
3594 && viewport.getGlobalColourScheme() != null)
3596 SliderPanel.setConservationSlider(alignPanel,
3597 viewport.getGlobalColourScheme(), "Background");
3598 SliderPanel.showConservationSlider();
3609 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3611 viewport.setConservationSelected(conservationMenuItem.isSelected());
3613 viewport.setAbovePIDThreshold(false);
3614 abovePIDThreshold.setSelected(false);
3616 changeColour(viewport.getGlobalColourScheme());
3618 modifyConservation_actionPerformed(null);
3628 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3630 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3632 conservationMenuItem.setSelected(false);
3633 viewport.setConservationSelected(false);
3635 changeColour(viewport.getGlobalColourScheme());
3637 modifyPID_actionPerformed(null);
3647 public void userDefinedColour_actionPerformed(ActionEvent e)
3649 if (e.getActionCommand().equals(
3650 MessageManager.getString("action.user_defined")))
3652 new UserDefinedColours(alignPanel, null);
3656 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3657 .getUserColourSchemes().get(e.getActionCommand());
3663 public void updateUserColourMenu()
3666 Component[] menuItems = colourMenu.getMenuComponents();
3667 int iSize = menuItems.length;
3668 for (int i = 0; i < iSize; i++)
3670 if (menuItems[i].getName() != null
3671 && menuItems[i].getName().equals("USER_DEFINED"))
3673 colourMenu.remove(menuItems[i]);
3677 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3679 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3680 .getUserColourSchemes().keys();
3682 while (userColours.hasMoreElements())
3684 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3685 userColours.nextElement().toString());
3686 radioItem.setName("USER_DEFINED");
3687 radioItem.addMouseListener(new MouseAdapter()
3690 public void mousePressed(MouseEvent evt)
3692 if (evt.isControlDown()
3693 || SwingUtilities.isRightMouseButton(evt))
3695 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3697 int option = JOptionPane.showInternalConfirmDialog(
3698 jalview.gui.Desktop.desktop,
3700 .getString("label.remove_from_default_list"),
3702 .getString("label.remove_user_defined_colour"),
3703 JOptionPane.YES_NO_OPTION);
3704 if (option == JOptionPane.YES_OPTION)
3706 jalview.gui.UserDefinedColours
3707 .removeColourFromDefaults(radioItem.getText());
3708 colourMenu.remove(radioItem);
3712 radioItem.addActionListener(new ActionListener()
3715 public void actionPerformed(ActionEvent evt)
3717 userDefinedColour_actionPerformed(evt);
3724 radioItem.addActionListener(new ActionListener()
3727 public void actionPerformed(ActionEvent evt)
3729 userDefinedColour_actionPerformed(evt);
3733 colourMenu.insert(radioItem, 15);
3734 colours.add(radioItem);
3746 public void PIDColour_actionPerformed(ActionEvent e)
3748 changeColour(new PIDColourScheme());
3758 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3760 changeColour(new Blosum62ColourScheme());
3770 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3772 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3773 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3774 .getAlignment().getSequenceAt(0), null);
3775 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3776 viewport.getAlignment()));
3777 alignPanel.paintAlignment(true);
3787 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3789 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3790 AlignmentSorter.sortByID(viewport.getAlignment());
3791 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3792 viewport.getAlignment()));
3793 alignPanel.paintAlignment(true);
3803 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3805 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3806 AlignmentSorter.sortByLength(viewport.getAlignment());
3807 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3808 viewport.getAlignment()));
3809 alignPanel.paintAlignment(true);
3819 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3821 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3822 AlignmentSorter.sortByGroup(viewport.getAlignment());
3823 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3824 viewport.getAlignment()));
3826 alignPanel.paintAlignment(true);
3836 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3838 new RedundancyPanel(alignPanel, this);
3848 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3850 if ((viewport.getSelectionGroup() == null)
3851 || (viewport.getSelectionGroup().getSize() < 2))
3853 JOptionPane.showInternalMessageDialog(this, MessageManager
3854 .getString("label.you_must_select_least_two_sequences"),
3855 MessageManager.getString("label.invalid_selection"),
3856 JOptionPane.WARNING_MESSAGE);
3860 JInternalFrame frame = new JInternalFrame();
3861 frame.setContentPane(new PairwiseAlignPanel(viewport));
3862 Desktop.addInternalFrame(frame,
3863 MessageManager.getString("action.pairwise_alignment"), 600,
3875 public void PCAMenuItem_actionPerformed(ActionEvent e)
3877 if (((viewport.getSelectionGroup() != null)
3878 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3879 .getSelectionGroup().getSize() > 0))
3880 || (viewport.getAlignment().getHeight() < 4))
3883 .showInternalMessageDialog(
3886 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3888 .getString("label.sequence_selection_insufficient"),
3889 JOptionPane.WARNING_MESSAGE);
3894 new PCAPanel(alignPanel);
3898 public void autoCalculate_actionPerformed(ActionEvent e)
3900 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3901 if (viewport.autoCalculateConsensus)
3903 viewport.firePropertyChange("alignment", null, viewport
3904 .getAlignment().getSequences());
3909 public void sortByTreeOption_actionPerformed(ActionEvent e)
3911 viewport.sortByTree = sortByTree.isSelected();
3915 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3917 viewport.followSelection = listenToViewSelections.isSelected();
3927 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3929 newTreePanel("AV", "PID", "Average distance tree using PID");
3939 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3941 newTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3951 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3953 newTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3963 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3965 newTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3978 void newTreePanel(String type, String pwType, String title)
3982 if (viewport.getSelectionGroup() != null
3983 && viewport.getSelectionGroup().getSize() > 0)
3985 if (viewport.getSelectionGroup().getSize() < 3)
3991 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3993 .getString("label.not_enough_sequences"),
3994 JOptionPane.WARNING_MESSAGE);
3998 SequenceGroup sg = viewport.getSelectionGroup();
4000 /* Decide if the selection is a column region */
4001 for (SequenceI _s : sg.getSequences())
4003 if (_s.getLength() < sg.getEndRes())
4009 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
4011 .getString("label.sequences_selection_not_aligned"),
4012 JOptionPane.WARNING_MESSAGE);
4018 title = title + " on region";
4019 tp = new TreePanel(alignPanel, type, pwType);
4023 // are the visible sequences aligned?
4024 if (!viewport.getAlignment().isAligned(false))
4030 .getString("label.sequences_must_be_aligned_before_creating_tree"),
4032 .getString("label.sequences_not_aligned"),
4033 JOptionPane.WARNING_MESSAGE);
4038 if (viewport.getAlignment().getHeight() < 2)
4043 tp = new TreePanel(alignPanel, type, pwType);
4048 if (viewport.viewName != null)
4050 title += viewport.viewName + " of ";
4053 title += this.title;
4055 Desktop.addInternalFrame(tp, title, 600, 500);
4066 public void addSortByOrderMenuItem(String title,
4067 final AlignmentOrder order)
4069 final JMenuItem item = new JMenuItem(MessageManager.formatMessage("action.by_title_param", new Object[]{title}));
4071 item.addActionListener(new java.awt.event.ActionListener()
4074 public void actionPerformed(ActionEvent e)
4076 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4078 // TODO: JBPNote - have to map order entries to curent SequenceI
4080 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4082 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
4085 alignPanel.paintAlignment(true);
4091 * Add a new sort by annotation score menu item
4094 * the menu to add the option to
4096 * the label used to retrieve scores for each sequence on the
4099 public void addSortByAnnotScoreMenuItem(JMenu sort,
4100 final String scoreLabel)
4102 final JMenuItem item = new JMenuItem(scoreLabel);
4104 item.addActionListener(new java.awt.event.ActionListener()
4107 public void actionPerformed(ActionEvent e)
4109 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4110 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4111 viewport.getAlignment());// ,viewport.getSelectionGroup());
4112 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4113 viewport.getAlignment()));
4114 alignPanel.paintAlignment(true);
4120 * last hash for alignment's annotation array - used to minimise cost of
4123 protected int _annotationScoreVectorHash;
4126 * search the alignment and rebuild the sort by annotation score submenu the
4127 * last alignment annotation vector hash is stored to minimize cost of
4128 * rebuilding in subsequence calls.
4132 public void buildSortByAnnotationScoresMenu()
4134 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4139 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4141 sortByAnnotScore.removeAll();
4142 // almost certainly a quicker way to do this - but we keep it simple
4143 Hashtable scoreSorts = new Hashtable();
4144 AlignmentAnnotation aann[];
4145 for (SequenceI sqa : viewport.getAlignment().getSequences())
4147 aann = sqa.getAnnotation();
4148 for (int i = 0; aann != null && i < aann.length; i++)
4150 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4152 scoreSorts.put(aann[i].label, aann[i].label);
4156 Enumeration labels = scoreSorts.keys();
4157 while (labels.hasMoreElements())
4159 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4160 (String) labels.nextElement());
4162 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4165 _annotationScoreVectorHash = viewport.getAlignment()
4166 .getAlignmentAnnotation().hashCode();
4171 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4172 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4173 * call. Listeners are added to remove the menu item when the treePanel is
4174 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4178 * Displayed tree window.
4180 * SortBy menu item title.
4183 public void buildTreeMenu()
4185 calculateTree.removeAll();
4186 // build the calculate menu
4188 for (final String type : new String[]
4191 String treecalcnm = MessageManager.getString("label.tree_calc_"
4192 + type.toLowerCase());
4193 for (final String pwtype : ResidueProperties.scoreMatrices.keySet())
4195 JMenuItem tm = new JMenuItem();
4196 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4197 if (sm.isProtein() == !viewport.getAlignment().isNucleotide())
4199 String smn = MessageManager.getStringOrReturn(
4200 "label.score_model_", sm.getName());
4201 final String title = MessageManager.formatMessage(
4202 "label.treecalc_title", treecalcnm, smn);
4203 tm.setText(title);//
4204 tm.addActionListener(new java.awt.event.ActionListener()
4207 public void actionPerformed(ActionEvent e)
4209 newTreePanel(type, pwtype, title);
4212 calculateTree.add(tm);
4217 sortByTreeMenu.removeAll();
4219 List<Component> comps = PaintRefresher.components.get(viewport
4220 .getSequenceSetId());
4221 List<TreePanel> treePanels = new ArrayList<TreePanel>();
4222 for (Component comp : comps)
4224 if (comp instanceof TreePanel)
4226 treePanels.add((TreePanel) comp);
4230 if (treePanels.size() < 1)
4232 sortByTreeMenu.setVisible(false);
4236 sortByTreeMenu.setVisible(true);
4238 for (final TreePanel tp : treePanels)
4240 final JMenuItem item = new JMenuItem(tp.getTitle());
4241 item.addActionListener(new java.awt.event.ActionListener()
4244 public void actionPerformed(ActionEvent e)
4246 tp.sortByTree_actionPerformed();
4247 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4252 sortByTreeMenu.add(item);
4256 public boolean sortBy(AlignmentOrder alorder, String undoname)
4258 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4259 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4260 if (undoname != null)
4262 addHistoryItem(new OrderCommand(undoname, oldOrder,
4263 viewport.getAlignment()));
4265 alignPanel.paintAlignment(true);
4270 * Work out whether the whole set of sequences or just the selected set will
4271 * be submitted for multiple alignment.
4274 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4276 // Now, check we have enough sequences
4277 AlignmentView msa = null;
4279 if ((viewport.getSelectionGroup() != null)
4280 && (viewport.getSelectionGroup().getSize() > 1))
4282 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4283 // some common interface!
4285 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4286 * SequenceI[sz = seqs.getSize(false)];
4288 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4289 * seqs.getSequenceAt(i); }
4291 msa = viewport.getAlignmentView(true);
4293 else if (viewport.getSelectionGroup() != null
4294 && viewport.getSelectionGroup().getSize() == 1)
4296 int option = JOptionPane.showConfirmDialog(this,
4297 MessageManager.getString("warn.oneseq_msainput_selection"),
4298 MessageManager.getString("label.invalid_selection"),
4299 JOptionPane.OK_CANCEL_OPTION);
4300 if (option == JOptionPane.OK_OPTION)
4302 msa = viewport.getAlignmentView(false);
4307 msa = viewport.getAlignmentView(false);
4313 * Decides what is submitted to a secondary structure prediction service: the
4314 * first sequence in the alignment, or in the current selection, or, if the
4315 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4316 * region or the whole alignment. (where the first sequence in the set is the
4317 * one that the prediction will be for).
4319 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4321 AlignmentView seqs = null;
4323 if ((viewport.getSelectionGroup() != null)
4324 && (viewport.getSelectionGroup().getSize() > 0))
4326 seqs = viewport.getAlignmentView(true);
4330 seqs = viewport.getAlignmentView(false);
4332 // limit sequences - JBPNote in future - could spawn multiple prediction
4334 // TODO: viewport.getAlignment().isAligned is a global state - the local
4335 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4336 if (!viewport.getAlignment().isAligned(false))
4338 seqs.setSequences(new SeqCigar[]
4339 { seqs.getSequences()[0] });
4340 // TODO: if seqs.getSequences().length>1 then should really have warned
4354 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
4356 // Pick the tree file
4357 JalviewFileChooser chooser = new JalviewFileChooser(
4358 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4359 chooser.setFileView(new JalviewFileView());
4360 chooser.setDialogTitle(MessageManager
4361 .getString("label.select_newick_like_tree_file"));
4362 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4364 int value = chooser.showOpenDialog(null);
4366 if (value == JalviewFileChooser.APPROVE_OPTION)
4368 String choice = chooser.getSelectedFile().getPath();
4369 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4370 jalview.io.NewickFile fin = null;
4373 fin = new jalview.io.NewickFile(choice, "File");
4374 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4375 } catch (Exception ex)
4382 .getString("label.problem_reading_tree_file"),
4383 JOptionPane.WARNING_MESSAGE);
4384 ex.printStackTrace();
4386 if (fin != null && fin.hasWarningMessage())
4388 JOptionPane.showMessageDialog(Desktop.desktop, fin
4389 .getWarningMessage(), MessageManager
4390 .getString("label.possible_problem_with_tree_file"),
4391 JOptionPane.WARNING_MESSAGE);
4397 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4399 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4402 public TreePanel ShowNewickTree(NewickFile nf, String title)
4404 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4407 public TreePanel ShowNewickTree(NewickFile nf, String title,
4408 AlignmentView input)
4410 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4413 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4414 int h, int x, int y)
4416 return ShowNewickTree(nf, title, null, w, h, x, y);
4420 * Add a treeviewer for the tree extracted from a newick file object to the
4421 * current alignment view
4428 * Associated alignment input data (or null)
4437 * @return TreePanel handle
4439 public TreePanel ShowNewickTree(NewickFile nf, String title,
4440 AlignmentView input, int w, int h, int x, int y)
4442 TreePanel tp = null;
4448 if (nf.getTree() != null)
4450 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4456 tp.setLocation(x, y);
4459 Desktop.addInternalFrame(tp, title, w, h);
4461 } catch (Exception ex)
4463 ex.printStackTrace();
4469 private boolean buildingMenu = false;
4472 * Generates menu items and listener event actions for web service clients
4475 public void BuildWebServiceMenu()
4477 while (buildingMenu)
4481 System.err.println("Waiting for building menu to finish.");
4483 } catch (Exception e)
4487 final AlignFrame me = this;
4488 buildingMenu = true;
4489 new Thread(new Runnable()
4494 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4497 System.err.println("Building ws menu again "
4498 + Thread.currentThread());
4499 // TODO: add support for context dependent disabling of services based
4501 // alignment and current selection
4502 // TODO: add additional serviceHandle parameter to specify abstract
4504 // class independently of AbstractName
4505 // TODO: add in rediscovery GUI function to restart discoverer
4506 // TODO: group services by location as well as function and/or
4508 // object broker mechanism.
4509 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4510 final IProgressIndicator af = me;
4511 final JMenu msawsmenu = new JMenu("Alignment");
4512 final JMenu secstrmenu = new JMenu(
4513 "Secondary Structure Prediction");
4514 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4515 final JMenu analymenu = new JMenu("Analysis");
4516 final JMenu dismenu = new JMenu("Protein Disorder");
4517 // final JMenu msawsmenu = new
4518 // JMenu(MessageManager.getString("label.alignment"));
4519 // final JMenu secstrmenu = new
4520 // JMenu(MessageManager.getString("label.secondary_structure_prediction"));
4521 // final JMenu seqsrchmenu = new
4522 // JMenu(MessageManager.getString("label.sequence_database_search"));
4523 // final JMenu analymenu = new
4524 // JMenu(MessageManager.getString("label.analysis"));
4525 // final JMenu dismenu = new
4526 // JMenu(MessageManager.getString("label.protein_disorder"));
4527 // JAL-940 - only show secondary structure prediction services from
4528 // the legacy server
4529 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4531 Discoverer.services != null && (Discoverer.services.size() > 0))
4533 // TODO: refactor to allow list of AbstractName/Handler bindings to
4535 // stored or retrieved from elsewhere
4536 // No MSAWS used any more:
4537 // Vector msaws = null; // (Vector)
4538 // Discoverer.services.get("MsaWS");
4539 Vector secstrpr = (Vector) Discoverer.services
4541 if (secstrpr != null)
4543 // Add any secondary structure prediction services
4544 for (int i = 0, j = secstrpr.size(); i < j; i++)
4546 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4548 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4549 .getServiceClient(sh);
4550 int p = secstrmenu.getItemCount();
4551 impl.attachWSMenuEntry(secstrmenu, me);
4552 int q = secstrmenu.getItemCount();
4553 for (int litm = p; litm < q; litm++)
4555 legacyItems.add(secstrmenu.getItem(litm));
4561 // Add all submenus in the order they should appear on the web
4563 wsmenu.add(msawsmenu);
4564 wsmenu.add(secstrmenu);
4565 wsmenu.add(dismenu);
4566 wsmenu.add(analymenu);
4567 // No search services yet
4568 // wsmenu.add(seqsrchmenu);
4570 javax.swing.SwingUtilities.invokeLater(new Runnable()
4577 webService.removeAll();
4578 // first, add discovered services onto the webservices menu
4579 if (wsmenu.size() > 0)
4581 for (int i = 0, j = wsmenu.size(); i < j; i++)
4583 webService.add(wsmenu.get(i));
4588 webService.add(me.webServiceNoServices);
4590 // TODO: move into separate menu builder class.
4591 boolean new_sspred = false;
4592 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4594 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4595 if (jws2servs != null)
4597 if (jws2servs.hasServices())
4599 jws2servs.attachWSMenuEntry(webService, me);
4600 for (Jws2Instance sv : jws2servs.getServices())
4602 if (sv.description.toLowerCase().contains("jpred"))
4604 for (JMenuItem jmi : legacyItems)
4606 jmi.setVisible(false);
4612 if (jws2servs.isRunning())
4614 JMenuItem tm = new JMenuItem(
4615 "Still discovering JABA Services");
4616 tm.setEnabled(false);
4621 build_urlServiceMenu(me.webService);
4622 build_fetchdbmenu(webService);
4623 for (JMenu item : wsmenu)
4625 if (item.getItemCount() == 0)
4627 item.setEnabled(false);
4631 item.setEnabled(true);
4634 } catch (Exception e)
4637 .debug("Exception during web service menu building process.",
4642 } catch (Exception e)
4645 buildingMenu = false;
4652 * construct any groupURL type service menu entries.
4656 private void build_urlServiceMenu(JMenu webService)
4658 // TODO: remove this code when 2.7 is released
4659 // DEBUG - alignmentView
4661 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4662 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4664 * @Override public void actionPerformed(ActionEvent e) {
4665 * jalview.datamodel.AlignmentView
4666 * .testSelectionViews(af.viewport.getAlignment(),
4667 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4669 * }); webService.add(testAlView);
4671 // TODO: refactor to RestClient discoverer and merge menu entries for
4672 // rest-style services with other types of analysis/calculation service
4673 // SHmmr test client - still being implemented.
4674 // DEBUG - alignmentView
4676 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4679 client.attachWSMenuEntry(
4680 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4686 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
4687 * chooser = new JalviewFileChooser(jalview.bin.Cache.
4688 * getProperty("LAST_DIRECTORY"));
4690 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
4691 * to Vamsas file"); chooser.setToolTipText("Export");
4693 * int value = chooser.showSaveDialog(this);
4695 * if (value == JalviewFileChooser.APPROVE_OPTION) {
4696 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
4697 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
4698 * chooser.getSelectedFile().getAbsolutePath(), this); } }
4701 * prototype of an automatically enabled/disabled analysis function
4704 protected void setShowProductsEnabled()
4706 SequenceI[] selection = viewport.getSequenceSelection();
4707 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
4708 viewport.getAlignment().getDataset()))
4710 showProducts.setEnabled(true);
4715 showProducts.setEnabled(false);
4720 * search selection for sequence xRef products and build the show products
4725 * @return true if showProducts menu should be enabled.
4727 public boolean canShowProducts(SequenceI[] selection,
4728 boolean isRegionSelection, Alignment dataset)
4730 boolean showp = false;
4733 showProducts.removeAll();
4734 final boolean dna = viewport.getAlignment().isNucleotide();
4735 final Alignment ds = dataset;
4736 String[] ptypes = (selection == null || selection.length == 0) ? null
4737 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4739 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4740 // selection, dataset, true);
4741 final SequenceI[] sel = selection;
4742 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4745 final boolean isRegSel = isRegionSelection;
4746 final AlignFrame af = this;
4747 final String source = ptypes[t];
4748 JMenuItem xtype = new JMenuItem(ptypes[t]);
4749 xtype.addActionListener(new ActionListener()
4753 public void actionPerformed(ActionEvent e)
4755 // TODO: new thread for this call with vis-delay
4756 af.showProductsFor(af.viewport.getSequenceSelection(), ds,
4757 isRegSel, dna, source);
4761 showProducts.add(xtype);
4763 showProducts.setVisible(showp);
4764 showProducts.setEnabled(showp);
4765 } catch (Exception e)
4767 jalview.bin.Cache.log
4768 .warn("canTranslate threw an exception - please report to help@jalview.org",
4775 protected void showProductsFor(SequenceI[] sel, Alignment ds,
4776 boolean isRegSel, boolean dna, String source)
4778 final boolean fisRegSel = isRegSel;
4779 final boolean fdna = dna;
4780 final String fsrc = source;
4781 final AlignFrame ths = this;
4782 final SequenceI[] fsel = sel;
4783 Runnable foo = new Runnable()
4789 final long sttime = System.currentTimeMillis();
4790 ths.setProgressBar(MessageManager.formatMessage("status.searching_for_sequences_from", new Object[]{fsrc}), sttime);
4793 Alignment ds = ths.getViewport().getAlignment().getDataset(); // update
4797 Alignment prods = CrossRef
4798 .findXrefSequences(fsel, fdna, fsrc, ds);
4801 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4802 for (int s = 0; s < sprods.length; s++)
4804 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4805 if (ds.getSequences() == null
4806 || !ds.getSequences().contains(
4807 sprods[s].getDatasetSequence()))
4809 ds.addSequence(sprods[s].getDatasetSequence());
4811 sprods[s].updatePDBIds();
4813 Alignment al = new Alignment(sprods);
4814 Set<AlignedCodonFrame> cf = prods.getCodonFrames();
4816 for (AlignedCodonFrame acf : cf)
4818 al.addCodonFrame(acf);
4820 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4822 String newtitle = "" + ((fdna) ? "Proteins " : "Nucleotides ")
4823 + " for " + ((fisRegSel) ? "selected region of " : "")
4825 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4830 System.err.println("No Sequences generated for xRef type "
4833 } catch (Exception e)
4835 jalview.bin.Cache.log.error(
4836 "Exception when finding crossreferences", e);
4837 } catch (OutOfMemoryError e)
4839 new OOMWarning("whilst fetching crossreferences", e);
4842 jalview.bin.Cache.log.error("Error when finding crossreferences",
4845 ths.setProgressBar(MessageManager.formatMessage("status.finished_searching_for_sequences_from", new Object[]{fsrc}),
4850 Thread frunner = new Thread(foo);
4854 public boolean canShowTranslationProducts(SequenceI[] selection,
4855 AlignmentI alignment)
4860 return (jalview.analysis.Dna.canTranslate(selection,
4861 viewport.getViewAsVisibleContigs(true)));
4862 } catch (Exception e)
4864 jalview.bin.Cache.log
4865 .warn("canTranslate threw an exception - please report to help@jalview.org",
4872 * Construct and display a new frame containing the translation of this
4873 * frame's cDNA sequences to their aligned protein (amino acid) equivalents.
4876 public void showTranslation_actionPerformed(ActionEvent e)
4878 AlignmentI al = null;
4881 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4883 al = dna.translateCdna();
4884 } catch (Exception ex)
4886 jalview.bin.Cache.log.error(
4887 "Exception during translation. Please report this !", ex);
4888 final String msg = MessageManager
4889 .getString("label.error_when_translating_sequences_submit_bug_report");
4890 final String title = MessageManager
4891 .getString("label.implementation_error")
4892 + MessageManager.getString("translation_failed");
4893 JOptionPane.showMessageDialog(Desktop.desktop, msg, title,
4894 JOptionPane.ERROR_MESSAGE);
4897 if (al == null || al.getHeight() == 0)
4899 final String msg = MessageManager
4900 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4901 final String title = MessageManager
4902 .getString("label.translation_failed");
4903 JOptionPane.showMessageDialog(Desktop.desktop, msg, title,
4904 JOptionPane.WARNING_MESSAGE);
4908 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4909 Desktop.addInternalFrame(af, MessageManager.formatMessage(
4910 "label.translation_of_params", new Object[]
4911 { this.getTitle() }), DEFAULT_WIDTH, DEFAULT_HEIGHT);
4912 // enable next line for linked editing
4913 // viewport.getStructureSelectionManager().addCommandListener(viewport);
4918 * Try to load a features file onto the alignment.
4921 * contents or path to retrieve file
4923 * access mode of file (see jalview.io.AlignFile)
4924 * @return true if features file was parsed corectly.
4926 public boolean parseFeaturesFile(String file, String type)
4928 boolean featuresFile = false;
4931 featuresFile = new FeaturesFile(file, type).parse(viewport
4932 .getAlignment().getDataset(), alignPanel.getSeqPanel().seqCanvas
4933 .getFeatureRenderer().getFeatureColours(), false,
4934 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4935 } catch (Exception ex)
4937 ex.printStackTrace();
4942 viewport.setShowSequenceFeatures(true);
4943 showSeqFeatures.setSelected(true);
4944 if (alignPanel.getSeqPanel().seqCanvas.fr != null)
4946 // update the min/max ranges where necessary
4947 alignPanel.getSeqPanel().seqCanvas.fr.findAllFeatures(true);
4949 if (featureSettings != null)
4951 featureSettings.setTableData();
4953 alignPanel.paintAlignment(true);
4956 return featuresFile;
4960 public void dragEnter(DropTargetDragEvent evt)
4965 public void dragExit(DropTargetEvent evt)
4970 public void dragOver(DropTargetDragEvent evt)
4975 public void dropActionChanged(DropTargetDragEvent evt)
4980 public void drop(DropTargetDropEvent evt)
4982 Transferable t = evt.getTransferable();
4983 java.util.List files = null;
4987 DataFlavor uriListFlavor = new DataFlavor(
4988 "text/uri-list;class=java.lang.String");
4989 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
4991 // Works on Windows and MacOSX
4992 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4993 files = (java.util.List) t
4994 .getTransferData(DataFlavor.javaFileListFlavor);
4996 else if (t.isDataFlavorSupported(uriListFlavor))
4998 // This is used by Unix drag system
4999 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
5000 String data = (String) t.getTransferData(uriListFlavor);
5001 files = new java.util.ArrayList(1);
5002 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
5003 data, "\r\n"); st.hasMoreTokens();)
5005 String s = st.nextToken();
5006 if (s.startsWith("#"))
5008 // the line is a comment (as per the RFC 2483)
5012 java.net.URI uri = new java.net.URI(s);
5013 // check to see if we can handle this kind of URI
5014 if (uri.getScheme().toLowerCase().startsWith("http"))
5016 files.add(uri.toString());
5020 // otherwise preserve old behaviour: catch all for file objects
5021 java.io.File file = new java.io.File(uri);
5022 files.add(file.toString());
5026 } catch (Exception e)
5028 e.printStackTrace();
5034 // check to see if any of these files have names matching sequences in
5036 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5037 .getAlignment().getSequencesArray());
5039 * Object[] { String,SequenceI}
5041 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
5042 ArrayList<String> filesnotmatched = new ArrayList<String>();
5043 for (int i = 0; i < files.size(); i++)
5045 String file = files.get(i).toString();
5047 String protocol = FormatAdapter.checkProtocol(file);
5048 if (protocol == jalview.io.FormatAdapter.FILE)
5050 File fl = new File(file);
5051 pdbfn = fl.getName();
5053 else if (protocol == jalview.io.FormatAdapter.URL)
5055 URL url = new URL(file);
5056 pdbfn = url.getFile();
5058 if (pdbfn.length() > 0)
5060 // attempt to find a match in the alignment
5061 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5062 int l = 0, c = pdbfn.indexOf(".");
5063 while (mtch == null && c != -1)
5068 } while ((c = pdbfn.indexOf(".", l)) > l);
5071 pdbfn = pdbfn.substring(0, l);
5073 mtch = idm.findAllIdMatches(pdbfn);
5080 type = new IdentifyFile().Identify(file, protocol);
5081 } catch (Exception ex)
5087 if (type.equalsIgnoreCase("PDB"))
5089 filesmatched.add(new Object[]
5090 { file, protocol, mtch });
5095 // File wasn't named like one of the sequences or wasn't a PDB file.
5096 filesnotmatched.add(file);
5100 if (filesmatched.size() > 0)
5102 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
5108 "label.automatically_associate_pdb_files_with_sequences_same_name",
5115 .getString("label.automatically_associate_pdb_files_by_name"),
5116 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
5119 for (Object[] fm : filesmatched)
5121 // try and associate
5122 // TODO: may want to set a standard ID naming formalism for
5123 // associating PDB files which have no IDs.
5124 for (SequenceI toassoc : (SequenceI[]) fm[2])
5126 PDBEntry pe = new AssociatePdbFileWithSeq()
5127 .associatePdbWithSeq((String) fm[0],
5128 (String) fm[1], toassoc, false,
5132 System.err.println("Associated file : "
5133 + ((String) fm[0]) + " with "
5134 + toassoc.getDisplayId(true));
5138 alignPanel.paintAlignment(true);
5142 if (filesnotmatched.size() > 0)
5145 && (Cache.getDefault(
5146 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
5149 "<html>"+MessageManager
5151 "label.ignore_unmatched_dropped_files_info",
5156 .toString() })+"</html>",
5158 .getString("label.ignore_unmatched_dropped_files"),
5159 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
5163 for (String fn : filesnotmatched)
5165 loadJalviewDataFile(fn, null, null, null);
5169 } catch (Exception ex)
5171 ex.printStackTrace();
5177 * Attempt to load a "dropped" file or URL string: First by testing whether
5178 * it's and Annotation file, then a JNet file, and finally a features file. If
5179 * all are false then the user may have dropped an alignment file onto this
5183 * either a filename or a URL string.
5185 public void loadJalviewDataFile(String file, String protocol,
5186 String format, SequenceI assocSeq)
5190 if (protocol == null)
5192 protocol = jalview.io.FormatAdapter.checkProtocol(file);
5194 // if the file isn't identified, or not positively identified as some
5195 // other filetype (PFAM is default unidentified alignment file type) then
5196 // try to parse as annotation.
5197 boolean isAnnotation = (format == null || format
5198 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
5199 .annotateAlignmentView(viewport, file, protocol)
5204 // first see if its a T-COFFEE score file
5205 TCoffeeScoreFile tcf = null;
5208 tcf = new TCoffeeScoreFile(file, protocol);
5211 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5213 tcoffeeColour.setEnabled(true);
5214 tcoffeeColour.setSelected(true);
5215 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5216 isAnnotation = true;
5218 .setText(MessageManager
5219 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5223 // some problem - if no warning its probable that the ID matching
5224 // process didn't work
5228 tcf.getWarningMessage() == null ? MessageManager
5229 .getString("label.check_file_matches_sequence_ids_alignment")
5230 : tcf.getWarningMessage(),
5232 .getString("label.problem_reading_tcoffee_score_file"),
5233 JOptionPane.WARNING_MESSAGE);
5240 } catch (Exception x)
5243 .debug("Exception when processing data source as T-COFFEE score file",
5249 // try to see if its a JNet 'concise' style annotation file *before*
5251 // try to parse it as a features file
5254 format = new IdentifyFile().Identify(file, protocol);
5256 if (format.equalsIgnoreCase("JnetFile"))
5258 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5260 new JnetAnnotationMaker();
5261 JnetAnnotationMaker.add_annotation(predictions,
5262 viewport.getAlignment(), 0, false);
5263 isAnnotation = true;
5268 * if (format.equalsIgnoreCase("PDB")) {
5270 * String pdbfn = ""; // try to match up filename with sequence id
5271 * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
5272 * new File(file); pdbfn = fl.getName(); } else if (protocol ==
5273 * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
5274 * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
5275 * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5276 * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
5277 * // attempt to find a match in the alignment SequenceI mtch =
5278 * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
5279 * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
5280 * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
5281 * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
5282 * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
5283 * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
5284 * { System.err.println("Associated file : " + file + " with " +
5285 * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
5286 * TODO: maybe need to load as normal otherwise return; } }
5288 // try to parse it as a features file
5289 boolean isGroupsFile = parseFeaturesFile(file, protocol);
5290 // if it wasn't a features file then we just treat it as a general
5291 // alignment file to load into the current view.
5294 new FileLoader().LoadFile(viewport, file, protocol, format);
5298 alignPanel.paintAlignment(true);
5306 alignPanel.adjustAnnotationHeight();
5307 viewport.updateSequenceIdColours();
5308 buildSortByAnnotationScoresMenu();
5309 alignPanel.paintAlignment(true);
5311 } catch (Exception ex)
5313 ex.printStackTrace();
5314 } catch (OutOfMemoryError oom)
5319 } catch (Exception x)
5325 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5326 : "using " + protocol + " from " + file)
5328 + (format != null ? "(parsing as '" + format
5329 + "' file)" : ""), oom, Desktop.desktop);
5334 * Method invoked by the ChangeListener on the tabbed pane, in other words
5335 * when a different tabbed pane is selected by the user or programmatically.
5338 public void tabSelectionChanged(int index)
5342 alignPanel = alignPanels.get(index);
5343 viewport = alignPanel.av;
5344 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5345 setMenusFromViewport(viewport);
5349 * If there is a frame linked to this one in a SplitPane, switch it to the
5350 * same view tab index. No infinite recursion of calls should happen, since
5351 * tabSelectionChanged() should not get invoked on setting the selected
5352 * index to an unchanged value. Guard against setting an invalid index
5353 * before the new view peer tab has been created.
5355 final AlignViewportI peer = viewport.getCodingComplement();
5358 AlignFrame linkedAlignFrame = ((AlignViewport) peer).getAlignPanel().alignFrame;
5359 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5361 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5367 * On right mouse click on view tab, prompt for and set new view name.
5370 public void tabbedPane_mousePressed(MouseEvent e)
5372 if (SwingUtilities.isRightMouseButton(e))
5374 String msg = MessageManager.getString("label.enter_view_name");
5375 String reply = JOptionPane.showInternalInputDialog(this, msg, msg,
5376 JOptionPane.QUESTION_MESSAGE);
5380 viewport.viewName = reply;
5381 // TODO warn if reply is in getExistingViewNames()?
5382 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5387 public AlignViewport getCurrentView()
5393 * Open the dialog for regex description parsing.
5396 protected void extractScores_actionPerformed(ActionEvent e)
5398 ParseProperties pp = new jalview.analysis.ParseProperties(
5399 viewport.getAlignment());
5400 // TODO: verify regex and introduce GUI dialog for version 2.5
5401 // if (pp.getScoresFromDescription("col", "score column ",
5402 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5404 if (pp.getScoresFromDescription("description column",
5405 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5407 buildSortByAnnotationScoresMenu();
5415 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5419 protected void showDbRefs_actionPerformed(ActionEvent e)
5421 viewport.setShowDbRefs(showDbRefsMenuitem.isSelected());
5427 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5431 protected void showNpFeats_actionPerformed(ActionEvent e)
5433 viewport.setShowNpFeats(showNpFeatsMenuitem.isSelected());
5437 * find the viewport amongst the tabs in this alignment frame and close that
5442 public boolean closeView(AlignViewportI av)
5446 this.closeMenuItem_actionPerformed(false);
5449 Component[] comp = tabbedPane.getComponents();
5450 for (int i = 0; comp != null && i < comp.length; i++)
5452 if (comp[i] instanceof AlignmentPanel)
5454 if (((AlignmentPanel) comp[i]).av == av)
5457 closeView((AlignmentPanel) comp[i]);
5465 protected void build_fetchdbmenu(JMenu webService)
5467 // Temporary hack - DBRef Fetcher always top level ws entry.
5468 // TODO We probably want to store a sequence database checklist in
5469 // preferences and have checkboxes.. rather than individual sources selected
5471 final JMenu rfetch = new JMenu(
5472 MessageManager.getString("action.fetch_db_references"));
5473 rfetch.setToolTipText(MessageManager
5474 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5475 webService.add(rfetch);
5477 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5478 MessageManager.getString("option.trim_retrieved_seqs"));
5479 trimrs.setToolTipText(MessageManager
5480 .getString("label.trim_retrieved_sequences"));
5481 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5482 trimrs.addActionListener(new ActionListener()
5485 public void actionPerformed(ActionEvent e)
5487 trimrs.setSelected(trimrs.isSelected());
5488 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5489 Boolean.valueOf(trimrs.isSelected()).toString());
5493 JMenuItem fetchr = new JMenuItem(
5494 MessageManager.getString("label.standard_databases"));
5495 fetchr.setToolTipText(MessageManager
5496 .getString("label.fetch_embl_uniprot"));
5497 fetchr.addActionListener(new ActionListener()
5501 public void actionPerformed(ActionEvent e)
5503 new Thread(new Runnable()
5509 new jalview.ws.DBRefFetcher(alignPanel.av
5510 .getSequenceSelection(), alignPanel.alignFrame)
5511 .fetchDBRefs(false);
5519 final AlignFrame me = this;
5520 new Thread(new Runnable()
5525 final jalview.ws.SequenceFetcher sf = SequenceFetcher
5526 .getSequenceFetcherSingleton(me);
5527 javax.swing.SwingUtilities.invokeLater(new Runnable()
5532 String[] dbclasses = sf.getOrderedSupportedSources();
5533 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5534 // jalview.util.QuickSort.sort(otherdb, otherdb);
5535 List<DbSourceProxy> otherdb;
5536 JMenu dfetch = new JMenu();
5537 JMenu ifetch = new JMenu();
5538 JMenuItem fetchr = null;
5539 int comp = 0, icomp = 0, mcomp = 15;
5540 String mname = null;
5542 for (String dbclass : dbclasses)
5544 otherdb = sf.getSourceProxy(dbclass);
5545 // add a single entry for this class, or submenu allowing 'fetch
5547 if (otherdb == null || otherdb.size() < 1)
5551 // List<DbSourceProxy> dbs=otherdb;
5552 // otherdb=new ArrayList<DbSourceProxy>();
5553 // for (DbSourceProxy db:dbs)
5555 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5559 mname = "From " + dbclass;
5561 if (otherdb.size() == 1)
5563 final DbSourceProxy[] dassource = otherdb
5564 .toArray(new DbSourceProxy[0]);
5565 DbSourceProxy src = otherdb.get(0);
5566 fetchr = new JMenuItem(src.getDbSource());
5567 fetchr.addActionListener(new ActionListener()
5571 public void actionPerformed(ActionEvent e)
5573 new Thread(new Runnable()
5579 new jalview.ws.DBRefFetcher(alignPanel.av
5580 .getSequenceSelection(),
5581 alignPanel.alignFrame, dassource)
5582 .fetchDBRefs(false);
5588 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from", new Object[]{src.getDbName()})));
5594 final DbSourceProxy[] dassource = otherdb
5595 .toArray(new DbSourceProxy[0]);
5597 DbSourceProxy src = otherdb.get(0);
5598 fetchr = new JMenuItem(MessageManager.formatMessage(
5599 "label.fetch_all_param", new Object[]
5600 { src.getDbSource() }));
5601 fetchr.addActionListener(new ActionListener()
5604 public void actionPerformed(ActionEvent e)
5606 new Thread(new Runnable()
5612 new jalview.ws.DBRefFetcher(alignPanel.av
5613 .getSequenceSelection(),
5614 alignPanel.alignFrame, dassource)
5615 .fetchDBRefs(false);
5621 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from_all_sources", new Object[]{Integer.valueOf(otherdb.size()).toString(), src.getDbSource(), src.getDbName()})));
5624 // and then build the rest of the individual menus
5625 ifetch = new JMenu(MessageManager.formatMessage("label.source_from_db_source", new Object[]{src.getDbSource()}));
5627 String imname = null;
5629 for (DbSourceProxy sproxy : otherdb)
5631 String dbname = sproxy.getDbName();
5632 String sname = dbname.length() > 5 ? dbname.substring(0,
5633 5) + "..." : dbname;
5634 String msname = dbname.length() > 10 ? dbname.substring(
5635 0, 10) + "..." : dbname;
5638 imname = MessageManager.formatMessage("label.from_msname", new Object[]{sname});
5640 fetchr = new JMenuItem(msname);
5641 final DbSourceProxy[] dassrc =
5643 fetchr.addActionListener(new ActionListener()
5647 public void actionPerformed(ActionEvent e)
5649 new Thread(new Runnable()
5655 new jalview.ws.DBRefFetcher(alignPanel.av
5656 .getSequenceSelection(),
5657 alignPanel.alignFrame, dassrc)
5658 .fetchDBRefs(false);
5664 fetchr.setToolTipText("<html>"
5665 + MessageManager.formatMessage("label.fetch_retrieve_from", new Object[]{dbname}));
5668 if (++icomp >= mcomp || i == (otherdb.size()))
5670 ifetch.setText(MessageManager.formatMessage(
5671 "label.source_to_target", imname, sname));
5673 ifetch = new JMenu();
5681 if (comp >= mcomp || dbi >= (dbclasses.length))
5683 dfetch.setText(MessageManager.formatMessage(
5684 "label.source_to_target", mname, dbclass));
5686 dfetch = new JMenu();
5699 * Left justify the whole alignment.
5702 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5704 AlignmentI al = viewport.getAlignment();
5706 viewport.firePropertyChange("alignment", null, al);
5710 * Right justify the whole alignment.
5713 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5715 AlignmentI al = viewport.getAlignment();
5717 viewport.firePropertyChange("alignment", null, al);
5720 public void setShowSeqFeatures(boolean b)
5722 showSeqFeatures.setSelected(true);
5723 viewport.setShowSequenceFeatures(true);
5730 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5731 * awt.event.ActionEvent)
5734 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5736 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5737 alignPanel.paintAlignment(true);
5744 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5748 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5750 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5751 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5759 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5760 * .event.ActionEvent)
5763 protected void showGroupConservation_actionPerformed(ActionEvent e)
5765 viewport.setShowGroupConservation(showGroupConservation.getState());
5766 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5773 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5774 * .event.ActionEvent)
5777 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5779 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5780 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5787 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5788 * .event.ActionEvent)
5791 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5793 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5794 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5798 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5800 showSequenceLogo.setState(true);
5801 viewport.setShowSequenceLogo(true);
5802 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5803 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5807 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5809 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5816 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5817 * .event.ActionEvent)
5820 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5822 if (avc.makeGroupsFromSelection())
5824 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5825 alignPanel.updateAnnotation();
5826 alignPanel.paintAlignment(true);
5829 public void clearAlignmentSeqRep()
5831 // TODO refactor alignmentseqrep to controller
5832 if (viewport.getAlignment().hasSeqrep()) {
5833 viewport.getAlignment().setSeqrep(null);
5834 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5835 alignPanel.updateAnnotation();
5836 alignPanel.paintAlignment(true);
5841 protected void createGroup_actionPerformed(ActionEvent e)
5843 if (avc.createGroup())
5845 alignPanel.alignmentChanged();
5850 protected void unGroup_actionPerformed(ActionEvent e)
5854 alignPanel.alignmentChanged();
5859 * make the given alignmentPanel the currently selected tab
5861 * @param alignmentPanel
5863 public void setDisplayedView(AlignmentPanel alignmentPanel)
5865 if (!viewport.getSequenceSetId().equals(
5866 alignmentPanel.av.getSequenceSetId()))
5868 throw new Error(MessageManager.getString("error.implementation_error_cannot_show_view_alignment_frame"));
5870 if (tabbedPane != null
5871 & alignPanels.indexOf(alignmentPanel) != tabbedPane
5872 .getSelectedIndex())
5874 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5879 * Action on selection of menu options to Show or Hide annotations.
5882 * @param forSequences
5883 * update sequence-related annotations
5884 * @param forAlignment
5885 * update non-sequence-related annotations
5888 protected void setAnnotationsVisibility(boolean visible,
5889 boolean forSequences, boolean forAlignment)
5891 for (AlignmentAnnotation aa : alignPanel.getAlignment()
5892 .getAlignmentAnnotation())
5894 boolean apply = (aa.sequenceRef == null && forAlignment)
5895 || (aa.sequenceRef != null && forSequences);
5898 aa.visible = visible;
5901 alignPanel.validateAnnotationDimensions(false);
5902 alignPanel.alignmentChanged();
5906 * Store selected annotation sort order for the view and repaint.
5909 protected void sortAnnotations_actionPerformed()
5911 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5913 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5914 alignPanel.paintAlignment(true);
5919 * @return alignment panels in this alignment frame
5921 public List<? extends AlignmentViewPanel> getAlignPanels()
5923 return alignPanels == null ? Arrays.asList(alignPanel)
5928 * Open a new alignment window, with the cDNA associated with this (protein)
5929 * alignment, aligned as is the protein.
5932 protected void viewAsCdna_actionPerformed()
5934 final AlignmentI alignment = getViewport().getAlignment();
5935 Set<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5936 if (mappings == null)
5940 List<SequenceI> cdnaSeqs = new ArrayList<SequenceI>();
5941 for (SequenceI aaSeq : alignment.getSequences()) {
5942 for (AlignedCodonFrame acf : mappings) {
5943 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5947 * There is a cDNA mapping for this protein sequence - add to new
5948 * alignment. It will share the same dataset sequence as other mapped
5949 * cDNA (no new mappings need to be created).
5951 final Sequence newSeq = new Sequence(dnaSeq);
5952 newSeq.setDatasetSequence(dnaSeq);
5953 cdnaSeqs.add(newSeq);
5957 if (cdnaSeqs.size() == 0)
5959 // show a warning dialog no mapped cDNA
5962 AlignmentI cdna = new Alignment(cdnaSeqs.toArray(new SequenceI[cdnaSeqs
5964 AlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5965 AlignFrame.DEFAULT_HEIGHT);
5966 cdna.alignAs(alignment);
5967 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5969 Desktop.addInternalFrame(alignFrame, newtitle,
5970 AlignFrame.DEFAULT_WIDTH,
5971 AlignFrame.DEFAULT_HEIGHT);
5976 class PrintThread extends Thread
5980 public PrintThread(AlignmentPanel ap)
5985 static PageFormat pf;
5990 PrinterJob printJob = PrinterJob.getPrinterJob();
5994 printJob.setPrintable(ap, pf);
5998 printJob.setPrintable(ap);
6001 if (printJob.printDialog())
6006 } catch (Exception PrintException)
6008 PrintException.printStackTrace();