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.Conservation;
27 import jalview.analysis.CrossRef;
28 import jalview.analysis.NJTree;
29 import jalview.analysis.ParseProperties;
30 import jalview.analysis.SequenceIdMatcher;
31 import jalview.api.AlignViewControllerGuiI;
32 import jalview.api.AlignViewControllerI;
33 import jalview.api.AlignmentViewPanel;
34 import jalview.api.analysis.ScoreModelI;
35 import jalview.bin.Cache;
36 import jalview.commands.CommandI;
37 import jalview.commands.EditCommand;
38 import jalview.commands.EditCommand.Action;
39 import jalview.commands.OrderCommand;
40 import jalview.commands.RemoveGapColCommand;
41 import jalview.commands.RemoveGapsCommand;
42 import jalview.commands.SlideSequencesCommand;
43 import jalview.commands.TrimRegionCommand;
44 import jalview.datamodel.AlignedCodonFrame;
45 import jalview.datamodel.Alignment;
46 import jalview.datamodel.AlignmentAnnotation;
47 import jalview.datamodel.AlignmentI;
48 import jalview.datamodel.AlignmentOrder;
49 import jalview.datamodel.AlignmentView;
50 import jalview.datamodel.ColumnSelection;
51 import jalview.datamodel.PDBEntry;
52 import jalview.datamodel.SeqCigar;
53 import jalview.datamodel.Sequence;
54 import jalview.datamodel.SequenceGroup;
55 import jalview.datamodel.SequenceI;
56 import jalview.io.AlignmentProperties;
57 import jalview.io.AnnotationFile;
58 import jalview.io.FeaturesFile;
59 import jalview.io.FileLoader;
60 import jalview.io.FormatAdapter;
61 import jalview.io.HTMLOutput;
62 import jalview.io.IdentifyFile;
63 import jalview.io.JalviewFileChooser;
64 import jalview.io.JalviewFileView;
65 import jalview.io.JnetAnnotationMaker;
66 import jalview.io.NewickFile;
67 import jalview.io.TCoffeeScoreFile;
68 import jalview.jbgui.GAlignFrame;
69 import jalview.schemes.Blosum62ColourScheme;
70 import jalview.schemes.BuriedColourScheme;
71 import jalview.schemes.ClustalxColourScheme;
72 import jalview.schemes.ColourSchemeI;
73 import jalview.schemes.ColourSchemeProperty;
74 import jalview.schemes.HelixColourScheme;
75 import jalview.schemes.HydrophobicColourScheme;
76 import jalview.schemes.NucleotideColourScheme;
77 import jalview.schemes.PIDColourScheme;
78 import jalview.schemes.PurinePyrimidineColourScheme;
79 import jalview.schemes.RNAHelicesColourChooser;
80 import jalview.schemes.ResidueProperties;
81 import jalview.schemes.StrandColourScheme;
82 import jalview.schemes.TCoffeeColourScheme;
83 import jalview.schemes.TaylorColourScheme;
84 import jalview.schemes.TurnColourScheme;
85 import jalview.schemes.UserColourScheme;
86 import jalview.schemes.ZappoColourScheme;
87 import jalview.util.MessageManager;
88 import jalview.ws.jws1.Discoverer;
89 import jalview.ws.jws2.Jws2Discoverer;
90 import jalview.ws.jws2.jabaws2.Jws2Instance;
91 import jalview.ws.seqfetcher.DbSourceProxy;
93 import java.awt.BorderLayout;
94 import java.awt.Component;
95 import java.awt.GridLayout;
96 import java.awt.Rectangle;
97 import java.awt.Toolkit;
98 import java.awt.datatransfer.Clipboard;
99 import java.awt.datatransfer.DataFlavor;
100 import java.awt.datatransfer.StringSelection;
101 import java.awt.datatransfer.Transferable;
102 import java.awt.dnd.DnDConstants;
103 import java.awt.dnd.DropTargetDragEvent;
104 import java.awt.dnd.DropTargetDropEvent;
105 import java.awt.dnd.DropTargetEvent;
106 import java.awt.dnd.DropTargetListener;
107 import java.awt.event.ActionEvent;
108 import java.awt.event.ActionListener;
109 import java.awt.event.KeyAdapter;
110 import java.awt.event.KeyEvent;
111 import java.awt.event.MouseAdapter;
112 import java.awt.event.MouseEvent;
113 import java.awt.print.PageFormat;
114 import java.awt.print.PrinterJob;
115 import java.beans.PropertyChangeEvent;
118 import java.util.ArrayList;
119 import java.util.Arrays;
120 import java.util.Enumeration;
121 import java.util.Hashtable;
122 import java.util.List;
123 import java.util.Vector;
125 import javax.swing.JButton;
126 import javax.swing.JCheckBoxMenuItem;
127 import javax.swing.JEditorPane;
128 import javax.swing.JInternalFrame;
129 import javax.swing.JLabel;
130 import javax.swing.JLayeredPane;
131 import javax.swing.JMenu;
132 import javax.swing.JMenuItem;
133 import javax.swing.JOptionPane;
134 import javax.swing.JPanel;
135 import javax.swing.JProgressBar;
136 import javax.swing.JRadioButtonMenuItem;
137 import javax.swing.JScrollPane;
138 import javax.swing.SwingUtilities;
144 * @version $Revision$
146 public class AlignFrame extends GAlignFrame implements DropTargetListener,
147 IProgressIndicator, AlignViewControllerGuiI
151 public static final int DEFAULT_WIDTH = 700;
154 public static final int DEFAULT_HEIGHT = 500;
156 public AlignmentPanel alignPanel;
158 AlignViewport viewport;
160 public AlignViewControllerI avc;
162 Vector alignPanels = new Vector();
165 * Last format used to load or save alignments in this window
167 String currentFileFormat = null;
170 * Current filename for this alignment
172 String fileName = null;
175 * Creates a new AlignFrame object with specific width and height.
181 public AlignFrame(AlignmentI al, int width, int height)
183 this(al, null, width, height);
187 * Creates a new AlignFrame object with specific width, height and
193 * @param sequenceSetId
195 public AlignFrame(AlignmentI al, int width, int height,
196 String sequenceSetId)
198 this(al, null, width, height, sequenceSetId);
202 * Creates a new AlignFrame object with specific width, height and
208 * @param sequenceSetId
211 public AlignFrame(AlignmentI al, int width, int height,
212 String sequenceSetId, String viewId)
214 this(al, null, width, height, sequenceSetId, viewId);
218 * new alignment window with hidden columns
222 * @param hiddenColumns
223 * ColumnSelection or null
225 * Width of alignment frame
229 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
230 int width, int height)
232 this(al, hiddenColumns, width, height, null);
236 * Create alignment frame for al with hiddenColumns, a specific width and
237 * height, and specific sequenceId
240 * @param hiddenColumns
243 * @param sequenceSetId
246 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
247 int width, int height, String sequenceSetId)
249 this(al, hiddenColumns, width, height, sequenceSetId, null);
253 * Create alignment frame for al with hiddenColumns, a specific width and
254 * height, and specific sequenceId
257 * @param hiddenColumns
260 * @param sequenceSetId
265 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
266 int width, int height, String sequenceSetId, String viewId)
268 setSize(width, height);
270 if (al.getDataset() == null)
275 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
277 alignPanel = new AlignmentPanel(this, viewport);
280 addAlignmentPanel(alignPanel, true);
285 * Make a new AlignFrame from existing alignmentPanels
292 public AlignFrame(AlignmentPanel ap)
296 addAlignmentPanel(ap, false);
301 * initalise the alignframe from the underlying viewport data and the
306 avc = new jalview.controller.AlignViewController(this, viewport,
308 if (viewport.getAlignmentConservationAnnotation() == null)
310 BLOSUM62Colour.setEnabled(false);
311 conservationMenuItem.setEnabled(false);
312 modifyConservation.setEnabled(false);
313 // PIDColour.setEnabled(false);
314 // abovePIDThreshold.setEnabled(false);
315 // modifyPID.setEnabled(false);
318 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
321 if (sortby.equals("Id"))
323 sortIDMenuItem_actionPerformed(null);
325 else if (sortby.equals("Pairwise Identity"))
327 sortPairwiseMenuItem_actionPerformed(null);
330 if (Desktop.desktop != null)
332 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
333 addServiceListeners();
334 setGUINucleotide(viewport.getAlignment().isNucleotide());
337 setMenusFromViewport(viewport);
338 buildSortByAnnotationScoresMenu();
341 if (viewport.wrapAlignment)
343 wrapMenuItem_actionPerformed(null);
346 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
348 this.overviewMenuItem_actionPerformed(null);
356 * Change the filename and format for the alignment, and enable the 'reload'
357 * button functionality.
364 public void setFileName(String file, String format)
367 currentFileFormat = format;
368 reload.setEnabled(true);
371 void addKeyListener()
373 addKeyListener(new KeyAdapter()
376 public void keyPressed(KeyEvent evt)
378 if (viewport.cursorMode
379 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
380 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
381 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
382 && Character.isDigit(evt.getKeyChar()))
384 alignPanel.seqPanel.numberPressed(evt.getKeyChar());
387 switch (evt.getKeyCode())
390 case 27: // escape key
391 deselectAllSequenceMenuItem_actionPerformed(null);
395 case KeyEvent.VK_DOWN:
396 if (evt.isAltDown() || !viewport.cursorMode)
398 moveSelectedSequences(false);
400 if (viewport.cursorMode)
402 alignPanel.seqPanel.moveCursor(0, 1);
407 if (evt.isAltDown() || !viewport.cursorMode)
409 moveSelectedSequences(true);
411 if (viewport.cursorMode)
413 alignPanel.seqPanel.moveCursor(0, -1);
418 case KeyEvent.VK_LEFT:
419 if (evt.isAltDown() || !viewport.cursorMode)
421 slideSequences(false, alignPanel.seqPanel.getKeyboardNo1());
425 alignPanel.seqPanel.moveCursor(-1, 0);
430 case KeyEvent.VK_RIGHT:
431 if (evt.isAltDown() || !viewport.cursorMode)
433 slideSequences(true, alignPanel.seqPanel.getKeyboardNo1());
437 alignPanel.seqPanel.moveCursor(1, 0);
441 case KeyEvent.VK_SPACE:
442 if (viewport.cursorMode)
444 alignPanel.seqPanel.insertGapAtCursor(evt.isControlDown()
445 || evt.isShiftDown() || evt.isAltDown());
449 // case KeyEvent.VK_A:
450 // if (viewport.cursorMode)
452 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
453 // //System.out.println("A");
457 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
458 * System.out.println("closing bracket"); } break;
460 case KeyEvent.VK_DELETE:
461 case KeyEvent.VK_BACK_SPACE:
462 if (!viewport.cursorMode)
464 cut_actionPerformed(null);
468 alignPanel.seqPanel.deleteGapAtCursor(evt.isControlDown()
469 || evt.isShiftDown() || evt.isAltDown());
475 if (viewport.cursorMode)
477 alignPanel.seqPanel.setCursorRow();
481 if (viewport.cursorMode && !evt.isControlDown())
483 alignPanel.seqPanel.setCursorColumn();
487 if (viewport.cursorMode)
489 alignPanel.seqPanel.setCursorPosition();
493 case KeyEvent.VK_ENTER:
494 case KeyEvent.VK_COMMA:
495 if (viewport.cursorMode)
497 alignPanel.seqPanel.setCursorRowAndColumn();
502 if (viewport.cursorMode)
504 alignPanel.seqPanel.setSelectionAreaAtCursor(true);
508 if (viewport.cursorMode)
510 alignPanel.seqPanel.setSelectionAreaAtCursor(false);
515 viewport.cursorMode = !viewport.cursorMode;
516 statusBar.setText(MessageManager.formatMessage(
517 "label.keyboard_editing_mode", new String[]
518 { (viewport.cursorMode ? "on" : "off") }));
519 if (viewport.cursorMode)
521 alignPanel.seqPanel.seqCanvas.cursorX = viewport.startRes;
522 alignPanel.seqPanel.seqCanvas.cursorY = viewport.startSeq;
524 alignPanel.seqPanel.seqCanvas.repaint();
530 Help.showHelpWindow();
531 } catch (Exception ex)
533 ex.printStackTrace();
538 boolean toggleSeqs = !evt.isControlDown();
539 boolean toggleCols = !evt.isShiftDown();
540 toggleHiddenRegions(toggleSeqs, toggleCols);
543 case KeyEvent.VK_PAGE_UP:
544 if (viewport.wrapAlignment)
546 alignPanel.scrollUp(true);
550 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
551 - viewport.endSeq + viewport.startSeq);
554 case KeyEvent.VK_PAGE_DOWN:
555 if (viewport.wrapAlignment)
557 alignPanel.scrollUp(false);
561 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
562 + viewport.endSeq - viewport.startSeq);
569 public void keyReleased(KeyEvent evt)
571 switch (evt.getKeyCode())
573 case KeyEvent.VK_LEFT:
574 if (evt.isAltDown() || !viewport.cursorMode)
576 viewport.firePropertyChange("alignment", null, viewport
577 .getAlignment().getSequences());
581 case KeyEvent.VK_RIGHT:
582 if (evt.isAltDown() || !viewport.cursorMode)
584 viewport.firePropertyChange("alignment", null, viewport
585 .getAlignment().getSequences());
593 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
595 ap.alignFrame = this;
596 avc = new jalview.controller.AlignViewController(this, viewport,
599 alignPanels.addElement(ap);
601 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
603 int aSize = alignPanels.size();
605 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
607 if (aSize == 1 && ap.av.viewName == null)
609 this.getContentPane().add(ap, BorderLayout.CENTER);
615 setInitialTabVisible();
618 expandViews.setEnabled(true);
619 gatherViews.setEnabled(true);
620 tabbedPane.addTab(ap.av.viewName, ap);
622 ap.setVisible(false);
627 if (ap.av.isPadGaps())
629 ap.av.getAlignment().padGaps();
631 ap.av.updateConservation(ap);
632 ap.av.updateConsensus(ap);
633 ap.av.updateStrucConsensus(ap);
637 public void setInitialTabVisible()
639 expandViews.setEnabled(true);
640 gatherViews.setEnabled(true);
641 tabbedPane.setVisible(true);
642 AlignmentPanel first = (AlignmentPanel) alignPanels.firstElement();
643 tabbedPane.addTab(first.av.viewName, first);
644 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
647 public AlignViewport getViewport()
652 /* Set up intrinsic listeners for dynamically generated GUI bits. */
653 private void addServiceListeners()
655 final java.beans.PropertyChangeListener thisListener;
656 Desktop.instance.addJalviewPropertyChangeListener("services",
657 thisListener = new java.beans.PropertyChangeListener()
660 public void propertyChange(PropertyChangeEvent evt)
662 // // System.out.println("Discoverer property change.");
663 // if (evt.getPropertyName().equals("services"))
665 SwingUtilities.invokeLater(new Runnable()
672 .println("Rebuild WS Menu for service change");
673 BuildWebServiceMenu();
680 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
683 public void internalFrameClosed(
684 javax.swing.event.InternalFrameEvent evt)
686 System.out.println("deregistering discoverer listener");
687 Desktop.instance.removeJalviewPropertyChangeListener("services",
689 closeMenuItem_actionPerformed(true);
692 // Finally, build the menu once to get current service state
693 new Thread(new Runnable()
698 BuildWebServiceMenu();
703 public void setGUINucleotide(boolean nucleotide)
705 showTranslation.setVisible(nucleotide);
706 conservationMenuItem.setEnabled(!nucleotide);
707 modifyConservation.setEnabled(!nucleotide);
708 showGroupConservation.setEnabled(!nucleotide);
709 rnahelicesColour.setEnabled(nucleotide);
710 purinePyrimidineColour.setEnabled(nucleotide);
711 // Remember AlignFrame always starts as protein
715 // calculateMenu.remove(calculateMenu.getItemCount() - 2);
720 * set up menus for the currently viewport. This may be called after any
721 * operation that affects the data in the current view (selection changed,
722 * etc) to update the menus to reflect the new state.
724 public void setMenusForViewport()
726 setMenusFromViewport(viewport);
730 * Need to call this method when tabs are selected for multiple views, or when
731 * loading from Jalview2XML.java
736 void setMenusFromViewport(AlignViewport av)
738 padGapsMenuitem.setSelected(av.isPadGaps());
739 colourTextMenuItem.setSelected(av.showColourText);
740 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
741 conservationMenuItem.setSelected(av.getConservationSelected());
742 seqLimits.setSelected(av.getShowJVSuffix());
743 idRightAlign.setSelected(av.rightAlignIds);
744 centreColumnLabelsMenuItem.setState(av.centreColumnLabels);
745 renderGapsMenuItem.setSelected(av.renderGaps);
746 wrapMenuItem.setSelected(av.wrapAlignment);
747 scaleAbove.setVisible(av.wrapAlignment);
748 scaleLeft.setVisible(av.wrapAlignment);
749 scaleRight.setVisible(av.wrapAlignment);
750 annotationPanelMenuItem.setState(av.showAnnotation);
752 * Show/hide annotations only enabled if annotation panel is shown
754 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
755 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
756 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
757 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
758 viewBoxesMenuItem.setSelected(av.showBoxes);
759 viewTextMenuItem.setSelected(av.showText);
760 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
761 showGroupConsensus.setSelected(av.isShowGroupConsensus());
762 showGroupConservation.setSelected(av.isShowGroupConservation());
763 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
764 showSequenceLogo.setSelected(av.isShowSequenceLogo());
765 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
767 setColourSelected(ColourSchemeProperty.getColourName(av
768 .getGlobalColourScheme()));
770 showSeqFeatures.setSelected(av.showSequenceFeatures);
771 hiddenMarkers.setState(av.showHiddenMarkers);
772 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
773 showNpFeatsMenuitem.setSelected(av.isShowNpFeats());
774 showDbRefsMenuitem.setSelected(av.isShowDbRefs());
775 autoCalculate.setSelected(av.autoCalculateConsensus);
776 sortByTree.setSelected(av.sortByTree);
777 listenToViewSelections.setSelected(av.followSelection);
778 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
780 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
781 setShowProductsEnabled();
785 // methods for implementing IProgressIndicator
786 // need to refactor to a reusable stub class
787 Hashtable progressBars, progressBarHandlers;
792 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
795 public void setProgressBar(String message, long id)
797 if (progressBars == null)
799 progressBars = new Hashtable();
800 progressBarHandlers = new Hashtable();
803 JPanel progressPanel;
804 Long lId = new Long(id);
805 GridLayout layout = (GridLayout) statusPanel.getLayout();
806 if (progressBars.get(lId) != null)
808 progressPanel = (JPanel) progressBars.get(new Long(id));
809 statusPanel.remove(progressPanel);
810 progressBars.remove(lId);
811 progressPanel = null;
814 statusBar.setText(message);
816 if (progressBarHandlers.contains(lId))
818 progressBarHandlers.remove(lId);
820 layout.setRows(layout.getRows() - 1);
824 progressPanel = new JPanel(new BorderLayout(10, 5));
826 JProgressBar progressBar = new JProgressBar();
827 progressBar.setIndeterminate(true);
829 progressPanel.add(new JLabel(message), BorderLayout.WEST);
830 progressPanel.add(progressBar, BorderLayout.CENTER);
832 layout.setRows(layout.getRows() + 1);
833 statusPanel.add(progressPanel);
835 progressBars.put(lId, progressPanel);
838 // setMenusForViewport();
843 public void registerHandler(final long id,
844 final IProgressIndicatorHandler handler)
846 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
848 throw new Error(MessageManager.getString("error.call_setprogressbar_before_registering_handler"));
850 progressBarHandlers.put(new Long(id), handler);
851 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
852 if (handler.canCancel())
854 JButton cancel = new JButton(
855 MessageManager.getString("action.cancel"));
856 final IProgressIndicator us = this;
857 cancel.addActionListener(new ActionListener()
861 public void actionPerformed(ActionEvent e)
863 handler.cancelActivity(id);
864 us.setProgressBar(MessageManager.formatMessage("label.cancelled_params", new String[]{((JLabel) progressPanel.getComponent(0)).getText()}), id);
867 progressPanel.add(cancel, BorderLayout.EAST);
873 * @return true if any progress bars are still active
876 public boolean operationInProgress()
878 if (progressBars != null && progressBars.size() > 0)
886 public void setStatus(String text)
888 statusBar.setText(text);
892 * Added so Castor Mapping file can obtain Jalview Version
894 public String getVersion()
896 return jalview.bin.Cache.getProperty("VERSION");
899 public FeatureRenderer getFeatureRenderer()
901 return alignPanel.seqPanel.seqCanvas.getFeatureRenderer();
905 public void fetchSequence_actionPerformed(ActionEvent e)
907 new SequenceFetcher(this);
911 public void addFromFile_actionPerformed(ActionEvent e)
913 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
917 public void reload_actionPerformed(ActionEvent e)
919 if (fileName != null)
921 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
922 // originating file's format
923 // TODO: work out how to recover feature settings for correct view(s) when
925 if (currentFileFormat.equals("Jalview"))
927 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
928 for (int i = 0; i < frames.length; i++)
930 if (frames[i] instanceof AlignFrame && frames[i] != this
931 && ((AlignFrame) frames[i]).fileName != null
932 && ((AlignFrame) frames[i]).fileName.equals(fileName))
936 frames[i].setSelected(true);
937 Desktop.instance.closeAssociatedWindows();
938 } catch (java.beans.PropertyVetoException ex)
944 Desktop.instance.closeAssociatedWindows();
946 FileLoader loader = new FileLoader();
947 String protocol = fileName.startsWith("http:") ? "URL" : "File";
948 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
952 Rectangle bounds = this.getBounds();
954 FileLoader loader = new FileLoader();
955 String protocol = fileName.startsWith("http:") ? "URL" : "File";
956 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
957 protocol, currentFileFormat);
959 newframe.setBounds(bounds);
960 if (featureSettings != null && featureSettings.isShowing())
962 final Rectangle fspos = featureSettings.frame.getBounds();
963 // TODO: need a 'show feature settings' function that takes bounds -
964 // need to refactor Desktop.addFrame
965 newframe.featureSettings_actionPerformed(null);
966 final FeatureSettings nfs = newframe.featureSettings;
967 SwingUtilities.invokeLater(new Runnable()
972 nfs.frame.setBounds(fspos);
975 this.featureSettings.close();
976 this.featureSettings = null;
978 this.closeMenuItem_actionPerformed(true);
984 public void addFromText_actionPerformed(ActionEvent e)
986 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
990 public void addFromURL_actionPerformed(ActionEvent e)
992 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
996 public void save_actionPerformed(ActionEvent e)
999 || (currentFileFormat == null || !jalview.io.FormatAdapter
1000 .isValidIOFormat(currentFileFormat, true))
1001 || fileName.startsWith("http"))
1003 saveAs_actionPerformed(null);
1007 saveAlignment(fileName, currentFileFormat);
1018 public void saveAs_actionPerformed(ActionEvent e)
1020 JalviewFileChooser chooser = new JalviewFileChooser(
1021 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
1022 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
1023 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
1024 currentFileFormat, false);
1026 chooser.setFileView(new JalviewFileView());
1027 chooser.setDialogTitle(MessageManager.getString("label.save_alignment_to_file"));
1028 chooser.setToolTipText(MessageManager.getString("action.save"));
1030 int value = chooser.showSaveDialog(this);
1032 if (value == JalviewFileChooser.APPROVE_OPTION)
1034 currentFileFormat = chooser.getSelectedFormat();
1035 if (currentFileFormat == null)
1038 .showInternalMessageDialog(
1041 .getString("label.select_file_format_before_saving"),
1043 .getString("label.file_format_not_specified"),
1044 JOptionPane.WARNING_MESSAGE);
1045 value = chooser.showSaveDialog(this);
1049 fileName = chooser.getSelectedFile().getPath();
1051 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
1054 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
1055 if (currentFileFormat.indexOf(" ") > -1)
1057 currentFileFormat = currentFileFormat.substring(0,
1058 currentFileFormat.indexOf(" "));
1060 saveAlignment(fileName, currentFileFormat);
1064 public boolean saveAlignment(String file, String format)
1066 boolean success = true;
1068 if (format.equalsIgnoreCase("Jalview"))
1070 String shortName = title;
1072 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1074 shortName = shortName.substring(shortName
1075 .lastIndexOf(java.io.File.separatorChar) + 1);
1078 success = new Jalview2XML().SaveAlignment(this, file, shortName);
1080 statusBar.setText(MessageManager.formatMessage(
1081 "label.successfully_saved_to_file_in_format", new String[]
1082 { fileName, format }));
1087 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1089 warningMessage("Cannot save file " + fileName + " using format "
1090 + format, "Alignment output format not supported");
1091 saveAs_actionPerformed(null);
1092 // JBPNote need to have a raise_gui flag here
1096 String[] omitHidden = null;
1098 if (viewport.hasHiddenColumns())
1100 int reply = JOptionPane
1101 .showInternalConfirmDialog(
1104 .getString("label.alignment_contains_hidden_columns"),
1106 .getString("action.save_omit_hidden_columns"),
1107 JOptionPane.YES_NO_OPTION,
1108 JOptionPane.QUESTION_MESSAGE);
1110 if (reply == JOptionPane.YES_OPTION)
1112 omitHidden = viewport.getViewAsString(false);
1115 FormatAdapter f = new FormatAdapter();
1116 String output = f.formatSequences(format,
1117 viewport.getAlignment(), // class cast exceptions will
1118 // occur in the distant future
1119 omitHidden, f.getCacheSuffixDefault(format),
1120 viewport.getColumnSelection());
1130 java.io.PrintWriter out = new java.io.PrintWriter(
1131 new java.io.FileWriter(file));
1135 this.setTitle(file);
1136 statusBar.setText(MessageManager.formatMessage(
1137 "label.successfully_saved_to_file_in_format",
1139 { fileName, format }));
1140 } catch (Exception ex)
1143 ex.printStackTrace();
1150 JOptionPane.showInternalMessageDialog(this, MessageManager
1151 .formatMessage("label.couldnt_save_file", new String[]
1152 { fileName }), MessageManager
1153 .getString("label.error_saving_file"),
1154 JOptionPane.WARNING_MESSAGE);
1160 private void warningMessage(String warning, String title)
1162 if (new jalview.util.Platform().isHeadless())
1164 System.err.println("Warning: " + title + "\nWarning: " + warning);
1169 JOptionPane.showInternalMessageDialog(this, warning, title,
1170 JOptionPane.WARNING_MESSAGE);
1182 protected void outputText_actionPerformed(ActionEvent e)
1184 String[] omitHidden = null;
1186 if (viewport.hasHiddenColumns())
1188 int reply = JOptionPane
1189 .showInternalConfirmDialog(
1192 .getString("label.alignment_contains_hidden_columns"),
1194 .getString("action.save_omit_hidden_columns"),
1195 JOptionPane.YES_NO_OPTION,
1196 JOptionPane.QUESTION_MESSAGE);
1198 if (reply == JOptionPane.YES_OPTION)
1200 omitHidden = viewport.getViewAsString(false);
1204 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1205 cap.setForInput(null);
1209 cap.setText(new FormatAdapter().formatSequences(e.getActionCommand(),
1210 viewport.getAlignment(), omitHidden,
1211 viewport.getColumnSelection()));
1212 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1213 "label.alignment_output_command", new String[]
1214 { e.getActionCommand() }), 600, 500);
1215 } catch (OutOfMemoryError oom)
1217 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1230 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1232 new HTMLOutput(alignPanel,
1233 alignPanel.seqPanel.seqCanvas.getSequenceRenderer(),
1234 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
1237 public void createImageMap(File file, String image)
1239 alignPanel.makePNGImageMap(file, image);
1249 public void createPNG(File f)
1251 alignPanel.makePNG(f);
1261 public void createEPS(File f)
1263 alignPanel.makeEPS(f);
1266 public void createSVG(File f)
1268 alignPanel.makeSVG(f);
1271 public void pageSetup_actionPerformed(ActionEvent e)
1273 PrinterJob printJob = PrinterJob.getPrinterJob();
1274 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1284 public void printMenuItem_actionPerformed(ActionEvent e)
1286 // Putting in a thread avoids Swing painting problems
1287 PrintThread thread = new PrintThread(alignPanel);
1292 public void exportFeatures_actionPerformed(ActionEvent e)
1294 new AnnotationExporter().exportFeatures(alignPanel);
1298 public void exportAnnotations_actionPerformed(ActionEvent e)
1300 new AnnotationExporter().exportAnnotations(alignPanel,
1301 viewport.showAnnotation ? viewport.getAlignment()
1302 .getAlignmentAnnotation() : null, viewport
1303 .getAlignment().getGroups(), ((Alignment) viewport
1304 .getAlignment()).alignmentProperties);
1308 public void associatedData_actionPerformed(ActionEvent e)
1310 // Pick the tree file
1311 JalviewFileChooser chooser = new JalviewFileChooser(
1312 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1313 chooser.setFileView(new JalviewFileView());
1314 chooser.setDialogTitle(MessageManager
1315 .getString("label.load_jalview_annotations"));
1316 chooser.setToolTipText(MessageManager
1317 .getString("label.load_jalview_annotations"));
1319 int value = chooser.showOpenDialog(null);
1321 if (value == JalviewFileChooser.APPROVE_OPTION)
1323 String choice = chooser.getSelectedFile().getPath();
1324 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1325 loadJalviewDataFile(choice, null, null, null);
1331 * Close the current view or all views in the alignment frame. If the frame
1332 * only contains one view then the alignment will be removed from memory.
1334 * @param closeAllTabs
1337 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1339 if (alignPanels != null && alignPanels.size() < 2)
1341 closeAllTabs = true;
1346 if (alignPanels != null)
1350 if (this.isClosed())
1352 // really close all the windows - otherwise wait till
1353 // setClosed(true) is called
1354 for (int i = 0; i < alignPanels.size(); i++)
1356 AlignmentPanel ap = (AlignmentPanel) alignPanels.elementAt(i);
1363 closeView(alignPanel);
1369 this.setClosed(true);
1371 } catch (Exception ex)
1373 ex.printStackTrace();
1378 * close alignPanel2 and shuffle tabs appropriately.
1380 * @param alignPanel2
1382 public void closeView(AlignmentPanel alignPanel2)
1384 int index = tabbedPane.getSelectedIndex();
1385 int closedindex = tabbedPane.indexOfComponent(alignPanel2);
1386 alignPanels.removeElement(alignPanel2);
1388 // if (viewport == alignPanel2.av)
1392 alignPanel2.closePanel();
1395 tabbedPane.removeTabAt(closedindex);
1396 tabbedPane.validate();
1398 if (index > closedindex || index == tabbedPane.getTabCount())
1400 // modify currently selected tab index if necessary.
1404 this.tabSelectionChanged(index);
1410 void updateEditMenuBar()
1413 if (viewport.historyList.size() > 0)
1415 undoMenuItem.setEnabled(true);
1416 CommandI command = viewport.historyList.peek();
1417 undoMenuItem.setText(MessageManager.formatMessage(
1418 "label.undo_command", new String[]
1419 { command.getDescription() }));
1423 undoMenuItem.setEnabled(false);
1424 undoMenuItem.setText(MessageManager.getString("action.undo"));
1427 if (viewport.redoList.size() > 0)
1429 redoMenuItem.setEnabled(true);
1431 CommandI command = viewport.redoList.peek();
1432 redoMenuItem.setText(MessageManager.formatMessage(
1433 "label.redo_command", new String[]
1434 { command.getDescription() }));
1438 redoMenuItem.setEnabled(false);
1439 redoMenuItem.setText(MessageManager.getString("action.redo"));
1443 public void addHistoryItem(CommandI command)
1445 if (command.getSize() > 0)
1447 viewport.historyList.push(command);
1448 viewport.redoList.clear();
1449 updateEditMenuBar();
1450 viewport.updateHiddenColumns();
1451 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1452 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1453 // viewport.getColumnSelection()
1454 // .getHiddenColumns().size() > 0);
1460 * @return alignment objects for all views
1462 AlignmentI[] getViewAlignments()
1464 if (alignPanels != null)
1466 Enumeration e = alignPanels.elements();
1467 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1468 for (int i = 0; e.hasMoreElements(); i++)
1470 als[i] = ((AlignmentPanel) e.nextElement()).av.getAlignment();
1474 if (viewport != null)
1476 return new AlignmentI[]
1477 { viewport.getAlignment() };
1489 protected void undoMenuItem_actionPerformed(ActionEvent e)
1491 if (viewport.historyList.empty())
1495 CommandI command = viewport.historyList.pop();
1496 viewport.redoList.push(command);
1497 command.undoCommand(getViewAlignments());
1499 AlignViewport originalSource = getOriginatingSource(command);
1500 updateEditMenuBar();
1502 if (originalSource != null)
1504 if (originalSource != viewport)
1507 .warn("Implementation worry: mismatch of viewport origin for undo");
1509 originalSource.updateHiddenColumns();
1510 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1512 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1513 // viewport.getColumnSelection()
1514 // .getHiddenColumns().size() > 0);
1515 originalSource.firePropertyChange("alignment", null, originalSource
1516 .getAlignment().getSequences());
1527 protected void redoMenuItem_actionPerformed(ActionEvent e)
1529 if (viewport.redoList.size() < 1)
1534 CommandI command = viewport.redoList.pop();
1535 viewport.historyList.push(command);
1536 command.doCommand(getViewAlignments());
1538 AlignViewport originalSource = getOriginatingSource(command);
1539 updateEditMenuBar();
1541 if (originalSource != null)
1544 if (originalSource != viewport)
1547 .warn("Implementation worry: mismatch of viewport origin for redo");
1549 originalSource.updateHiddenColumns();
1550 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1552 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1553 // viewport.getColumnSelection()
1554 // .getHiddenColumns().size() > 0);
1555 originalSource.firePropertyChange("alignment", null, originalSource
1556 .getAlignment().getSequences());
1560 AlignViewport getOriginatingSource(CommandI command)
1562 AlignViewport originalSource = null;
1563 // For sequence removal and addition, we need to fire
1564 // the property change event FROM the viewport where the
1565 // original alignment was altered
1566 AlignmentI al = null;
1567 if (command instanceof EditCommand)
1569 EditCommand editCommand = (EditCommand) command;
1570 al = editCommand.getAlignment();
1571 Vector comps = (Vector) PaintRefresher.components.get(viewport
1572 .getSequenceSetId());
1574 for (int i = 0; i < comps.size(); i++)
1576 if (comps.elementAt(i) instanceof AlignmentPanel)
1578 if (al == ((AlignmentPanel) comps.elementAt(i)).av.getAlignment())
1580 originalSource = ((AlignmentPanel) comps.elementAt(i)).av;
1587 if (originalSource == null)
1589 // The original view is closed, we must validate
1590 // the current view against the closed view first
1593 PaintRefresher.validateSequences(al, viewport.getAlignment());
1596 originalSource = viewport;
1599 return originalSource;
1608 public void moveSelectedSequences(boolean up)
1610 SequenceGroup sg = viewport.getSelectionGroup();
1616 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1617 viewport.getHiddenRepSequences(), up);
1618 alignPanel.paintAlignment(true);
1621 synchronized void slideSequences(boolean right, int size)
1623 List<SequenceI> sg = new Vector();
1624 if (viewport.cursorMode)
1626 sg.add(viewport.getAlignment().getSequenceAt(
1627 alignPanel.seqPanel.seqCanvas.cursorY));
1629 else if (viewport.getSelectionGroup() != null
1630 && viewport.getSelectionGroup().getSize() != viewport
1631 .getAlignment().getHeight())
1633 sg = viewport.getSelectionGroup().getSequences(
1634 viewport.getHiddenRepSequences());
1642 Vector invertGroup = new Vector();
1644 for (int i = 0; i < viewport.getAlignment().getHeight(); i++)
1646 if (!sg.contains(viewport.getAlignment().getSequenceAt(i)))
1648 invertGroup.add(viewport.getAlignment().getSequenceAt(i));
1652 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1654 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1655 for (int i = 0; i < invertGroup.size(); i++)
1657 seqs2[i] = (SequenceI) invertGroup.elementAt(i);
1660 SlideSequencesCommand ssc;
1663 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1664 size, viewport.getGapCharacter());
1668 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1669 size, viewport.getGapCharacter());
1672 int groupAdjustment = 0;
1673 if (ssc.getGapsInsertedBegin() && right)
1675 if (viewport.cursorMode)
1677 alignPanel.seqPanel.moveCursor(size, 0);
1681 groupAdjustment = size;
1684 else if (!ssc.getGapsInsertedBegin() && !right)
1686 if (viewport.cursorMode)
1688 alignPanel.seqPanel.moveCursor(-size, 0);
1692 groupAdjustment = -size;
1696 if (groupAdjustment != 0)
1698 viewport.getSelectionGroup().setStartRes(
1699 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1700 viewport.getSelectionGroup().setEndRes(
1701 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1704 boolean appendHistoryItem = false;
1705 if (viewport.historyList != null && viewport.historyList.size() > 0
1706 && viewport.historyList.peek() instanceof SlideSequencesCommand)
1708 appendHistoryItem = ssc
1709 .appendSlideCommand((SlideSequencesCommand) viewport.historyList
1713 if (!appendHistoryItem)
1715 addHistoryItem(ssc);
1728 protected void copy_actionPerformed(ActionEvent e)
1731 if (viewport.getSelectionGroup() == null)
1735 // TODO: preserve the ordering of displayed alignment annotation in any
1736 // internal paste (particularly sequence associated annotation)
1737 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1738 String[] omitHidden = null;
1740 if (viewport.hasHiddenColumns())
1742 omitHidden = viewport.getViewAsString(true);
1745 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1748 StringSelection ss = new StringSelection(output);
1752 jalview.gui.Desktop.internalCopy = true;
1753 // Its really worth setting the clipboard contents
1754 // to empty before setting the large StringSelection!!
1755 Toolkit.getDefaultToolkit().getSystemClipboard()
1756 .setContents(new StringSelection(""), null);
1758 Toolkit.getDefaultToolkit().getSystemClipboard()
1759 .setContents(ss, Desktop.instance);
1760 } catch (OutOfMemoryError er)
1762 new OOMWarning("copying region", er);
1766 Vector hiddenColumns = null;
1767 if (viewport.hasHiddenColumns())
1769 hiddenColumns = new Vector();
1770 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1771 .getSelectionGroup().getEndRes();
1772 for (int i = 0; i < viewport.getColumnSelection().getHiddenColumns()
1775 int[] region = (int[]) viewport.getColumnSelection()
1776 .getHiddenColumns().elementAt(i);
1777 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1779 hiddenColumns.addElement(new int[]
1780 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1785 Desktop.jalviewClipboard = new Object[]
1786 { seqs, viewport.getAlignment().getDataset(), hiddenColumns };
1787 statusBar.setText(MessageManager.formatMessage(
1788 "label.copied_sequences_to_clipboard", new String[]
1789 { Integer.valueOf(seqs.length).toString() }));
1799 protected void pasteNew_actionPerformed(ActionEvent e)
1811 protected void pasteThis_actionPerformed(ActionEvent e)
1817 * Paste contents of Jalview clipboard
1819 * @param newAlignment
1820 * true to paste to a new alignment, otherwise add to this.
1822 void paste(boolean newAlignment)
1824 boolean externalPaste = true;
1827 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1828 Transferable contents = c.getContents(this);
1830 if (contents == null)
1838 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1839 if (str.length() < 1)
1844 format = new IdentifyFile().Identify(str, "Paste");
1846 } catch (OutOfMemoryError er)
1848 new OOMWarning("Out of memory pasting sequences!!", er);
1852 SequenceI[] sequences;
1853 boolean annotationAdded = false;
1854 AlignmentI alignment = null;
1856 if (Desktop.jalviewClipboard != null)
1858 // The clipboard was filled from within Jalview, we must use the
1860 // And dataset from the copied alignment
1861 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1862 // be doubly sure that we create *new* sequence objects.
1863 sequences = new SequenceI[newseq.length];
1864 for (int i = 0; i < newseq.length; i++)
1866 sequences[i] = new Sequence(newseq[i]);
1868 alignment = new Alignment(sequences);
1869 externalPaste = false;
1873 // parse the clipboard as an alignment.
1874 alignment = new FormatAdapter().readFile(str, "Paste", format);
1875 sequences = alignment.getSequencesArray();
1879 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1885 if (Desktop.jalviewClipboard != null)
1887 // dataset is inherited
1888 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1892 // new dataset is constructed
1893 alignment.setDataset(null);
1895 alwidth = alignment.getWidth() + 1;
1899 AlignmentI pastedal = alignment; // preserve pasted alignment object
1900 // Add pasted sequences and dataset into existing alignment.
1901 alignment = viewport.getAlignment();
1902 alwidth = alignment.getWidth() + 1;
1903 // decide if we need to import sequences from an existing dataset
1904 boolean importDs = Desktop.jalviewClipboard != null
1905 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1906 // importDs==true instructs us to copy over new dataset sequences from
1907 // an existing alignment
1908 Vector newDs = (importDs) ? new Vector() : null; // used to create
1909 // minimum dataset set
1911 for (int i = 0; i < sequences.length; i++)
1915 newDs.addElement(null);
1917 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
1919 if (importDs && ds != null)
1921 if (!newDs.contains(ds))
1923 newDs.setElementAt(ds, i);
1924 ds = new Sequence(ds);
1925 // update with new dataset sequence
1926 sequences[i].setDatasetSequence(ds);
1930 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
1935 // copy and derive new dataset sequence
1936 sequences[i] = sequences[i].deriveSequence();
1937 alignment.getDataset().addSequence(
1938 sequences[i].getDatasetSequence());
1939 // TODO: avoid creation of duplicate dataset sequences with a
1940 // 'contains' method using SequenceI.equals()/SequenceI.contains()
1942 alignment.addSequence(sequences[i]); // merges dataset
1946 newDs.clear(); // tidy up
1948 if (alignment.getAlignmentAnnotation() != null)
1950 for (AlignmentAnnotation alan : alignment
1951 .getAlignmentAnnotation())
1953 if (alan.graphGroup > fgroup)
1955 fgroup = alan.graphGroup;
1959 if (pastedal.getAlignmentAnnotation() != null)
1961 // Add any annotation attached to alignment.
1962 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
1963 for (int i = 0; i < alann.length; i++)
1965 annotationAdded = true;
1966 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
1968 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
1969 if (newann.graphGroup > -1)
1971 if (newGraphGroups.size() <= newann.graphGroup
1972 || newGraphGroups.get(newann.graphGroup) == null)
1974 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
1976 newGraphGroups.add(q, null);
1978 newGraphGroups.set(newann.graphGroup, new Integer(
1981 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
1985 newann.padAnnotation(alwidth);
1986 alignment.addAnnotation(newann);
1996 addHistoryItem(new EditCommand(
1997 MessageManager.getString("label.add_sequences"),
1999 sequences, 0, alignment.getWidth(), alignment));
2001 // Add any annotations attached to sequences
2002 for (int i = 0; i < sequences.length; i++)
2004 if (sequences[i].getAnnotation() != null)
2006 AlignmentAnnotation newann;
2007 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2009 annotationAdded = true;
2010 newann = sequences[i].getAnnotation()[a];
2011 newann.adjustForAlignment();
2012 newann.padAnnotation(alwidth);
2013 if (newann.graphGroup > -1)
2015 if (newann.graphGroup > -1)
2017 if (newGraphGroups.size() <= newann.graphGroup
2018 || newGraphGroups.get(newann.graphGroup) == null)
2020 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2022 newGraphGroups.add(q, null);
2024 newGraphGroups.set(newann.graphGroup, new Integer(
2027 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2031 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2036 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2043 // propagate alignment changed.
2044 viewport.setEndSeq(alignment.getHeight());
2045 if (annotationAdded)
2047 // Duplicate sequence annotation in all views.
2048 AlignmentI[] alview = this.getViewAlignments();
2049 for (int i = 0; i < sequences.length; i++)
2051 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2056 for (int avnum = 0; avnum < alview.length; avnum++)
2058 if (alview[avnum] != alignment)
2060 // duplicate in a view other than the one with input focus
2061 int avwidth = alview[avnum].getWidth() + 1;
2062 // this relies on sann being preserved after we
2063 // modify the sequence's annotation array for each duplication
2064 for (int a = 0; a < sann.length; a++)
2066 AlignmentAnnotation newann = new AlignmentAnnotation(
2068 sequences[i].addAlignmentAnnotation(newann);
2069 newann.padAnnotation(avwidth);
2070 alview[avnum].addAnnotation(newann); // annotation was
2071 // duplicated earlier
2072 // TODO JAL-1145 graphGroups are not updated for sequence
2073 // annotation added to several views. This may cause
2075 alview[avnum].setAnnotationIndex(newann, a);
2080 buildSortByAnnotationScoresMenu();
2082 viewport.firePropertyChange("alignment", null,
2083 alignment.getSequences());
2084 if (alignPanels != null)
2086 for (AlignmentPanel ap : ((Vector<AlignmentPanel>) alignPanels))
2088 ap.validateAnnotationDimensions(false);
2093 alignPanel.validateAnnotationDimensions(false);
2099 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2101 String newtitle = new String("Copied sequences");
2103 if (Desktop.jalviewClipboard != null
2104 && Desktop.jalviewClipboard[2] != null)
2106 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2107 for (int i = 0; i < hc.size(); i++)
2109 int[] region = (int[]) hc.elementAt(i);
2110 af.viewport.hideColumns(region[0], region[1]);
2114 // >>>This is a fix for the moment, until a better solution is
2116 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
2118 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
2120 // TODO: maintain provenance of an alignment, rather than just make the
2121 // title a concatenation of operations.
2124 if (title.startsWith("Copied sequences"))
2130 newtitle = newtitle.concat("- from " + title);
2135 newtitle = new String("Pasted sequences");
2138 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2143 } catch (Exception ex)
2145 ex.printStackTrace();
2146 System.out.println("Exception whilst pasting: " + ex);
2147 // could be anything being pasted in here
2153 protected void expand_newalign(ActionEvent e)
2157 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2158 .getAlignment(), -1);
2159 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2161 String newtitle = new String("Flanking alignment");
2163 if (Desktop.jalviewClipboard != null
2164 && Desktop.jalviewClipboard[2] != null)
2166 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2167 for (int i = 0; i < hc.size(); i++)
2169 int[] region = (int[]) hc.elementAt(i);
2170 af.viewport.hideColumns(region[0], region[1]);
2174 // >>>This is a fix for the moment, until a better solution is
2176 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
2178 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
2180 // TODO: maintain provenance of an alignment, rather than just make the
2181 // title a concatenation of operations.
2183 if (title.startsWith("Copied sequences"))
2189 newtitle = newtitle.concat("- from " + title);
2193 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2195 } catch (Exception ex)
2197 ex.printStackTrace();
2198 System.out.println("Exception whilst pasting: " + ex);
2199 // could be anything being pasted in here
2200 } catch (OutOfMemoryError oom)
2202 new OOMWarning("Viewing flanking region of alignment", oom);
2213 protected void cut_actionPerformed(ActionEvent e)
2215 copy_actionPerformed(null);
2216 delete_actionPerformed(null);
2226 protected void delete_actionPerformed(ActionEvent evt)
2229 SequenceGroup sg = viewport.getSelectionGroup();
2235 List<SequenceI> seqs = new ArrayList<SequenceI>(sg.getSize());
2237 for (int i = 0; i < sg.getSize(); i++)
2239 seq = sg.getSequenceAt(i);
2243 // If the cut affects all sequences, warn, remove highlighted columns
2244 if (sg.getSize() == viewport.getAlignment().getHeight())
2246 int confirm = JOptionPane.showConfirmDialog(this,
2247 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2248 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2249 JOptionPane.OK_CANCEL_OPTION);
2251 if (confirm == JOptionPane.CANCEL_OPTION
2252 || confirm == JOptionPane.CLOSED_OPTION)
2256 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2257 sg.getEndRes() + 1);
2260 SequenceI[] cut = new SequenceI[seqs.size()];
2261 for (int i = 0; i < seqs.size(); i++)
2263 cut[i] = seqs.get(i);
2267 * //ADD HISTORY ITEM
2269 addHistoryItem(new EditCommand(
2270 MessageManager.getString("label.cut_sequences"), Action.CUT,
2271 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2272 viewport.getAlignment()));
2274 viewport.setSelectionGroup(null);
2275 viewport.sendSelection();
2276 viewport.getAlignment().deleteGroup(sg);
2278 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2280 if (viewport.getAlignment().getHeight() < 1)
2284 this.setClosed(true);
2285 } catch (Exception ex)
2298 protected void deleteGroups_actionPerformed(ActionEvent e)
2300 if (avc.deleteGroups())
2302 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2303 alignPanel.updateAnnotation();
2304 alignPanel.paintAlignment(true);
2315 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2317 SequenceGroup sg = new SequenceGroup();
2319 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2321 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2324 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2325 viewport.setSelectionGroup(sg);
2326 viewport.sendSelection();
2327 alignPanel.paintAlignment(true);
2328 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2338 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2340 if (viewport.cursorMode)
2342 alignPanel.seqPanel.keyboardNo1 = null;
2343 alignPanel.seqPanel.keyboardNo2 = null;
2345 viewport.setSelectionGroup(null);
2346 viewport.getColumnSelection().clear();
2347 viewport.setSelectionGroup(null);
2348 alignPanel.seqPanel.seqCanvas.highlightSearchResults(null);
2349 alignPanel.idPanel.idCanvas.searchResults = null;
2350 alignPanel.paintAlignment(true);
2351 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2352 viewport.sendSelection();
2362 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2364 SequenceGroup sg = viewport.getSelectionGroup();
2368 selectAllSequenceMenuItem_actionPerformed(null);
2373 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2375 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2378 alignPanel.paintAlignment(true);
2379 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2380 viewport.sendSelection();
2384 public void invertColSel_actionPerformed(ActionEvent e)
2386 viewport.invertColumnSelection();
2387 alignPanel.paintAlignment(true);
2388 viewport.sendSelection();
2398 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2400 trimAlignment(true);
2410 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2412 trimAlignment(false);
2415 void trimAlignment(boolean trimLeft)
2417 ColumnSelection colSel = viewport.getColumnSelection();
2420 if (colSel.size() > 0)
2424 column = colSel.getMin();
2428 column = colSel.getMax();
2432 if (viewport.getSelectionGroup() != null)
2434 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2435 viewport.getHiddenRepSequences());
2439 seqs = viewport.getAlignment().getSequencesArray();
2442 TrimRegionCommand trimRegion;
2445 trimRegion = new TrimRegionCommand("Remove Left",
2446 TrimRegionCommand.TRIM_LEFT, seqs, column,
2447 viewport.getAlignment(), viewport.getColumnSelection(),
2448 viewport.getSelectionGroup());
2449 viewport.setStartRes(0);
2453 trimRegion = new TrimRegionCommand("Remove Right",
2454 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2455 viewport.getAlignment(), viewport.getColumnSelection(),
2456 viewport.getSelectionGroup());
2459 statusBar.setText(MessageManager.formatMessage(
2460 "label.removed_columns", new String[]
2461 { Integer.valueOf(trimRegion.getSize()).toString() }));
2463 addHistoryItem(trimRegion);
2465 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2467 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2468 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2470 viewport.getAlignment().deleteGroup(sg);
2474 viewport.firePropertyChange("alignment", null, viewport
2475 .getAlignment().getSequences());
2486 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2488 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2491 if (viewport.getSelectionGroup() != null)
2493 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2494 viewport.getHiddenRepSequences());
2495 start = viewport.getSelectionGroup().getStartRes();
2496 end = viewport.getSelectionGroup().getEndRes();
2500 seqs = viewport.getAlignment().getSequencesArray();
2503 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2504 "Remove Gapped Columns", seqs, start, end,
2505 viewport.getAlignment());
2507 addHistoryItem(removeGapCols);
2509 statusBar.setText(MessageManager.formatMessage(
2510 "label.removed_empty_columns", new String[]
2511 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2513 // This is to maintain viewport position on first residue
2514 // of first sequence
2515 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2516 int startRes = seq.findPosition(viewport.startRes);
2517 // ShiftList shifts;
2518 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2519 // edit.alColumnChanges=shifts.getInverse();
2520 // if (viewport.hasHiddenColumns)
2521 // viewport.getColumnSelection().compensateForEdits(shifts);
2522 viewport.setStartRes(seq.findIndex(startRes) - 1);
2523 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2535 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2537 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2540 if (viewport.getSelectionGroup() != null)
2542 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2543 viewport.getHiddenRepSequences());
2544 start = viewport.getSelectionGroup().getStartRes();
2545 end = viewport.getSelectionGroup().getEndRes();
2549 seqs = viewport.getAlignment().getSequencesArray();
2552 // This is to maintain viewport position on first residue
2553 // of first sequence
2554 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2555 int startRes = seq.findPosition(viewport.startRes);
2557 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2558 viewport.getAlignment()));
2560 viewport.setStartRes(seq.findIndex(startRes) - 1);
2562 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2574 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2576 viewport.setPadGaps(padGapsMenuitem.isSelected());
2577 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2583 // if (justifySeqs>0)
2585 // alignment.justify(justifySeqs!=RIGHT_JUSTIFY);
2598 public void findMenuItem_actionPerformed(ActionEvent e)
2604 public void newView_actionPerformed(ActionEvent e)
2611 * @param copyAnnotation
2612 * if true then duplicate all annnotation, groups and settings
2613 * @return new alignment panel, already displayed.
2615 public AlignmentPanel newView(boolean copyAnnotation)
2617 return newView(null, copyAnnotation);
2623 * title of newly created view
2624 * @return new alignment panel, already displayed.
2626 public AlignmentPanel newView(String viewTitle)
2628 return newView(viewTitle, true);
2634 * title of newly created view
2635 * @param copyAnnotation
2636 * if true then duplicate all annnotation, groups and settings
2637 * @return new alignment panel, already displayed.
2639 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2641 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2643 if (!copyAnnotation)
2645 // just remove all the current annotation except for the automatic stuff
2646 newap.av.getAlignment().deleteAllGroups();
2647 for (AlignmentAnnotation alan : newap.av.getAlignment()
2648 .getAlignmentAnnotation())
2650 if (!alan.autoCalculated)
2652 newap.av.getAlignment().deleteAnnotation(alan);
2658 newap.av.gatherViewsHere = false;
2660 if (viewport.viewName == null)
2662 viewport.viewName = "Original";
2665 newap.av.historyList = viewport.historyList;
2666 newap.av.redoList = viewport.redoList;
2668 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2669 // make sure the new view has a unique name - this is essential for Jalview
2671 boolean addFirstIndex = false;
2672 if (viewTitle == null || viewTitle.trim().length() == 0)
2674 viewTitle = MessageManager.getString("action.view");
2675 addFirstIndex = true;
2679 index = 1;// we count from 1 if given a specific name
2681 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2682 Vector comps = (Vector) PaintRefresher.components.get(viewport
2683 .getSequenceSetId());
2684 Vector existingNames = new Vector();
2685 for (int i = 0; i < comps.size(); i++)
2687 if (comps.elementAt(i) instanceof AlignmentPanel)
2689 AlignmentPanel ap = (AlignmentPanel) comps.elementAt(i);
2690 if (!existingNames.contains(ap.av.viewName))
2692 existingNames.addElement(ap.av.viewName);
2697 while (existingNames.contains(newViewName))
2699 newViewName = viewTitle + " " + (++index);
2702 newap.av.viewName = newViewName;
2704 addAlignmentPanel(newap, true);
2705 newap.alignmentChanged();
2707 if (alignPanels.size() == 2)
2709 viewport.gatherViewsHere = true;
2711 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2716 public void expandViews_actionPerformed(ActionEvent e)
2718 Desktop.instance.explodeViews(this);
2722 public void gatherViews_actionPerformed(ActionEvent e)
2724 Desktop.instance.gatherViews(this);
2734 public void font_actionPerformed(ActionEvent e)
2736 new FontChooser(alignPanel);
2746 protected void seqLimit_actionPerformed(ActionEvent e)
2748 viewport.setShowJVSuffix(seqLimits.isSelected());
2750 alignPanel.idPanel.idCanvas.setPreferredSize(alignPanel
2751 .calculateIdWidth());
2752 alignPanel.paintAlignment(true);
2756 public void idRightAlign_actionPerformed(ActionEvent e)
2758 viewport.rightAlignIds = idRightAlign.isSelected();
2759 alignPanel.paintAlignment(true);
2763 public void centreColumnLabels_actionPerformed(ActionEvent e)
2765 viewport.centreColumnLabels = centreColumnLabelsMenuItem.getState();
2766 alignPanel.paintAlignment(true);
2772 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2775 protected void followHighlight_actionPerformed()
2777 if (viewport.followHighlight = this.followHighlightMenuItem.getState())
2779 alignPanel.scrollToPosition(
2780 alignPanel.seqPanel.seqCanvas.searchResults, false);
2791 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2793 viewport.setColourText(colourTextMenuItem.isSelected());
2794 alignPanel.paintAlignment(true);
2804 public void wrapMenuItem_actionPerformed(ActionEvent e)
2806 scaleAbove.setVisible(wrapMenuItem.isSelected());
2807 scaleLeft.setVisible(wrapMenuItem.isSelected());
2808 scaleRight.setVisible(wrapMenuItem.isSelected());
2809 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2810 alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2814 public void showAllSeqs_actionPerformed(ActionEvent e)
2816 viewport.showAllHiddenSeqs();
2820 public void showAllColumns_actionPerformed(ActionEvent e)
2822 viewport.showAllHiddenColumns();
2827 public void hideSelSequences_actionPerformed(ActionEvent e)
2829 viewport.hideAllSelectedSeqs();
2830 alignPanel.paintAlignment(true);
2834 * called by key handler and the hide all/show all menu items
2839 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2842 boolean hide = false;
2843 SequenceGroup sg = viewport.getSelectionGroup();
2844 if (!toggleSeqs && !toggleCols)
2846 // Hide everything by the current selection - this is a hack - we do the
2847 // invert and then hide
2848 // first check that there will be visible columns after the invert.
2849 if ((viewport.getColumnSelection() != null
2850 && viewport.getColumnSelection().getSelected() != null && viewport
2851 .getColumnSelection().getSelected().size() > 0)
2852 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2855 // now invert the sequence set, if required - empty selection implies
2856 // that no hiding is required.
2859 invertSequenceMenuItem_actionPerformed(null);
2860 sg = viewport.getSelectionGroup();
2864 viewport.expandColSelection(sg, true);
2865 // finally invert the column selection and get the new sequence
2867 invertColSel_actionPerformed(null);
2874 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
2876 hideSelSequences_actionPerformed(null);
2879 else if (!(toggleCols && viewport.getColumnSelection().getSelected()
2882 showAllSeqs_actionPerformed(null);
2888 if (viewport.getColumnSelection().getSelected().size() > 0)
2890 hideSelColumns_actionPerformed(null);
2893 viewport.setSelectionGroup(sg);
2898 showAllColumns_actionPerformed(null);
2907 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
2908 * event.ActionEvent)
2911 public void hideAllButSelection_actionPerformed(ActionEvent e)
2913 toggleHiddenRegions(false, false);
2920 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
2924 public void hideAllSelection_actionPerformed(ActionEvent e)
2926 SequenceGroup sg = viewport.getSelectionGroup();
2927 viewport.expandColSelection(sg, false);
2928 viewport.hideAllSelectedSeqs();
2929 viewport.hideSelectedColumns();
2930 alignPanel.paintAlignment(true);
2937 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
2941 public void showAllhidden_actionPerformed(ActionEvent e)
2943 viewport.showAllHiddenColumns();
2944 viewport.showAllHiddenSeqs();
2945 alignPanel.paintAlignment(true);
2949 public void hideSelColumns_actionPerformed(ActionEvent e)
2951 viewport.hideSelectedColumns();
2952 alignPanel.paintAlignment(true);
2956 public void hiddenMarkers_actionPerformed(ActionEvent e)
2958 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
2969 protected void scaleAbove_actionPerformed(ActionEvent e)
2971 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
2972 alignPanel.paintAlignment(true);
2982 protected void scaleLeft_actionPerformed(ActionEvent e)
2984 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
2985 alignPanel.paintAlignment(true);
2995 protected void scaleRight_actionPerformed(ActionEvent e)
2997 viewport.setScaleRightWrapped(scaleRight.isSelected());
2998 alignPanel.paintAlignment(true);
3008 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3010 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3011 alignPanel.paintAlignment(true);
3021 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3023 viewport.setShowText(viewTextMenuItem.isSelected());
3024 alignPanel.paintAlignment(true);
3034 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3036 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3037 alignPanel.paintAlignment(true);
3040 public FeatureSettings featureSettings;
3043 public void featureSettings_actionPerformed(ActionEvent e)
3045 if (featureSettings != null)
3047 featureSettings.close();
3048 featureSettings = null;
3050 if (!showSeqFeatures.isSelected())
3052 // make sure features are actually displayed
3053 showSeqFeatures.setSelected(true);
3054 showSeqFeatures_actionPerformed(null);
3056 featureSettings = new FeatureSettings(this);
3060 * Set or clear 'Show Sequence Features'
3066 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3068 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3069 alignPanel.paintAlignment(true);
3070 if (alignPanel.getOverviewPanel() != null)
3072 alignPanel.getOverviewPanel().updateOverviewImage();
3077 * Set or clear 'Show Sequence Features'
3083 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
3085 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
3087 if (viewport.getShowSequenceFeaturesHeight())
3089 // ensure we're actually displaying features
3090 viewport.setShowSequenceFeatures(true);
3091 showSeqFeatures.setSelected(true);
3093 alignPanel.paintAlignment(true);
3094 if (alignPanel.getOverviewPanel() != null)
3096 alignPanel.getOverviewPanel().updateOverviewImage();
3101 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3102 * the annotations panel as a whole.
3104 * The options to show/hide all annotations should be enabled when the panel
3105 * is shown, and disabled when the panel is hidden.
3110 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3112 final boolean setVisible = annotationPanelMenuItem.isSelected();
3113 viewport.setShowAnnotation(setVisible);
3114 alignPanel.setAnnotationVisible(setVisible);
3115 this.showAllSeqAnnotations.setEnabled(setVisible);
3116 this.hideAllSeqAnnotations.setEnabled(setVisible);
3117 this.showAllAlAnnotations.setEnabled(setVisible);
3118 this.hideAllAlAnnotations.setEnabled(setVisible);
3122 public void alignmentProperties()
3124 JEditorPane editPane = new JEditorPane("text/html", "");
3125 editPane.setEditable(false);
3126 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3128 editPane.setText(MessageManager.formatMessage("label.html_content",
3130 { contents.toString() }));
3131 JInternalFrame frame = new JInternalFrame();
3132 frame.getContentPane().add(new JScrollPane(editPane));
3134 Desktop.instance.addInternalFrame(frame, MessageManager.formatMessage(
3135 "label.alignment_properties", new String[]
3136 { getTitle() }), 500, 400);
3146 public void overviewMenuItem_actionPerformed(ActionEvent e)
3148 if (alignPanel.overviewPanel != null)
3153 JInternalFrame frame = new JInternalFrame();
3154 OverviewPanel overview = new OverviewPanel(alignPanel);
3155 frame.setContentPane(overview);
3156 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3157 "label.overview_params", new String[]
3158 { this.getTitle() }), frame.getWidth(), frame.getHeight());
3160 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3161 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3164 public void internalFrameClosed(
3165 javax.swing.event.InternalFrameEvent evt)
3167 alignPanel.setOverviewPanel(null);
3171 alignPanel.setOverviewPanel(overview);
3175 public void textColour_actionPerformed(ActionEvent e)
3177 new TextColourChooser().chooseColour(alignPanel, null);
3187 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3199 public void clustalColour_actionPerformed(ActionEvent e)
3201 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3202 viewport.getHiddenRepSequences()));
3212 public void zappoColour_actionPerformed(ActionEvent e)
3214 changeColour(new ZappoColourScheme());
3224 public void taylorColour_actionPerformed(ActionEvent e)
3226 changeColour(new TaylorColourScheme());
3236 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3238 changeColour(new HydrophobicColourScheme());
3248 public void helixColour_actionPerformed(ActionEvent e)
3250 changeColour(new HelixColourScheme());
3260 public void strandColour_actionPerformed(ActionEvent e)
3262 changeColour(new StrandColourScheme());
3272 public void turnColour_actionPerformed(ActionEvent e)
3274 changeColour(new TurnColourScheme());
3284 public void buriedColour_actionPerformed(ActionEvent e)
3286 changeColour(new BuriedColourScheme());
3296 public void nucleotideColour_actionPerformed(ActionEvent e)
3298 changeColour(new NucleotideColourScheme());
3302 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3304 changeColour(new PurinePyrimidineColourScheme());
3308 * public void covariationColour_actionPerformed(ActionEvent e) {
3310 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3314 public void annotationColour_actionPerformed(ActionEvent e)
3316 new AnnotationColourChooser(viewport, alignPanel);
3320 public void rnahelicesColour_actionPerformed(ActionEvent e)
3322 new RNAHelicesColourChooser(viewport, alignPanel);
3332 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3334 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3343 public void changeColour(ColourSchemeI cs)
3345 // TODO: compare with applet and pull up to model method
3350 if (viewport.getAbovePIDThreshold())
3352 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3354 cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3358 cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3361 if (viewport.getConservationSelected())
3364 Alignment al = (Alignment) viewport.getAlignment();
3365 Conservation c = new Conservation("All",
3366 ResidueProperties.propHash, 3, al.getSequences(), 0,
3370 c.verdict(false, viewport.getConsPercGaps());
3372 cs.setConservation(c);
3374 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3379 cs.setConservation(null);
3382 cs.setConsensus(viewport.getSequenceConsensusHash());
3385 viewport.setGlobalColourScheme(cs);
3387 if (viewport.getColourAppliesToAllGroups())
3390 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3398 if (cs instanceof ClustalxColourScheme)
3400 sg.cs = new ClustalxColourScheme(sg,
3401 viewport.getHiddenRepSequences());
3403 else if (cs instanceof UserColourScheme)
3405 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
3411 sg.cs = cs.getClass().newInstance();
3412 } catch (Exception ex)
3417 if (viewport.getAbovePIDThreshold()
3418 || cs instanceof PIDColourScheme
3419 || cs instanceof Blosum62ColourScheme)
3421 sg.cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3423 sg.cs.setConsensus(AAFrequency.calculate(
3424 sg.getSequences(viewport.getHiddenRepSequences()),
3425 sg.getStartRes(), sg.getEndRes() + 1));
3429 sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3432 if (viewport.getConservationSelected())
3434 Conservation c = new Conservation("Group",
3435 ResidueProperties.propHash, 3, sg.getSequences(viewport
3436 .getHiddenRepSequences()), sg.getStartRes(),
3437 sg.getEndRes() + 1);
3439 c.verdict(false, viewport.getConsPercGaps());
3440 sg.cs.setConservation(c);
3444 sg.cs.setConservation(null);
3449 if (alignPanel.getOverviewPanel() != null)
3451 alignPanel.getOverviewPanel().updateOverviewImage();
3454 alignPanel.paintAlignment(true);
3464 protected void modifyPID_actionPerformed(ActionEvent e)
3466 if (viewport.getAbovePIDThreshold()
3467 && viewport.getGlobalColourScheme() != null)
3469 SliderPanel.setPIDSliderSource(alignPanel,
3470 viewport.getGlobalColourScheme(), "Background");
3471 SliderPanel.showPIDSlider();
3482 protected void modifyConservation_actionPerformed(ActionEvent e)
3484 if (viewport.getConservationSelected()
3485 && viewport.getGlobalColourScheme() != null)
3487 SliderPanel.setConservationSlider(alignPanel,
3488 viewport.getGlobalColourScheme(), "Background");
3489 SliderPanel.showConservationSlider();
3500 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3502 viewport.setConservationSelected(conservationMenuItem.isSelected());
3504 viewport.setAbovePIDThreshold(false);
3505 abovePIDThreshold.setSelected(false);
3507 changeColour(viewport.getGlobalColourScheme());
3509 modifyConservation_actionPerformed(null);
3519 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3521 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3523 conservationMenuItem.setSelected(false);
3524 viewport.setConservationSelected(false);
3526 changeColour(viewport.getGlobalColourScheme());
3528 modifyPID_actionPerformed(null);
3538 public void userDefinedColour_actionPerformed(ActionEvent e)
3540 if (e.getActionCommand().equals(
3541 MessageManager.getString("action.user_defined")))
3543 new UserDefinedColours(alignPanel, null);
3547 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3548 .getUserColourSchemes().get(e.getActionCommand());
3554 public void updateUserColourMenu()
3557 Component[] menuItems = colourMenu.getMenuComponents();
3558 int i, iSize = menuItems.length;
3559 for (i = 0; i < iSize; i++)
3561 if (menuItems[i].getName() != null
3562 && menuItems[i].getName().equals("USER_DEFINED"))
3564 colourMenu.remove(menuItems[i]);
3568 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3570 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3571 .getUserColourSchemes().keys();
3573 while (userColours.hasMoreElements())
3575 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3576 userColours.nextElement().toString());
3577 radioItem.setName("USER_DEFINED");
3578 radioItem.addMouseListener(new MouseAdapter()
3581 public void mousePressed(MouseEvent evt)
3583 if (evt.isControlDown()
3584 || SwingUtilities.isRightMouseButton(evt))
3586 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3588 int option = JOptionPane.showInternalConfirmDialog(
3589 jalview.gui.Desktop.desktop,
3591 .getString("label.remove_from_default_list"),
3593 .getString("label.remove_user_defined_colour"),
3594 JOptionPane.YES_NO_OPTION);
3595 if (option == JOptionPane.YES_OPTION)
3597 jalview.gui.UserDefinedColours
3598 .removeColourFromDefaults(radioItem.getText());
3599 colourMenu.remove(radioItem);
3603 radioItem.addActionListener(new ActionListener()
3606 public void actionPerformed(ActionEvent evt)
3608 userDefinedColour_actionPerformed(evt);
3615 radioItem.addActionListener(new ActionListener()
3618 public void actionPerformed(ActionEvent evt)
3620 userDefinedColour_actionPerformed(evt);
3624 colourMenu.insert(radioItem, 15);
3625 colours.add(radioItem);
3637 public void PIDColour_actionPerformed(ActionEvent e)
3639 changeColour(new PIDColourScheme());
3649 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3651 changeColour(new Blosum62ColourScheme());
3661 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3663 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3664 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3665 .getAlignment().getSequenceAt(0), null);
3666 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3667 viewport.getAlignment()));
3668 alignPanel.paintAlignment(true);
3678 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3680 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3681 AlignmentSorter.sortByID(viewport.getAlignment());
3682 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3683 viewport.getAlignment()));
3684 alignPanel.paintAlignment(true);
3694 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3696 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3697 AlignmentSorter.sortByLength(viewport.getAlignment());
3698 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3699 viewport.getAlignment()));
3700 alignPanel.paintAlignment(true);
3710 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3712 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3713 AlignmentSorter.sortByGroup(viewport.getAlignment());
3714 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3715 viewport.getAlignment()));
3717 alignPanel.paintAlignment(true);
3727 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3729 new RedundancyPanel(alignPanel, this);
3739 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3741 if ((viewport.getSelectionGroup() == null)
3742 || (viewport.getSelectionGroup().getSize() < 2))
3744 JOptionPane.showInternalMessageDialog(this, MessageManager
3745 .getString("label.you_must_select_least_two_sequences"),
3746 MessageManager.getString("label.invalid_selection"),
3747 JOptionPane.WARNING_MESSAGE);
3751 JInternalFrame frame = new JInternalFrame();
3752 frame.setContentPane(new PairwiseAlignPanel(viewport));
3753 Desktop.addInternalFrame(frame,
3754 MessageManager.getString("action.pairwise_alignment"), 600,
3766 public void PCAMenuItem_actionPerformed(ActionEvent e)
3768 if (((viewport.getSelectionGroup() != null)
3769 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3770 .getSelectionGroup().getSize() > 0))
3771 || (viewport.getAlignment().getHeight() < 4))
3774 .showInternalMessageDialog(
3777 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3779 .getString("label.sequence_selection_insufficient"),
3780 JOptionPane.WARNING_MESSAGE);
3785 new PCAPanel(alignPanel);
3789 public void autoCalculate_actionPerformed(ActionEvent e)
3791 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3792 if (viewport.autoCalculateConsensus)
3794 viewport.firePropertyChange("alignment", null, viewport
3795 .getAlignment().getSequences());
3800 public void sortByTreeOption_actionPerformed(ActionEvent e)
3802 viewport.sortByTree = sortByTree.isSelected();
3806 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3808 viewport.followSelection = listenToViewSelections.isSelected();
3818 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3820 NewTreePanel("AV", "PID", "Average distance tree using PID");
3830 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3832 NewTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3842 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3844 NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3854 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3856 NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3869 void NewTreePanel(String type, String pwType, String title)
3873 if (viewport.getSelectionGroup() != null
3874 && viewport.getSelectionGroup().getSize() > 0)
3876 if (viewport.getSelectionGroup().getSize() < 3)
3882 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3884 .getString("label.not_enough_sequences"),
3885 JOptionPane.WARNING_MESSAGE);
3889 SequenceGroup sg = viewport.getSelectionGroup();
3891 /* Decide if the selection is a column region */
3892 for (SequenceI _s : sg.getSequences())
3894 if (_s.getLength() < sg.getEndRes())
3900 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3902 .getString("label.sequences_selection_not_aligned"),
3903 JOptionPane.WARNING_MESSAGE);
3909 title = title + " on region";
3910 tp = new TreePanel(alignPanel, type, pwType);
3914 // are the visible sequences aligned?
3915 if (!viewport.getAlignment().isAligned(false))
3921 .getString("label.sequences_must_be_aligned_before_creating_tree"),
3923 .getString("label.sequences_not_aligned"),
3924 JOptionPane.WARNING_MESSAGE);
3929 if (viewport.getAlignment().getHeight() < 2)
3934 tp = new TreePanel(alignPanel, type, pwType);
3939 if (viewport.viewName != null)
3941 title += viewport.viewName + " of ";
3944 title += this.title;
3946 Desktop.addInternalFrame(tp, title, 600, 500);
3957 public void addSortByOrderMenuItem(String title,
3958 final AlignmentOrder order)
3960 final JMenuItem item = new JMenuItem(MessageManager.formatMessage("action.by_title_param", new String[]{title}));
3962 item.addActionListener(new java.awt.event.ActionListener()
3965 public void actionPerformed(ActionEvent e)
3967 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3969 // TODO: JBPNote - have to map order entries to curent SequenceI
3971 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3973 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
3976 alignPanel.paintAlignment(true);
3982 * Add a new sort by annotation score menu item
3985 * the menu to add the option to
3987 * the label used to retrieve scores for each sequence on the
3990 public void addSortByAnnotScoreMenuItem(JMenu sort,
3991 final String scoreLabel)
3993 final JMenuItem item = new JMenuItem(scoreLabel);
3995 item.addActionListener(new java.awt.event.ActionListener()
3998 public void actionPerformed(ActionEvent e)
4000 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4001 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4002 viewport.getAlignment());// ,viewport.getSelectionGroup());
4003 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4004 viewport.getAlignment()));
4005 alignPanel.paintAlignment(true);
4011 * last hash for alignment's annotation array - used to minimise cost of
4014 protected int _annotationScoreVectorHash;
4017 * search the alignment and rebuild the sort by annotation score submenu the
4018 * last alignment annotation vector hash is stored to minimize cost of
4019 * rebuilding in subsequence calls.
4023 public void buildSortByAnnotationScoresMenu()
4025 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4030 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4032 sortByAnnotScore.removeAll();
4033 // almost certainly a quicker way to do this - but we keep it simple
4034 Hashtable scoreSorts = new Hashtable();
4035 AlignmentAnnotation aann[];
4036 for (SequenceI sqa : viewport.getAlignment().getSequences())
4038 aann = sqa.getAnnotation();
4039 for (int i = 0; aann != null && i < aann.length; i++)
4041 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4043 scoreSorts.put(aann[i].label, aann[i].label);
4047 Enumeration labels = scoreSorts.keys();
4048 while (labels.hasMoreElements())
4050 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4051 (String) labels.nextElement());
4053 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4056 _annotationScoreVectorHash = viewport.getAlignment()
4057 .getAlignmentAnnotation().hashCode();
4062 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4063 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4064 * call. Listeners are added to remove the menu item when the treePanel is
4065 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4069 * Displayed tree window.
4071 * SortBy menu item title.
4074 public void buildTreeMenu()
4076 calculateTree.removeAll();
4077 // build the calculate menu
4079 for (final String type : new String[]
4082 String treecalcnm = MessageManager.getString("label.tree_calc_"
4083 + type.toLowerCase());
4084 for (final Object pwtype : ResidueProperties.scoreMatrices.keySet())
4086 JMenuItem tm = new JMenuItem();
4087 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4088 if (sm.isProtein() == !viewport.getAlignment().isNucleotide())
4090 String smn = MessageManager.getStringOrReturn(
4091 "label.score_model_", sm.getName());
4092 final String title = MessageManager.formatMessage(
4093 "label.treecalc_title", treecalcnm, smn);
4094 tm.setText(title);//
4095 tm.addActionListener(new java.awt.event.ActionListener()
4098 public void actionPerformed(ActionEvent e)
4100 NewTreePanel(type, (String) pwtype, title);
4103 calculateTree.add(tm);
4108 sortByTreeMenu.removeAll();
4110 Vector comps = (Vector) PaintRefresher.components.get(viewport
4111 .getSequenceSetId());
4112 Vector treePanels = new Vector();
4113 int i, iSize = comps.size();
4114 for (i = 0; i < iSize; i++)
4116 if (comps.elementAt(i) instanceof TreePanel)
4118 treePanels.add(comps.elementAt(i));
4122 iSize = treePanels.size();
4126 sortByTreeMenu.setVisible(false);
4130 sortByTreeMenu.setVisible(true);
4132 for (i = 0; i < treePanels.size(); i++)
4134 final TreePanel tp = (TreePanel) treePanels.elementAt(i);
4135 final JMenuItem item = new JMenuItem(tp.getTitle());
4136 final NJTree tree = ((TreePanel) treePanels.elementAt(i)).getTree();
4137 item.addActionListener(new java.awt.event.ActionListener()
4140 public void actionPerformed(ActionEvent e)
4142 tp.sortByTree_actionPerformed(null);
4143 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4148 sortByTreeMenu.add(item);
4152 public boolean sortBy(AlignmentOrder alorder, String undoname)
4154 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4155 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4156 if (undoname != null)
4158 addHistoryItem(new OrderCommand(undoname, oldOrder,
4159 viewport.getAlignment()));
4161 alignPanel.paintAlignment(true);
4166 * Work out whether the whole set of sequences or just the selected set will
4167 * be submitted for multiple alignment.
4170 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4172 // Now, check we have enough sequences
4173 AlignmentView msa = null;
4175 if ((viewport.getSelectionGroup() != null)
4176 && (viewport.getSelectionGroup().getSize() > 1))
4178 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4179 // some common interface!
4181 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4182 * SequenceI[sz = seqs.getSize(false)];
4184 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4185 * seqs.getSequenceAt(i); }
4187 msa = viewport.getAlignmentView(true);
4189 else if (viewport.getSelectionGroup() != null
4190 && viewport.getSelectionGroup().getSize() == 1)
4192 int option = JOptionPane
4195 "More than one sequece group selection is required for this Job, click \n'Cancel' to edit your selection or 'Ok' to submit the entire sequence.",
4196 "Invalid selection",
4197 JOptionPane.OK_CANCEL_OPTION);
4198 if (option == JOptionPane.OK_OPTION)
4200 msa = viewport.getAlignmentView(false);
4207 * Vector seqs = viewport.getAlignment().getSequences();
4209 * if (seqs.size() > 1) { msa = new SequenceI[seqs.size()];
4211 * for (int i = 0; i < seqs.size(); i++) { msa[i] = (SequenceI)
4212 * seqs.elementAt(i); } }
4214 msa = viewport.getAlignmentView(false);
4220 * Decides what is submitted to a secondary structure prediction service: the
4221 * first sequence in the alignment, or in the current selection, or, if the
4222 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4223 * region or the whole alignment. (where the first sequence in the set is the
4224 * one that the prediction will be for).
4226 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4228 AlignmentView seqs = null;
4230 if ((viewport.getSelectionGroup() != null)
4231 && (viewport.getSelectionGroup().getSize() > 0))
4233 seqs = viewport.getAlignmentView(true);
4237 seqs = viewport.getAlignmentView(false);
4239 // limit sequences - JBPNote in future - could spawn multiple prediction
4241 // TODO: viewport.getAlignment().isAligned is a global state - the local
4242 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4243 if (!viewport.getAlignment().isAligned(false))
4245 seqs.setSequences(new SeqCigar[]
4246 { seqs.getSequences()[0] });
4247 // TODO: if seqs.getSequences().length>1 then should really have warned
4261 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
4263 // Pick the tree file
4264 JalviewFileChooser chooser = new JalviewFileChooser(
4265 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4266 chooser.setFileView(new JalviewFileView());
4267 chooser.setDialogTitle(MessageManager
4268 .getString("label.select_newick_like_tree_file"));
4269 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4271 int value = chooser.showOpenDialog(null);
4273 if (value == JalviewFileChooser.APPROVE_OPTION)
4275 String choice = chooser.getSelectedFile().getPath();
4276 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4277 jalview.io.NewickFile fin = null;
4280 fin = new jalview.io.NewickFile(choice, "File");
4281 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4282 } catch (Exception ex)
4289 .getString("label.problem_reading_tree_file"),
4290 JOptionPane.WARNING_MESSAGE);
4291 ex.printStackTrace();
4293 if (fin != null && fin.hasWarningMessage())
4295 JOptionPane.showMessageDialog(Desktop.desktop, fin
4296 .getWarningMessage(), MessageManager
4297 .getString("label.possible_problem_with_tree_file"),
4298 JOptionPane.WARNING_MESSAGE);
4304 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4306 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4309 public TreePanel ShowNewickTree(NewickFile nf, String title)
4311 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4314 public TreePanel ShowNewickTree(NewickFile nf, String title,
4315 AlignmentView input)
4317 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4320 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4321 int h, int x, int y)
4323 return ShowNewickTree(nf, title, null, w, h, x, y);
4327 * Add a treeviewer for the tree extracted from a newick file object to the
4328 * current alignment view
4335 * Associated alignment input data (or null)
4344 * @return TreePanel handle
4346 public TreePanel ShowNewickTree(NewickFile nf, String title,
4347 AlignmentView input, int w, int h, int x, int y)
4349 TreePanel tp = null;
4355 if (nf.getTree() != null)
4357 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4363 tp.setLocation(x, y);
4366 Desktop.addInternalFrame(tp, title, w, h);
4368 } catch (Exception ex)
4370 ex.printStackTrace();
4376 private boolean buildingMenu = false;
4379 * Generates menu items and listener event actions for web service clients
4382 public void BuildWebServiceMenu()
4384 while (buildingMenu)
4388 System.err.println("Waiting for building menu to finish.");
4390 } catch (Exception e)
4395 final AlignFrame me = this;
4396 buildingMenu = true;
4397 new Thread(new Runnable()
4402 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4405 System.err.println("Building ws menu again "
4406 + Thread.currentThread());
4407 // TODO: add support for context dependent disabling of services based
4409 // alignment and current selection
4410 // TODO: add additional serviceHandle parameter to specify abstract
4412 // class independently of AbstractName
4413 // TODO: add in rediscovery GUI function to restart discoverer
4414 // TODO: group services by location as well as function and/or
4416 // object broker mechanism.
4417 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4418 final IProgressIndicator af = me;
4419 final JMenu msawsmenu = new JMenu("Alignment");
4420 final JMenu secstrmenu = new JMenu(
4421 "Secondary Structure Prediction");
4422 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4423 final JMenu analymenu = new JMenu("Analysis");
4424 final JMenu dismenu = new JMenu("Protein Disorder");
4425 // final JMenu msawsmenu = new
4426 // JMenu(MessageManager.getString("label.alignment"));
4427 // final JMenu secstrmenu = new
4428 // JMenu(MessageManager.getString("label.secondary_structure_prediction"));
4429 // final JMenu seqsrchmenu = new
4430 // JMenu(MessageManager.getString("label.sequence_database_search"));
4431 // final JMenu analymenu = new
4432 // JMenu(MessageManager.getString("label.analysis"));
4433 // final JMenu dismenu = new
4434 // JMenu(MessageManager.getString("label.protein_disorder"));
4435 // JAL-940 - only show secondary structure prediction services from
4436 // the legacy server
4437 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4439 Discoverer.services != null && (Discoverer.services.size() > 0))
4441 // TODO: refactor to allow list of AbstractName/Handler bindings to
4443 // stored or retrieved from elsewhere
4444 // No MSAWS used any more:
4445 // Vector msaws = null; // (Vector)
4446 // Discoverer.services.get("MsaWS");
4447 Vector secstrpr = (Vector) Discoverer.services
4449 if (secstrpr != null)
4451 // Add any secondary structure prediction services
4452 for (int i = 0, j = secstrpr.size(); i < j; i++)
4454 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4456 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4457 .getServiceClient(sh);
4458 int p = secstrmenu.getItemCount();
4459 impl.attachWSMenuEntry(secstrmenu, me);
4460 int q = secstrmenu.getItemCount();
4461 for (int litm = p; litm < q; litm++)
4463 legacyItems.add(secstrmenu.getItem(litm));
4469 // Add all submenus in the order they should appear on the web
4471 wsmenu.add(msawsmenu);
4472 wsmenu.add(secstrmenu);
4473 wsmenu.add(dismenu);
4474 wsmenu.add(analymenu);
4475 // No search services yet
4476 // wsmenu.add(seqsrchmenu);
4478 javax.swing.SwingUtilities.invokeLater(new Runnable()
4485 webService.removeAll();
4486 // first, add discovered services onto the webservices menu
4487 if (wsmenu.size() > 0)
4489 for (int i = 0, j = wsmenu.size(); i < j; i++)
4491 webService.add(wsmenu.get(i));
4496 webService.add(me.webServiceNoServices);
4498 // TODO: move into separate menu builder class.
4499 boolean new_sspred = false;
4500 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4502 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4503 if (jws2servs != null)
4505 if (jws2servs.hasServices())
4507 jws2servs.attachWSMenuEntry(webService, me);
4508 for (Jws2Instance sv : jws2servs.getServices())
4510 if (sv.description.toLowerCase().contains("jpred"))
4512 for (JMenuItem jmi : legacyItems)
4514 jmi.setVisible(false);
4520 if (jws2servs.isRunning())
4522 JMenuItem tm = new JMenuItem(
4523 "Still discovering JABA Services");
4524 tm.setEnabled(false);
4529 build_urlServiceMenu(me.webService);
4530 build_fetchdbmenu(webService);
4531 for (JMenu item : wsmenu)
4533 if (item.getItemCount() == 0)
4535 item.setEnabled(false);
4539 item.setEnabled(true);
4542 } catch (Exception e)
4545 .debug("Exception during web service menu building process.",
4551 } catch (Exception e)
4556 buildingMenu = false;
4563 * construct any groupURL type service menu entries.
4567 private void build_urlServiceMenu(JMenu webService)
4569 // TODO: remove this code when 2.7 is released
4570 // DEBUG - alignmentView
4572 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4573 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4575 * @Override public void actionPerformed(ActionEvent e) {
4576 * jalview.datamodel.AlignmentView
4577 * .testSelectionViews(af.viewport.getAlignment(),
4578 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4580 * }); webService.add(testAlView);
4582 // TODO: refactor to RestClient discoverer and merge menu entries for
4583 // rest-style services with other types of analysis/calculation service
4584 // SHmmr test client - still being implemented.
4585 // DEBUG - alignmentView
4587 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4590 client.attachWSMenuEntry(
4591 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4597 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
4598 * chooser = new JalviewFileChooser(jalview.bin.Cache.
4599 * getProperty("LAST_DIRECTORY"));
4601 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
4602 * to Vamsas file"); chooser.setToolTipText("Export");
4604 * int value = chooser.showSaveDialog(this);
4606 * if (value == JalviewFileChooser.APPROVE_OPTION) {
4607 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
4608 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
4609 * chooser.getSelectedFile().getAbsolutePath(), this); } }
4612 * prototype of an automatically enabled/disabled analysis function
4615 protected void setShowProductsEnabled()
4617 SequenceI[] selection = viewport.getSequenceSelection();
4618 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
4619 viewport.getAlignment().getDataset()))
4621 showProducts.setEnabled(true);
4626 showProducts.setEnabled(false);
4631 * search selection for sequence xRef products and build the show products
4636 * @return true if showProducts menu should be enabled.
4638 public boolean canShowProducts(SequenceI[] selection,
4639 boolean isRegionSelection, Alignment dataset)
4641 boolean showp = false;
4644 showProducts.removeAll();
4645 final boolean dna = viewport.getAlignment().isNucleotide();
4646 final Alignment ds = dataset;
4647 String[] ptypes = (selection == null || selection.length == 0) ? null
4648 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4650 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4651 // selection, dataset, true);
4652 final SequenceI[] sel = selection;
4653 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4656 final boolean isRegSel = isRegionSelection;
4657 final AlignFrame af = this;
4658 final String source = ptypes[t];
4659 JMenuItem xtype = new JMenuItem(ptypes[t]);
4660 xtype.addActionListener(new ActionListener()
4664 public void actionPerformed(ActionEvent e)
4666 // TODO: new thread for this call with vis-delay
4667 af.showProductsFor(af.viewport.getSequenceSelection(), ds,
4668 isRegSel, dna, source);
4672 showProducts.add(xtype);
4674 showProducts.setVisible(showp);
4675 showProducts.setEnabled(showp);
4676 } catch (Exception e)
4678 jalview.bin.Cache.log
4679 .warn("canTranslate threw an exception - please report to help@jalview.org",
4686 protected void showProductsFor(SequenceI[] sel, Alignment ds,
4687 boolean isRegSel, boolean dna, String source)
4689 final boolean fisRegSel = isRegSel;
4690 final boolean fdna = dna;
4691 final String fsrc = source;
4692 final AlignFrame ths = this;
4693 final SequenceI[] fsel = sel;
4694 Runnable foo = new Runnable()
4700 final long sttime = System.currentTimeMillis();
4701 ths.setProgressBar(MessageManager.formatMessage("status.searching_for_sequences_from", new String[]{fsrc}), sttime);
4704 Alignment ds = ths.getViewport().getAlignment().getDataset(); // update
4708 Alignment prods = CrossRef
4709 .findXrefSequences(fsel, fdna, fsrc, ds);
4712 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4713 for (int s = 0; s < sprods.length; s++)
4715 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4716 if (ds.getSequences() == null
4717 || !ds.getSequences().contains(
4718 sprods[s].getDatasetSequence()))
4720 ds.addSequence(sprods[s].getDatasetSequence());
4722 sprods[s].updatePDBIds();
4724 Alignment al = new Alignment(sprods);
4725 AlignedCodonFrame[] cf = prods.getCodonFrames();
4727 for (int s = 0; cf != null && s < cf.length; s++)
4729 al.addCodonFrame(cf[s]);
4732 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4734 String newtitle = "" + ((fdna) ? "Proteins " : "Nucleotides ")
4735 + " for " + ((fisRegSel) ? "selected region of " : "")
4737 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4742 System.err.println("No Sequences generated for xRef type "
4745 } catch (Exception e)
4747 jalview.bin.Cache.log.error(
4748 "Exception when finding crossreferences", e);
4749 } catch (OutOfMemoryError e)
4751 new OOMWarning("whilst fetching crossreferences", e);
4754 jalview.bin.Cache.log.error("Error when finding crossreferences",
4757 ths.setProgressBar(MessageManager.formatMessage("status.finished_searching_for_sequences_from", new String[]{fsrc}),
4762 Thread frunner = new Thread(foo);
4766 public boolean canShowTranslationProducts(SequenceI[] selection,
4767 AlignmentI alignment)
4772 return (jalview.analysis.Dna.canTranslate(selection,
4773 viewport.getViewAsVisibleContigs(true)));
4774 } catch (Exception e)
4776 jalview.bin.Cache.log
4777 .warn("canTranslate threw an exception - please report to help@jalview.org",
4784 public void showProducts_actionPerformed(ActionEvent e)
4786 // /////////////////////////////
4787 // Collect Data to be translated/transferred
4789 SequenceI[] selection = viewport.getSequenceSelection();
4790 AlignmentI al = null;
4793 al = jalview.analysis.Dna.CdnaTranslate(selection, viewport
4794 .getViewAsVisibleContigs(true), viewport.getGapCharacter(),
4795 viewport.getAlignment().getDataset());
4796 } catch (Exception ex)
4799 jalview.bin.Cache.log.debug("Exception during translation.", ex);
4807 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation"),
4808 MessageManager.getString("label.translation_failed"),
4809 JOptionPane.WARNING_MESSAGE);
4813 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4814 Desktop.addInternalFrame(af, MessageManager.formatMessage(
4815 "label.translation_of_params", new String[]
4816 { this.getTitle() }), DEFAULT_WIDTH, DEFAULT_HEIGHT);
4821 public void showTranslation_actionPerformed(ActionEvent e)
4823 // /////////////////////////////
4824 // Collect Data to be translated/transferred
4826 SequenceI[] selection = viewport.getSequenceSelection();
4827 String[] seqstring = viewport.getViewAsString(true);
4828 AlignmentI al = null;
4831 al = jalview.analysis.Dna.CdnaTranslate(selection, seqstring,
4832 viewport.getViewAsVisibleContigs(true), viewport
4833 .getGapCharacter(), viewport.getAlignment()
4834 .getAlignmentAnnotation(), viewport.getAlignment()
4835 .getWidth(), viewport.getAlignment().getDataset());
4836 } catch (Exception ex)
4839 jalview.bin.Cache.log.error(
4840 "Exception during translation. Please report this !", ex);
4845 .getString("label.error_when_translating_sequences_submit_bug_report"),
4847 .getString("label.implementation_error")
4849 .getString("translation_failed"),
4850 JOptionPane.ERROR_MESSAGE);
4859 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation"),
4860 MessageManager.getString("label.translation_failed"),
4861 JOptionPane.WARNING_MESSAGE);
4865 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4866 Desktop.addInternalFrame(af, MessageManager.formatMessage(
4867 "label.translation_of_params", new String[]
4868 { this.getTitle() }), DEFAULT_WIDTH, DEFAULT_HEIGHT);
4873 * Try to load a features file onto the alignment.
4876 * contents or path to retrieve file
4878 * access mode of file (see jalview.io.AlignFile)
4879 * @return true if features file was parsed corectly.
4881 public boolean parseFeaturesFile(String file, String type)
4883 boolean featuresFile = false;
4886 featuresFile = new FeaturesFile(file, type).parse(viewport
4887 .getAlignment().getDataset(), alignPanel.seqPanel.seqCanvas
4888 .getFeatureRenderer().featureColours, false,
4889 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4890 } catch (Exception ex)
4892 ex.printStackTrace();
4897 viewport.showSequenceFeatures = true;
4898 showSeqFeatures.setSelected(true);
4899 if (alignPanel.seqPanel.seqCanvas.fr != null)
4901 // update the min/max ranges where necessary
4902 alignPanel.seqPanel.seqCanvas.fr.findAllFeatures(true);
4904 if (featureSettings != null)
4906 featureSettings.setTableData();
4908 alignPanel.paintAlignment(true);
4911 return featuresFile;
4915 public void dragEnter(DropTargetDragEvent evt)
4920 public void dragExit(DropTargetEvent evt)
4925 public void dragOver(DropTargetDragEvent evt)
4930 public void dropActionChanged(DropTargetDragEvent evt)
4935 public void drop(DropTargetDropEvent evt)
4937 Transferable t = evt.getTransferable();
4938 java.util.List files = null;
4942 DataFlavor uriListFlavor = new DataFlavor(
4943 "text/uri-list;class=java.lang.String");
4944 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
4946 // Works on Windows and MacOSX
4947 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4948 files = (java.util.List) t
4949 .getTransferData(DataFlavor.javaFileListFlavor);
4951 else if (t.isDataFlavorSupported(uriListFlavor))
4953 // This is used by Unix drag system
4954 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4955 String data = (String) t.getTransferData(uriListFlavor);
4956 files = new java.util.ArrayList(1);
4957 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
4958 data, "\r\n"); st.hasMoreTokens();)
4960 String s = st.nextToken();
4961 if (s.startsWith("#"))
4963 // the line is a comment (as per the RFC 2483)
4967 java.net.URI uri = new java.net.URI(s);
4968 // check to see if we can handle this kind of URI
4969 if (uri.getScheme().toLowerCase().startsWith("http"))
4971 files.add(uri.toString());
4975 // otherwise preserve old behaviour: catch all for file objects
4976 java.io.File file = new java.io.File(uri);
4977 files.add(file.toString());
4981 } catch (Exception e)
4983 e.printStackTrace();
4989 // check to see if any of these files have names matching sequences in
4991 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4992 .getAlignment().getSequencesArray());
4994 * Object[] { String,SequenceI}
4996 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
4997 ArrayList<String> filesnotmatched = new ArrayList<String>();
4998 for (int i = 0; i < files.size(); i++)
5000 String file = files.get(i).toString();
5002 String protocol = FormatAdapter.checkProtocol(file);
5003 if (protocol == jalview.io.FormatAdapter.FILE)
5005 File fl = new File(file);
5006 pdbfn = fl.getName();
5008 else if (protocol == jalview.io.FormatAdapter.URL)
5010 URL url = new URL(file);
5011 pdbfn = url.getFile();
5013 if (pdbfn.length() > 0)
5015 // attempt to find a match in the alignment
5016 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5017 int l = 0, c = pdbfn.indexOf(".");
5018 while (mtch == null && c != -1)
5023 } while ((c = pdbfn.indexOf(".", l)) > l);
5026 pdbfn = pdbfn.substring(0, l);
5028 mtch = idm.findAllIdMatches(pdbfn);
5035 type = new IdentifyFile().Identify(file, protocol);
5036 } catch (Exception ex)
5042 if (type.equalsIgnoreCase("PDB"))
5044 filesmatched.add(new Object[]
5045 { file, protocol, mtch });
5050 // File wasn't named like one of the sequences or wasn't a PDB file.
5051 filesnotmatched.add(file);
5055 if (filesmatched.size() > 0)
5057 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
5063 "label.automatically_associate_pdb_files_with_sequences_same_name",
5070 .getString("label.automatically_associate_pdb_files_by_name"),
5071 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
5074 for (Object[] fm : filesmatched)
5076 // try and associate
5077 // TODO: may want to set a standard ID naming formalism for
5078 // associating PDB files which have no IDs.
5079 for (SequenceI toassoc : (SequenceI[]) fm[2])
5081 PDBEntry pe = new AssociatePdbFileWithSeq()
5082 .associatePdbWithSeq((String) fm[0],
5083 (String) fm[1], toassoc, false,
5087 System.err.println("Associated file : "
5088 + ((String) fm[0]) + " with "
5089 + toassoc.getDisplayId(true));
5093 alignPanel.paintAlignment(true);
5097 if (filesnotmatched.size() > 0)
5100 && (Cache.getDefault(
5101 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
5104 "<html>"+MessageManager
5106 "label.ignore_unmatched_dropped_files_info",
5111 .toString() })+"</html>",
5113 .getString("label.ignore_unmatched_dropped_files"),
5114 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
5118 for (String fn : filesnotmatched)
5120 loadJalviewDataFile(fn, null, null, null);
5124 } catch (Exception ex)
5126 ex.printStackTrace();
5132 * Attempt to load a "dropped" file or URL string: First by testing whether
5133 * it's and Annotation file, then a JNet file, and finally a features file. If
5134 * all are false then the user may have dropped an alignment file onto this
5138 * either a filename or a URL string.
5140 public void loadJalviewDataFile(String file, String protocol,
5141 String format, SequenceI assocSeq)
5145 if (protocol == null)
5147 protocol = jalview.io.FormatAdapter.checkProtocol(file);
5149 // if the file isn't identified, or not positively identified as some
5150 // other filetype (PFAM is default unidentified alignment file type) then
5151 // try to parse as annotation.
5152 boolean isAnnotation = (format == null || format
5153 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
5154 .readAnnotationFile(viewport.getAlignment(), file, protocol)
5159 // first see if its a T-COFFEE score file
5160 TCoffeeScoreFile tcf = null;
5163 tcf = new TCoffeeScoreFile(file, protocol);
5166 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5168 tcoffeeColour.setEnabled(true);
5169 tcoffeeColour.setSelected(true);
5170 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5171 isAnnotation = true;
5173 .setText(MessageManager
5174 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5178 // some problem - if no warning its probable that the ID matching
5179 // process didn't work
5183 tcf.getWarningMessage() == null ? MessageManager
5184 .getString("label.check_file_matches_sequence_ids_alignment")
5185 : tcf.getWarningMessage(),
5187 .getString("label.problem_reading_tcoffee_score_file"),
5188 JOptionPane.WARNING_MESSAGE);
5195 } catch (Exception x)
5198 .debug("Exception when processing data source as T-COFFEE score file",
5204 // try to see if its a JNet 'concise' style annotation file *before*
5206 // try to parse it as a features file
5209 format = new IdentifyFile().Identify(file, protocol);
5211 if (format.equalsIgnoreCase("JnetFile"))
5213 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5215 new JnetAnnotationMaker().add_annotation(predictions,
5216 viewport.getAlignment(), 0, false);
5217 isAnnotation = true;
5222 * if (format.equalsIgnoreCase("PDB")) {
5224 * String pdbfn = ""; // try to match up filename with sequence id
5225 * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
5226 * new File(file); pdbfn = fl.getName(); } else if (protocol ==
5227 * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
5228 * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
5229 * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5230 * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
5231 * // attempt to find a match in the alignment SequenceI mtch =
5232 * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
5233 * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
5234 * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
5235 * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
5236 * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
5237 * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
5238 * { System.err.println("Associated file : " + file + " with " +
5239 * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
5240 * TODO: maybe need to load as normal otherwise return; } }
5242 // try to parse it as a features file
5243 boolean isGroupsFile = parseFeaturesFile(file, protocol);
5244 // if it wasn't a features file then we just treat it as a general
5245 // alignment file to load into the current view.
5248 new FileLoader().LoadFile(viewport, file, protocol, format);
5252 alignPanel.paintAlignment(true);
5260 alignPanel.adjustAnnotationHeight();
5261 viewport.updateSequenceIdColours();
5262 buildSortByAnnotationScoresMenu();
5263 alignPanel.paintAlignment(true);
5265 } catch (Exception ex)
5267 ex.printStackTrace();
5268 } catch (OutOfMemoryError oom)
5273 } catch (Exception x)
5279 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5280 : "using " + protocol + " from " + file)
5282 + (format != null ? "(parsing as '" + format
5283 + "' file)" : ""), oom, Desktop.desktop);
5288 public void tabSelectionChanged(int index)
5292 alignPanel = (AlignmentPanel) alignPanels.elementAt(index);
5293 viewport = alignPanel.av;
5294 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5295 setMenusFromViewport(viewport);
5300 public void tabbedPane_mousePressed(MouseEvent e)
5302 if (SwingUtilities.isRightMouseButton(e))
5304 String reply = JOptionPane.showInternalInputDialog(this,
5305 MessageManager.getString("label.enter_view_name"),
5306 MessageManager.getString("label.enter_view_name"),
5307 JOptionPane.QUESTION_MESSAGE);
5311 viewport.viewName = reply;
5312 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5317 public AlignViewport getCurrentView()
5323 * Open the dialog for regex description parsing.
5326 protected void extractScores_actionPerformed(ActionEvent e)
5328 ParseProperties pp = new jalview.analysis.ParseProperties(
5329 viewport.getAlignment());
5330 // TODO: verify regex and introduce GUI dialog for version 2.5
5331 // if (pp.getScoresFromDescription("col", "score column ",
5332 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5334 if (pp.getScoresFromDescription("description column",
5335 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5337 buildSortByAnnotationScoresMenu();
5345 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5349 protected void showDbRefs_actionPerformed(ActionEvent e)
5351 viewport.setShowDbRefs(showDbRefsMenuitem.isSelected());
5357 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5361 protected void showNpFeats_actionPerformed(ActionEvent e)
5363 viewport.setShowNpFeats(showNpFeatsMenuitem.isSelected());
5367 * find the viewport amongst the tabs in this alignment frame and close that
5372 public boolean closeView(AlignViewport av)
5376 this.closeMenuItem_actionPerformed(false);
5379 Component[] comp = tabbedPane.getComponents();
5380 for (int i = 0; comp != null && i < comp.length; i++)
5382 if (comp[i] instanceof AlignmentPanel)
5384 if (((AlignmentPanel) comp[i]).av == av)
5387 closeView((AlignmentPanel) comp[i]);
5395 protected void build_fetchdbmenu(JMenu webService)
5397 // Temporary hack - DBRef Fetcher always top level ws entry.
5398 // TODO We probably want to store a sequence database checklist in
5399 // preferences and have checkboxes.. rather than individual sources selected
5401 final JMenu rfetch = new JMenu(
5402 MessageManager.getString("action.fetch_db_references"));
5403 rfetch.setToolTipText(MessageManager
5404 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5405 webService.add(rfetch);
5407 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5408 MessageManager.getString("option.trim_retrieved_seqs"));
5409 trimrs.setToolTipText(MessageManager
5410 .getString("label.trim_retrieved_sequences"));
5411 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5412 trimrs.addActionListener(new ActionListener()
5415 public void actionPerformed(ActionEvent e)
5417 trimrs.setSelected(trimrs.isSelected());
5418 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5419 Boolean.valueOf(trimrs.isSelected()).toString());
5423 JMenuItem fetchr = new JMenuItem(
5424 MessageManager.getString("label.standard_databases"));
5425 fetchr.setToolTipText(MessageManager
5426 .getString("label.fetch_embl_uniprot"));
5427 fetchr.addActionListener(new ActionListener()
5431 public void actionPerformed(ActionEvent e)
5433 new Thread(new Runnable()
5439 new jalview.ws.DBRefFetcher(alignPanel.av
5440 .getSequenceSelection(), alignPanel.alignFrame)
5441 .fetchDBRefs(false);
5449 final AlignFrame me = this;
5450 new Thread(new Runnable()
5455 final jalview.ws.SequenceFetcher sf = SequenceFetcher
5456 .getSequenceFetcherSingleton(me);
5457 javax.swing.SwingUtilities.invokeLater(new Runnable()
5462 String[] dbclasses = sf.getOrderedSupportedSources();
5463 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5464 // jalview.util.QuickSort.sort(otherdb, otherdb);
5465 List<DbSourceProxy> otherdb;
5466 JMenu dfetch = new JMenu();
5467 JMenu ifetch = new JMenu();
5468 JMenuItem fetchr = null;
5469 int comp = 0, icomp = 0, mcomp = 15;
5470 String mname = null;
5472 for (String dbclass : dbclasses)
5474 otherdb = sf.getSourceProxy(dbclass);
5475 // add a single entry for this class, or submenu allowing 'fetch
5477 if (otherdb == null || otherdb.size() < 1)
5481 // List<DbSourceProxy> dbs=otherdb;
5482 // otherdb=new ArrayList<DbSourceProxy>();
5483 // for (DbSourceProxy db:dbs)
5485 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5489 mname = "From " + dbclass;
5491 if (otherdb.size() == 1)
5493 final DbSourceProxy[] dassource = otherdb
5494 .toArray(new DbSourceProxy[0]);
5495 DbSourceProxy src = otherdb.get(0);
5496 fetchr = new JMenuItem(src.getDbSource());
5497 fetchr.addActionListener(new ActionListener()
5501 public void actionPerformed(ActionEvent e)
5503 new Thread(new Runnable()
5509 new jalview.ws.DBRefFetcher(alignPanel.av
5510 .getSequenceSelection(),
5511 alignPanel.alignFrame, dassource)
5512 .fetchDBRefs(false);
5518 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from", new String[]{src.getDbName()})));
5524 final DbSourceProxy[] dassource = otherdb
5525 .toArray(new DbSourceProxy[0]);
5527 DbSourceProxy src = otherdb.get(0);
5528 fetchr = new JMenuItem(MessageManager.formatMessage(
5529 "label.fetch_all_param", new String[]
5530 { src.getDbSource() }));
5531 fetchr.addActionListener(new ActionListener()
5534 public void actionPerformed(ActionEvent e)
5536 new Thread(new Runnable()
5542 new jalview.ws.DBRefFetcher(alignPanel.av
5543 .getSequenceSelection(),
5544 alignPanel.alignFrame, dassource)
5545 .fetchDBRefs(false);
5551 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from_all_sources", new String[]{Integer.valueOf(otherdb.size()).toString(), src.getDbSource(), src.getDbName()})));
5554 // and then build the rest of the individual menus
5555 ifetch = new JMenu(MessageManager.formatMessage("label.source_from_db_source", new String[]{src.getDbSource()}));
5557 String imname = null;
5559 for (DbSourceProxy sproxy : otherdb)
5561 String dbname = sproxy.getDbName();
5562 String sname = dbname.length() > 5 ? dbname.substring(0,
5563 5) + "..." : dbname;
5564 String msname = dbname.length() > 10 ? dbname.substring(
5565 0, 10) + "..." : dbname;
5568 imname = MessageManager.formatMessage("label.from_msname", new String[]{sname});
5570 fetchr = new JMenuItem(msname);
5571 final DbSourceProxy[] dassrc =
5573 fetchr.addActionListener(new ActionListener()
5577 public void actionPerformed(ActionEvent e)
5579 new Thread(new Runnable()
5585 new jalview.ws.DBRefFetcher(alignPanel.av
5586 .getSequenceSelection(),
5587 alignPanel.alignFrame, dassrc)
5588 .fetchDBRefs(false);
5594 fetchr.setToolTipText("<html>"
5595 + MessageManager.formatMessage("label.fetch_retrieve_from", new String[]{dbname}));
5598 if (++icomp >= mcomp || i == (otherdb.size()))
5600 ifetch.setText(MessageManager.formatMessage(
5601 "label.source_to_target", imname, sname));
5603 ifetch = new JMenu();
5611 if (comp >= mcomp || dbi >= (dbclasses.length))
5613 dfetch.setText(MessageManager.formatMessage(
5614 "label.source_to_target", mname, dbclass));
5616 dfetch = new JMenu();
5629 * Left justify the whole alignment.
5632 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5634 AlignmentI al = viewport.getAlignment();
5636 viewport.firePropertyChange("alignment", null, al);
5640 * Right justify the whole alignment.
5643 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5645 AlignmentI al = viewport.getAlignment();
5647 viewport.firePropertyChange("alignment", null, al);
5650 public void setShowSeqFeatures(boolean b)
5652 showSeqFeatures.setSelected(true);
5653 viewport.setShowSequenceFeatures(true);
5660 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5661 * awt.event.ActionEvent)
5664 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5666 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5667 alignPanel.paintAlignment(true);
5674 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5678 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5680 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5681 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5689 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5690 * .event.ActionEvent)
5693 protected void showGroupConservation_actionPerformed(ActionEvent e)
5695 viewport.setShowGroupConservation(showGroupConservation.getState());
5696 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5703 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5704 * .event.ActionEvent)
5707 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5709 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5710 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5717 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5718 * .event.ActionEvent)
5721 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5723 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5724 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5728 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5730 showSequenceLogo.setState(true);
5731 viewport.setShowSequenceLogo(true);
5732 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5733 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5737 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5739 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5746 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5747 * .event.ActionEvent)
5750 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5752 if (avc.makeGroupsFromSelection())
5754 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5755 alignPanel.updateAnnotation();
5756 alignPanel.paintAlignment(true);
5761 protected void createGroup_actionPerformed(ActionEvent e)
5763 if (avc.createGroup())
5765 alignPanel.alignmentChanged();
5770 protected void unGroup_actionPerformed(ActionEvent e)
5774 alignPanel.alignmentChanged();
5779 * make the given alignmentPanel the currently selected tab
5781 * @param alignmentPanel
5783 public void setDisplayedView(AlignmentPanel alignmentPanel)
5785 if (!viewport.getSequenceSetId().equals(
5786 alignmentPanel.av.getSequenceSetId()))
5788 throw new Error(MessageManager.getString("error.implementation_error_cannot_show_view_alignment_frame"));
5790 if (tabbedPane != null
5791 & alignPanels.indexOf(alignmentPanel) != tabbedPane
5792 .getSelectedIndex())
5794 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5799 * Action on selection of menu options to Show or Hide annotations.
5802 * @param forSequences
5803 * update sequence-related annotations
5804 * @param forAlignment
5805 * update non-sequence-related annotations
5808 protected void setAnnotationsVisibility(boolean visible,
5809 boolean forSequences, boolean forAlignment)
5811 for (AlignmentAnnotation aa : alignPanel.getAlignment()
5812 .getAlignmentAnnotation())
5814 boolean apply = (aa.sequenceRef == null && forAlignment)
5815 || (aa.sequenceRef != null && forSequences);
5818 aa.visible = visible;
5821 alignPanel.validateAnnotationDimensions(false);
5822 alignPanel.alignmentChanged();
5826 * Store selected annotation sort order for the view and repaint.
5829 protected void sortAnnotations_actionPerformed()
5831 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5833 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5834 alignPanel.paintAlignment(true);
5839 * @return alignment panels in this alignemnt frame
5841 public List<AlignmentViewPanel> getAlignPanels()
5843 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5847 class PrintThread extends Thread
5851 public PrintThread(AlignmentPanel ap)
5856 static PageFormat pf;
5861 PrinterJob printJob = PrinterJob.getPrinterJob();
5865 printJob.setPrintable(ap, pf);
5869 printJob.setPrintable(ap);
5872 if (printJob.printDialog())
5877 } catch (Exception PrintException)
5879 PrintException.printStackTrace();