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 alignPanel2 and shuffle tabs appropriately.
1485 * @param alignPanel2
1487 public void closeView(AlignmentPanel alignPanel2)
1489 int index = tabbedPane.getSelectedIndex();
1490 int closedindex = tabbedPane.indexOfComponent(alignPanel2);
1491 alignPanels.remove(alignPanel2);
1493 // if (viewport == alignPanel2.av)
1497 alignPanel2.closePanel();
1500 tabbedPane.removeTabAt(closedindex);
1501 tabbedPane.validate();
1503 if (index > closedindex || index == tabbedPane.getTabCount())
1505 // modify currently selected tab index if necessary.
1509 this.tabSelectionChanged(index);
1515 void updateEditMenuBar()
1518 if (viewport.getHistoryList().size() > 0)
1520 undoMenuItem.setEnabled(true);
1521 CommandI command = viewport.getHistoryList().peek();
1522 undoMenuItem.setText(MessageManager.formatMessage(
1523 "label.undo_command", new Object[]
1524 { command.getDescription() }));
1528 undoMenuItem.setEnabled(false);
1529 undoMenuItem.setText(MessageManager.getString("action.undo"));
1532 if (viewport.getRedoList().size() > 0)
1534 redoMenuItem.setEnabled(true);
1536 CommandI command = viewport.getRedoList().peek();
1537 redoMenuItem.setText(MessageManager.formatMessage(
1538 "label.redo_command", new Object[]
1539 { command.getDescription() }));
1543 redoMenuItem.setEnabled(false);
1544 redoMenuItem.setText(MessageManager.getString("action.redo"));
1548 public void addHistoryItem(CommandI command)
1550 if (command.getSize() > 0)
1552 viewport.addToHistoryList(command);
1553 viewport.clearRedoList();
1554 updateEditMenuBar();
1555 viewport.updateHiddenColumns();
1556 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1557 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1558 // viewport.getColumnSelection()
1559 // .getHiddenColumns().size() > 0);
1565 * @return alignment objects for all views
1567 AlignmentI[] getViewAlignments()
1569 if (alignPanels != null)
1571 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1573 for (AlignmentPanel ap : alignPanels)
1575 als[i++] = ap.av.getAlignment();
1579 if (viewport != null)
1581 return new AlignmentI[]
1582 { viewport.getAlignment() };
1594 protected void undoMenuItem_actionPerformed(ActionEvent e)
1596 if (viewport.getHistoryList().isEmpty())
1600 CommandI command = viewport.getHistoryList().pop();
1601 viewport.addToRedoList(command);
1602 command.undoCommand(getViewAlignments());
1604 AlignmentViewport originalSource = getOriginatingSource(command);
1605 updateEditMenuBar();
1607 if (originalSource != null)
1609 if (originalSource != viewport)
1612 .warn("Implementation worry: mismatch of viewport origin for undo");
1614 originalSource.updateHiddenColumns();
1615 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1617 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1618 // viewport.getColumnSelection()
1619 // .getHiddenColumns().size() > 0);
1620 originalSource.firePropertyChange("alignment", null, originalSource
1621 .getAlignment().getSequences());
1632 protected void redoMenuItem_actionPerformed(ActionEvent e)
1634 if (viewport.getRedoList().size() < 1)
1639 CommandI command = viewport.getRedoList().pop();
1640 viewport.addToHistoryList(command);
1641 command.doCommand(getViewAlignments());
1643 AlignmentViewport originalSource = getOriginatingSource(command);
1644 updateEditMenuBar();
1646 if (originalSource != null)
1649 if (originalSource != viewport)
1652 .warn("Implementation worry: mismatch of viewport origin for redo");
1654 originalSource.updateHiddenColumns();
1655 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1657 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1658 // viewport.getColumnSelection()
1659 // .getHiddenColumns().size() > 0);
1660 originalSource.firePropertyChange("alignment", null, originalSource
1661 .getAlignment().getSequences());
1665 AlignmentViewport getOriginatingSource(CommandI command)
1667 AlignmentViewport originalSource = null;
1668 // For sequence removal and addition, we need to fire
1669 // the property change event FROM the viewport where the
1670 // original alignment was altered
1671 AlignmentI al = null;
1672 if (command instanceof EditCommand)
1674 EditCommand editCommand = (EditCommand) command;
1675 al = editCommand.getAlignment();
1676 List<Component> comps = PaintRefresher.components.get(viewport
1677 .getSequenceSetId());
1679 for (Component comp : comps)
1681 if (comp instanceof AlignmentPanel)
1683 if (al == ((AlignmentPanel) comp).av.getAlignment())
1685 originalSource = ((AlignmentPanel) comp).av;
1692 if (originalSource == null)
1694 // The original view is closed, we must validate
1695 // the current view against the closed view first
1698 PaintRefresher.validateSequences(al, viewport.getAlignment());
1701 originalSource = viewport;
1704 return originalSource;
1713 public void moveSelectedSequences(boolean up)
1715 SequenceGroup sg = viewport.getSelectionGroup();
1721 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1722 viewport.getHiddenRepSequences(), up);
1723 alignPanel.paintAlignment(true);
1725 final AlignViewportI peer = viewport.getCodingComplement();
1728 final SequenceGroup selectionGroup = peer.getSelectionGroup();
1729 if (selectionGroup != null)
1731 peer.getAlignment().moveSelectedSequencesByOne(
1732 peer.getSelectionGroup(), peer.getHiddenRepSequences(), up);
1733 ((AlignViewport) peer).getAlignPanel().paintAlignment(true);
1738 synchronized void slideSequences(boolean right, int size)
1740 List<SequenceI> sg = new ArrayList<SequenceI>();
1741 if (viewport.cursorMode)
1743 sg.add(viewport.getAlignment().getSequenceAt(
1744 alignPanel.getSeqPanel().seqCanvas.cursorY));
1746 else if (viewport.getSelectionGroup() != null
1747 && viewport.getSelectionGroup().getSize() != viewport
1748 .getAlignment().getHeight())
1750 sg = viewport.getSelectionGroup().getSequences(
1751 viewport.getHiddenRepSequences());
1759 List<SequenceI> invertGroup = new ArrayList<SequenceI>();
1761 for (SequenceI seq : viewport.getAlignment().getSequences())
1763 if (!sg.contains(seq))
1765 invertGroup.add(seq);
1769 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1771 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1772 for (int i = 0; i < invertGroup.size(); i++)
1774 seqs2[i] = invertGroup.get(i);
1777 SlideSequencesCommand ssc;
1780 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1781 size, viewport.getGapCharacter());
1785 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1786 size, viewport.getGapCharacter());
1789 int groupAdjustment = 0;
1790 if (ssc.getGapsInsertedBegin() && right)
1792 if (viewport.cursorMode)
1794 alignPanel.getSeqPanel().moveCursor(size, 0);
1798 groupAdjustment = size;
1801 else if (!ssc.getGapsInsertedBegin() && !right)
1803 if (viewport.cursorMode)
1805 alignPanel.getSeqPanel().moveCursor(-size, 0);
1809 groupAdjustment = -size;
1813 if (groupAdjustment != 0)
1815 viewport.getSelectionGroup().setStartRes(
1816 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1817 viewport.getSelectionGroup().setEndRes(
1818 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1821 boolean appendHistoryItem = false;
1822 Deque<CommandI> historyList = viewport.getHistoryList();
1823 if (historyList != null
1824 && historyList.size() > 0
1825 && historyList.peek() instanceof SlideSequencesCommand)
1827 appendHistoryItem = ssc
1828 .appendSlideCommand((SlideSequencesCommand) historyList
1832 if (!appendHistoryItem)
1834 addHistoryItem(ssc);
1847 protected void copy_actionPerformed(ActionEvent e)
1850 if (viewport.getSelectionGroup() == null)
1854 // TODO: preserve the ordering of displayed alignment annotation in any
1855 // internal paste (particularly sequence associated annotation)
1856 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1857 String[] omitHidden = null;
1859 if (viewport.hasHiddenColumns())
1861 omitHidden = viewport.getViewAsString(true);
1864 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1867 StringSelection ss = new StringSelection(output);
1871 jalview.gui.Desktop.internalCopy = true;
1872 // Its really worth setting the clipboard contents
1873 // to empty before setting the large StringSelection!!
1874 Toolkit.getDefaultToolkit().getSystemClipboard()
1875 .setContents(new StringSelection(""), null);
1877 Toolkit.getDefaultToolkit().getSystemClipboard()
1878 .setContents(ss, Desktop.instance);
1879 } catch (OutOfMemoryError er)
1881 new OOMWarning("copying region", er);
1885 ArrayList<int[]> hiddenColumns = null;
1886 if (viewport.hasHiddenColumns())
1888 hiddenColumns = new ArrayList<int[]>();
1889 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1890 .getSelectionGroup().getEndRes();
1891 for (int[] region : viewport.getColumnSelection().getHiddenColumns())
1893 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1895 hiddenColumns.add(new int[]
1896 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1901 Desktop.jalviewClipboard = new Object[]
1902 { seqs, viewport.getAlignment().getDataset(), hiddenColumns };
1903 statusBar.setText(MessageManager.formatMessage(
1904 "label.copied_sequences_to_clipboard", new Object[]
1905 { Integer.valueOf(seqs.length).toString() }));
1915 protected void pasteNew_actionPerformed(ActionEvent e)
1927 protected void pasteThis_actionPerformed(ActionEvent e)
1933 * Paste contents of Jalview clipboard
1935 * @param newAlignment
1936 * true to paste to a new alignment, otherwise add to this.
1938 void paste(boolean newAlignment)
1940 boolean externalPaste = true;
1943 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1944 Transferable contents = c.getContents(this);
1946 if (contents == null)
1954 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1955 if (str.length() < 1)
1960 format = new IdentifyFile().Identify(str, "Paste");
1962 } catch (OutOfMemoryError er)
1964 new OOMWarning("Out of memory pasting sequences!!", er);
1968 SequenceI[] sequences;
1969 boolean annotationAdded = false;
1970 AlignmentI alignment = null;
1972 if (Desktop.jalviewClipboard != null)
1974 // The clipboard was filled from within Jalview, we must use the
1976 // And dataset from the copied alignment
1977 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1978 // be doubly sure that we create *new* sequence objects.
1979 sequences = new SequenceI[newseq.length];
1980 for (int i = 0; i < newseq.length; i++)
1982 sequences[i] = new Sequence(newseq[i]);
1984 alignment = new Alignment(sequences);
1985 externalPaste = false;
1989 // parse the clipboard as an alignment.
1990 alignment = new FormatAdapter().readFile(str, "Paste", format);
1991 sequences = alignment.getSequencesArray();
1995 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
2001 if (Desktop.jalviewClipboard != null)
2003 // dataset is inherited
2004 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2008 // new dataset is constructed
2009 alignment.setDataset(null);
2011 alwidth = alignment.getWidth() + 1;
2015 AlignmentI pastedal = alignment; // preserve pasted alignment object
2016 // Add pasted sequences and dataset into existing alignment.
2017 alignment = viewport.getAlignment();
2018 alwidth = alignment.getWidth() + 1;
2019 // decide if we need to import sequences from an existing dataset
2020 boolean importDs = Desktop.jalviewClipboard != null
2021 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2022 // importDs==true instructs us to copy over new dataset sequences from
2023 // an existing alignment
2024 Vector newDs = (importDs) ? new Vector() : null; // used to create
2025 // minimum dataset set
2027 for (int i = 0; i < sequences.length; i++)
2031 newDs.addElement(null);
2033 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2035 if (importDs && ds != null)
2037 if (!newDs.contains(ds))
2039 newDs.setElementAt(ds, i);
2040 ds = new Sequence(ds);
2041 // update with new dataset sequence
2042 sequences[i].setDatasetSequence(ds);
2046 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2051 // copy and derive new dataset sequence
2052 sequences[i] = sequences[i].deriveSequence();
2053 alignment.getDataset().addSequence(
2054 sequences[i].getDatasetSequence());
2055 // TODO: avoid creation of duplicate dataset sequences with a
2056 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2058 alignment.addSequence(sequences[i]); // merges dataset
2062 newDs.clear(); // tidy up
2064 if (alignment.getAlignmentAnnotation() != null)
2066 for (AlignmentAnnotation alan : alignment
2067 .getAlignmentAnnotation())
2069 if (alan.graphGroup > fgroup)
2071 fgroup = alan.graphGroup;
2075 if (pastedal.getAlignmentAnnotation() != null)
2077 // Add any annotation attached to alignment.
2078 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2079 for (int i = 0; i < alann.length; i++)
2081 annotationAdded = true;
2082 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2084 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2085 if (newann.graphGroup > -1)
2087 if (newGraphGroups.size() <= newann.graphGroup
2088 || newGraphGroups.get(newann.graphGroup) == null)
2090 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2092 newGraphGroups.add(q, null);
2094 newGraphGroups.set(newann.graphGroup, new Integer(
2097 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2101 newann.padAnnotation(alwidth);
2102 alignment.addAnnotation(newann);
2112 addHistoryItem(new EditCommand(
2113 MessageManager.getString("label.add_sequences"),
2115 sequences, 0, alignment.getWidth(), alignment));
2117 // Add any annotations attached to sequences
2118 for (int i = 0; i < sequences.length; i++)
2120 if (sequences[i].getAnnotation() != null)
2122 AlignmentAnnotation newann;
2123 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2125 annotationAdded = true;
2126 newann = sequences[i].getAnnotation()[a];
2127 newann.adjustForAlignment();
2128 newann.padAnnotation(alwidth);
2129 if (newann.graphGroup > -1)
2131 if (newann.graphGroup > -1)
2133 if (newGraphGroups.size() <= newann.graphGroup
2134 || newGraphGroups.get(newann.graphGroup) == null)
2136 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2138 newGraphGroups.add(q, null);
2140 newGraphGroups.set(newann.graphGroup, new Integer(
2143 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2147 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2152 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2159 // propagate alignment changed.
2160 viewport.setEndSeq(alignment.getHeight());
2161 if (annotationAdded)
2163 // Duplicate sequence annotation in all views.
2164 AlignmentI[] alview = this.getViewAlignments();
2165 for (int i = 0; i < sequences.length; i++)
2167 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2172 for (int avnum = 0; avnum < alview.length; avnum++)
2174 if (alview[avnum] != alignment)
2176 // duplicate in a view other than the one with input focus
2177 int avwidth = alview[avnum].getWidth() + 1;
2178 // this relies on sann being preserved after we
2179 // modify the sequence's annotation array for each duplication
2180 for (int a = 0; a < sann.length; a++)
2182 AlignmentAnnotation newann = new AlignmentAnnotation(
2184 sequences[i].addAlignmentAnnotation(newann);
2185 newann.padAnnotation(avwidth);
2186 alview[avnum].addAnnotation(newann); // annotation was
2187 // duplicated earlier
2188 // TODO JAL-1145 graphGroups are not updated for sequence
2189 // annotation added to several views. This may cause
2191 alview[avnum].setAnnotationIndex(newann, a);
2196 buildSortByAnnotationScoresMenu();
2198 viewport.firePropertyChange("alignment", null,
2199 alignment.getSequences());
2200 if (alignPanels != null)
2202 for (AlignmentPanel ap : alignPanels)
2204 ap.validateAnnotationDimensions(false);
2209 alignPanel.validateAnnotationDimensions(false);
2215 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2217 String newtitle = new String("Copied sequences");
2219 if (Desktop.jalviewClipboard != null
2220 && Desktop.jalviewClipboard[2] != null)
2222 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2223 for (int[] region : hc)
2225 af.viewport.hideColumns(region[0], region[1]);
2229 // >>>This is a fix for the moment, until a better solution is
2231 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2233 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
2235 // TODO: maintain provenance of an alignment, rather than just make the
2236 // title a concatenation of operations.
2239 if (title.startsWith("Copied sequences"))
2245 newtitle = newtitle.concat("- from " + title);
2250 newtitle = new String("Pasted sequences");
2253 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2258 } catch (Exception ex)
2260 ex.printStackTrace();
2261 System.out.println("Exception whilst pasting: " + ex);
2262 // could be anything being pasted in here
2268 protected void expand_newalign(ActionEvent e)
2272 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2273 .getAlignment(), -1);
2274 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2276 String newtitle = new String("Flanking alignment");
2278 if (Desktop.jalviewClipboard != null
2279 && Desktop.jalviewClipboard[2] != null)
2281 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2282 for (int region[] : hc)
2284 af.viewport.hideColumns(region[0], region[1]);
2288 // >>>This is a fix for the moment, until a better solution is
2290 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2292 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
2294 // TODO: maintain provenance of an alignment, rather than just make the
2295 // title a concatenation of operations.
2297 if (title.startsWith("Copied sequences"))
2303 newtitle = newtitle.concat("- from " + title);
2307 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2309 } catch (Exception ex)
2311 ex.printStackTrace();
2312 System.out.println("Exception whilst pasting: " + ex);
2313 // could be anything being pasted in here
2314 } catch (OutOfMemoryError oom)
2316 new OOMWarning("Viewing flanking region of alignment", oom);
2327 protected void cut_actionPerformed(ActionEvent e)
2329 copy_actionPerformed(null);
2330 delete_actionPerformed(null);
2340 protected void delete_actionPerformed(ActionEvent evt)
2343 SequenceGroup sg = viewport.getSelectionGroup();
2349 List<SequenceI> seqs = new ArrayList<SequenceI>(sg.getSize());
2351 for (int i = 0; i < sg.getSize(); i++)
2353 seq = sg.getSequenceAt(i);
2357 // If the cut affects all sequences, warn, remove highlighted columns
2358 if (sg.getSize() == viewport.getAlignment().getHeight())
2360 int confirm = JOptionPane.showConfirmDialog(this,
2361 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2362 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2363 JOptionPane.OK_CANCEL_OPTION);
2365 if (confirm == JOptionPane.CANCEL_OPTION
2366 || confirm == JOptionPane.CLOSED_OPTION)
2370 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2371 sg.getEndRes() + 1);
2374 SequenceI[] cut = new SequenceI[seqs.size()];
2375 for (int i = 0; i < seqs.size(); i++)
2377 cut[i] = seqs.get(i);
2381 * //ADD HISTORY ITEM
2383 addHistoryItem(new EditCommand(
2384 MessageManager.getString("label.cut_sequences"), Action.CUT,
2385 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2386 viewport.getAlignment()));
2388 viewport.setSelectionGroup(null);
2389 viewport.sendSelection();
2390 viewport.getAlignment().deleteGroup(sg);
2392 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2394 if (viewport.getAlignment().getHeight() < 1)
2398 this.setClosed(true);
2399 } catch (Exception ex)
2412 protected void deleteGroups_actionPerformed(ActionEvent e)
2414 if (avc.deleteGroups())
2416 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2417 alignPanel.updateAnnotation();
2418 alignPanel.paintAlignment(true);
2429 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2431 SequenceGroup sg = new SequenceGroup();
2433 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2435 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2438 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2439 viewport.setSelectionGroup(sg);
2440 viewport.sendSelection();
2441 alignPanel.paintAlignment(true);
2442 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2452 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2454 if (viewport.cursorMode)
2456 alignPanel.getSeqPanel().keyboardNo1 = null;
2457 alignPanel.getSeqPanel().keyboardNo2 = null;
2459 viewport.setSelectionGroup(null);
2460 viewport.getColumnSelection().clear();
2461 viewport.setSelectionGroup(null);
2462 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2463 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2464 alignPanel.paintAlignment(true);
2465 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2466 viewport.sendSelection();
2476 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2478 SequenceGroup sg = viewport.getSelectionGroup();
2482 selectAllSequenceMenuItem_actionPerformed(null);
2487 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2489 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2492 alignPanel.paintAlignment(true);
2493 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2494 viewport.sendSelection();
2498 public void invertColSel_actionPerformed(ActionEvent e)
2500 viewport.invertColumnSelection();
2501 alignPanel.paintAlignment(true);
2502 viewport.sendSelection();
2512 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2514 trimAlignment(true);
2524 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2526 trimAlignment(false);
2529 void trimAlignment(boolean trimLeft)
2531 ColumnSelection colSel = viewport.getColumnSelection();
2534 if (colSel.size() > 0)
2538 column = colSel.getMin();
2542 column = colSel.getMax();
2546 if (viewport.getSelectionGroup() != null)
2548 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2549 viewport.getHiddenRepSequences());
2553 seqs = viewport.getAlignment().getSequencesArray();
2556 TrimRegionCommand trimRegion;
2559 trimRegion = new TrimRegionCommand("Remove Left",
2560 TrimRegionCommand.TRIM_LEFT, seqs, column,
2561 viewport.getAlignment(), viewport.getColumnSelection(),
2562 viewport.getSelectionGroup());
2563 viewport.setStartRes(0);
2567 trimRegion = new TrimRegionCommand("Remove Right",
2568 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2569 viewport.getAlignment(), viewport.getColumnSelection(),
2570 viewport.getSelectionGroup());
2573 statusBar.setText(MessageManager.formatMessage(
2574 "label.removed_columns", new String[]
2575 { Integer.valueOf(trimRegion.getSize()).toString() }));
2577 addHistoryItem(trimRegion);
2579 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2581 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2582 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2584 viewport.getAlignment().deleteGroup(sg);
2588 viewport.firePropertyChange("alignment", null, viewport
2589 .getAlignment().getSequences());
2600 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2602 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2605 if (viewport.getSelectionGroup() != null)
2607 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2608 viewport.getHiddenRepSequences());
2609 start = viewport.getSelectionGroup().getStartRes();
2610 end = viewport.getSelectionGroup().getEndRes();
2614 seqs = viewport.getAlignment().getSequencesArray();
2617 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2618 "Remove Gapped Columns", seqs, start, end,
2619 viewport.getAlignment());
2621 addHistoryItem(removeGapCols);
2623 statusBar.setText(MessageManager.formatMessage(
2624 "label.removed_empty_columns", new Object[]
2625 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2627 // This is to maintain viewport position on first residue
2628 // of first sequence
2629 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2630 int startRes = seq.findPosition(viewport.startRes);
2631 // ShiftList shifts;
2632 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2633 // edit.alColumnChanges=shifts.getInverse();
2634 // if (viewport.hasHiddenColumns)
2635 // viewport.getColumnSelection().compensateForEdits(shifts);
2636 viewport.setStartRes(seq.findIndex(startRes) - 1);
2637 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2649 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2651 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2654 if (viewport.getSelectionGroup() != null)
2656 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2657 viewport.getHiddenRepSequences());
2658 start = viewport.getSelectionGroup().getStartRes();
2659 end = viewport.getSelectionGroup().getEndRes();
2663 seqs = viewport.getAlignment().getSequencesArray();
2666 // This is to maintain viewport position on first residue
2667 // of first sequence
2668 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2669 int startRes = seq.findPosition(viewport.startRes);
2671 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2672 viewport.getAlignment()));
2674 viewport.setStartRes(seq.findIndex(startRes) - 1);
2676 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2688 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2690 viewport.setPadGaps(padGapsMenuitem.isSelected());
2691 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2702 public void findMenuItem_actionPerformed(ActionEvent e)
2708 * Create a new view of the current alignment.
2711 public void newView_actionPerformed(ActionEvent e)
2714 * Note if the current view has a protein/cdna complementary view
2716 AlignViewportI linkedView = this.viewport.getCodingComplement();
2718 AlignmentPanel newPanel = newView(null, true);
2721 * If the original view has a protein/cdna linked view, make and link a new
2724 // TODO refactor the hell out of this - move to a controller, lose the casts
2725 // and direct member access, etc
2726 if (linkedView != null)
2728 AlignFrame linkedAlignFrame = ((AlignViewport) linkedView)
2729 .getAlignPanel().alignFrame;
2730 AlignmentPanel newLinkedPanel = linkedAlignFrame.newView(null, true);
2731 newLinkedPanel.av.viewName = newPanel.av.viewName;
2732 newPanel.av.setCodingComplement(newLinkedPanel.av);
2733 final StructureSelectionManager ssm = StructureSelectionManager
2734 .getStructureSelectionManager(Desktop.instance);
2735 ssm.addCommandListener(newPanel.av);
2736 ssm.addCommandListener(newLinkedPanel.av);
2742 * Creates and shows a new view of the current alignment.
2745 * title of newly created view; if null, one will be generated
2746 * @param copyAnnotation
2747 * if true then duplicate all annnotation, groups and settings
2748 * @return new alignment panel, already displayed.
2750 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2753 * Create a new AlignmentPanel (with its own, new Viewport)
2755 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2757 if (!copyAnnotation)
2760 * remove all groups and annotation except for the automatic stuff
2762 newap.av.getAlignment().deleteAllGroups();
2763 newap.av.getAlignment().deleteAllAnnotations(false);
2766 newap.av.gatherViewsHere = false;
2768 if (viewport.viewName == null)
2770 viewport.viewName = MessageManager
2771 .getString("label.view_name_original");
2775 * Views share the same edits, undo and redo stacks, mappings.
2777 newap.av.setHistoryList(viewport.getHistoryList());
2778 newap.av.setRedoList(viewport.getRedoList());
2779 newap.av.getAlignment().setCodonFrames(
2780 viewport.getAlignment().getCodonFrames());
2782 newap.av.viewName = getNewViewName(viewTitle);
2784 addAlignmentPanel(newap, true);
2785 newap.alignmentChanged();
2787 if (alignPanels.size() == 2)
2789 viewport.gatherViewsHere = true;
2791 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2796 * Make a new name for the view, ensuring it is unique within the current
2797 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2798 * these now use viewId. Unique view names are still desirable for usability.)
2803 protected String getNewViewName(String viewTitle)
2805 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2806 boolean addFirstIndex = false;
2807 if (viewTitle == null || viewTitle.trim().length() == 0)
2809 viewTitle = MessageManager.getString("action.view");
2810 addFirstIndex = true;
2814 index = 1;// we count from 1 if given a specific name
2816 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2818 List<Component> comps = PaintRefresher.components.get(viewport
2819 .getSequenceSetId());
2821 List<String> existingNames = getExistingViewNames(comps);
2823 while (existingNames.contains(newViewName))
2825 newViewName = viewTitle + " " + (++index);
2831 * Returns a list of distinct view names found in the given list of
2832 * components. View names are held on the viewport of an AlignmentPanel.
2837 protected List<String> getExistingViewNames(List<Component> comps)
2839 List<String> existingNames = new ArrayList<String>();
2840 for (Component comp : comps)
2842 if (comp instanceof AlignmentPanel)
2844 AlignmentPanel ap = (AlignmentPanel) comp;
2845 if (!existingNames.contains(ap.av.viewName))
2847 existingNames.add(ap.av.viewName);
2851 return existingNames;
2855 * Explode tabbed views into separate windows.
2858 public void expandViews_actionPerformed(ActionEvent e)
2860 Desktop.instance.explodeViews(this);
2864 * Gather views in separate windows back into a tabbed presentation.
2867 public void gatherViews_actionPerformed(ActionEvent e)
2869 Desktop.instance.gatherViews(this);
2879 public void font_actionPerformed(ActionEvent e)
2881 new FontChooser(alignPanel);
2891 protected void seqLimit_actionPerformed(ActionEvent e)
2893 viewport.setShowJVSuffix(seqLimits.isSelected());
2895 alignPanel.getIdPanel().getIdCanvas().setPreferredSize(alignPanel
2896 .calculateIdWidth());
2897 alignPanel.paintAlignment(true);
2901 public void idRightAlign_actionPerformed(ActionEvent e)
2903 viewport.setRightAlignIds(idRightAlign.isSelected());
2904 alignPanel.paintAlignment(true);
2908 public void centreColumnLabels_actionPerformed(ActionEvent e)
2910 viewport.centreColumnLabels = centreColumnLabelsMenuItem.getState();
2911 alignPanel.paintAlignment(true);
2917 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2920 protected void followHighlight_actionPerformed()
2922 if (viewport.followHighlight = this.followHighlightMenuItem.getState())
2924 alignPanel.scrollToPosition(
2925 alignPanel.getSeqPanel().seqCanvas.searchResults, false);
2936 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2938 viewport.setColourText(colourTextMenuItem.isSelected());
2939 alignPanel.paintAlignment(true);
2949 public void wrapMenuItem_actionPerformed(ActionEvent e)
2951 scaleAbove.setVisible(wrapMenuItem.isSelected());
2952 scaleLeft.setVisible(wrapMenuItem.isSelected());
2953 scaleRight.setVisible(wrapMenuItem.isSelected());
2954 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2955 alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2959 public void showAllSeqs_actionPerformed(ActionEvent e)
2961 viewport.showAllHiddenSeqs();
2965 public void showAllColumns_actionPerformed(ActionEvent e)
2967 viewport.showAllHiddenColumns();
2972 public void hideSelSequences_actionPerformed(ActionEvent e)
2974 viewport.hideAllSelectedSeqs();
2975 alignPanel.paintAlignment(true);
2979 * called by key handler and the hide all/show all menu items
2984 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2987 boolean hide = false;
2988 SequenceGroup sg = viewport.getSelectionGroup();
2989 if (!toggleSeqs && !toggleCols)
2991 // Hide everything by the current selection - this is a hack - we do the
2992 // invert and then hide
2993 // first check that there will be visible columns after the invert.
2994 if ((viewport.getColumnSelection() != null
2995 && viewport.getColumnSelection().getSelected() != null && viewport
2996 .getColumnSelection().getSelected().size() > 0)
2997 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
3000 // now invert the sequence set, if required - empty selection implies
3001 // that no hiding is required.
3004 invertSequenceMenuItem_actionPerformed(null);
3005 sg = viewport.getSelectionGroup();
3009 viewport.expandColSelection(sg, true);
3010 // finally invert the column selection and get the new sequence
3012 invertColSel_actionPerformed(null);
3019 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3021 hideSelSequences_actionPerformed(null);
3024 else if (!(toggleCols && viewport.getColumnSelection().getSelected()
3027 showAllSeqs_actionPerformed(null);
3033 if (viewport.getColumnSelection().getSelected().size() > 0)
3035 hideSelColumns_actionPerformed(null);
3038 viewport.setSelectionGroup(sg);
3043 showAllColumns_actionPerformed(null);
3052 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3053 * event.ActionEvent)
3056 public void hideAllButSelection_actionPerformed(ActionEvent e)
3058 toggleHiddenRegions(false, false);
3065 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3069 public void hideAllSelection_actionPerformed(ActionEvent e)
3071 SequenceGroup sg = viewport.getSelectionGroup();
3072 viewport.expandColSelection(sg, false);
3073 viewport.hideAllSelectedSeqs();
3074 viewport.hideSelectedColumns();
3075 alignPanel.paintAlignment(true);
3082 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3086 public void showAllhidden_actionPerformed(ActionEvent e)
3088 viewport.showAllHiddenColumns();
3089 viewport.showAllHiddenSeqs();
3090 alignPanel.paintAlignment(true);
3094 public void hideSelColumns_actionPerformed(ActionEvent e)
3096 viewport.hideSelectedColumns();
3097 alignPanel.paintAlignment(true);
3101 public void hiddenMarkers_actionPerformed(ActionEvent e)
3103 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3114 protected void scaleAbove_actionPerformed(ActionEvent e)
3116 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3117 alignPanel.paintAlignment(true);
3127 protected void scaleLeft_actionPerformed(ActionEvent e)
3129 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3130 alignPanel.paintAlignment(true);
3140 protected void scaleRight_actionPerformed(ActionEvent e)
3142 viewport.setScaleRightWrapped(scaleRight.isSelected());
3143 alignPanel.paintAlignment(true);
3153 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3155 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3156 alignPanel.paintAlignment(true);
3166 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3168 viewport.setShowText(viewTextMenuItem.isSelected());
3169 alignPanel.paintAlignment(true);
3179 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3181 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3182 alignPanel.paintAlignment(true);
3185 public FeatureSettings featureSettings;
3188 public void featureSettings_actionPerformed(ActionEvent e)
3190 if (featureSettings != null)
3192 featureSettings.close();
3193 featureSettings = null;
3195 if (!showSeqFeatures.isSelected())
3197 // make sure features are actually displayed
3198 showSeqFeatures.setSelected(true);
3199 showSeqFeatures_actionPerformed(null);
3201 featureSettings = new FeatureSettings(this);
3205 * Set or clear 'Show Sequence Features'
3211 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3213 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3214 alignPanel.paintAlignment(true);
3215 if (alignPanel.getOverviewPanel() != null)
3217 alignPanel.getOverviewPanel().updateOverviewImage();
3222 * Set or clear 'Show Sequence Features'
3228 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
3230 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
3232 if (viewport.isShowSequenceFeaturesHeight())
3234 // ensure we're actually displaying features
3235 viewport.setShowSequenceFeatures(true);
3236 showSeqFeatures.setSelected(true);
3238 alignPanel.paintAlignment(true);
3239 if (alignPanel.getOverviewPanel() != null)
3241 alignPanel.getOverviewPanel().updateOverviewImage();
3246 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3247 * the annotations panel as a whole.
3249 * The options to show/hide all annotations should be enabled when the panel
3250 * is shown, and disabled when the panel is hidden.
3255 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3257 final boolean setVisible = annotationPanelMenuItem.isSelected();
3258 viewport.setShowAnnotation(setVisible);
3259 alignPanel.setAnnotationVisible(setVisible);
3260 this.showAllSeqAnnotations.setEnabled(setVisible);
3261 this.hideAllSeqAnnotations.setEnabled(setVisible);
3262 this.showAllAlAnnotations.setEnabled(setVisible);
3263 this.hideAllAlAnnotations.setEnabled(setVisible);
3267 public void alignmentProperties()
3269 JEditorPane editPane = new JEditorPane("text/html", "");
3270 editPane.setEditable(false);
3271 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3273 editPane.setText(MessageManager.formatMessage("label.html_content",
3275 { contents.toString() }));
3276 JInternalFrame frame = new JInternalFrame();
3277 frame.getContentPane().add(new JScrollPane(editPane));
3279 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3280 "label.alignment_properties", new Object[]
3281 { getTitle() }), 500, 400);
3291 public void overviewMenuItem_actionPerformed(ActionEvent e)
3293 if (alignPanel.overviewPanel != null)
3298 JInternalFrame frame = new JInternalFrame();
3299 OverviewPanel overview = new OverviewPanel(alignPanel);
3300 frame.setContentPane(overview);
3301 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3302 "label.overview_params", new Object[]
3303 { this.getTitle() }), frame.getWidth(), frame.getHeight());
3305 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3306 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3309 public void internalFrameClosed(
3310 javax.swing.event.InternalFrameEvent evt)
3312 alignPanel.setOverviewPanel(null);
3316 alignPanel.setOverviewPanel(overview);
3320 public void textColour_actionPerformed(ActionEvent e)
3322 new TextColourChooser().chooseColour(alignPanel, null);
3332 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3344 public void clustalColour_actionPerformed(ActionEvent e)
3346 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3347 viewport.getHiddenRepSequences()));
3357 public void zappoColour_actionPerformed(ActionEvent e)
3359 changeColour(new ZappoColourScheme());
3369 public void taylorColour_actionPerformed(ActionEvent e)
3371 changeColour(new TaylorColourScheme());
3381 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3383 changeColour(new HydrophobicColourScheme());
3393 public void helixColour_actionPerformed(ActionEvent e)
3395 changeColour(new HelixColourScheme());
3405 public void strandColour_actionPerformed(ActionEvent e)
3407 changeColour(new StrandColourScheme());
3417 public void turnColour_actionPerformed(ActionEvent e)
3419 changeColour(new TurnColourScheme());
3429 public void buriedColour_actionPerformed(ActionEvent e)
3431 changeColour(new BuriedColourScheme());
3441 public void nucleotideColour_actionPerformed(ActionEvent e)
3443 changeColour(new NucleotideColourScheme());
3447 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3449 changeColour(new PurinePyrimidineColourScheme());
3453 * public void covariationColour_actionPerformed(ActionEvent e) {
3455 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3459 public void annotationColour_actionPerformed(ActionEvent e)
3461 new AnnotationColourChooser(viewport, alignPanel);
3465 public void annotationColumn_actionPerformed(ActionEvent e)
3467 new AnnotationColumnChooser(viewport, alignPanel);
3471 public void rnahelicesColour_actionPerformed(ActionEvent e)
3473 new RNAHelicesColourChooser(viewport, alignPanel);
3483 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3485 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3494 public void changeColour(ColourSchemeI cs)
3496 // TODO: compare with applet and pull up to model method
3501 if (viewport.getAbovePIDThreshold())
3503 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3505 cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3509 cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3512 if (viewport.getConservationSelected())
3515 Alignment al = (Alignment) viewport.getAlignment();
3516 Conservation c = new Conservation("All",
3517 ResidueProperties.propHash, 3, al.getSequences(), 0,
3521 c.verdict(false, viewport.getConsPercGaps());
3523 cs.setConservation(c);
3525 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3530 cs.setConservation(null);
3533 cs.setConsensus(viewport.getSequenceConsensusHash());
3536 viewport.setGlobalColourScheme(cs);
3538 if (viewport.getColourAppliesToAllGroups())
3541 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3549 if (cs instanceof ClustalxColourScheme)
3551 sg.cs = new ClustalxColourScheme(sg,
3552 viewport.getHiddenRepSequences());
3554 else if (cs instanceof UserColourScheme)
3556 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
3562 sg.cs = cs.getClass().newInstance();
3563 } catch (Exception ex)
3568 if (viewport.getAbovePIDThreshold()
3569 || cs instanceof PIDColourScheme
3570 || cs instanceof Blosum62ColourScheme)
3572 sg.cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3574 sg.cs.setConsensus(AAFrequency.calculate(
3575 sg.getSequences(viewport.getHiddenRepSequences()),
3576 sg.getStartRes(), sg.getEndRes() + 1));
3580 sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3583 if (viewport.getConservationSelected())
3585 Conservation c = new Conservation("Group",
3586 ResidueProperties.propHash, 3, sg.getSequences(viewport
3587 .getHiddenRepSequences()), sg.getStartRes(),
3588 sg.getEndRes() + 1);
3590 c.verdict(false, viewport.getConsPercGaps());
3591 sg.cs.setConservation(c);
3595 sg.cs.setConservation(null);
3600 if (alignPanel.getOverviewPanel() != null)
3602 alignPanel.getOverviewPanel().updateOverviewImage();
3605 alignPanel.paintAlignment(true);
3615 protected void modifyPID_actionPerformed(ActionEvent e)
3617 if (viewport.getAbovePIDThreshold()
3618 && viewport.getGlobalColourScheme() != null)
3620 SliderPanel.setPIDSliderSource(alignPanel,
3621 viewport.getGlobalColourScheme(), "Background");
3622 SliderPanel.showPIDSlider();
3633 protected void modifyConservation_actionPerformed(ActionEvent e)
3635 if (viewport.getConservationSelected()
3636 && viewport.getGlobalColourScheme() != null)
3638 SliderPanel.setConservationSlider(alignPanel,
3639 viewport.getGlobalColourScheme(), "Background");
3640 SliderPanel.showConservationSlider();
3651 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3653 viewport.setConservationSelected(conservationMenuItem.isSelected());
3655 viewport.setAbovePIDThreshold(false);
3656 abovePIDThreshold.setSelected(false);
3658 changeColour(viewport.getGlobalColourScheme());
3660 modifyConservation_actionPerformed(null);
3670 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3672 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3674 conservationMenuItem.setSelected(false);
3675 viewport.setConservationSelected(false);
3677 changeColour(viewport.getGlobalColourScheme());
3679 modifyPID_actionPerformed(null);
3689 public void userDefinedColour_actionPerformed(ActionEvent e)
3691 if (e.getActionCommand().equals(
3692 MessageManager.getString("action.user_defined")))
3694 new UserDefinedColours(alignPanel, null);
3698 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3699 .getUserColourSchemes().get(e.getActionCommand());
3705 public void updateUserColourMenu()
3708 Component[] menuItems = colourMenu.getMenuComponents();
3709 int iSize = menuItems.length;
3710 for (int i = 0; i < iSize; i++)
3712 if (menuItems[i].getName() != null
3713 && menuItems[i].getName().equals("USER_DEFINED"))
3715 colourMenu.remove(menuItems[i]);
3719 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3721 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3722 .getUserColourSchemes().keys();
3724 while (userColours.hasMoreElements())
3726 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3727 userColours.nextElement().toString());
3728 radioItem.setName("USER_DEFINED");
3729 radioItem.addMouseListener(new MouseAdapter()
3732 public void mousePressed(MouseEvent evt)
3734 if (evt.isControlDown()
3735 || SwingUtilities.isRightMouseButton(evt))
3737 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3739 int option = JOptionPane.showInternalConfirmDialog(
3740 jalview.gui.Desktop.desktop,
3742 .getString("label.remove_from_default_list"),
3744 .getString("label.remove_user_defined_colour"),
3745 JOptionPane.YES_NO_OPTION);
3746 if (option == JOptionPane.YES_OPTION)
3748 jalview.gui.UserDefinedColours
3749 .removeColourFromDefaults(radioItem.getText());
3750 colourMenu.remove(radioItem);
3754 radioItem.addActionListener(new ActionListener()
3757 public void actionPerformed(ActionEvent evt)
3759 userDefinedColour_actionPerformed(evt);
3766 radioItem.addActionListener(new ActionListener()
3769 public void actionPerformed(ActionEvent evt)
3771 userDefinedColour_actionPerformed(evt);
3775 colourMenu.insert(radioItem, 15);
3776 colours.add(radioItem);
3788 public void PIDColour_actionPerformed(ActionEvent e)
3790 changeColour(new PIDColourScheme());
3800 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3802 changeColour(new Blosum62ColourScheme());
3812 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3814 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3815 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3816 .getAlignment().getSequenceAt(0), null);
3817 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3818 viewport.getAlignment()));
3819 alignPanel.paintAlignment(true);
3829 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3831 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3832 AlignmentSorter.sortByID(viewport.getAlignment());
3833 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3834 viewport.getAlignment()));
3835 alignPanel.paintAlignment(true);
3845 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3847 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3848 AlignmentSorter.sortByLength(viewport.getAlignment());
3849 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3850 viewport.getAlignment()));
3851 alignPanel.paintAlignment(true);
3861 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3863 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3864 AlignmentSorter.sortByGroup(viewport.getAlignment());
3865 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3866 viewport.getAlignment()));
3868 alignPanel.paintAlignment(true);
3878 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3880 new RedundancyPanel(alignPanel, this);
3890 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3892 if ((viewport.getSelectionGroup() == null)
3893 || (viewport.getSelectionGroup().getSize() < 2))
3895 JOptionPane.showInternalMessageDialog(this, MessageManager
3896 .getString("label.you_must_select_least_two_sequences"),
3897 MessageManager.getString("label.invalid_selection"),
3898 JOptionPane.WARNING_MESSAGE);
3902 JInternalFrame frame = new JInternalFrame();
3903 frame.setContentPane(new PairwiseAlignPanel(viewport));
3904 Desktop.addInternalFrame(frame,
3905 MessageManager.getString("action.pairwise_alignment"), 600,
3917 public void PCAMenuItem_actionPerformed(ActionEvent e)
3919 if (((viewport.getSelectionGroup() != null)
3920 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3921 .getSelectionGroup().getSize() > 0))
3922 || (viewport.getAlignment().getHeight() < 4))
3925 .showInternalMessageDialog(
3928 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3930 .getString("label.sequence_selection_insufficient"),
3931 JOptionPane.WARNING_MESSAGE);
3936 new PCAPanel(alignPanel);
3940 public void autoCalculate_actionPerformed(ActionEvent e)
3942 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3943 if (viewport.autoCalculateConsensus)
3945 viewport.firePropertyChange("alignment", null, viewport
3946 .getAlignment().getSequences());
3951 public void sortByTreeOption_actionPerformed(ActionEvent e)
3953 viewport.sortByTree = sortByTree.isSelected();
3957 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3959 viewport.followSelection = listenToViewSelections.isSelected();
3969 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3971 newTreePanel("AV", "PID", "Average distance tree using PID");
3981 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3983 newTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3993 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3995 newTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
4005 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
4007 newTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
4020 void newTreePanel(String type, String pwType, String title)
4024 if (viewport.getSelectionGroup() != null
4025 && viewport.getSelectionGroup().getSize() > 0)
4027 if (viewport.getSelectionGroup().getSize() < 3)
4033 .getString("label.you_need_more_two_sequences_selected_build_tree"),
4035 .getString("label.not_enough_sequences"),
4036 JOptionPane.WARNING_MESSAGE);
4040 SequenceGroup sg = viewport.getSelectionGroup();
4042 /* Decide if the selection is a column region */
4043 for (SequenceI _s : sg.getSequences())
4045 if (_s.getLength() < sg.getEndRes())
4051 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
4053 .getString("label.sequences_selection_not_aligned"),
4054 JOptionPane.WARNING_MESSAGE);
4060 title = title + " on region";
4061 tp = new TreePanel(alignPanel, type, pwType);
4065 // are the visible sequences aligned?
4066 if (!viewport.getAlignment().isAligned(false))
4072 .getString("label.sequences_must_be_aligned_before_creating_tree"),
4074 .getString("label.sequences_not_aligned"),
4075 JOptionPane.WARNING_MESSAGE);
4080 if (viewport.getAlignment().getHeight() < 2)
4085 tp = new TreePanel(alignPanel, type, pwType);
4090 if (viewport.viewName != null)
4092 title += viewport.viewName + " of ";
4095 title += this.title;
4097 Desktop.addInternalFrame(tp, title, 600, 500);
4108 public void addSortByOrderMenuItem(String title,
4109 final AlignmentOrder order)
4111 final JMenuItem item = new JMenuItem(MessageManager.formatMessage("action.by_title_param", new Object[]{title}));
4113 item.addActionListener(new java.awt.event.ActionListener()
4116 public void actionPerformed(ActionEvent e)
4118 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4120 // TODO: JBPNote - have to map order entries to curent SequenceI
4122 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4124 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
4127 alignPanel.paintAlignment(true);
4133 * Add a new sort by annotation score menu item
4136 * the menu to add the option to
4138 * the label used to retrieve scores for each sequence on the
4141 public void addSortByAnnotScoreMenuItem(JMenu sort,
4142 final String scoreLabel)
4144 final JMenuItem item = new JMenuItem(scoreLabel);
4146 item.addActionListener(new java.awt.event.ActionListener()
4149 public void actionPerformed(ActionEvent e)
4151 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4152 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4153 viewport.getAlignment());// ,viewport.getSelectionGroup());
4154 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4155 viewport.getAlignment()));
4156 alignPanel.paintAlignment(true);
4162 * last hash for alignment's annotation array - used to minimise cost of
4165 protected int _annotationScoreVectorHash;
4168 * search the alignment and rebuild the sort by annotation score submenu the
4169 * last alignment annotation vector hash is stored to minimize cost of
4170 * rebuilding in subsequence calls.
4174 public void buildSortByAnnotationScoresMenu()
4176 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4181 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4183 sortByAnnotScore.removeAll();
4184 // almost certainly a quicker way to do this - but we keep it simple
4185 Hashtable scoreSorts = new Hashtable();
4186 AlignmentAnnotation aann[];
4187 for (SequenceI sqa : viewport.getAlignment().getSequences())
4189 aann = sqa.getAnnotation();
4190 for (int i = 0; aann != null && i < aann.length; i++)
4192 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4194 scoreSorts.put(aann[i].label, aann[i].label);
4198 Enumeration labels = scoreSorts.keys();
4199 while (labels.hasMoreElements())
4201 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4202 (String) labels.nextElement());
4204 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4207 _annotationScoreVectorHash = viewport.getAlignment()
4208 .getAlignmentAnnotation().hashCode();
4213 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4214 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4215 * call. Listeners are added to remove the menu item when the treePanel is
4216 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4220 * Displayed tree window.
4222 * SortBy menu item title.
4225 public void buildTreeMenu()
4227 calculateTree.removeAll();
4228 // build the calculate menu
4230 for (final String type : new String[]
4233 String treecalcnm = MessageManager.getString("label.tree_calc_"
4234 + type.toLowerCase());
4235 for (final String pwtype : ResidueProperties.scoreMatrices.keySet())
4237 JMenuItem tm = new JMenuItem();
4238 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4239 if (sm.isProtein() == !viewport.getAlignment().isNucleotide())
4241 String smn = MessageManager.getStringOrReturn(
4242 "label.score_model_", sm.getName());
4243 final String title = MessageManager.formatMessage(
4244 "label.treecalc_title", treecalcnm, smn);
4245 tm.setText(title);//
4246 tm.addActionListener(new java.awt.event.ActionListener()
4249 public void actionPerformed(ActionEvent e)
4251 newTreePanel(type, pwtype, title);
4254 calculateTree.add(tm);
4259 sortByTreeMenu.removeAll();
4261 List<Component> comps = PaintRefresher.components.get(viewport
4262 .getSequenceSetId());
4263 List<TreePanel> treePanels = new ArrayList<TreePanel>();
4264 for (Component comp : comps)
4266 if (comp instanceof TreePanel)
4268 treePanels.add((TreePanel) comp);
4272 if (treePanels.size() < 1)
4274 sortByTreeMenu.setVisible(false);
4278 sortByTreeMenu.setVisible(true);
4280 for (final TreePanel tp : treePanels)
4282 final JMenuItem item = new JMenuItem(tp.getTitle());
4283 item.addActionListener(new java.awt.event.ActionListener()
4286 public void actionPerformed(ActionEvent e)
4288 tp.sortByTree_actionPerformed();
4289 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4294 sortByTreeMenu.add(item);
4298 public boolean sortBy(AlignmentOrder alorder, String undoname)
4300 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4301 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4302 if (undoname != null)
4304 addHistoryItem(new OrderCommand(undoname, oldOrder,
4305 viewport.getAlignment()));
4307 alignPanel.paintAlignment(true);
4312 * Work out whether the whole set of sequences or just the selected set will
4313 * be submitted for multiple alignment.
4316 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4318 // Now, check we have enough sequences
4319 AlignmentView msa = null;
4321 if ((viewport.getSelectionGroup() != null)
4322 && (viewport.getSelectionGroup().getSize() > 1))
4324 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4325 // some common interface!
4327 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4328 * SequenceI[sz = seqs.getSize(false)];
4330 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4331 * seqs.getSequenceAt(i); }
4333 msa = viewport.getAlignmentView(true);
4335 else if (viewport.getSelectionGroup() != null
4336 && viewport.getSelectionGroup().getSize() == 1)
4338 int option = JOptionPane.showConfirmDialog(this,
4339 MessageManager.getString("warn.oneseq_msainput_selection"),
4340 MessageManager.getString("label.invalid_selection"),
4341 JOptionPane.OK_CANCEL_OPTION);
4342 if (option == JOptionPane.OK_OPTION)
4344 msa = viewport.getAlignmentView(false);
4349 msa = viewport.getAlignmentView(false);
4355 * Decides what is submitted to a secondary structure prediction service: the
4356 * first sequence in the alignment, or in the current selection, or, if the
4357 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4358 * region or the whole alignment. (where the first sequence in the set is the
4359 * one that the prediction will be for).
4361 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4363 AlignmentView seqs = null;
4365 if ((viewport.getSelectionGroup() != null)
4366 && (viewport.getSelectionGroup().getSize() > 0))
4368 seqs = viewport.getAlignmentView(true);
4372 seqs = viewport.getAlignmentView(false);
4374 // limit sequences - JBPNote in future - could spawn multiple prediction
4376 // TODO: viewport.getAlignment().isAligned is a global state - the local
4377 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4378 if (!viewport.getAlignment().isAligned(false))
4380 seqs.setSequences(new SeqCigar[]
4381 { seqs.getSequences()[0] });
4382 // TODO: if seqs.getSequences().length>1 then should really have warned
4396 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
4398 // Pick the tree file
4399 JalviewFileChooser chooser = new JalviewFileChooser(
4400 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4401 chooser.setFileView(new JalviewFileView());
4402 chooser.setDialogTitle(MessageManager
4403 .getString("label.select_newick_like_tree_file"));
4404 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4406 int value = chooser.showOpenDialog(null);
4408 if (value == JalviewFileChooser.APPROVE_OPTION)
4410 String choice = chooser.getSelectedFile().getPath();
4411 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4412 jalview.io.NewickFile fin = null;
4415 fin = new jalview.io.NewickFile(choice, "File");
4416 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4417 } catch (Exception ex)
4424 .getString("label.problem_reading_tree_file"),
4425 JOptionPane.WARNING_MESSAGE);
4426 ex.printStackTrace();
4428 if (fin != null && fin.hasWarningMessage())
4430 JOptionPane.showMessageDialog(Desktop.desktop, fin
4431 .getWarningMessage(), MessageManager
4432 .getString("label.possible_problem_with_tree_file"),
4433 JOptionPane.WARNING_MESSAGE);
4439 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4441 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4444 public TreePanel ShowNewickTree(NewickFile nf, String title)
4446 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4449 public TreePanel ShowNewickTree(NewickFile nf, String title,
4450 AlignmentView input)
4452 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4455 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4456 int h, int x, int y)
4458 return ShowNewickTree(nf, title, null, w, h, x, y);
4462 * Add a treeviewer for the tree extracted from a newick file object to the
4463 * current alignment view
4470 * Associated alignment input data (or null)
4479 * @return TreePanel handle
4481 public TreePanel ShowNewickTree(NewickFile nf, String title,
4482 AlignmentView input, int w, int h, int x, int y)
4484 TreePanel tp = null;
4490 if (nf.getTree() != null)
4492 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4498 tp.setLocation(x, y);
4501 Desktop.addInternalFrame(tp, title, w, h);
4503 } catch (Exception ex)
4505 ex.printStackTrace();
4511 private boolean buildingMenu = false;
4514 * Generates menu items and listener event actions for web service clients
4517 public void BuildWebServiceMenu()
4519 while (buildingMenu)
4523 System.err.println("Waiting for building menu to finish.");
4525 } catch (Exception e)
4529 final AlignFrame me = this;
4530 buildingMenu = true;
4531 new Thread(new Runnable()
4536 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4539 System.err.println("Building ws menu again "
4540 + Thread.currentThread());
4541 // TODO: add support for context dependent disabling of services based
4543 // alignment and current selection
4544 // TODO: add additional serviceHandle parameter to specify abstract
4546 // class independently of AbstractName
4547 // TODO: add in rediscovery GUI function to restart discoverer
4548 // TODO: group services by location as well as function and/or
4550 // object broker mechanism.
4551 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4552 final IProgressIndicator af = me;
4553 final JMenu msawsmenu = new JMenu("Alignment");
4554 final JMenu secstrmenu = new JMenu(
4555 "Secondary Structure Prediction");
4556 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4557 final JMenu analymenu = new JMenu("Analysis");
4558 final JMenu dismenu = new JMenu("Protein Disorder");
4559 // final JMenu msawsmenu = new
4560 // JMenu(MessageManager.getString("label.alignment"));
4561 // final JMenu secstrmenu = new
4562 // JMenu(MessageManager.getString("label.secondary_structure_prediction"));
4563 // final JMenu seqsrchmenu = new
4564 // JMenu(MessageManager.getString("label.sequence_database_search"));
4565 // final JMenu analymenu = new
4566 // JMenu(MessageManager.getString("label.analysis"));
4567 // final JMenu dismenu = new
4568 // JMenu(MessageManager.getString("label.protein_disorder"));
4569 // JAL-940 - only show secondary structure prediction services from
4570 // the legacy server
4571 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4573 Discoverer.services != null && (Discoverer.services.size() > 0))
4575 // TODO: refactor to allow list of AbstractName/Handler bindings to
4577 // stored or retrieved from elsewhere
4578 // No MSAWS used any more:
4579 // Vector msaws = null; // (Vector)
4580 // Discoverer.services.get("MsaWS");
4581 Vector secstrpr = (Vector) Discoverer.services
4583 if (secstrpr != null)
4585 // Add any secondary structure prediction services
4586 for (int i = 0, j = secstrpr.size(); i < j; i++)
4588 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4590 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4591 .getServiceClient(sh);
4592 int p = secstrmenu.getItemCount();
4593 impl.attachWSMenuEntry(secstrmenu, me);
4594 int q = secstrmenu.getItemCount();
4595 for (int litm = p; litm < q; litm++)
4597 legacyItems.add(secstrmenu.getItem(litm));
4603 // Add all submenus in the order they should appear on the web
4605 wsmenu.add(msawsmenu);
4606 wsmenu.add(secstrmenu);
4607 wsmenu.add(dismenu);
4608 wsmenu.add(analymenu);
4609 // No search services yet
4610 // wsmenu.add(seqsrchmenu);
4612 javax.swing.SwingUtilities.invokeLater(new Runnable()
4619 webService.removeAll();
4620 // first, add discovered services onto the webservices menu
4621 if (wsmenu.size() > 0)
4623 for (int i = 0, j = wsmenu.size(); i < j; i++)
4625 webService.add(wsmenu.get(i));
4630 webService.add(me.webServiceNoServices);
4632 // TODO: move into separate menu builder class.
4633 boolean new_sspred = false;
4634 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4636 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4637 if (jws2servs != null)
4639 if (jws2servs.hasServices())
4641 jws2servs.attachWSMenuEntry(webService, me);
4642 for (Jws2Instance sv : jws2servs.getServices())
4644 if (sv.description.toLowerCase().contains("jpred"))
4646 for (JMenuItem jmi : legacyItems)
4648 jmi.setVisible(false);
4654 if (jws2servs.isRunning())
4656 JMenuItem tm = new JMenuItem(
4657 "Still discovering JABA Services");
4658 tm.setEnabled(false);
4663 build_urlServiceMenu(me.webService);
4664 build_fetchdbmenu(webService);
4665 for (JMenu item : wsmenu)
4667 if (item.getItemCount() == 0)
4669 item.setEnabled(false);
4673 item.setEnabled(true);
4676 } catch (Exception e)
4679 .debug("Exception during web service menu building process.",
4684 } catch (Exception e)
4687 buildingMenu = false;
4694 * construct any groupURL type service menu entries.
4698 private void build_urlServiceMenu(JMenu webService)
4700 // TODO: remove this code when 2.7 is released
4701 // DEBUG - alignmentView
4703 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4704 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4706 * @Override public void actionPerformed(ActionEvent e) {
4707 * jalview.datamodel.AlignmentView
4708 * .testSelectionViews(af.viewport.getAlignment(),
4709 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4711 * }); webService.add(testAlView);
4713 // TODO: refactor to RestClient discoverer and merge menu entries for
4714 // rest-style services with other types of analysis/calculation service
4715 // SHmmr test client - still being implemented.
4716 // DEBUG - alignmentView
4718 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4721 client.attachWSMenuEntry(
4722 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4728 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
4729 * chooser = new JalviewFileChooser(jalview.bin.Cache.
4730 * getProperty("LAST_DIRECTORY"));
4732 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
4733 * to Vamsas file"); chooser.setToolTipText("Export");
4735 * int value = chooser.showSaveDialog(this);
4737 * if (value == JalviewFileChooser.APPROVE_OPTION) {
4738 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
4739 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
4740 * chooser.getSelectedFile().getAbsolutePath(), this); } }
4743 * prototype of an automatically enabled/disabled analysis function
4746 protected void setShowProductsEnabled()
4748 SequenceI[] selection = viewport.getSequenceSelection();
4749 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
4750 viewport.getAlignment().getDataset()))
4752 showProducts.setEnabled(true);
4757 showProducts.setEnabled(false);
4762 * search selection for sequence xRef products and build the show products
4767 * @return true if showProducts menu should be enabled.
4769 public boolean canShowProducts(SequenceI[] selection,
4770 boolean isRegionSelection, Alignment dataset)
4772 boolean showp = false;
4775 showProducts.removeAll();
4776 final boolean dna = viewport.getAlignment().isNucleotide();
4777 final Alignment ds = dataset;
4778 String[] ptypes = (selection == null || selection.length == 0) ? null
4779 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4781 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4782 // selection, dataset, true);
4783 final SequenceI[] sel = selection;
4784 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4787 final boolean isRegSel = isRegionSelection;
4788 final AlignFrame af = this;
4789 final String source = ptypes[t];
4790 JMenuItem xtype = new JMenuItem(ptypes[t]);
4791 xtype.addActionListener(new ActionListener()
4795 public void actionPerformed(ActionEvent e)
4797 // TODO: new thread for this call with vis-delay
4798 af.showProductsFor(af.viewport.getSequenceSelection(), ds,
4799 isRegSel, dna, source);
4803 showProducts.add(xtype);
4805 showProducts.setVisible(showp);
4806 showProducts.setEnabled(showp);
4807 } catch (Exception e)
4809 jalview.bin.Cache.log
4810 .warn("canTranslate threw an exception - please report to help@jalview.org",
4817 protected void showProductsFor(SequenceI[] sel, Alignment ds,
4818 boolean isRegSel, boolean dna, String source)
4820 final boolean fisRegSel = isRegSel;
4821 final boolean fdna = dna;
4822 final String fsrc = source;
4823 final AlignFrame ths = this;
4824 final SequenceI[] fsel = sel;
4825 Runnable foo = new Runnable()
4831 final long sttime = System.currentTimeMillis();
4832 ths.setProgressBar(MessageManager.formatMessage("status.searching_for_sequences_from", new Object[]{fsrc}), sttime);
4835 Alignment ds = ths.getViewport().getAlignment().getDataset(); // update
4839 Alignment prods = CrossRef
4840 .findXrefSequences(fsel, fdna, fsrc, ds);
4843 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4844 for (int s = 0; s < sprods.length; s++)
4846 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4847 if (ds.getSequences() == null
4848 || !ds.getSequences().contains(
4849 sprods[s].getDatasetSequence()))
4851 ds.addSequence(sprods[s].getDatasetSequence());
4853 sprods[s].updatePDBIds();
4855 Alignment al = new Alignment(sprods);
4856 Set<AlignedCodonFrame> cf = prods.getCodonFrames();
4858 for (AlignedCodonFrame acf : cf)
4860 al.addCodonFrame(acf);
4862 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4864 String newtitle = "" + ((fdna) ? "Proteins " : "Nucleotides ")
4865 + " for " + ((fisRegSel) ? "selected region of " : "")
4867 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4872 System.err.println("No Sequences generated for xRef type "
4875 } catch (Exception e)
4877 jalview.bin.Cache.log.error(
4878 "Exception when finding crossreferences", e);
4879 } catch (OutOfMemoryError e)
4881 new OOMWarning("whilst fetching crossreferences", e);
4884 jalview.bin.Cache.log.error("Error when finding crossreferences",
4887 ths.setProgressBar(MessageManager.formatMessage("status.finished_searching_for_sequences_from", new Object[]{fsrc}),
4892 Thread frunner = new Thread(foo);
4896 public boolean canShowTranslationProducts(SequenceI[] selection,
4897 AlignmentI alignment)
4902 return (jalview.analysis.Dna.canTranslate(selection,
4903 viewport.getViewAsVisibleContigs(true)));
4904 } catch (Exception e)
4906 jalview.bin.Cache.log
4907 .warn("canTranslate threw an exception - please report to help@jalview.org",
4914 * Construct and display a new frame containing the translation of this
4915 * frame's cDNA sequences to their aligned protein (amino acid) equivalents.
4918 public void showTranslation_actionPerformed(ActionEvent e)
4920 AlignmentI al = null;
4923 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4925 al = dna.translateCdna();
4926 } catch (Exception ex)
4928 jalview.bin.Cache.log.error(
4929 "Exception during translation. Please report this !", ex);
4930 final String msg = MessageManager
4931 .getString("label.error_when_translating_sequences_submit_bug_report");
4932 final String title = MessageManager
4933 .getString("label.implementation_error")
4934 + MessageManager.getString("translation_failed");
4935 JOptionPane.showMessageDialog(Desktop.desktop, msg, title,
4936 JOptionPane.ERROR_MESSAGE);
4939 if (al == null || al.getHeight() == 0)
4941 final String msg = MessageManager
4942 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4943 final String title = MessageManager
4944 .getString("label.translation_failed");
4945 JOptionPane.showMessageDialog(Desktop.desktop, msg, title,
4946 JOptionPane.WARNING_MESSAGE);
4950 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4951 Desktop.addInternalFrame(af, MessageManager.formatMessage(
4952 "label.translation_of_params", new Object[]
4953 { this.getTitle() }), DEFAULT_WIDTH, DEFAULT_HEIGHT);
4954 // enable next line for linked editing
4955 // viewport.getStructureSelectionManager().addCommandListener(viewport);
4960 * Try to load a features file onto the alignment.
4963 * contents or path to retrieve file
4965 * access mode of file (see jalview.io.AlignFile)
4966 * @return true if features file was parsed corectly.
4968 public boolean parseFeaturesFile(String file, String type)
4970 boolean featuresFile = false;
4973 featuresFile = new FeaturesFile(file, type).parse(viewport
4974 .getAlignment().getDataset(), alignPanel.getSeqPanel().seqCanvas
4975 .getFeatureRenderer().getFeatureColours(), false,
4976 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4977 } catch (Exception ex)
4979 ex.printStackTrace();
4984 viewport.setShowSequenceFeatures(true);
4985 showSeqFeatures.setSelected(true);
4986 if (alignPanel.getSeqPanel().seqCanvas.fr != null)
4988 // update the min/max ranges where necessary
4989 alignPanel.getSeqPanel().seqCanvas.fr.findAllFeatures(true);
4991 if (featureSettings != null)
4993 featureSettings.setTableData();
4995 alignPanel.paintAlignment(true);
4998 return featuresFile;
5002 public void dragEnter(DropTargetDragEvent evt)
5007 public void dragExit(DropTargetEvent evt)
5012 public void dragOver(DropTargetDragEvent evt)
5017 public void dropActionChanged(DropTargetDragEvent evt)
5022 public void drop(DropTargetDropEvent evt)
5024 Transferable t = evt.getTransferable();
5025 java.util.List files = null;
5029 DataFlavor uriListFlavor = new DataFlavor(
5030 "text/uri-list;class=java.lang.String");
5031 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
5033 // Works on Windows and MacOSX
5034 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
5035 files = (java.util.List) t
5036 .getTransferData(DataFlavor.javaFileListFlavor);
5038 else if (t.isDataFlavorSupported(uriListFlavor))
5040 // This is used by Unix drag system
5041 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
5042 String data = (String) t.getTransferData(uriListFlavor);
5043 files = new java.util.ArrayList(1);
5044 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
5045 data, "\r\n"); st.hasMoreTokens();)
5047 String s = st.nextToken();
5048 if (s.startsWith("#"))
5050 // the line is a comment (as per the RFC 2483)
5054 java.net.URI uri = new java.net.URI(s);
5055 // check to see if we can handle this kind of URI
5056 if (uri.getScheme().toLowerCase().startsWith("http"))
5058 files.add(uri.toString());
5062 // otherwise preserve old behaviour: catch all for file objects
5063 java.io.File file = new java.io.File(uri);
5064 files.add(file.toString());
5068 } catch (Exception e)
5070 e.printStackTrace();
5076 // check to see if any of these files have names matching sequences in
5078 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5079 .getAlignment().getSequencesArray());
5081 * Object[] { String,SequenceI}
5083 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
5084 ArrayList<String> filesnotmatched = new ArrayList<String>();
5085 for (int i = 0; i < files.size(); i++)
5087 String file = files.get(i).toString();
5089 String protocol = FormatAdapter.checkProtocol(file);
5090 if (protocol == jalview.io.FormatAdapter.FILE)
5092 File fl = new File(file);
5093 pdbfn = fl.getName();
5095 else if (protocol == jalview.io.FormatAdapter.URL)
5097 URL url = new URL(file);
5098 pdbfn = url.getFile();
5100 if (pdbfn.length() > 0)
5102 // attempt to find a match in the alignment
5103 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5104 int l = 0, c = pdbfn.indexOf(".");
5105 while (mtch == null && c != -1)
5110 } while ((c = pdbfn.indexOf(".", l)) > l);
5113 pdbfn = pdbfn.substring(0, l);
5115 mtch = idm.findAllIdMatches(pdbfn);
5122 type = new IdentifyFile().Identify(file, protocol);
5123 } catch (Exception ex)
5129 if (type.equalsIgnoreCase("PDB"))
5131 filesmatched.add(new Object[]
5132 { file, protocol, mtch });
5137 // File wasn't named like one of the sequences or wasn't a PDB file.
5138 filesnotmatched.add(file);
5142 if (filesmatched.size() > 0)
5144 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
5150 "label.automatically_associate_pdb_files_with_sequences_same_name",
5157 .getString("label.automatically_associate_pdb_files_by_name"),
5158 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
5161 for (Object[] fm : filesmatched)
5163 // try and associate
5164 // TODO: may want to set a standard ID naming formalism for
5165 // associating PDB files which have no IDs.
5166 for (SequenceI toassoc : (SequenceI[]) fm[2])
5168 PDBEntry pe = new AssociatePdbFileWithSeq()
5169 .associatePdbWithSeq((String) fm[0],
5170 (String) fm[1], toassoc, false,
5174 System.err.println("Associated file : "
5175 + ((String) fm[0]) + " with "
5176 + toassoc.getDisplayId(true));
5180 alignPanel.paintAlignment(true);
5184 if (filesnotmatched.size() > 0)
5187 && (Cache.getDefault(
5188 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
5191 "<html>"+MessageManager
5193 "label.ignore_unmatched_dropped_files_info",
5198 .toString() })+"</html>",
5200 .getString("label.ignore_unmatched_dropped_files"),
5201 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
5205 for (String fn : filesnotmatched)
5207 loadJalviewDataFile(fn, null, null, null);
5211 } catch (Exception ex)
5213 ex.printStackTrace();
5219 * Attempt to load a "dropped" file or URL string: First by testing whether
5220 * it's and Annotation file, then a JNet file, and finally a features file. If
5221 * all are false then the user may have dropped an alignment file onto this
5225 * either a filename or a URL string.
5227 public void loadJalviewDataFile(String file, String protocol,
5228 String format, SequenceI assocSeq)
5232 if (protocol == null)
5234 protocol = jalview.io.FormatAdapter.checkProtocol(file);
5236 // if the file isn't identified, or not positively identified as some
5237 // other filetype (PFAM is default unidentified alignment file type) then
5238 // try to parse as annotation.
5239 boolean isAnnotation = (format == null || format
5240 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
5241 .annotateAlignmentView(viewport, file, protocol)
5246 // first see if its a T-COFFEE score file
5247 TCoffeeScoreFile tcf = null;
5250 tcf = new TCoffeeScoreFile(file, protocol);
5253 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5255 tcoffeeColour.setEnabled(true);
5256 tcoffeeColour.setSelected(true);
5257 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5258 isAnnotation = true;
5260 .setText(MessageManager
5261 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5265 // some problem - if no warning its probable that the ID matching
5266 // process didn't work
5270 tcf.getWarningMessage() == null ? MessageManager
5271 .getString("label.check_file_matches_sequence_ids_alignment")
5272 : tcf.getWarningMessage(),
5274 .getString("label.problem_reading_tcoffee_score_file"),
5275 JOptionPane.WARNING_MESSAGE);
5282 } catch (Exception x)
5285 .debug("Exception when processing data source as T-COFFEE score file",
5291 // try to see if its a JNet 'concise' style annotation file *before*
5293 // try to parse it as a features file
5296 format = new IdentifyFile().Identify(file, protocol);
5298 if (format.equalsIgnoreCase("JnetFile"))
5300 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5302 new JnetAnnotationMaker();
5303 JnetAnnotationMaker.add_annotation(predictions,
5304 viewport.getAlignment(), 0, false);
5305 isAnnotation = true;
5310 * if (format.equalsIgnoreCase("PDB")) {
5312 * String pdbfn = ""; // try to match up filename with sequence id
5313 * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
5314 * new File(file); pdbfn = fl.getName(); } else if (protocol ==
5315 * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
5316 * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
5317 * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5318 * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
5319 * // attempt to find a match in the alignment SequenceI mtch =
5320 * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
5321 * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
5322 * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
5323 * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
5324 * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
5325 * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
5326 * { System.err.println("Associated file : " + file + " with " +
5327 * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
5328 * TODO: maybe need to load as normal otherwise return; } }
5330 // try to parse it as a features file
5331 boolean isGroupsFile = parseFeaturesFile(file, protocol);
5332 // if it wasn't a features file then we just treat it as a general
5333 // alignment file to load into the current view.
5336 new FileLoader().LoadFile(viewport, file, protocol, format);
5340 alignPanel.paintAlignment(true);
5348 alignPanel.adjustAnnotationHeight();
5349 viewport.updateSequenceIdColours();
5350 buildSortByAnnotationScoresMenu();
5351 alignPanel.paintAlignment(true);
5353 } catch (Exception ex)
5355 ex.printStackTrace();
5356 } catch (OutOfMemoryError oom)
5361 } catch (Exception x)
5367 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5368 : "using " + protocol + " from " + file)
5370 + (format != null ? "(parsing as '" + format
5371 + "' file)" : ""), oom, Desktop.desktop);
5376 * Method invoked by the ChangeListener on the tabbed pane, in other words
5377 * when a different tabbed pane is selected by the user or programmatically.
5380 public void tabSelectionChanged(int index)
5384 alignPanel = alignPanels.get(index);
5385 viewport = alignPanel.av;
5386 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5387 setMenusFromViewport(viewport);
5392 * On right mouse click on view tab, prompt for and set new view name.
5395 public void tabbedPane_mousePressed(MouseEvent e)
5397 if (SwingUtilities.isRightMouseButton(e))
5399 String msg = MessageManager.getString("label.enter_view_name");
5400 String reply = JOptionPane.showInternalInputDialog(this, msg, msg,
5401 JOptionPane.QUESTION_MESSAGE);
5405 viewport.viewName = reply;
5406 // TODO warn if reply is in getExistingViewNames()?
5407 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5412 public AlignViewport getCurrentView()
5418 * Open the dialog for regex description parsing.
5421 protected void extractScores_actionPerformed(ActionEvent e)
5423 ParseProperties pp = new jalview.analysis.ParseProperties(
5424 viewport.getAlignment());
5425 // TODO: verify regex and introduce GUI dialog for version 2.5
5426 // if (pp.getScoresFromDescription("col", "score column ",
5427 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5429 if (pp.getScoresFromDescription("description column",
5430 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5432 buildSortByAnnotationScoresMenu();
5440 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5444 protected void showDbRefs_actionPerformed(ActionEvent e)
5446 viewport.setShowDbRefs(showDbRefsMenuitem.isSelected());
5452 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5456 protected void showNpFeats_actionPerformed(ActionEvent e)
5458 viewport.setShowNpFeats(showNpFeatsMenuitem.isSelected());
5462 * find the viewport amongst the tabs in this alignment frame and close that
5467 public boolean closeView(AlignmentViewport av)
5471 this.closeMenuItem_actionPerformed(false);
5474 Component[] comp = tabbedPane.getComponents();
5475 for (int i = 0; comp != null && i < comp.length; i++)
5477 if (comp[i] instanceof AlignmentPanel)
5479 if (((AlignmentPanel) comp[i]).av == av)
5482 closeView((AlignmentPanel) comp[i]);
5490 protected void build_fetchdbmenu(JMenu webService)
5492 // Temporary hack - DBRef Fetcher always top level ws entry.
5493 // TODO We probably want to store a sequence database checklist in
5494 // preferences and have checkboxes.. rather than individual sources selected
5496 final JMenu rfetch = new JMenu(
5497 MessageManager.getString("action.fetch_db_references"));
5498 rfetch.setToolTipText(MessageManager
5499 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5500 webService.add(rfetch);
5502 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5503 MessageManager.getString("option.trim_retrieved_seqs"));
5504 trimrs.setToolTipText(MessageManager
5505 .getString("label.trim_retrieved_sequences"));
5506 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5507 trimrs.addActionListener(new ActionListener()
5510 public void actionPerformed(ActionEvent e)
5512 trimrs.setSelected(trimrs.isSelected());
5513 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5514 Boolean.valueOf(trimrs.isSelected()).toString());
5518 JMenuItem fetchr = new JMenuItem(
5519 MessageManager.getString("label.standard_databases"));
5520 fetchr.setToolTipText(MessageManager
5521 .getString("label.fetch_embl_uniprot"));
5522 fetchr.addActionListener(new ActionListener()
5526 public void actionPerformed(ActionEvent e)
5528 new Thread(new Runnable()
5534 new jalview.ws.DBRefFetcher(alignPanel.av
5535 .getSequenceSelection(), alignPanel.alignFrame)
5536 .fetchDBRefs(false);
5544 final AlignFrame me = this;
5545 new Thread(new Runnable()
5550 final jalview.ws.SequenceFetcher sf = SequenceFetcher
5551 .getSequenceFetcherSingleton(me);
5552 javax.swing.SwingUtilities.invokeLater(new Runnable()
5557 String[] dbclasses = sf.getOrderedSupportedSources();
5558 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5559 // jalview.util.QuickSort.sort(otherdb, otherdb);
5560 List<DbSourceProxy> otherdb;
5561 JMenu dfetch = new JMenu();
5562 JMenu ifetch = new JMenu();
5563 JMenuItem fetchr = null;
5564 int comp = 0, icomp = 0, mcomp = 15;
5565 String mname = null;
5567 for (String dbclass : dbclasses)
5569 otherdb = sf.getSourceProxy(dbclass);
5570 // add a single entry for this class, or submenu allowing 'fetch
5572 if (otherdb == null || otherdb.size() < 1)
5576 // List<DbSourceProxy> dbs=otherdb;
5577 // otherdb=new ArrayList<DbSourceProxy>();
5578 // for (DbSourceProxy db:dbs)
5580 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5584 mname = "From " + dbclass;
5586 if (otherdb.size() == 1)
5588 final DbSourceProxy[] dassource = otherdb
5589 .toArray(new DbSourceProxy[0]);
5590 DbSourceProxy src = otherdb.get(0);
5591 fetchr = new JMenuItem(src.getDbSource());
5592 fetchr.addActionListener(new ActionListener()
5596 public void actionPerformed(ActionEvent e)
5598 new Thread(new Runnable()
5604 new jalview.ws.DBRefFetcher(alignPanel.av
5605 .getSequenceSelection(),
5606 alignPanel.alignFrame, dassource)
5607 .fetchDBRefs(false);
5613 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from", new Object[]{src.getDbName()})));
5619 final DbSourceProxy[] dassource = otherdb
5620 .toArray(new DbSourceProxy[0]);
5622 DbSourceProxy src = otherdb.get(0);
5623 fetchr = new JMenuItem(MessageManager.formatMessage(
5624 "label.fetch_all_param", new Object[]
5625 { src.getDbSource() }));
5626 fetchr.addActionListener(new ActionListener()
5629 public void actionPerformed(ActionEvent e)
5631 new Thread(new Runnable()
5637 new jalview.ws.DBRefFetcher(alignPanel.av
5638 .getSequenceSelection(),
5639 alignPanel.alignFrame, dassource)
5640 .fetchDBRefs(false);
5646 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from_all_sources", new Object[]{Integer.valueOf(otherdb.size()).toString(), src.getDbSource(), src.getDbName()})));
5649 // and then build the rest of the individual menus
5650 ifetch = new JMenu(MessageManager.formatMessage("label.source_from_db_source", new Object[]{src.getDbSource()}));
5652 String imname = null;
5654 for (DbSourceProxy sproxy : otherdb)
5656 String dbname = sproxy.getDbName();
5657 String sname = dbname.length() > 5 ? dbname.substring(0,
5658 5) + "..." : dbname;
5659 String msname = dbname.length() > 10 ? dbname.substring(
5660 0, 10) + "..." : dbname;
5663 imname = MessageManager.formatMessage("label.from_msname", new Object[]{sname});
5665 fetchr = new JMenuItem(msname);
5666 final DbSourceProxy[] dassrc =
5668 fetchr.addActionListener(new ActionListener()
5672 public void actionPerformed(ActionEvent e)
5674 new Thread(new Runnable()
5680 new jalview.ws.DBRefFetcher(alignPanel.av
5681 .getSequenceSelection(),
5682 alignPanel.alignFrame, dassrc)
5683 .fetchDBRefs(false);
5689 fetchr.setToolTipText("<html>"
5690 + MessageManager.formatMessage("label.fetch_retrieve_from", new Object[]{dbname}));
5693 if (++icomp >= mcomp || i == (otherdb.size()))
5695 ifetch.setText(MessageManager.formatMessage(
5696 "label.source_to_target", imname, sname));
5698 ifetch = new JMenu();
5706 if (comp >= mcomp || dbi >= (dbclasses.length))
5708 dfetch.setText(MessageManager.formatMessage(
5709 "label.source_to_target", mname, dbclass));
5711 dfetch = new JMenu();
5724 * Left justify the whole alignment.
5727 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5729 AlignmentI al = viewport.getAlignment();
5731 viewport.firePropertyChange("alignment", null, al);
5735 * Right justify the whole alignment.
5738 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5740 AlignmentI al = viewport.getAlignment();
5742 viewport.firePropertyChange("alignment", null, al);
5745 public void setShowSeqFeatures(boolean b)
5747 showSeqFeatures.setSelected(true);
5748 viewport.setShowSequenceFeatures(true);
5755 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5756 * awt.event.ActionEvent)
5759 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5761 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5762 alignPanel.paintAlignment(true);
5769 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5773 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5775 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5776 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5784 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5785 * .event.ActionEvent)
5788 protected void showGroupConservation_actionPerformed(ActionEvent e)
5790 viewport.setShowGroupConservation(showGroupConservation.getState());
5791 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5798 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5799 * .event.ActionEvent)
5802 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5804 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5805 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5812 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5813 * .event.ActionEvent)
5816 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5818 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5819 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5823 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5825 showSequenceLogo.setState(true);
5826 viewport.setShowSequenceLogo(true);
5827 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5828 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5832 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5834 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5841 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5842 * .event.ActionEvent)
5845 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5847 if (avc.makeGroupsFromSelection())
5849 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5850 alignPanel.updateAnnotation();
5851 alignPanel.paintAlignment(true);
5854 public void clearAlignmentSeqRep()
5856 // TODO refactor alignmentseqrep to controller
5857 if (viewport.getAlignment().hasSeqrep()) {
5858 viewport.getAlignment().setSeqrep(null);
5859 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5860 alignPanel.updateAnnotation();
5861 alignPanel.paintAlignment(true);
5866 protected void createGroup_actionPerformed(ActionEvent e)
5868 if (avc.createGroup())
5870 alignPanel.alignmentChanged();
5875 protected void unGroup_actionPerformed(ActionEvent e)
5879 alignPanel.alignmentChanged();
5884 * make the given alignmentPanel the currently selected tab
5886 * @param alignmentPanel
5888 public void setDisplayedView(AlignmentPanel alignmentPanel)
5890 if (!viewport.getSequenceSetId().equals(
5891 alignmentPanel.av.getSequenceSetId()))
5893 throw new Error(MessageManager.getString("error.implementation_error_cannot_show_view_alignment_frame"));
5895 if (tabbedPane != null
5896 & alignPanels.indexOf(alignmentPanel) != tabbedPane
5897 .getSelectedIndex())
5899 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5904 * Action on selection of menu options to Show or Hide annotations.
5907 * @param forSequences
5908 * update sequence-related annotations
5909 * @param forAlignment
5910 * update non-sequence-related annotations
5913 protected void setAnnotationsVisibility(boolean visible,
5914 boolean forSequences, boolean forAlignment)
5916 for (AlignmentAnnotation aa : alignPanel.getAlignment()
5917 .getAlignmentAnnotation())
5919 boolean apply = (aa.sequenceRef == null && forAlignment)
5920 || (aa.sequenceRef != null && forSequences);
5923 aa.visible = visible;
5926 alignPanel.validateAnnotationDimensions(false);
5927 alignPanel.alignmentChanged();
5931 * Store selected annotation sort order for the view and repaint.
5934 protected void sortAnnotations_actionPerformed()
5936 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5938 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5939 alignPanel.paintAlignment(true);
5944 * @return alignment panels in this alignment frame
5946 public List<? extends AlignmentViewPanel> getAlignPanels()
5948 return alignPanels == null ? Arrays.asList(alignPanel)
5953 * Open a new alignment window, with the cDNA associated with this (protein)
5954 * alignment, aligned as is the protein.
5957 protected void viewAsCdna_actionPerformed()
5959 final AlignmentI alignment = getViewport().getAlignment();
5960 Set<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5961 if (mappings == null)
5965 List<SequenceI> cdnaSeqs = new ArrayList<SequenceI>();
5966 for (SequenceI aaSeq : alignment.getSequences()) {
5967 for (AlignedCodonFrame acf : mappings) {
5968 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5972 * There is a cDNA mapping for this protein sequence - add to new
5973 * alignment. It will share the same dataset sequence as other mapped
5974 * cDNA (no new mappings need to be created).
5976 final Sequence newSeq = new Sequence(dnaSeq);
5977 newSeq.setDatasetSequence(dnaSeq);
5978 cdnaSeqs.add(newSeq);
5982 if (cdnaSeqs.size() == 0)
5984 // show a warning dialog no mapped cDNA
5987 AlignmentI cdna = new Alignment(cdnaSeqs.toArray(new SequenceI[cdnaSeqs
5989 AlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5990 AlignFrame.DEFAULT_HEIGHT);
5991 cdna.alignAs(alignment);
5992 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5994 Desktop.addInternalFrame(alignFrame, newtitle,
5995 AlignFrame.DEFAULT_WIDTH,
5996 AlignFrame.DEFAULT_HEIGHT);
6001 class PrintThread extends Thread
6005 public PrintThread(AlignmentPanel ap)
6010 static PageFormat pf;
6015 PrinterJob printJob = PrinterJob.getPrinterJob();
6019 printJob.setPrintable(ap, pf);
6023 printJob.setPrintable(ap);
6026 if (printJob.printDialog())
6031 } catch (Exception PrintException)
6033 PrintException.printStackTrace();