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.analysis.ScoreModelI;
34 import jalview.bin.Cache;
35 import jalview.commands.CommandI;
36 import jalview.commands.EditCommand;
37 import jalview.commands.OrderCommand;
38 import jalview.commands.RemoveGapColCommand;
39 import jalview.commands.RemoveGapsCommand;
40 import jalview.commands.SlideSequencesCommand;
41 import jalview.commands.TrimRegionCommand;
42 import jalview.datamodel.AlignedCodonFrame;
43 import jalview.datamodel.Alignment;
44 import jalview.datamodel.AlignmentAnnotation;
45 import jalview.datamodel.AlignmentI;
46 import jalview.datamodel.AlignmentOrder;
47 import jalview.datamodel.AlignmentView;
48 import jalview.datamodel.ColumnSelection;
49 import jalview.datamodel.PDBEntry;
50 import jalview.datamodel.SeqCigar;
51 import jalview.datamodel.Sequence;
52 import jalview.datamodel.SequenceGroup;
53 import jalview.datamodel.SequenceI;
54 import jalview.io.AlignmentProperties;
55 import jalview.io.AnnotationFile;
56 import jalview.io.BioJsHTMLOutput;
57 import jalview.io.FeaturesFile;
58 import jalview.io.FileLoader;
59 import jalview.io.FormatAdapter;
60 import jalview.io.HTMLOutput;
61 import jalview.io.IdentifyFile;
62 import jalview.io.JalviewFileChooser;
63 import jalview.io.JalviewFileView;
64 import jalview.io.JnetAnnotationMaker;
65 import jalview.io.NewickFile;
66 import jalview.io.TCoffeeScoreFile;
67 import jalview.jbgui.GAlignFrame;
68 import jalview.schemes.Blosum62ColourScheme;
69 import jalview.schemes.BuriedColourScheme;
70 import jalview.schemes.ClustalxColourScheme;
71 import jalview.schemes.ColourSchemeI;
72 import jalview.schemes.ColourSchemeProperty;
73 import jalview.schemes.HelixColourScheme;
74 import jalview.schemes.HydrophobicColourScheme;
75 import jalview.schemes.NucleotideColourScheme;
76 import jalview.schemes.PIDColourScheme;
77 import jalview.schemes.PurinePyrimidineColourScheme;
78 import jalview.schemes.RNAHelicesColourChooser;
79 import jalview.schemes.ResidueProperties;
80 import jalview.schemes.StrandColourScheme;
81 import jalview.schemes.TCoffeeColourScheme;
82 import jalview.schemes.TaylorColourScheme;
83 import jalview.schemes.TurnColourScheme;
84 import jalview.schemes.UserColourScheme;
85 import jalview.schemes.ZappoColourScheme;
86 import jalview.util.MessageManager;
87 import jalview.ws.jws1.Discoverer;
88 import jalview.ws.jws2.Jws2Discoverer;
89 import jalview.ws.jws2.jabaws2.Jws2Instance;
90 import jalview.ws.seqfetcher.DbSourceProxy;
92 import java.awt.BorderLayout;
93 import java.awt.Component;
94 import java.awt.GridLayout;
95 import java.awt.Rectangle;
96 import java.awt.Toolkit;
97 import java.awt.datatransfer.Clipboard;
98 import java.awt.datatransfer.DataFlavor;
99 import java.awt.datatransfer.StringSelection;
100 import java.awt.datatransfer.Transferable;
101 import java.awt.dnd.DnDConstants;
102 import java.awt.dnd.DropTargetDragEvent;
103 import java.awt.dnd.DropTargetDropEvent;
104 import java.awt.dnd.DropTargetEvent;
105 import java.awt.dnd.DropTargetListener;
106 import java.awt.event.ActionEvent;
107 import java.awt.event.ActionListener;
108 import java.awt.event.KeyAdapter;
109 import java.awt.event.KeyEvent;
110 import java.awt.event.MouseAdapter;
111 import java.awt.event.MouseEvent;
112 import java.awt.print.PageFormat;
113 import java.awt.print.PrinterJob;
114 import java.beans.PropertyChangeEvent;
117 import java.util.ArrayList;
118 import java.util.Enumeration;
119 import java.util.Hashtable;
120 import java.util.List;
121 import java.util.Vector;
123 import javax.swing.JButton;
124 import javax.swing.JCheckBoxMenuItem;
125 import javax.swing.JEditorPane;
126 import javax.swing.JInternalFrame;
127 import javax.swing.JLabel;
128 import javax.swing.JLayeredPane;
129 import javax.swing.JMenu;
130 import javax.swing.JMenuItem;
131 import javax.swing.JOptionPane;
132 import javax.swing.JPanel;
133 import javax.swing.JProgressBar;
134 import javax.swing.JRadioButtonMenuItem;
135 import javax.swing.JScrollPane;
136 import javax.swing.SwingUtilities;
142 * @version $Revision$
144 public class AlignFrame extends GAlignFrame implements DropTargetListener,
145 IProgressIndicator, AlignViewControllerGuiI
149 public static final int DEFAULT_WIDTH = 700;
152 public static final int DEFAULT_HEIGHT = 500;
154 public AlignmentPanel alignPanel;
156 AlignViewport viewport;
158 public AlignViewControllerI avc;
160 Vector alignPanels = new Vector();
163 * Last format used to load or save alignments in this window
165 String currentFileFormat = null;
168 * Current filename for this alignment
170 String fileName = null;
173 * Creates a new AlignFrame object with specific width and height.
179 public AlignFrame(AlignmentI al, int width, int height)
181 this(al, null, width, height);
185 * Creates a new AlignFrame object with specific width, height and
191 * @param sequenceSetId
193 public AlignFrame(AlignmentI al, int width, int height,
194 String sequenceSetId)
196 this(al, null, width, height, sequenceSetId);
200 * Creates a new AlignFrame object with specific width, height and
206 * @param sequenceSetId
209 public AlignFrame(AlignmentI al, int width, int height,
210 String sequenceSetId, String viewId)
212 this(al, null, width, height, sequenceSetId, viewId);
216 * new alignment window with hidden columns
220 * @param hiddenColumns
221 * ColumnSelection or null
223 * Width of alignment frame
227 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
228 int width, int height)
230 this(al, hiddenColumns, width, height, null);
234 * Create alignment frame for al with hiddenColumns, a specific width and
235 * height, and specific sequenceId
238 * @param hiddenColumns
241 * @param sequenceSetId
244 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
245 int width, int height, String sequenceSetId)
247 this(al, hiddenColumns, width, height, sequenceSetId, null);
251 * Create alignment frame for al with hiddenColumns, a specific width and
252 * height, and specific sequenceId
255 * @param hiddenColumns
258 * @param sequenceSetId
263 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
264 int width, int height, String sequenceSetId, String viewId)
266 setSize(width, height);
268 if (al.getDataset() == null)
273 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
275 alignPanel = new AlignmentPanel(this, viewport);
278 addAlignmentPanel(alignPanel, true);
283 * Make a new AlignFrame from existing alignmentPanels
290 public AlignFrame(AlignmentPanel ap)
294 addAlignmentPanel(ap, false);
299 * initalise the alignframe from the underlying viewport data and the
304 avc = new jalview.controller.AlignViewController(this, viewport,
306 if (viewport.getAlignmentConservationAnnotation() == null)
308 BLOSUM62Colour.setEnabled(false);
309 conservationMenuItem.setEnabled(false);
310 modifyConservation.setEnabled(false);
311 // PIDColour.setEnabled(false);
312 // abovePIDThreshold.setEnabled(false);
313 // modifyPID.setEnabled(false);
316 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
319 if (sortby.equals("Id"))
321 sortIDMenuItem_actionPerformed(null);
323 else if (sortby.equals("Pairwise Identity"))
325 sortPairwiseMenuItem_actionPerformed(null);
328 if (Desktop.desktop != null)
330 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
331 addServiceListeners();
332 setGUINucleotide(viewport.getAlignment().isNucleotide());
335 setMenusFromViewport(viewport);
336 buildSortByAnnotationScoresMenu();
339 if (viewport.wrapAlignment)
341 wrapMenuItem_actionPerformed(null);
344 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
346 this.overviewMenuItem_actionPerformed(null);
354 * Change the filename and format for the alignment, and enable the 'reload'
355 * button functionality.
362 public void setFileName(String file, String format)
365 currentFileFormat = format;
366 reload.setEnabled(true);
369 void addKeyListener()
371 addKeyListener(new KeyAdapter()
374 public void keyPressed(KeyEvent evt)
376 if (viewport.cursorMode
377 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
378 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
379 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
380 && Character.isDigit(evt.getKeyChar()))
382 alignPanel.seqPanel.numberPressed(evt.getKeyChar());
385 switch (evt.getKeyCode())
388 case 27: // escape key
389 deselectAllSequenceMenuItem_actionPerformed(null);
393 case KeyEvent.VK_DOWN:
394 if (evt.isAltDown() || !viewport.cursorMode)
396 moveSelectedSequences(false);
398 if (viewport.cursorMode)
400 alignPanel.seqPanel.moveCursor(0, 1);
405 if (evt.isAltDown() || !viewport.cursorMode)
407 moveSelectedSequences(true);
409 if (viewport.cursorMode)
411 alignPanel.seqPanel.moveCursor(0, -1);
416 case KeyEvent.VK_LEFT:
417 if (evt.isAltDown() || !viewport.cursorMode)
419 slideSequences(false, alignPanel.seqPanel.getKeyboardNo1());
423 alignPanel.seqPanel.moveCursor(-1, 0);
428 case KeyEvent.VK_RIGHT:
429 if (evt.isAltDown() || !viewport.cursorMode)
431 slideSequences(true, alignPanel.seqPanel.getKeyboardNo1());
435 alignPanel.seqPanel.moveCursor(1, 0);
439 case KeyEvent.VK_SPACE:
440 if (viewport.cursorMode)
442 alignPanel.seqPanel.insertGapAtCursor(evt.isControlDown()
443 || evt.isShiftDown() || evt.isAltDown());
447 // case KeyEvent.VK_A:
448 // if (viewport.cursorMode)
450 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
451 // //System.out.println("A");
455 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
456 * System.out.println("closing bracket"); } break;
458 case KeyEvent.VK_DELETE:
459 case KeyEvent.VK_BACK_SPACE:
460 if (!viewport.cursorMode)
462 cut_actionPerformed(null);
466 alignPanel.seqPanel.deleteGapAtCursor(evt.isControlDown()
467 || evt.isShiftDown() || evt.isAltDown());
473 if (viewport.cursorMode)
475 alignPanel.seqPanel.setCursorRow();
479 if (viewport.cursorMode && !evt.isControlDown())
481 alignPanel.seqPanel.setCursorColumn();
485 if (viewport.cursorMode)
487 alignPanel.seqPanel.setCursorPosition();
491 case KeyEvent.VK_ENTER:
492 case KeyEvent.VK_COMMA:
493 if (viewport.cursorMode)
495 alignPanel.seqPanel.setCursorRowAndColumn();
500 if (viewport.cursorMode)
502 alignPanel.seqPanel.setSelectionAreaAtCursor(true);
506 if (viewport.cursorMode)
508 alignPanel.seqPanel.setSelectionAreaAtCursor(false);
513 viewport.cursorMode = !viewport.cursorMode;
514 statusBar.setText(MessageManager.formatMessage(
515 "label.keyboard_editing_mode", new String[]
516 { (viewport.cursorMode ? "on" : "off") }));
517 if (viewport.cursorMode)
519 alignPanel.seqPanel.seqCanvas.cursorX = viewport.startRes;
520 alignPanel.seqPanel.seqCanvas.cursorY = viewport.startSeq;
522 alignPanel.seqPanel.seqCanvas.repaint();
528 Help.showHelpWindow();
529 } catch (Exception ex)
531 ex.printStackTrace();
536 boolean toggleSeqs = !evt.isControlDown();
537 boolean toggleCols = !evt.isShiftDown();
538 toggleHiddenRegions(toggleSeqs, toggleCols);
541 case KeyEvent.VK_PAGE_UP:
542 if (viewport.wrapAlignment)
544 alignPanel.scrollUp(true);
548 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
549 - viewport.endSeq + viewport.startSeq);
552 case KeyEvent.VK_PAGE_DOWN:
553 if (viewport.wrapAlignment)
555 alignPanel.scrollUp(false);
559 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
560 + viewport.endSeq - viewport.startSeq);
567 public void keyReleased(KeyEvent evt)
569 switch (evt.getKeyCode())
571 case KeyEvent.VK_LEFT:
572 if (evt.isAltDown() || !viewport.cursorMode)
574 viewport.firePropertyChange("alignment", null, viewport
575 .getAlignment().getSequences());
579 case KeyEvent.VK_RIGHT:
580 if (evt.isAltDown() || !viewport.cursorMode)
582 viewport.firePropertyChange("alignment", null, viewport
583 .getAlignment().getSequences());
591 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
593 ap.alignFrame = this;
594 avc = new jalview.controller.AlignViewController(this, viewport,
597 alignPanels.addElement(ap);
599 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
601 int aSize = alignPanels.size();
603 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
605 if (aSize == 1 && ap.av.viewName == null)
607 this.getContentPane().add(ap, BorderLayout.CENTER);
613 setInitialTabVisible();
616 expandViews.setEnabled(true);
617 gatherViews.setEnabled(true);
618 tabbedPane.addTab(ap.av.viewName, ap);
620 ap.setVisible(false);
625 if (ap.av.isPadGaps())
627 ap.av.getAlignment().padGaps();
629 ap.av.updateConservation(ap);
630 ap.av.updateConsensus(ap);
631 ap.av.updateStrucConsensus(ap);
635 public void setInitialTabVisible()
637 expandViews.setEnabled(true);
638 gatherViews.setEnabled(true);
639 tabbedPane.setVisible(true);
640 AlignmentPanel first = (AlignmentPanel) alignPanels.firstElement();
641 tabbedPane.addTab(first.av.viewName, first);
642 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
645 public AlignViewport getViewport()
650 /* Set up intrinsic listeners for dynamically generated GUI bits. */
651 private void addServiceListeners()
653 final java.beans.PropertyChangeListener thisListener;
654 Desktop.instance.addJalviewPropertyChangeListener("services",
655 thisListener = new java.beans.PropertyChangeListener()
658 public void propertyChange(PropertyChangeEvent evt)
660 // // System.out.println("Discoverer property change.");
661 // if (evt.getPropertyName().equals("services"))
663 SwingUtilities.invokeLater(new Runnable()
670 .println("Rebuild WS Menu for service change");
671 BuildWebServiceMenu();
678 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
681 public void internalFrameClosed(
682 javax.swing.event.InternalFrameEvent evt)
684 System.out.println("deregistering discoverer listener");
685 Desktop.instance.removeJalviewPropertyChangeListener("services",
687 closeMenuItem_actionPerformed(true);
690 // Finally, build the menu once to get current service state
691 new Thread(new Runnable()
696 BuildWebServiceMenu();
701 public void setGUINucleotide(boolean nucleotide)
703 showTranslation.setVisible(nucleotide);
704 conservationMenuItem.setEnabled(!nucleotide);
705 modifyConservation.setEnabled(!nucleotide);
706 showGroupConservation.setEnabled(!nucleotide);
707 rnahelicesColour.setEnabled(nucleotide);
708 purinePyrimidineColour.setEnabled(nucleotide);
709 // Remember AlignFrame always starts as protein
713 // calculateMenu.remove(calculateMenu.getItemCount() - 2);
718 * set up menus for the currently viewport. This may be called after any
719 * operation that affects the data in the current view (selection changed,
720 * etc) to update the menus to reflect the new state.
722 public void setMenusForViewport()
724 setMenusFromViewport(viewport);
728 * Need to call this method when tabs are selected for multiple views, or when
729 * loading from Jalview2XML.java
734 void setMenusFromViewport(AlignViewport av)
736 padGapsMenuitem.setSelected(av.isPadGaps());
737 colourTextMenuItem.setSelected(av.showColourText);
738 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
739 conservationMenuItem.setSelected(av.getConservationSelected());
740 seqLimits.setSelected(av.getShowJVSuffix());
741 idRightAlign.setSelected(av.rightAlignIds);
742 centreColumnLabelsMenuItem.setState(av.centreColumnLabels);
743 renderGapsMenuItem.setSelected(av.renderGaps);
744 wrapMenuItem.setSelected(av.wrapAlignment);
745 scaleAbove.setVisible(av.wrapAlignment);
746 scaleLeft.setVisible(av.wrapAlignment);
747 scaleRight.setVisible(av.wrapAlignment);
748 annotationPanelMenuItem.setState(av.showAnnotation);
750 * Show/hide annotations only enabled if annotation panel is shown
752 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
753 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
754 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
755 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
756 viewBoxesMenuItem.setSelected(av.showBoxes);
757 viewTextMenuItem.setSelected(av.showText);
758 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
759 showGroupConsensus.setSelected(av.isShowGroupConsensus());
760 showGroupConservation.setSelected(av.isShowGroupConservation());
761 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
762 showSequenceLogo.setSelected(av.isShowSequenceLogo());
763 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
765 setColourSelected(ColourSchemeProperty.getColourName(av
766 .getGlobalColourScheme()));
768 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
769 hiddenMarkers.setState(av.showHiddenMarkers);
770 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
771 showNpFeatsMenuitem.setSelected(av.isShowNpFeats());
772 showDbRefsMenuitem.setSelected(av.isShowDbRefs());
773 autoCalculate.setSelected(av.autoCalculateConsensus);
774 sortByTree.setSelected(av.sortByTree);
775 listenToViewSelections.setSelected(av.followSelection);
776 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
778 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
779 setShowProductsEnabled();
783 // methods for implementing IProgressIndicator
784 // need to refactor to a reusable stub class
785 Hashtable progressBars, progressBarHandlers;
790 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
793 public void setProgressBar(String message, long id)
795 if (progressBars == null)
797 progressBars = new Hashtable();
798 progressBarHandlers = new Hashtable();
801 JPanel progressPanel;
802 Long lId = new Long(id);
803 GridLayout layout = (GridLayout) statusPanel.getLayout();
804 if (progressBars.get(lId) != null)
806 progressPanel = (JPanel) progressBars.get(new Long(id));
807 statusPanel.remove(progressPanel);
808 progressBars.remove(lId);
809 progressPanel = null;
812 statusBar.setText(message);
814 if (progressBarHandlers.contains(lId))
816 progressBarHandlers.remove(lId);
818 layout.setRows(layout.getRows() - 1);
822 progressPanel = new JPanel(new BorderLayout(10, 5));
824 JProgressBar progressBar = new JProgressBar();
825 progressBar.setIndeterminate(true);
827 progressPanel.add(new JLabel(message), BorderLayout.WEST);
828 progressPanel.add(progressBar, BorderLayout.CENTER);
830 layout.setRows(layout.getRows() + 1);
831 statusPanel.add(progressPanel);
833 progressBars.put(lId, progressPanel);
836 // setMenusForViewport();
841 public void registerHandler(final long id,
842 final IProgressIndicatorHandler handler)
844 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
846 throw new Error(MessageManager.getString("error.call_setprogressbar_before_registering_handler"));
848 progressBarHandlers.put(new Long(id), handler);
849 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
850 if (handler.canCancel())
852 JButton cancel = new JButton(
853 MessageManager.getString("action.cancel"));
854 final IProgressIndicator us = this;
855 cancel.addActionListener(new ActionListener()
859 public void actionPerformed(ActionEvent e)
861 handler.cancelActivity(id);
862 us.setProgressBar(MessageManager.formatMessage("label.cancelled_params", new String[]{((JLabel) progressPanel.getComponent(0)).getText()}), id);
865 progressPanel.add(cancel, BorderLayout.EAST);
871 * @return true if any progress bars are still active
874 public boolean operationInProgress()
876 if (progressBars != null && progressBars.size() > 0)
884 public void setStatus(String text)
886 statusBar.setText(text);
890 * Added so Castor Mapping file can obtain Jalview Version
892 public String getVersion()
894 return jalview.bin.Cache.getProperty("VERSION");
897 public FeatureRenderer getFeatureRenderer()
899 return alignPanel.seqPanel.seqCanvas.getFeatureRenderer();
903 public void fetchSequence_actionPerformed(ActionEvent e)
905 new SequenceFetcher(this);
909 public void addFromFile_actionPerformed(ActionEvent e)
911 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
915 public void reload_actionPerformed(ActionEvent e)
917 if (fileName != null)
919 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
920 // originating file's format
921 // TODO: work out how to recover feature settings for correct view(s) when
923 if (currentFileFormat.equals("Jalview"))
925 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
926 for (int i = 0; i < frames.length; i++)
928 if (frames[i] instanceof AlignFrame && frames[i] != this
929 && ((AlignFrame) frames[i]).fileName != null
930 && ((AlignFrame) frames[i]).fileName.equals(fileName))
934 frames[i].setSelected(true);
935 Desktop.instance.closeAssociatedWindows();
936 } catch (java.beans.PropertyVetoException ex)
942 Desktop.instance.closeAssociatedWindows();
944 FileLoader loader = new FileLoader();
945 String protocol = fileName.startsWith("http:") ? "URL" : "File";
946 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
950 Rectangle bounds = this.getBounds();
952 FileLoader loader = new FileLoader();
953 String protocol = fileName.startsWith("http:") ? "URL" : "File";
954 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
955 protocol, currentFileFormat);
957 newframe.setBounds(bounds);
958 if (featureSettings != null && featureSettings.isShowing())
960 final Rectangle fspos = featureSettings.frame.getBounds();
961 // TODO: need a 'show feature settings' function that takes bounds -
962 // need to refactor Desktop.addFrame
963 newframe.featureSettings_actionPerformed(null);
964 final FeatureSettings nfs = newframe.featureSettings;
965 SwingUtilities.invokeLater(new Runnable()
970 nfs.frame.setBounds(fspos);
973 this.featureSettings.close();
974 this.featureSettings = null;
976 this.closeMenuItem_actionPerformed(true);
982 public void addFromText_actionPerformed(ActionEvent e)
984 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
988 public void addFromURL_actionPerformed(ActionEvent e)
990 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
994 public void save_actionPerformed(ActionEvent e)
997 || (currentFileFormat == null || !jalview.io.FormatAdapter
998 .isValidIOFormat(currentFileFormat, true))
999 || fileName.startsWith("http"))
1001 saveAs_actionPerformed(null);
1005 saveAlignment(fileName, currentFileFormat);
1016 public void saveAs_actionPerformed(ActionEvent e)
1018 JalviewFileChooser chooser = new JalviewFileChooser(
1019 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
1020 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
1021 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
1022 currentFileFormat, false);
1024 chooser.setFileView(new JalviewFileView());
1025 chooser.setDialogTitle(MessageManager.getString("label.save_alignment_to_file"));
1026 chooser.setToolTipText(MessageManager.getString("action.save"));
1028 int value = chooser.showSaveDialog(this);
1030 if (value == JalviewFileChooser.APPROVE_OPTION)
1032 currentFileFormat = chooser.getSelectedFormat();
1033 if (currentFileFormat == null)
1036 .showInternalMessageDialog(
1039 .getString("label.select_file_format_before_saving"),
1041 .getString("label.file_format_not_specified"),
1042 JOptionPane.WARNING_MESSAGE);
1043 value = chooser.showSaveDialog(this);
1047 fileName = chooser.getSelectedFile().getPath();
1049 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
1052 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
1053 if (currentFileFormat.indexOf(" ") > -1)
1055 currentFileFormat = currentFileFormat.substring(0,
1056 currentFileFormat.indexOf(" "));
1058 saveAlignment(fileName, currentFileFormat);
1062 public boolean saveAlignment(String file, String format)
1064 boolean success = true;
1066 if (format.equalsIgnoreCase("Jalview"))
1068 String shortName = title;
1070 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1072 shortName = shortName.substring(shortName
1073 .lastIndexOf(java.io.File.separatorChar) + 1);
1076 success = new Jalview2XML().SaveAlignment(this, file, shortName);
1078 statusBar.setText(MessageManager.formatMessage(
1079 "label.successfully_saved_to_file_in_format", new String[]
1080 { fileName, format }));
1085 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1087 warningMessage("Cannot save file " + fileName + " using format "
1088 + format, "Alignment output format not supported");
1089 saveAs_actionPerformed(null);
1090 // JBPNote need to have a raise_gui flag here
1094 String[] omitHidden = null;
1096 if (viewport.hasHiddenColumns())
1098 int reply = JOptionPane
1099 .showInternalConfirmDialog(
1102 .getString("label.alignment_contains_hidden_columns"),
1104 .getString("action.save_omit_hidden_columns"),
1105 JOptionPane.YES_NO_OPTION,
1106 JOptionPane.QUESTION_MESSAGE);
1108 if (reply == JOptionPane.YES_OPTION)
1110 omitHidden = viewport.getViewAsString(false);
1113 FormatAdapter f = new FormatAdapter();
1114 String output = f.formatSequences(format,
1115 viewport.getAlignment(), // class cast exceptions will
1116 // occur in the distant future
1117 omitHidden, f.getCacheSuffixDefault(format),
1118 viewport.getColumnSelection());
1128 java.io.PrintWriter out = new java.io.PrintWriter(
1129 new java.io.FileWriter(file));
1133 this.setTitle(file);
1134 statusBar.setText(MessageManager.formatMessage(
1135 "label.successfully_saved_to_file_in_format",
1137 { fileName, format }));
1138 } catch (Exception ex)
1141 ex.printStackTrace();
1148 JOptionPane.showInternalMessageDialog(this, MessageManager
1149 .formatMessage("label.couldnt_save_file", new String[]
1150 { fileName }), MessageManager
1151 .getString("label.error_saving_file"),
1152 JOptionPane.WARNING_MESSAGE);
1158 private void warningMessage(String warning, String title)
1160 if (new jalview.util.Platform().isHeadless())
1162 System.err.println("Warning: " + title + "\nWarning: " + warning);
1167 JOptionPane.showInternalMessageDialog(this, warning, title,
1168 JOptionPane.WARNING_MESSAGE);
1180 protected void outputText_actionPerformed(ActionEvent e)
1182 String[] omitHidden = null;
1184 if (viewport.hasHiddenColumns())
1186 int reply = JOptionPane
1187 .showInternalConfirmDialog(
1190 .getString("label.alignment_contains_hidden_columns"),
1192 .getString("action.save_omit_hidden_columns"),
1193 JOptionPane.YES_NO_OPTION,
1194 JOptionPane.QUESTION_MESSAGE);
1196 if (reply == JOptionPane.YES_OPTION)
1198 omitHidden = viewport.getViewAsString(false);
1202 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1203 cap.setForInput(null);
1207 cap.setText(new FormatAdapter().formatSequences(e.getActionCommand(),
1208 viewport.getAlignment(), omitHidden,
1209 viewport.getColumnSelection()));
1210 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1211 "label.alignment_output_command", new String[]
1212 { e.getActionCommand() }), 600, 500);
1213 } catch (OutOfMemoryError oom)
1215 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1228 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1230 new HTMLOutput(alignPanel,
1231 alignPanel.seqPanel.seqCanvas.getSequenceRenderer(),
1232 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
1236 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1238 new BioJsHTMLOutput(alignPanel,
1239 alignPanel.seqPanel.seqCanvas.getSequenceRenderer(),
1240 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
1242 public void createImageMap(File file, String image)
1244 alignPanel.makePNGImageMap(file, image);
1254 public void createPNG(File f)
1256 alignPanel.makePNG(f);
1266 public void createEPS(File f)
1268 alignPanel.makeEPS(f);
1271 public void createSVG(File f)
1273 alignPanel.makeSVG(f);
1276 public void pageSetup_actionPerformed(ActionEvent e)
1278 PrinterJob printJob = PrinterJob.getPrinterJob();
1279 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1289 public void printMenuItem_actionPerformed(ActionEvent e)
1291 // Putting in a thread avoids Swing painting problems
1292 PrintThread thread = new PrintThread(alignPanel);
1297 public void exportFeatures_actionPerformed(ActionEvent e)
1299 new AnnotationExporter().exportFeatures(alignPanel);
1303 public void exportAnnotations_actionPerformed(ActionEvent e)
1305 new AnnotationExporter().exportAnnotations(alignPanel,
1306 viewport.showAnnotation ? viewport.getAlignment()
1307 .getAlignmentAnnotation() : null, viewport
1308 .getAlignment().getGroups(), ((Alignment) viewport
1309 .getAlignment()).alignmentProperties);
1313 public void associatedData_actionPerformed(ActionEvent e)
1315 // Pick the tree file
1316 JalviewFileChooser chooser = new JalviewFileChooser(
1317 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1318 chooser.setFileView(new JalviewFileView());
1319 chooser.setDialogTitle(MessageManager
1320 .getString("label.load_jalview_annotations"));
1321 chooser.setToolTipText(MessageManager
1322 .getString("label.load_jalview_annotations"));
1324 int value = chooser.showOpenDialog(null);
1326 if (value == JalviewFileChooser.APPROVE_OPTION)
1328 String choice = chooser.getSelectedFile().getPath();
1329 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1330 loadJalviewDataFile(choice, null, null, null);
1336 * Close the current view or all views in the alignment frame. If the frame
1337 * only contains one view then the alignment will be removed from memory.
1339 * @param closeAllTabs
1342 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1344 if (alignPanels != null && alignPanels.size() < 2)
1346 closeAllTabs = true;
1351 if (alignPanels != null)
1355 if (this.isClosed())
1357 // really close all the windows - otherwise wait till
1358 // setClosed(true) is called
1359 for (int i = 0; i < alignPanels.size(); i++)
1361 AlignmentPanel ap = (AlignmentPanel) alignPanels.elementAt(i);
1368 closeView(alignPanel);
1374 this.setClosed(true);
1376 } catch (Exception ex)
1378 ex.printStackTrace();
1383 * close alignPanel2 and shuffle tabs appropriately.
1385 * @param alignPanel2
1387 public void closeView(AlignmentPanel alignPanel2)
1389 int index = tabbedPane.getSelectedIndex();
1390 int closedindex = tabbedPane.indexOfComponent(alignPanel2);
1391 alignPanels.removeElement(alignPanel2);
1393 // if (viewport == alignPanel2.av)
1397 alignPanel2.closePanel();
1400 tabbedPane.removeTabAt(closedindex);
1401 tabbedPane.validate();
1403 if (index > closedindex || index == tabbedPane.getTabCount())
1405 // modify currently selected tab index if necessary.
1409 this.tabSelectionChanged(index);
1415 void updateEditMenuBar()
1418 if (viewport.historyList.size() > 0)
1420 undoMenuItem.setEnabled(true);
1421 CommandI command = (CommandI) viewport.historyList.peek();
1422 undoMenuItem.setText(MessageManager.formatMessage(
1423 "label.undo_command", new String[]
1424 { command.getDescription() }));
1428 undoMenuItem.setEnabled(false);
1429 undoMenuItem.setText(MessageManager.getString("action.undo"));
1432 if (viewport.redoList.size() > 0)
1434 redoMenuItem.setEnabled(true);
1436 CommandI command = (CommandI) viewport.redoList.peek();
1437 redoMenuItem.setText(MessageManager.formatMessage(
1438 "label.redo_command", new String[]
1439 { command.getDescription() }));
1443 redoMenuItem.setEnabled(false);
1444 redoMenuItem.setText(MessageManager.getString("action.redo"));
1448 public void addHistoryItem(CommandI command)
1450 if (command.getSize() > 0)
1452 viewport.historyList.push(command);
1453 viewport.redoList.clear();
1454 updateEditMenuBar();
1455 viewport.updateHiddenColumns();
1456 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1457 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1458 // viewport.getColumnSelection()
1459 // .getHiddenColumns().size() > 0);
1465 * @return alignment objects for all views
1467 AlignmentI[] getViewAlignments()
1469 if (alignPanels != null)
1471 Enumeration e = alignPanels.elements();
1472 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1473 for (int i = 0; e.hasMoreElements(); i++)
1475 als[i] = ((AlignmentPanel) e.nextElement()).av.getAlignment();
1479 if (viewport != null)
1481 return new AlignmentI[]
1482 { viewport.getAlignment() };
1494 protected void undoMenuItem_actionPerformed(ActionEvent e)
1496 if (viewport.historyList.empty())
1500 CommandI command = (CommandI) viewport.historyList.pop();
1501 viewport.redoList.push(command);
1502 command.undoCommand(getViewAlignments());
1504 AlignViewport originalSource = getOriginatingSource(command);
1505 updateEditMenuBar();
1507 if (originalSource != null)
1509 if (originalSource != viewport)
1512 .warn("Implementation worry: mismatch of viewport origin for undo");
1514 originalSource.updateHiddenColumns();
1515 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1517 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1518 // viewport.getColumnSelection()
1519 // .getHiddenColumns().size() > 0);
1520 originalSource.firePropertyChange("alignment", null, originalSource
1521 .getAlignment().getSequences());
1532 protected void redoMenuItem_actionPerformed(ActionEvent e)
1534 if (viewport.redoList.size() < 1)
1539 CommandI command = (CommandI) viewport.redoList.pop();
1540 viewport.historyList.push(command);
1541 command.doCommand(getViewAlignments());
1543 AlignViewport originalSource = getOriginatingSource(command);
1544 updateEditMenuBar();
1546 if (originalSource != null)
1549 if (originalSource != viewport)
1552 .warn("Implementation worry: mismatch of viewport origin for redo");
1554 originalSource.updateHiddenColumns();
1555 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1557 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1558 // viewport.getColumnSelection()
1559 // .getHiddenColumns().size() > 0);
1560 originalSource.firePropertyChange("alignment", null, originalSource
1561 .getAlignment().getSequences());
1565 AlignViewport getOriginatingSource(CommandI command)
1567 AlignViewport originalSource = null;
1568 // For sequence removal and addition, we need to fire
1569 // the property change event FROM the viewport where the
1570 // original alignment was altered
1571 AlignmentI al = null;
1572 if (command instanceof EditCommand)
1574 EditCommand editCommand = (EditCommand) command;
1575 al = editCommand.getAlignment();
1576 Vector comps = (Vector) PaintRefresher.components.get(viewport
1577 .getSequenceSetId());
1579 for (int i = 0; i < comps.size(); i++)
1581 if (comps.elementAt(i) instanceof AlignmentPanel)
1583 if (al == ((AlignmentPanel) comps.elementAt(i)).av.getAlignment())
1585 originalSource = ((AlignmentPanel) comps.elementAt(i)).av;
1592 if (originalSource == null)
1594 // The original view is closed, we must validate
1595 // the current view against the closed view first
1598 PaintRefresher.validateSequences(al, viewport.getAlignment());
1601 originalSource = viewport;
1604 return originalSource;
1613 public void moveSelectedSequences(boolean up)
1615 SequenceGroup sg = viewport.getSelectionGroup();
1621 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1622 viewport.getHiddenRepSequences(), up);
1623 alignPanel.paintAlignment(true);
1626 synchronized void slideSequences(boolean right, int size)
1628 List<SequenceI> sg = new Vector();
1629 if (viewport.cursorMode)
1631 sg.add(viewport.getAlignment().getSequenceAt(
1632 alignPanel.seqPanel.seqCanvas.cursorY));
1634 else if (viewport.getSelectionGroup() != null
1635 && viewport.getSelectionGroup().getSize() != viewport
1636 .getAlignment().getHeight())
1638 sg = viewport.getSelectionGroup().getSequences(
1639 viewport.getHiddenRepSequences());
1647 Vector invertGroup = new Vector();
1649 for (int i = 0; i < viewport.getAlignment().getHeight(); i++)
1651 if (!sg.contains(viewport.getAlignment().getSequenceAt(i)))
1653 invertGroup.add(viewport.getAlignment().getSequenceAt(i));
1657 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1659 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1660 for (int i = 0; i < invertGroup.size(); i++)
1662 seqs2[i] = (SequenceI) invertGroup.elementAt(i);
1665 SlideSequencesCommand ssc;
1668 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1669 size, viewport.getGapCharacter());
1673 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1674 size, viewport.getGapCharacter());
1677 int groupAdjustment = 0;
1678 if (ssc.getGapsInsertedBegin() && right)
1680 if (viewport.cursorMode)
1682 alignPanel.seqPanel.moveCursor(size, 0);
1686 groupAdjustment = size;
1689 else if (!ssc.getGapsInsertedBegin() && !right)
1691 if (viewport.cursorMode)
1693 alignPanel.seqPanel.moveCursor(-size, 0);
1697 groupAdjustment = -size;
1701 if (groupAdjustment != 0)
1703 viewport.getSelectionGroup().setStartRes(
1704 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1705 viewport.getSelectionGroup().setEndRes(
1706 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1709 boolean appendHistoryItem = false;
1710 if (viewport.historyList != null && viewport.historyList.size() > 0
1711 && viewport.historyList.peek() instanceof SlideSequencesCommand)
1713 appendHistoryItem = ssc
1714 .appendSlideCommand((SlideSequencesCommand) viewport.historyList
1718 if (!appendHistoryItem)
1720 addHistoryItem(ssc);
1733 protected void copy_actionPerformed(ActionEvent e)
1736 if (viewport.getSelectionGroup() == null)
1740 // TODO: preserve the ordering of displayed alignment annotation in any
1741 // internal paste (particularly sequence associated annotation)
1742 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1743 String[] omitHidden = null;
1745 if (viewport.hasHiddenColumns())
1747 omitHidden = viewport.getViewAsString(true);
1750 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1753 StringSelection ss = new StringSelection(output);
1757 jalview.gui.Desktop.internalCopy = true;
1758 // Its really worth setting the clipboard contents
1759 // to empty before setting the large StringSelection!!
1760 Toolkit.getDefaultToolkit().getSystemClipboard()
1761 .setContents(new StringSelection(""), null);
1763 Toolkit.getDefaultToolkit().getSystemClipboard()
1764 .setContents(ss, Desktop.instance);
1765 } catch (OutOfMemoryError er)
1767 new OOMWarning("copying region", er);
1771 Vector hiddenColumns = null;
1772 if (viewport.hasHiddenColumns())
1774 hiddenColumns = new Vector();
1775 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1776 .getSelectionGroup().getEndRes();
1777 for (int i = 0; i < viewport.getColumnSelection().getHiddenColumns()
1780 int[] region = (int[]) viewport.getColumnSelection()
1781 .getHiddenColumns().elementAt(i);
1782 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1784 hiddenColumns.addElement(new int[]
1785 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1790 Desktop.jalviewClipboard = new Object[]
1791 { seqs, viewport.getAlignment().getDataset(), hiddenColumns };
1792 statusBar.setText(MessageManager.formatMessage(
1793 "label.copied_sequences_to_clipboard", new String[]
1794 { Integer.valueOf(seqs.length).toString() }));
1804 protected void pasteNew_actionPerformed(ActionEvent e)
1816 protected void pasteThis_actionPerformed(ActionEvent e)
1822 * Paste contents of Jalview clipboard
1824 * @param newAlignment
1825 * true to paste to a new alignment, otherwise add to this.
1827 void paste(boolean newAlignment)
1829 boolean externalPaste = true;
1832 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1833 Transferable contents = c.getContents(this);
1835 if (contents == null)
1843 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1844 if (str.length() < 1)
1849 format = new IdentifyFile().Identify(str, "Paste");
1851 } catch (OutOfMemoryError er)
1853 new OOMWarning("Out of memory pasting sequences!!", er);
1857 SequenceI[] sequences;
1858 boolean annotationAdded = false;
1859 AlignmentI alignment = null;
1861 if (Desktop.jalviewClipboard != null)
1863 // The clipboard was filled from within Jalview, we must use the
1865 // And dataset from the copied alignment
1866 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1867 // be doubly sure that we create *new* sequence objects.
1868 sequences = new SequenceI[newseq.length];
1869 for (int i = 0; i < newseq.length; i++)
1871 sequences[i] = new Sequence(newseq[i]);
1873 alignment = new Alignment(sequences);
1874 externalPaste = false;
1878 // parse the clipboard as an alignment.
1879 alignment = new FormatAdapter().readFile(str, "Paste", format);
1880 sequences = alignment.getSequencesArray();
1884 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1890 if (Desktop.jalviewClipboard != null)
1892 // dataset is inherited
1893 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1897 // new dataset is constructed
1898 alignment.setDataset(null);
1900 alwidth = alignment.getWidth() + 1;
1904 AlignmentI pastedal = alignment; // preserve pasted alignment object
1905 // Add pasted sequences and dataset into existing alignment.
1906 alignment = viewport.getAlignment();
1907 alwidth = alignment.getWidth() + 1;
1908 // decide if we need to import sequences from an existing dataset
1909 boolean importDs = Desktop.jalviewClipboard != null
1910 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1911 // importDs==true instructs us to copy over new dataset sequences from
1912 // an existing alignment
1913 Vector newDs = (importDs) ? new Vector() : null; // used to create
1914 // minimum dataset set
1916 for (int i = 0; i < sequences.length; i++)
1920 newDs.addElement(null);
1922 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
1924 if (importDs && ds != null)
1926 if (!newDs.contains(ds))
1928 newDs.setElementAt(ds, i);
1929 ds = new Sequence(ds);
1930 // update with new dataset sequence
1931 sequences[i].setDatasetSequence(ds);
1935 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
1940 // copy and derive new dataset sequence
1941 sequences[i] = sequences[i].deriveSequence();
1942 alignment.getDataset().addSequence(
1943 sequences[i].getDatasetSequence());
1944 // TODO: avoid creation of duplicate dataset sequences with a
1945 // 'contains' method using SequenceI.equals()/SequenceI.contains()
1947 alignment.addSequence(sequences[i]); // merges dataset
1951 newDs.clear(); // tidy up
1953 if (alignment.getAlignmentAnnotation() != null)
1955 for (AlignmentAnnotation alan : alignment
1956 .getAlignmentAnnotation())
1958 if (alan.graphGroup > fgroup)
1960 fgroup = alan.graphGroup;
1964 if (pastedal.getAlignmentAnnotation() != null)
1966 // Add any annotation attached to alignment.
1967 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
1968 for (int i = 0; i < alann.length; i++)
1970 annotationAdded = true;
1971 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
1973 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
1974 if (newann.graphGroup > -1)
1976 if (newGraphGroups.size() <= newann.graphGroup
1977 || newGraphGroups.get(newann.graphGroup) == null)
1979 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
1981 newGraphGroups.add(q, null);
1983 newGraphGroups.set(newann.graphGroup, new Integer(
1986 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
1990 newann.padAnnotation(alwidth);
1991 alignment.addAnnotation(newann);
2001 addHistoryItem(new EditCommand(MessageManager.getString("label.add_sequences"), EditCommand.PASTE,
2002 sequences, 0, alignment.getWidth(), alignment));
2004 // Add any annotations attached to sequences
2005 for (int i = 0; i < sequences.length; i++)
2007 if (sequences[i].getAnnotation() != null)
2009 AlignmentAnnotation newann;
2010 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2012 annotationAdded = true;
2013 newann = sequences[i].getAnnotation()[a];
2014 newann.adjustForAlignment();
2015 newann.padAnnotation(alwidth);
2016 if (newann.graphGroup > -1)
2018 if (newann.graphGroup > -1)
2020 if (newGraphGroups.size() <= newann.graphGroup
2021 || newGraphGroups.get(newann.graphGroup) == null)
2023 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2025 newGraphGroups.add(q, null);
2027 newGraphGroups.set(newann.graphGroup, new Integer(
2030 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2034 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2039 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2046 // propagate alignment changed.
2047 viewport.setEndSeq(alignment.getHeight());
2048 if (annotationAdded)
2050 // Duplicate sequence annotation in all views.
2051 AlignmentI[] alview = this.getViewAlignments();
2052 for (int i = 0; i < sequences.length; i++)
2054 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2059 for (int avnum = 0; avnum < alview.length; avnum++)
2061 if (alview[avnum] != alignment)
2063 // duplicate in a view other than the one with input focus
2064 int avwidth = alview[avnum].getWidth() + 1;
2065 // this relies on sann being preserved after we
2066 // modify the sequence's annotation array for each duplication
2067 for (int a = 0; a < sann.length; a++)
2069 AlignmentAnnotation newann = new AlignmentAnnotation(
2071 sequences[i].addAlignmentAnnotation(newann);
2072 newann.padAnnotation(avwidth);
2073 alview[avnum].addAnnotation(newann); // annotation was
2074 // duplicated earlier
2075 // TODO JAL-1145 graphGroups are not updated for sequence
2076 // annotation added to several views. This may cause
2078 alview[avnum].setAnnotationIndex(newann, a);
2083 buildSortByAnnotationScoresMenu();
2085 viewport.firePropertyChange("alignment", null,
2086 alignment.getSequences());
2087 if (alignPanels != null)
2089 for (AlignmentPanel ap : ((Vector<AlignmentPanel>) alignPanels))
2091 ap.validateAnnotationDimensions(false);
2096 alignPanel.validateAnnotationDimensions(false);
2102 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2104 String newtitle = new String("Copied sequences");
2106 if (Desktop.jalviewClipboard != null
2107 && Desktop.jalviewClipboard[2] != null)
2109 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2110 for (int i = 0; i < hc.size(); i++)
2112 int[] region = (int[]) hc.elementAt(i);
2113 af.viewport.hideColumns(region[0], region[1]);
2117 // >>>This is a fix for the moment, until a better solution is
2119 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
2121 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
2123 // TODO: maintain provenance of an alignment, rather than just make the
2124 // title a concatenation of operations.
2127 if (title.startsWith("Copied sequences"))
2133 newtitle = newtitle.concat("- from " + title);
2138 newtitle = new String("Pasted sequences");
2141 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2146 } catch (Exception ex)
2148 ex.printStackTrace();
2149 System.out.println("Exception whilst pasting: " + ex);
2150 // could be anything being pasted in here
2156 protected void expand_newalign(ActionEvent e)
2160 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2161 .getAlignment(), -1);
2162 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2164 String newtitle = new String("Flanking alignment");
2166 if (Desktop.jalviewClipboard != null
2167 && Desktop.jalviewClipboard[2] != null)
2169 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2170 for (int i = 0; i < hc.size(); i++)
2172 int[] region = (int[]) hc.elementAt(i);
2173 af.viewport.hideColumns(region[0], region[1]);
2177 // >>>This is a fix for the moment, until a better solution is
2179 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
2181 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
2183 // TODO: maintain provenance of an alignment, rather than just make the
2184 // title a concatenation of operations.
2186 if (title.startsWith("Copied sequences"))
2192 newtitle = newtitle.concat("- from " + title);
2196 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2198 } catch (Exception ex)
2200 ex.printStackTrace();
2201 System.out.println("Exception whilst pasting: " + ex);
2202 // could be anything being pasted in here
2203 } catch (OutOfMemoryError oom)
2205 new OOMWarning("Viewing flanking region of alignment", oom);
2216 protected void cut_actionPerformed(ActionEvent e)
2218 copy_actionPerformed(null);
2219 delete_actionPerformed(null);
2229 protected void delete_actionPerformed(ActionEvent evt)
2232 SequenceGroup sg = viewport.getSelectionGroup();
2238 List<SequenceI> seqs = new ArrayList<SequenceI>(sg.getSize());
2240 for (int i = 0; i < sg.getSize(); i++)
2242 seq = sg.getSequenceAt(i);
2246 // If the cut affects all sequences, warn, remove highlighted columns
2247 if (sg.getSize() == viewport.getAlignment().getHeight())
2249 int confirm = JOptionPane.showConfirmDialog(this,
2250 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2251 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2252 JOptionPane.OK_CANCEL_OPTION);
2254 if (confirm == JOptionPane.CANCEL_OPTION
2255 || confirm == JOptionPane.CLOSED_OPTION)
2259 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2260 sg.getEndRes() + 1);
2263 SequenceI[] cut = new SequenceI[seqs.size()];
2264 for (int i = 0; i < seqs.size(); i++)
2266 cut[i] = seqs.get(i);
2270 * //ADD HISTORY ITEM
2272 addHistoryItem(new EditCommand(MessageManager.getString("label.cut_sequences"), EditCommand.CUT, cut,
2273 sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2274 viewport.getAlignment()));
2276 viewport.setSelectionGroup(null);
2277 viewport.sendSelection();
2278 viewport.getAlignment().deleteGroup(sg);
2280 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2282 if (viewport.getAlignment().getHeight() < 1)
2286 this.setClosed(true);
2287 } catch (Exception ex)
2300 protected void deleteGroups_actionPerformed(ActionEvent e)
2302 if (avc.deleteGroups())
2304 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2305 alignPanel.updateAnnotation();
2306 alignPanel.paintAlignment(true);
2317 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2319 SequenceGroup sg = new SequenceGroup();
2321 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2323 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2326 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2327 viewport.setSelectionGroup(sg);
2328 viewport.sendSelection();
2329 alignPanel.paintAlignment(true);
2330 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2340 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2342 if (viewport.cursorMode)
2344 alignPanel.seqPanel.keyboardNo1 = null;
2345 alignPanel.seqPanel.keyboardNo2 = null;
2347 viewport.setSelectionGroup(null);
2348 viewport.getColumnSelection().clear();
2349 viewport.setSelectionGroup(null);
2350 alignPanel.seqPanel.seqCanvas.highlightSearchResults(null);
2351 alignPanel.idPanel.idCanvas.searchResults = null;
2352 alignPanel.paintAlignment(true);
2353 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2354 viewport.sendSelection();
2364 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2366 SequenceGroup sg = viewport.getSelectionGroup();
2370 selectAllSequenceMenuItem_actionPerformed(null);
2375 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2377 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2380 alignPanel.paintAlignment(true);
2381 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2382 viewport.sendSelection();
2386 public void invertColSel_actionPerformed(ActionEvent e)
2388 viewport.invertColumnSelection();
2389 alignPanel.paintAlignment(true);
2390 viewport.sendSelection();
2400 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2402 trimAlignment(true);
2412 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2414 trimAlignment(false);
2417 void trimAlignment(boolean trimLeft)
2419 ColumnSelection colSel = viewport.getColumnSelection();
2422 if (colSel.size() > 0)
2426 column = colSel.getMin();
2430 column = colSel.getMax();
2434 if (viewport.getSelectionGroup() != null)
2436 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2437 viewport.getHiddenRepSequences());
2441 seqs = viewport.getAlignment().getSequencesArray();
2444 TrimRegionCommand trimRegion;
2447 trimRegion = new TrimRegionCommand("Remove Left",
2448 TrimRegionCommand.TRIM_LEFT, seqs, column,
2449 viewport.getAlignment(), viewport.getColumnSelection(),
2450 viewport.getSelectionGroup());
2451 viewport.setStartRes(0);
2455 trimRegion = new TrimRegionCommand("Remove Right",
2456 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2457 viewport.getAlignment(), viewport.getColumnSelection(),
2458 viewport.getSelectionGroup());
2461 statusBar.setText(MessageManager.formatMessage(
2462 "label.removed_columns", new String[]
2463 { Integer.valueOf(trimRegion.getSize()).toString() }));
2465 addHistoryItem(trimRegion);
2467 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2469 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2470 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2472 viewport.getAlignment().deleteGroup(sg);
2476 viewport.firePropertyChange("alignment", null, viewport
2477 .getAlignment().getSequences());
2488 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2490 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2493 if (viewport.getSelectionGroup() != null)
2495 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2496 viewport.getHiddenRepSequences());
2497 start = viewport.getSelectionGroup().getStartRes();
2498 end = viewport.getSelectionGroup().getEndRes();
2502 seqs = viewport.getAlignment().getSequencesArray();
2505 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2506 "Remove Gapped Columns", seqs, start, end,
2507 viewport.getAlignment());
2509 addHistoryItem(removeGapCols);
2511 statusBar.setText(MessageManager.formatMessage(
2512 "label.removed_empty_columns", new String[]
2513 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2515 // This is to maintain viewport position on first residue
2516 // of first sequence
2517 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2518 int startRes = seq.findPosition(viewport.startRes);
2519 // ShiftList shifts;
2520 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2521 // edit.alColumnChanges=shifts.getInverse();
2522 // if (viewport.hasHiddenColumns)
2523 // viewport.getColumnSelection().compensateForEdits(shifts);
2524 viewport.setStartRes(seq.findIndex(startRes) - 1);
2525 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2537 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2539 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2542 if (viewport.getSelectionGroup() != null)
2544 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2545 viewport.getHiddenRepSequences());
2546 start = viewport.getSelectionGroup().getStartRes();
2547 end = viewport.getSelectionGroup().getEndRes();
2551 seqs = viewport.getAlignment().getSequencesArray();
2554 // This is to maintain viewport position on first residue
2555 // of first sequence
2556 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2557 int startRes = seq.findPosition(viewport.startRes);
2559 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2560 viewport.getAlignment()));
2562 viewport.setStartRes(seq.findIndex(startRes) - 1);
2564 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2576 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2578 viewport.setPadGaps(padGapsMenuitem.isSelected());
2579 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2585 // if (justifySeqs>0)
2587 // alignment.justify(justifySeqs!=RIGHT_JUSTIFY);
2600 public void findMenuItem_actionPerformed(ActionEvent e)
2606 public void newView_actionPerformed(ActionEvent e)
2613 * @param copyAnnotation
2614 * if true then duplicate all annnotation, groups and settings
2615 * @return new alignment panel, already displayed.
2617 public AlignmentPanel newView(boolean copyAnnotation)
2619 return newView(null, copyAnnotation);
2625 * title of newly created view
2626 * @return new alignment panel, already displayed.
2628 public AlignmentPanel newView(String viewTitle)
2630 return newView(viewTitle, true);
2636 * title of newly created view
2637 * @param copyAnnotation
2638 * if true then duplicate all annnotation, groups and settings
2639 * @return new alignment panel, already displayed.
2641 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2643 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2645 if (!copyAnnotation)
2647 // just remove all the current annotation except for the automatic stuff
2648 newap.av.getAlignment().deleteAllGroups();
2649 for (AlignmentAnnotation alan : newap.av.getAlignment()
2650 .getAlignmentAnnotation())
2652 if (!alan.autoCalculated)
2654 newap.av.getAlignment().deleteAnnotation(alan);
2660 newap.av.gatherViewsHere = false;
2662 if (viewport.viewName == null)
2664 viewport.viewName = "Original";
2667 newap.av.historyList = viewport.historyList;
2668 newap.av.redoList = viewport.redoList;
2670 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2671 // make sure the new view has a unique name - this is essential for Jalview
2673 boolean addFirstIndex = false;
2674 if (viewTitle == null || viewTitle.trim().length() == 0)
2676 viewTitle = MessageManager.getString("action.view");
2677 addFirstIndex = true;
2681 index = 1;// we count from 1 if given a specific name
2683 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2684 Vector comps = (Vector) PaintRefresher.components.get(viewport
2685 .getSequenceSetId());
2686 Vector existingNames = new Vector();
2687 for (int i = 0; i < comps.size(); i++)
2689 if (comps.elementAt(i) instanceof AlignmentPanel)
2691 AlignmentPanel ap = (AlignmentPanel) comps.elementAt(i);
2692 if (!existingNames.contains(ap.av.viewName))
2694 existingNames.addElement(ap.av.viewName);
2699 while (existingNames.contains(newViewName))
2701 newViewName = viewTitle + " " + (++index);
2704 newap.av.viewName = newViewName;
2706 addAlignmentPanel(newap, true);
2707 newap.alignmentChanged();
2709 if (alignPanels.size() == 2)
2711 viewport.gatherViewsHere = true;
2713 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2718 public void expandViews_actionPerformed(ActionEvent e)
2720 Desktop.instance.explodeViews(this);
2724 public void gatherViews_actionPerformed(ActionEvent e)
2726 Desktop.instance.gatherViews(this);
2736 public void font_actionPerformed(ActionEvent e)
2738 new FontChooser(alignPanel);
2748 protected void seqLimit_actionPerformed(ActionEvent e)
2750 viewport.setShowJVSuffix(seqLimits.isSelected());
2752 alignPanel.idPanel.idCanvas.setPreferredSize(alignPanel
2753 .calculateIdWidth());
2754 alignPanel.paintAlignment(true);
2758 public void idRightAlign_actionPerformed(ActionEvent e)
2760 viewport.rightAlignIds = idRightAlign.isSelected();
2761 alignPanel.paintAlignment(true);
2765 public void centreColumnLabels_actionPerformed(ActionEvent e)
2767 viewport.centreColumnLabels = centreColumnLabelsMenuItem.getState();
2768 alignPanel.paintAlignment(true);
2774 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2777 protected void followHighlight_actionPerformed()
2779 if (viewport.followHighlight = this.followHighlightMenuItem.getState())
2781 alignPanel.scrollToPosition(
2782 alignPanel.seqPanel.seqCanvas.searchResults, false);
2793 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2795 viewport.setColourText(colourTextMenuItem.isSelected());
2796 alignPanel.paintAlignment(true);
2806 public void wrapMenuItem_actionPerformed(ActionEvent e)
2808 scaleAbove.setVisible(wrapMenuItem.isSelected());
2809 scaleLeft.setVisible(wrapMenuItem.isSelected());
2810 scaleRight.setVisible(wrapMenuItem.isSelected());
2811 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2812 alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2816 public void showAllSeqs_actionPerformed(ActionEvent e)
2818 viewport.showAllHiddenSeqs();
2822 public void showAllColumns_actionPerformed(ActionEvent e)
2824 viewport.showAllHiddenColumns();
2829 public void hideSelSequences_actionPerformed(ActionEvent e)
2831 viewport.hideAllSelectedSeqs();
2832 alignPanel.paintAlignment(true);
2836 * called by key handler and the hide all/show all menu items
2841 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2844 boolean hide = false;
2845 SequenceGroup sg = viewport.getSelectionGroup();
2846 if (!toggleSeqs && !toggleCols)
2848 // Hide everything by the current selection - this is a hack - we do the
2849 // invert and then hide
2850 // first check that there will be visible columns after the invert.
2851 if ((viewport.getColumnSelection() != null
2852 && viewport.getColumnSelection().getSelected() != null && viewport
2853 .getColumnSelection().getSelected().size() > 0)
2854 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2857 // now invert the sequence set, if required - empty selection implies
2858 // that no hiding is required.
2861 invertSequenceMenuItem_actionPerformed(null);
2862 sg = viewport.getSelectionGroup();
2866 viewport.expandColSelection(sg, true);
2867 // finally invert the column selection and get the new sequence
2869 invertColSel_actionPerformed(null);
2876 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
2878 hideSelSequences_actionPerformed(null);
2881 else if (!(toggleCols && viewport.getColumnSelection().getSelected()
2884 showAllSeqs_actionPerformed(null);
2890 if (viewport.getColumnSelection().getSelected().size() > 0)
2892 hideSelColumns_actionPerformed(null);
2895 viewport.setSelectionGroup(sg);
2900 showAllColumns_actionPerformed(null);
2909 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
2910 * event.ActionEvent)
2913 public void hideAllButSelection_actionPerformed(ActionEvent e)
2915 toggleHiddenRegions(false, false);
2922 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
2926 public void hideAllSelection_actionPerformed(ActionEvent e)
2928 SequenceGroup sg = viewport.getSelectionGroup();
2929 viewport.expandColSelection(sg, false);
2930 viewport.hideAllSelectedSeqs();
2931 viewport.hideSelectedColumns();
2932 alignPanel.paintAlignment(true);
2939 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
2943 public void showAllhidden_actionPerformed(ActionEvent e)
2945 viewport.showAllHiddenColumns();
2946 viewport.showAllHiddenSeqs();
2947 alignPanel.paintAlignment(true);
2951 public void hideSelColumns_actionPerformed(ActionEvent e)
2953 viewport.hideSelectedColumns();
2954 alignPanel.paintAlignment(true);
2958 public void hiddenMarkers_actionPerformed(ActionEvent e)
2960 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
2971 protected void scaleAbove_actionPerformed(ActionEvent e)
2973 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
2974 alignPanel.paintAlignment(true);
2984 protected void scaleLeft_actionPerformed(ActionEvent e)
2986 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
2987 alignPanel.paintAlignment(true);
2997 protected void scaleRight_actionPerformed(ActionEvent e)
2999 viewport.setScaleRightWrapped(scaleRight.isSelected());
3000 alignPanel.paintAlignment(true);
3010 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3012 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3013 alignPanel.paintAlignment(true);
3023 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3025 viewport.setShowText(viewTextMenuItem.isSelected());
3026 alignPanel.paintAlignment(true);
3036 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3038 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3039 alignPanel.paintAlignment(true);
3042 public FeatureSettings featureSettings;
3045 public void featureSettings_actionPerformed(ActionEvent e)
3047 if (featureSettings != null)
3049 featureSettings.close();
3050 featureSettings = null;
3052 if (!showSeqFeatures.isSelected())
3054 // make sure features are actually displayed
3055 showSeqFeatures.setSelected(true);
3056 showSeqFeatures_actionPerformed(null);
3058 featureSettings = new FeatureSettings(this);
3062 * Set or clear 'Show Sequence Features'
3068 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3070 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3071 alignPanel.paintAlignment(true);
3072 if (alignPanel.getOverviewPanel() != null)
3074 alignPanel.getOverviewPanel().updateOverviewImage();
3079 * Set or clear 'Show Sequence Features'
3085 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
3087 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
3089 if (viewport.isShowSequenceFeaturesHeight())
3091 // ensure we're actually displaying features
3092 viewport.setShowSequenceFeatures(true);
3093 showSeqFeatures.setSelected(true);
3095 alignPanel.paintAlignment(true);
3096 if (alignPanel.getOverviewPanel() != null)
3098 alignPanel.getOverviewPanel().updateOverviewImage();
3103 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3104 * the annotations panel as a whole.
3106 * The options to show/hide all annotations should be enabled when the panel
3107 * is shown, and disabled when the panel is hidden.
3112 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3114 final boolean setVisible = annotationPanelMenuItem.isSelected();
3115 viewport.setShowAnnotation(setVisible);
3116 alignPanel.setAnnotationVisible(setVisible);
3117 this.showAllSeqAnnotations.setEnabled(setVisible);
3118 this.hideAllSeqAnnotations.setEnabled(setVisible);
3119 this.showAllAlAnnotations.setEnabled(setVisible);
3120 this.hideAllAlAnnotations.setEnabled(setVisible);
3124 public void alignmentProperties()
3126 JEditorPane editPane = new JEditorPane("text/html", "");
3127 editPane.setEditable(false);
3128 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3130 editPane.setText(MessageManager.formatMessage("label.html_content",
3132 { contents.toString() }));
3133 JInternalFrame frame = new JInternalFrame();
3134 frame.getContentPane().add(new JScrollPane(editPane));
3136 Desktop.instance.addInternalFrame(frame, MessageManager.formatMessage(
3137 "label.alignment_properties", new String[]
3138 { getTitle() }), 500, 400);
3148 public void overviewMenuItem_actionPerformed(ActionEvent e)
3150 if (alignPanel.overviewPanel != null)
3155 JInternalFrame frame = new JInternalFrame();
3156 OverviewPanel overview = new OverviewPanel(alignPanel);
3157 frame.setContentPane(overview);
3158 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3159 "label.overview_params", new String[]
3160 { this.getTitle() }), frame.getWidth(), frame.getHeight());
3162 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3163 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3166 public void internalFrameClosed(
3167 javax.swing.event.InternalFrameEvent evt)
3169 alignPanel.setOverviewPanel(null);
3173 alignPanel.setOverviewPanel(overview);
3177 public void textColour_actionPerformed(ActionEvent e)
3179 new TextColourChooser().chooseColour(alignPanel, null);
3189 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3201 public void clustalColour_actionPerformed(ActionEvent e)
3203 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3204 viewport.getHiddenRepSequences()));
3214 public void zappoColour_actionPerformed(ActionEvent e)
3216 changeColour(new ZappoColourScheme());
3226 public void taylorColour_actionPerformed(ActionEvent e)
3228 changeColour(new TaylorColourScheme());
3238 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3240 changeColour(new HydrophobicColourScheme());
3250 public void helixColour_actionPerformed(ActionEvent e)
3252 changeColour(new HelixColourScheme());
3262 public void strandColour_actionPerformed(ActionEvent e)
3264 changeColour(new StrandColourScheme());
3274 public void turnColour_actionPerformed(ActionEvent e)
3276 changeColour(new TurnColourScheme());
3286 public void buriedColour_actionPerformed(ActionEvent e)
3288 changeColour(new BuriedColourScheme());
3298 public void nucleotideColour_actionPerformed(ActionEvent e)
3300 changeColour(new NucleotideColourScheme());
3304 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3306 changeColour(new PurinePyrimidineColourScheme());
3310 * public void covariationColour_actionPerformed(ActionEvent e) {
3312 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3316 public void annotationColour_actionPerformed(ActionEvent e)
3318 new AnnotationColourChooser(viewport, alignPanel);
3322 public void rnahelicesColour_actionPerformed(ActionEvent e)
3324 new RNAHelicesColourChooser(viewport, alignPanel);
3334 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3336 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3345 public void changeColour(ColourSchemeI cs)
3347 // TODO: compare with applet and pull up to model method
3352 if (viewport.getAbovePIDThreshold())
3354 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3356 cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3360 cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3363 if (viewport.getConservationSelected())
3366 Alignment al = (Alignment) viewport.getAlignment();
3367 Conservation c = new Conservation("All",
3368 ResidueProperties.propHash, 3, al.getSequences(), 0,
3372 c.verdict(false, viewport.getConsPercGaps());
3374 cs.setConservation(c);
3376 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3381 cs.setConservation(null);
3384 cs.setConsensus(viewport.getSequenceConsensusHash());
3387 viewport.setGlobalColourScheme(cs);
3389 if (viewport.getColourAppliesToAllGroups())
3392 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3400 if (cs instanceof ClustalxColourScheme)
3402 sg.cs = new ClustalxColourScheme(sg,
3403 viewport.getHiddenRepSequences());
3405 else if (cs instanceof UserColourScheme)
3407 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
3413 sg.cs = cs.getClass().newInstance();
3414 } catch (Exception ex)
3419 if (viewport.getAbovePIDThreshold()
3420 || cs instanceof PIDColourScheme
3421 || cs instanceof Blosum62ColourScheme)
3423 sg.cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3425 sg.cs.setConsensus(AAFrequency.calculate(
3426 sg.getSequences(viewport.getHiddenRepSequences()),
3427 sg.getStartRes(), sg.getEndRes() + 1));
3431 sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3434 if (viewport.getConservationSelected())
3436 Conservation c = new Conservation("Group",
3437 ResidueProperties.propHash, 3, sg.getSequences(viewport
3438 .getHiddenRepSequences()), sg.getStartRes(),
3439 sg.getEndRes() + 1);
3441 c.verdict(false, viewport.getConsPercGaps());
3442 sg.cs.setConservation(c);
3446 sg.cs.setConservation(null);
3451 if (alignPanel.getOverviewPanel() != null)
3453 alignPanel.getOverviewPanel().updateOverviewImage();
3456 alignPanel.paintAlignment(true);
3466 protected void modifyPID_actionPerformed(ActionEvent e)
3468 if (viewport.getAbovePIDThreshold()
3469 && viewport.getGlobalColourScheme() != null)
3471 SliderPanel.setPIDSliderSource(alignPanel,
3472 viewport.getGlobalColourScheme(), "Background");
3473 SliderPanel.showPIDSlider();
3484 protected void modifyConservation_actionPerformed(ActionEvent e)
3486 if (viewport.getConservationSelected()
3487 && viewport.getGlobalColourScheme() != null)
3489 SliderPanel.setConservationSlider(alignPanel,
3490 viewport.getGlobalColourScheme(), "Background");
3491 SliderPanel.showConservationSlider();
3502 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3504 viewport.setConservationSelected(conservationMenuItem.isSelected());
3506 viewport.setAbovePIDThreshold(false);
3507 abovePIDThreshold.setSelected(false);
3509 changeColour(viewport.getGlobalColourScheme());
3511 modifyConservation_actionPerformed(null);
3521 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3523 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3525 conservationMenuItem.setSelected(false);
3526 viewport.setConservationSelected(false);
3528 changeColour(viewport.getGlobalColourScheme());
3530 modifyPID_actionPerformed(null);
3540 public void userDefinedColour_actionPerformed(ActionEvent e)
3542 if (e.getActionCommand().equals(
3543 MessageManager.getString("action.user_defined")))
3545 new UserDefinedColours(alignPanel, null);
3549 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3550 .getUserColourSchemes().get(e.getActionCommand());
3556 public void updateUserColourMenu()
3559 Component[] menuItems = colourMenu.getMenuComponents();
3560 int i, iSize = menuItems.length;
3561 for (i = 0; i < iSize; i++)
3563 if (menuItems[i].getName() != null
3564 && menuItems[i].getName().equals("USER_DEFINED"))
3566 colourMenu.remove(menuItems[i]);
3570 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3572 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3573 .getUserColourSchemes().keys();
3575 while (userColours.hasMoreElements())
3577 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3578 userColours.nextElement().toString());
3579 radioItem.setName("USER_DEFINED");
3580 radioItem.addMouseListener(new MouseAdapter()
3583 public void mousePressed(MouseEvent evt)
3585 if (evt.isControlDown()
3586 || SwingUtilities.isRightMouseButton(evt))
3588 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3590 int option = JOptionPane.showInternalConfirmDialog(
3591 jalview.gui.Desktop.desktop,
3593 .getString("label.remove_from_default_list"),
3595 .getString("label.remove_user_defined_colour"),
3596 JOptionPane.YES_NO_OPTION);
3597 if (option == JOptionPane.YES_OPTION)
3599 jalview.gui.UserDefinedColours
3600 .removeColourFromDefaults(radioItem.getText());
3601 colourMenu.remove(radioItem);
3605 radioItem.addActionListener(new ActionListener()
3608 public void actionPerformed(ActionEvent evt)
3610 userDefinedColour_actionPerformed(evt);
3617 radioItem.addActionListener(new ActionListener()
3620 public void actionPerformed(ActionEvent evt)
3622 userDefinedColour_actionPerformed(evt);
3626 colourMenu.insert(radioItem, 15);
3627 colours.add(radioItem);
3639 public void PIDColour_actionPerformed(ActionEvent e)
3641 changeColour(new PIDColourScheme());
3651 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3653 changeColour(new Blosum62ColourScheme());
3663 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3665 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3666 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3667 .getAlignment().getSequenceAt(0), null);
3668 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3669 viewport.getAlignment()));
3670 alignPanel.paintAlignment(true);
3680 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3682 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3683 AlignmentSorter.sortByID(viewport.getAlignment());
3684 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3685 viewport.getAlignment()));
3686 alignPanel.paintAlignment(true);
3696 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3698 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3699 AlignmentSorter.sortByLength(viewport.getAlignment());
3700 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3701 viewport.getAlignment()));
3702 alignPanel.paintAlignment(true);
3712 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3714 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3715 AlignmentSorter.sortByGroup(viewport.getAlignment());
3716 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3717 viewport.getAlignment()));
3719 alignPanel.paintAlignment(true);
3729 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3731 new RedundancyPanel(alignPanel, this);
3741 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3743 if ((viewport.getSelectionGroup() == null)
3744 || (viewport.getSelectionGroup().getSize() < 2))
3746 JOptionPane.showInternalMessageDialog(this, MessageManager
3747 .getString("label.you_must_select_least_two_sequences"),
3748 MessageManager.getString("label.invalid_selection"),
3749 JOptionPane.WARNING_MESSAGE);
3753 JInternalFrame frame = new JInternalFrame();
3754 frame.setContentPane(new PairwiseAlignPanel(viewport));
3755 Desktop.addInternalFrame(frame,
3756 MessageManager.getString("action.pairwise_alignment"), 600,
3768 public void PCAMenuItem_actionPerformed(ActionEvent e)
3770 if (((viewport.getSelectionGroup() != null)
3771 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3772 .getSelectionGroup().getSize() > 0))
3773 || (viewport.getAlignment().getHeight() < 4))
3776 .showInternalMessageDialog(
3779 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3781 .getString("label.sequence_selection_insufficient"),
3782 JOptionPane.WARNING_MESSAGE);
3787 new PCAPanel(alignPanel);
3791 public void autoCalculate_actionPerformed(ActionEvent e)
3793 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3794 if (viewport.autoCalculateConsensus)
3796 viewport.firePropertyChange("alignment", null, viewport
3797 .getAlignment().getSequences());
3802 public void sortByTreeOption_actionPerformed(ActionEvent e)
3804 viewport.sortByTree = sortByTree.isSelected();
3808 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3810 viewport.followSelection = listenToViewSelections.isSelected();
3820 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3822 NewTreePanel("AV", "PID", "Average distance tree using PID");
3832 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3834 NewTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3844 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3846 NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3856 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3858 NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3871 void NewTreePanel(String type, String pwType, String title)
3875 if (viewport.getSelectionGroup() != null
3876 && viewport.getSelectionGroup().getSize() > 0)
3878 if (viewport.getSelectionGroup().getSize() < 3)
3884 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3886 .getString("label.not_enough_sequences"),
3887 JOptionPane.WARNING_MESSAGE);
3891 SequenceGroup sg = viewport.getSelectionGroup();
3893 /* Decide if the selection is a column region */
3894 for (SequenceI _s : sg.getSequences())
3896 if (_s.getLength() < sg.getEndRes())
3902 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3904 .getString("label.sequences_selection_not_aligned"),
3905 JOptionPane.WARNING_MESSAGE);
3911 title = title + " on region";
3912 tp = new TreePanel(alignPanel, type, pwType);
3916 // are the visible sequences aligned?
3917 if (!viewport.getAlignment().isAligned(false))
3923 .getString("label.sequences_must_be_aligned_before_creating_tree"),
3925 .getString("label.sequences_not_aligned"),
3926 JOptionPane.WARNING_MESSAGE);
3931 if (viewport.getAlignment().getHeight() < 2)
3936 tp = new TreePanel(alignPanel, type, pwType);
3941 if (viewport.viewName != null)
3943 title += viewport.viewName + " of ";
3946 title += this.title;
3948 Desktop.addInternalFrame(tp, title, 600, 500);
3959 public void addSortByOrderMenuItem(String title,
3960 final AlignmentOrder order)
3962 final JMenuItem item = new JMenuItem(MessageManager.formatMessage("action.by_title_param", new String[]{title}));
3964 item.addActionListener(new java.awt.event.ActionListener()
3967 public void actionPerformed(ActionEvent e)
3969 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3971 // TODO: JBPNote - have to map order entries to curent SequenceI
3973 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3975 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
3978 alignPanel.paintAlignment(true);
3984 * Add a new sort by annotation score menu item
3987 * the menu to add the option to
3989 * the label used to retrieve scores for each sequence on the
3992 public void addSortByAnnotScoreMenuItem(JMenu sort,
3993 final String scoreLabel)
3995 final JMenuItem item = new JMenuItem(scoreLabel);
3997 item.addActionListener(new java.awt.event.ActionListener()
4000 public void actionPerformed(ActionEvent e)
4002 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4003 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4004 viewport.getAlignment());// ,viewport.getSelectionGroup());
4005 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4006 viewport.getAlignment()));
4007 alignPanel.paintAlignment(true);
4013 * last hash for alignment's annotation array - used to minimise cost of
4016 protected int _annotationScoreVectorHash;
4019 * search the alignment and rebuild the sort by annotation score submenu the
4020 * last alignment annotation vector hash is stored to minimize cost of
4021 * rebuilding in subsequence calls.
4025 public void buildSortByAnnotationScoresMenu()
4027 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4032 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4034 sortByAnnotScore.removeAll();
4035 // almost certainly a quicker way to do this - but we keep it simple
4036 Hashtable scoreSorts = new Hashtable();
4037 AlignmentAnnotation aann[];
4038 for (SequenceI sqa : viewport.getAlignment().getSequences())
4040 aann = sqa.getAnnotation();
4041 for (int i = 0; aann != null && i < aann.length; i++)
4043 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4045 scoreSorts.put(aann[i].label, aann[i].label);
4049 Enumeration labels = scoreSorts.keys();
4050 while (labels.hasMoreElements())
4052 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4053 (String) labels.nextElement());
4055 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4058 _annotationScoreVectorHash = viewport.getAlignment()
4059 .getAlignmentAnnotation().hashCode();
4064 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4065 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4066 * call. Listeners are added to remove the menu item when the treePanel is
4067 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4071 * Displayed tree window.
4073 * SortBy menu item title.
4076 public void buildTreeMenu()
4078 calculateTree.removeAll();
4079 // build the calculate menu
4081 for (final String type : new String[]
4084 String treecalcnm = MessageManager.getString("label.tree_calc_"
4085 + type.toLowerCase());
4086 for (final Object pwtype : ResidueProperties.scoreMatrices.keySet())
4088 JMenuItem tm = new JMenuItem();
4089 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4090 if (sm.isProtein() == !viewport.getAlignment().isNucleotide())
4092 String smn = MessageManager.getStringOrReturn(
4093 "label.score_model_", sm.getName());
4094 final String title = MessageManager.formatMessage(
4095 "label.treecalc_title", treecalcnm, smn);
4096 tm.setText(title);//
4097 tm.addActionListener(new java.awt.event.ActionListener()
4100 public void actionPerformed(ActionEvent e)
4102 NewTreePanel(type, (String) pwtype, title);
4105 calculateTree.add(tm);
4110 sortByTreeMenu.removeAll();
4112 Vector comps = (Vector) PaintRefresher.components.get(viewport
4113 .getSequenceSetId());
4114 Vector treePanels = new Vector();
4115 int i, iSize = comps.size();
4116 for (i = 0; i < iSize; i++)
4118 if (comps.elementAt(i) instanceof TreePanel)
4120 treePanels.add(comps.elementAt(i));
4124 iSize = treePanels.size();
4128 sortByTreeMenu.setVisible(false);
4132 sortByTreeMenu.setVisible(true);
4134 for (i = 0; i < treePanels.size(); i++)
4136 final TreePanel tp = (TreePanel) treePanels.elementAt(i);
4137 final JMenuItem item = new JMenuItem(tp.getTitle());
4138 final NJTree tree = ((TreePanel) treePanels.elementAt(i)).getTree();
4139 item.addActionListener(new java.awt.event.ActionListener()
4142 public void actionPerformed(ActionEvent e)
4144 tp.sortByTree_actionPerformed(null);
4145 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4150 sortByTreeMenu.add(item);
4154 public boolean sortBy(AlignmentOrder alorder, String undoname)
4156 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4157 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4158 if (undoname != null)
4160 addHistoryItem(new OrderCommand(undoname, oldOrder,
4161 viewport.getAlignment()));
4163 alignPanel.paintAlignment(true);
4168 * Work out whether the whole set of sequences or just the selected set will
4169 * be submitted for multiple alignment.
4172 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4174 // Now, check we have enough sequences
4175 AlignmentView msa = null;
4177 if ((viewport.getSelectionGroup() != null)
4178 && (viewport.getSelectionGroup().getSize() > 1))
4180 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4181 // some common interface!
4183 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4184 * SequenceI[sz = seqs.getSize(false)];
4186 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4187 * seqs.getSequenceAt(i); }
4189 msa = viewport.getAlignmentView(true);
4194 * Vector seqs = viewport.getAlignment().getSequences();
4196 * if (seqs.size() > 1) { msa = new SequenceI[seqs.size()];
4198 * for (int i = 0; i < seqs.size(); i++) { msa[i] = (SequenceI)
4199 * seqs.elementAt(i); } }
4201 msa = viewport.getAlignmentView(false);
4207 * Decides what is submitted to a secondary structure prediction service: the
4208 * first sequence in the alignment, or in the current selection, or, if the
4209 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4210 * region or the whole alignment. (where the first sequence in the set is the
4211 * one that the prediction will be for).
4213 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4215 AlignmentView seqs = null;
4217 if ((viewport.getSelectionGroup() != null)
4218 && (viewport.getSelectionGroup().getSize() > 0))
4220 seqs = viewport.getAlignmentView(true);
4224 seqs = viewport.getAlignmentView(false);
4226 // limit sequences - JBPNote in future - could spawn multiple prediction
4228 // TODO: viewport.getAlignment().isAligned is a global state - the local
4229 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4230 if (!viewport.getAlignment().isAligned(false))
4232 seqs.setSequences(new SeqCigar[]
4233 { seqs.getSequences()[0] });
4234 // TODO: if seqs.getSequences().length>1 then should really have warned
4248 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
4250 // Pick the tree file
4251 JalviewFileChooser chooser = new JalviewFileChooser(
4252 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4253 chooser.setFileView(new JalviewFileView());
4254 chooser.setDialogTitle(MessageManager
4255 .getString("label.select_newick_like_tree_file"));
4256 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4258 int value = chooser.showOpenDialog(null);
4260 if (value == JalviewFileChooser.APPROVE_OPTION)
4262 String choice = chooser.getSelectedFile().getPath();
4263 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4264 jalview.io.NewickFile fin = null;
4267 fin = new jalview.io.NewickFile(choice, "File");
4268 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4269 } catch (Exception ex)
4276 .getString("label.problem_reading_tree_file"),
4277 JOptionPane.WARNING_MESSAGE);
4278 ex.printStackTrace();
4280 if (fin != null && fin.hasWarningMessage())
4282 JOptionPane.showMessageDialog(Desktop.desktop, fin
4283 .getWarningMessage(), MessageManager
4284 .getString("label.possible_problem_with_tree_file"),
4285 JOptionPane.WARNING_MESSAGE);
4291 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4293 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4296 public TreePanel ShowNewickTree(NewickFile nf, String title)
4298 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4301 public TreePanel ShowNewickTree(NewickFile nf, String title,
4302 AlignmentView input)
4304 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4307 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4308 int h, int x, int y)
4310 return ShowNewickTree(nf, title, null, w, h, x, y);
4314 * Add a treeviewer for the tree extracted from a newick file object to the
4315 * current alignment view
4322 * Associated alignment input data (or null)
4331 * @return TreePanel handle
4333 public TreePanel ShowNewickTree(NewickFile nf, String title,
4334 AlignmentView input, int w, int h, int x, int y)
4336 TreePanel tp = null;
4342 if (nf.getTree() != null)
4344 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4350 tp.setLocation(x, y);
4353 Desktop.addInternalFrame(tp, title, w, h);
4355 } catch (Exception ex)
4357 ex.printStackTrace();
4363 private boolean buildingMenu = false;
4366 * Generates menu items and listener event actions for web service clients
4369 public void BuildWebServiceMenu()
4371 while (buildingMenu)
4375 System.err.println("Waiting for building menu to finish.");
4377 } catch (Exception e)
4382 final AlignFrame me = this;
4383 buildingMenu = true;
4384 new Thread(new Runnable()
4389 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4392 System.err.println("Building ws menu again "
4393 + Thread.currentThread());
4394 // TODO: add support for context dependent disabling of services based
4396 // alignment and current selection
4397 // TODO: add additional serviceHandle parameter to specify abstract
4399 // class independently of AbstractName
4400 // TODO: add in rediscovery GUI function to restart discoverer
4401 // TODO: group services by location as well as function and/or
4403 // object broker mechanism.
4404 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4405 final IProgressIndicator af = me;
4406 final JMenu msawsmenu = new JMenu("Alignment");
4407 final JMenu secstrmenu = new JMenu(
4408 "Secondary Structure Prediction");
4409 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4410 final JMenu analymenu = new JMenu("Analysis");
4411 final JMenu dismenu = new JMenu("Protein Disorder");
4412 // final JMenu msawsmenu = new
4413 // JMenu(MessageManager.getString("label.alignment"));
4414 // final JMenu secstrmenu = new
4415 // JMenu(MessageManager.getString("label.secondary_structure_prediction"));
4416 // final JMenu seqsrchmenu = new
4417 // JMenu(MessageManager.getString("label.sequence_database_search"));
4418 // final JMenu analymenu = new
4419 // JMenu(MessageManager.getString("label.analysis"));
4420 // final JMenu dismenu = new
4421 // JMenu(MessageManager.getString("label.protein_disorder"));
4422 // JAL-940 - only show secondary structure prediction services from
4423 // the legacy server
4424 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4426 Discoverer.services != null && (Discoverer.services.size() > 0))
4428 // TODO: refactor to allow list of AbstractName/Handler bindings to
4430 // stored or retrieved from elsewhere
4431 // No MSAWS used any more:
4432 // Vector msaws = null; // (Vector)
4433 // Discoverer.services.get("MsaWS");
4434 Vector secstrpr = (Vector) Discoverer.services
4436 if (secstrpr != null)
4438 // Add any secondary structure prediction services
4439 for (int i = 0, j = secstrpr.size(); i < j; i++)
4441 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4443 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4444 .getServiceClient(sh);
4445 int p = secstrmenu.getItemCount();
4446 impl.attachWSMenuEntry(secstrmenu, me);
4447 int q = secstrmenu.getItemCount();
4448 for (int litm = p; litm < q; litm++)
4450 legacyItems.add(secstrmenu.getItem(litm));
4456 // Add all submenus in the order they should appear on the web
4458 wsmenu.add(msawsmenu);
4459 wsmenu.add(secstrmenu);
4460 wsmenu.add(dismenu);
4461 wsmenu.add(analymenu);
4462 // No search services yet
4463 // wsmenu.add(seqsrchmenu);
4465 javax.swing.SwingUtilities.invokeLater(new Runnable()
4472 webService.removeAll();
4473 // first, add discovered services onto the webservices menu
4474 if (wsmenu.size() > 0)
4476 for (int i = 0, j = wsmenu.size(); i < j; i++)
4478 webService.add(wsmenu.get(i));
4483 webService.add(me.webServiceNoServices);
4485 // TODO: move into separate menu builder class.
4486 boolean new_sspred = false;
4487 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4489 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4490 if (jws2servs != null)
4492 if (jws2servs.hasServices())
4494 jws2servs.attachWSMenuEntry(webService, me);
4495 for (Jws2Instance sv : jws2servs.getServices())
4497 if (sv.description.toLowerCase().contains("jpred"))
4499 for (JMenuItem jmi : legacyItems)
4501 jmi.setVisible(false);
4507 if (jws2servs.isRunning())
4509 JMenuItem tm = new JMenuItem(
4510 "Still discovering JABA Services");
4511 tm.setEnabled(false);
4516 build_urlServiceMenu(me.webService);
4517 build_fetchdbmenu(webService);
4518 for (JMenu item : wsmenu)
4520 if (item.getItemCount() == 0)
4522 item.setEnabled(false);
4526 item.setEnabled(true);
4529 } catch (Exception e)
4532 .debug("Exception during web service menu building process.",
4538 } catch (Exception e)
4543 buildingMenu = false;
4550 * construct any groupURL type service menu entries.
4554 private void build_urlServiceMenu(JMenu webService)
4556 // TODO: remove this code when 2.7 is released
4557 // DEBUG - alignmentView
4559 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4560 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4562 * @Override public void actionPerformed(ActionEvent e) {
4563 * jalview.datamodel.AlignmentView
4564 * .testSelectionViews(af.viewport.getAlignment(),
4565 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4567 * }); webService.add(testAlView);
4569 // TODO: refactor to RestClient discoverer and merge menu entries for
4570 // rest-style services with other types of analysis/calculation service
4571 // SHmmr test client - still being implemented.
4572 // DEBUG - alignmentView
4574 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4577 client.attachWSMenuEntry(
4578 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4584 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
4585 * chooser = new JalviewFileChooser(jalview.bin.Cache.
4586 * getProperty("LAST_DIRECTORY"));
4588 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
4589 * to Vamsas file"); chooser.setToolTipText("Export");
4591 * int value = chooser.showSaveDialog(this);
4593 * if (value == JalviewFileChooser.APPROVE_OPTION) {
4594 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
4595 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
4596 * chooser.getSelectedFile().getAbsolutePath(), this); } }
4599 * prototype of an automatically enabled/disabled analysis function
4602 protected void setShowProductsEnabled()
4604 SequenceI[] selection = viewport.getSequenceSelection();
4605 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
4606 viewport.getAlignment().getDataset()))
4608 showProducts.setEnabled(true);
4613 showProducts.setEnabled(false);
4618 * search selection for sequence xRef products and build the show products
4623 * @return true if showProducts menu should be enabled.
4625 public boolean canShowProducts(SequenceI[] selection,
4626 boolean isRegionSelection, Alignment dataset)
4628 boolean showp = false;
4631 showProducts.removeAll();
4632 final boolean dna = viewport.getAlignment().isNucleotide();
4633 final Alignment ds = dataset;
4634 String[] ptypes = (selection == null || selection.length == 0) ? null
4635 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4637 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4638 // selection, dataset, true);
4639 final SequenceI[] sel = selection;
4640 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4643 final boolean isRegSel = isRegionSelection;
4644 final AlignFrame af = this;
4645 final String source = ptypes[t];
4646 JMenuItem xtype = new JMenuItem(ptypes[t]);
4647 xtype.addActionListener(new ActionListener()
4651 public void actionPerformed(ActionEvent e)
4653 // TODO: new thread for this call with vis-delay
4654 af.showProductsFor(af.viewport.getSequenceSelection(), ds,
4655 isRegSel, dna, source);
4659 showProducts.add(xtype);
4661 showProducts.setVisible(showp);
4662 showProducts.setEnabled(showp);
4663 } catch (Exception e)
4665 jalview.bin.Cache.log
4666 .warn("canTranslate threw an exception - please report to help@jalview.org",
4673 protected void showProductsFor(SequenceI[] sel, Alignment ds,
4674 boolean isRegSel, boolean dna, String source)
4676 final boolean fisRegSel = isRegSel;
4677 final boolean fdna = dna;
4678 final String fsrc = source;
4679 final AlignFrame ths = this;
4680 final SequenceI[] fsel = sel;
4681 Runnable foo = new Runnable()
4687 final long sttime = System.currentTimeMillis();
4688 ths.setProgressBar(MessageManager.formatMessage("status.searching_for_sequences_from", new String[]{fsrc}), sttime);
4691 Alignment ds = ths.getViewport().getAlignment().getDataset(); // update
4695 Alignment prods = CrossRef
4696 .findXrefSequences(fsel, fdna, fsrc, ds);
4699 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4700 for (int s = 0; s < sprods.length; s++)
4702 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4703 if (ds.getSequences() == null
4704 || !ds.getSequences().contains(
4705 sprods[s].getDatasetSequence()))
4707 ds.addSequence(sprods[s].getDatasetSequence());
4709 sprods[s].updatePDBIds();
4711 Alignment al = new Alignment(sprods);
4712 AlignedCodonFrame[] cf = prods.getCodonFrames();
4714 for (int s = 0; cf != null && s < cf.length; s++)
4716 al.addCodonFrame(cf[s]);
4719 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4721 String newtitle = "" + ((fdna) ? "Proteins " : "Nucleotides ")
4722 + " for " + ((fisRegSel) ? "selected region of " : "")
4724 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4729 System.err.println("No Sequences generated for xRef type "
4732 } catch (Exception e)
4734 jalview.bin.Cache.log.error(
4735 "Exception when finding crossreferences", e);
4736 } catch (OutOfMemoryError e)
4738 new OOMWarning("whilst fetching crossreferences", e);
4741 jalview.bin.Cache.log.error("Error when finding crossreferences",
4744 ths.setProgressBar(MessageManager.formatMessage("status.finished_searching_for_sequences_from", new String[]{fsrc}),
4749 Thread frunner = new Thread(foo);
4753 public boolean canShowTranslationProducts(SequenceI[] selection,
4754 AlignmentI alignment)
4759 return (jalview.analysis.Dna.canTranslate(selection,
4760 viewport.getViewAsVisibleContigs(true)));
4761 } catch (Exception e)
4763 jalview.bin.Cache.log
4764 .warn("canTranslate threw an exception - please report to help@jalview.org",
4771 public void showProducts_actionPerformed(ActionEvent e)
4773 // /////////////////////////////
4774 // Collect Data to be translated/transferred
4776 SequenceI[] selection = viewport.getSequenceSelection();
4777 AlignmentI al = null;
4780 al = jalview.analysis.Dna.CdnaTranslate(selection, viewport
4781 .getViewAsVisibleContigs(true), viewport.getGapCharacter(),
4782 viewport.getAlignment().getDataset());
4783 } catch (Exception ex)
4786 jalview.bin.Cache.log.debug("Exception during translation.", ex);
4794 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation"),
4795 MessageManager.getString("label.translation_failed"),
4796 JOptionPane.WARNING_MESSAGE);
4800 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4801 Desktop.addInternalFrame(af, MessageManager.formatMessage(
4802 "label.translation_of_params", new String[]
4803 { this.getTitle() }), DEFAULT_WIDTH, DEFAULT_HEIGHT);
4808 public void showTranslation_actionPerformed(ActionEvent e)
4810 // /////////////////////////////
4811 // Collect Data to be translated/transferred
4813 SequenceI[] selection = viewport.getSequenceSelection();
4814 String[] seqstring = viewport.getViewAsString(true);
4815 AlignmentI al = null;
4818 al = jalview.analysis.Dna.CdnaTranslate(selection, seqstring,
4819 viewport.getViewAsVisibleContigs(true), viewport
4820 .getGapCharacter(), viewport.getAlignment()
4821 .getAlignmentAnnotation(), viewport.getAlignment()
4822 .getWidth(), viewport.getAlignment().getDataset());
4823 } catch (Exception ex)
4826 jalview.bin.Cache.log.error(
4827 "Exception during translation. Please report this !", ex);
4832 .getString("label.error_when_translating_sequences_submit_bug_report"),
4834 .getString("label.implementation_error")
4836 .getString("translation_failed"),
4837 JOptionPane.ERROR_MESSAGE);
4846 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation"),
4847 MessageManager.getString("label.translation_failed"),
4848 JOptionPane.WARNING_MESSAGE);
4852 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4853 Desktop.addInternalFrame(af, MessageManager.formatMessage(
4854 "label.translation_of_params", new String[]
4855 { this.getTitle() }), DEFAULT_WIDTH, DEFAULT_HEIGHT);
4860 * Try to load a features file onto the alignment.
4863 * contents or path to retrieve file
4865 * access mode of file (see jalview.io.AlignFile)
4866 * @return true if features file was parsed corectly.
4868 public boolean parseFeaturesFile(String file, String type)
4870 boolean featuresFile = false;
4873 featuresFile = new FeaturesFile(file, type).parse(viewport
4874 .getAlignment().getDataset(), alignPanel.seqPanel.seqCanvas
4875 .getFeatureRenderer().getFeatureColours(), false,
4876 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4877 } catch (Exception ex)
4879 ex.printStackTrace();
4884 viewport.setShowSequenceFeatures(true);
4885 showSeqFeatures.setSelected(true);
4886 if (alignPanel.seqPanel.seqCanvas.fr != null)
4888 // update the min/max ranges where necessary
4889 alignPanel.seqPanel.seqCanvas.fr.findAllFeatures(true);
4891 if (featureSettings != null)
4893 featureSettings.setTableData();
4895 alignPanel.paintAlignment(true);
4898 return featuresFile;
4902 public void dragEnter(DropTargetDragEvent evt)
4907 public void dragExit(DropTargetEvent evt)
4912 public void dragOver(DropTargetDragEvent evt)
4917 public void dropActionChanged(DropTargetDragEvent evt)
4922 public void drop(DropTargetDropEvent evt)
4924 Transferable t = evt.getTransferable();
4925 java.util.List files = null;
4929 DataFlavor uriListFlavor = new DataFlavor(
4930 "text/uri-list;class=java.lang.String");
4931 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
4933 // Works on Windows and MacOSX
4934 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4935 files = (java.util.List) t
4936 .getTransferData(DataFlavor.javaFileListFlavor);
4938 else if (t.isDataFlavorSupported(uriListFlavor))
4940 // This is used by Unix drag system
4941 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4942 String data = (String) t.getTransferData(uriListFlavor);
4943 files = new java.util.ArrayList(1);
4944 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
4945 data, "\r\n"); st.hasMoreTokens();)
4947 String s = st.nextToken();
4948 if (s.startsWith("#"))
4950 // the line is a comment (as per the RFC 2483)
4954 java.net.URI uri = new java.net.URI(s);
4955 // check to see if we can handle this kind of URI
4956 if (uri.getScheme().toLowerCase().startsWith("http"))
4958 files.add(uri.toString());
4962 // otherwise preserve old behaviour: catch all for file objects
4963 java.io.File file = new java.io.File(uri);
4964 files.add(file.toString());
4968 } catch (Exception e)
4970 e.printStackTrace();
4976 // check to see if any of these files have names matching sequences in
4978 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4979 .getAlignment().getSequencesArray());
4981 * Object[] { String,SequenceI}
4983 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
4984 ArrayList<String> filesnotmatched = new ArrayList<String>();
4985 for (int i = 0; i < files.size(); i++)
4987 String file = files.get(i).toString();
4989 String protocol = FormatAdapter.checkProtocol(file);
4990 if (protocol == jalview.io.FormatAdapter.FILE)
4992 File fl = new File(file);
4993 pdbfn = fl.getName();
4995 else if (protocol == jalview.io.FormatAdapter.URL)
4997 URL url = new URL(file);
4998 pdbfn = url.getFile();
5000 if (pdbfn.length() > 0)
5002 // attempt to find a match in the alignment
5003 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5004 int l = 0, c = pdbfn.indexOf(".");
5005 while (mtch == null && c != -1)
5010 } while ((c = pdbfn.indexOf(".", l)) > l);
5013 pdbfn = pdbfn.substring(0, l);
5015 mtch = idm.findAllIdMatches(pdbfn);
5022 type = new IdentifyFile().Identify(file, protocol);
5023 } catch (Exception ex)
5029 if (type.equalsIgnoreCase("PDB"))
5031 filesmatched.add(new Object[]
5032 { file, protocol, mtch });
5037 // File wasn't named like one of the sequences or wasn't a PDB file.
5038 filesnotmatched.add(file);
5042 if (filesmatched.size() > 0)
5044 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
5050 "label.automatically_associate_pdb_files_with_sequences_same_name",
5057 .getString("label.automatically_associate_pdb_files_by_name"),
5058 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
5061 for (Object[] fm : filesmatched)
5063 // try and associate
5064 // TODO: may want to set a standard ID naming formalism for
5065 // associating PDB files which have no IDs.
5066 for (SequenceI toassoc : (SequenceI[]) fm[2])
5068 PDBEntry pe = new AssociatePdbFileWithSeq()
5069 .associatePdbWithSeq((String) fm[0],
5070 (String) fm[1], toassoc, false,
5074 System.err.println("Associated file : "
5075 + ((String) fm[0]) + " with "
5076 + toassoc.getDisplayId(true));
5080 alignPanel.paintAlignment(true);
5084 if (filesnotmatched.size() > 0)
5087 && (Cache.getDefault(
5088 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
5091 "<html>"+MessageManager
5093 "label.ignore_unmatched_dropped_files_info",
5098 .toString() })+"</html>",
5100 .getString("label.ignore_unmatched_dropped_files"),
5101 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
5105 for (String fn : filesnotmatched)
5107 loadJalviewDataFile(fn, null, null, null);
5111 } catch (Exception ex)
5113 ex.printStackTrace();
5119 * Attempt to load a "dropped" file or URL string: First by testing whether
5120 * it's and Annotation file, then a JNet file, and finally a features file. If
5121 * all are false then the user may have dropped an alignment file onto this
5125 * either a filename or a URL string.
5127 public void loadJalviewDataFile(String file, String protocol,
5128 String format, SequenceI assocSeq)
5132 if (protocol == null)
5134 protocol = jalview.io.FormatAdapter.checkProtocol(file);
5136 // if the file isn't identified, or not positively identified as some
5137 // other filetype (PFAM is default unidentified alignment file type) then
5138 // try to parse as annotation.
5139 boolean isAnnotation = (format == null || format
5140 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
5141 .readAnnotationFile(viewport.getAlignment(), file, protocol)
5146 // first see if its a T-COFFEE score file
5147 TCoffeeScoreFile tcf = null;
5150 tcf = new TCoffeeScoreFile(file, protocol);
5153 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5155 tcoffeeColour.setEnabled(true);
5156 tcoffeeColour.setSelected(true);
5157 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5158 isAnnotation = true;
5160 .setText(MessageManager
5161 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5165 // some problem - if no warning its probable that the ID matching
5166 // process didn't work
5170 tcf.getWarningMessage() == null ? MessageManager
5171 .getString("label.check_file_matches_sequence_ids_alignment")
5172 : tcf.getWarningMessage(),
5174 .getString("label.problem_reading_tcoffee_score_file"),
5175 JOptionPane.WARNING_MESSAGE);
5182 } catch (Exception x)
5185 .debug("Exception when processing data source as T-COFFEE score file",
5191 // try to see if its a JNet 'concise' style annotation file *before*
5193 // try to parse it as a features file
5196 format = new IdentifyFile().Identify(file, protocol);
5198 if (format.equalsIgnoreCase("JnetFile"))
5200 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5202 new JnetAnnotationMaker().add_annotation(predictions,
5203 viewport.getAlignment(), 0, false);
5204 isAnnotation = true;
5209 * if (format.equalsIgnoreCase("PDB")) {
5211 * String pdbfn = ""; // try to match up filename with sequence id
5212 * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
5213 * new File(file); pdbfn = fl.getName(); } else if (protocol ==
5214 * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
5215 * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
5216 * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5217 * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
5218 * // attempt to find a match in the alignment SequenceI mtch =
5219 * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
5220 * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
5221 * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
5222 * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
5223 * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
5224 * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
5225 * { System.err.println("Associated file : " + file + " with " +
5226 * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
5227 * TODO: maybe need to load as normal otherwise return; } }
5229 // try to parse it as a features file
5230 boolean isGroupsFile = parseFeaturesFile(file, protocol);
5231 // if it wasn't a features file then we just treat it as a general
5232 // alignment file to load into the current view.
5235 new FileLoader().LoadFile(viewport, file, protocol, format);
5239 alignPanel.paintAlignment(true);
5247 alignPanel.adjustAnnotationHeight();
5248 viewport.updateSequenceIdColours();
5249 buildSortByAnnotationScoresMenu();
5250 alignPanel.paintAlignment(true);
5252 } catch (Exception ex)
5254 ex.printStackTrace();
5255 } catch (OutOfMemoryError oom)
5260 } catch (Exception x)
5266 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5267 : "using " + protocol + " from " + file)
5269 + (format != null ? "(parsing as '" + format
5270 + "' file)" : ""), oom, Desktop.desktop);
5275 public void tabSelectionChanged(int index)
5279 alignPanel = (AlignmentPanel) alignPanels.elementAt(index);
5280 viewport = alignPanel.av;
5281 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5282 setMenusFromViewport(viewport);
5287 public void tabbedPane_mousePressed(MouseEvent e)
5289 if (SwingUtilities.isRightMouseButton(e))
5291 String reply = JOptionPane.showInternalInputDialog(this,
5292 MessageManager.getString("label.enter_view_name"),
5293 MessageManager.getString("label.enter_view_name"),
5294 JOptionPane.QUESTION_MESSAGE);
5298 viewport.viewName = reply;
5299 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5304 public AlignViewport getCurrentView()
5310 * Open the dialog for regex description parsing.
5313 protected void extractScores_actionPerformed(ActionEvent e)
5315 ParseProperties pp = new jalview.analysis.ParseProperties(
5316 viewport.getAlignment());
5317 // TODO: verify regex and introduce GUI dialog for version 2.5
5318 // if (pp.getScoresFromDescription("col", "score column ",
5319 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5321 if (pp.getScoresFromDescription("description column",
5322 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5324 buildSortByAnnotationScoresMenu();
5332 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5336 protected void showDbRefs_actionPerformed(ActionEvent e)
5338 viewport.setShowDbRefs(showDbRefsMenuitem.isSelected());
5344 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5348 protected void showNpFeats_actionPerformed(ActionEvent e)
5350 viewport.setShowNpFeats(showNpFeatsMenuitem.isSelected());
5354 * find the viewport amongst the tabs in this alignment frame and close that
5359 public boolean closeView(AlignViewport av)
5363 this.closeMenuItem_actionPerformed(false);
5366 Component[] comp = tabbedPane.getComponents();
5367 for (int i = 0; comp != null && i < comp.length; i++)
5369 if (comp[i] instanceof AlignmentPanel)
5371 if (((AlignmentPanel) comp[i]).av == av)
5374 closeView((AlignmentPanel) comp[i]);
5382 protected void build_fetchdbmenu(JMenu webService)
5384 // Temporary hack - DBRef Fetcher always top level ws entry.
5385 // TODO We probably want to store a sequence database checklist in
5386 // preferences and have checkboxes.. rather than individual sources selected
5388 final JMenu rfetch = new JMenu(
5389 MessageManager.getString("action.fetch_db_references"));
5390 rfetch.setToolTipText(MessageManager
5391 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5392 webService.add(rfetch);
5394 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5395 MessageManager.getString("option.trim_retrieved_seqs"));
5396 trimrs.setToolTipText(MessageManager
5397 .getString("label.trim_retrieved_sequences"));
5398 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5399 trimrs.addActionListener(new ActionListener()
5402 public void actionPerformed(ActionEvent e)
5404 trimrs.setSelected(trimrs.isSelected());
5405 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5406 Boolean.valueOf(trimrs.isSelected()).toString());
5410 JMenuItem fetchr = new JMenuItem(
5411 MessageManager.getString("label.standard_databases"));
5412 fetchr.setToolTipText(MessageManager
5413 .getString("label.fetch_embl_uniprot"));
5414 fetchr.addActionListener(new ActionListener()
5418 public void actionPerformed(ActionEvent e)
5420 new Thread(new Runnable()
5426 new jalview.ws.DBRefFetcher(alignPanel.av
5427 .getSequenceSelection(), alignPanel.alignFrame)
5428 .fetchDBRefs(false);
5436 final AlignFrame me = this;
5437 new Thread(new Runnable()
5442 final jalview.ws.SequenceFetcher sf = SequenceFetcher
5443 .getSequenceFetcherSingleton(me);
5444 javax.swing.SwingUtilities.invokeLater(new Runnable()
5449 String[] dbclasses = sf.getOrderedSupportedSources();
5450 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5451 // jalview.util.QuickSort.sort(otherdb, otherdb);
5452 List<DbSourceProxy> otherdb;
5453 JMenu dfetch = new JMenu();
5454 JMenu ifetch = new JMenu();
5455 JMenuItem fetchr = null;
5456 int comp = 0, icomp = 0, mcomp = 15;
5457 String mname = null;
5459 for (String dbclass : dbclasses)
5461 otherdb = sf.getSourceProxy(dbclass);
5462 // add a single entry for this class, or submenu allowing 'fetch
5464 if (otherdb == null || otherdb.size() < 1)
5468 // List<DbSourceProxy> dbs=otherdb;
5469 // otherdb=new ArrayList<DbSourceProxy>();
5470 // for (DbSourceProxy db:dbs)
5472 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5476 mname = "From " + dbclass;
5478 if (otherdb.size() == 1)
5480 final DbSourceProxy[] dassource = otherdb
5481 .toArray(new DbSourceProxy[0]);
5482 DbSourceProxy src = otherdb.get(0);
5483 fetchr = new JMenuItem(src.getDbSource());
5484 fetchr.addActionListener(new ActionListener()
5488 public void actionPerformed(ActionEvent e)
5490 new Thread(new Runnable()
5496 new jalview.ws.DBRefFetcher(alignPanel.av
5497 .getSequenceSelection(),
5498 alignPanel.alignFrame, dassource)
5499 .fetchDBRefs(false);
5505 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from", new String[]{src.getDbName()})));
5511 final DbSourceProxy[] dassource = otherdb
5512 .toArray(new DbSourceProxy[0]);
5514 DbSourceProxy src = otherdb.get(0);
5515 fetchr = new JMenuItem(MessageManager.formatMessage(
5516 "label.fetch_all_param", new String[]
5517 { src.getDbSource() }));
5518 fetchr.addActionListener(new ActionListener()
5521 public void actionPerformed(ActionEvent e)
5523 new Thread(new Runnable()
5529 new jalview.ws.DBRefFetcher(alignPanel.av
5530 .getSequenceSelection(),
5531 alignPanel.alignFrame, dassource)
5532 .fetchDBRefs(false);
5538 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from_all_sources", new String[]{Integer.valueOf(otherdb.size()).toString(), src.getDbSource(), src.getDbName()})));
5541 // and then build the rest of the individual menus
5542 ifetch = new JMenu(MessageManager.formatMessage("label.source_from_db_source", new String[]{src.getDbSource()}));
5544 String imname = null;
5546 for (DbSourceProxy sproxy : otherdb)
5548 String dbname = sproxy.getDbName();
5549 String sname = dbname.length() > 5 ? dbname.substring(0,
5550 5) + "..." : dbname;
5551 String msname = dbname.length() > 10 ? dbname.substring(
5552 0, 10) + "..." : dbname;
5555 imname = MessageManager.formatMessage("label.from_msname", new String[]{sname});
5557 fetchr = new JMenuItem(msname);
5558 final DbSourceProxy[] dassrc =
5560 fetchr.addActionListener(new ActionListener()
5564 public void actionPerformed(ActionEvent e)
5566 new Thread(new Runnable()
5572 new jalview.ws.DBRefFetcher(alignPanel.av
5573 .getSequenceSelection(),
5574 alignPanel.alignFrame, dassrc)
5575 .fetchDBRefs(false);
5581 fetchr.setToolTipText("<html>"
5582 + MessageManager.formatMessage("label.fetch_retrieve_from", new String[]{dbname}));
5585 if (++icomp >= mcomp || i == (otherdb.size()))
5587 ifetch.setText(MessageManager.formatMessage(
5588 "label.source_to_target", imname, sname));
5590 ifetch = new JMenu();
5598 if (comp >= mcomp || dbi >= (dbclasses.length))
5600 dfetch.setText(MessageManager.formatMessage(
5601 "label.source_to_target", mname, dbclass));
5603 dfetch = new JMenu();
5616 * Left justify the whole alignment.
5619 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5621 AlignmentI al = viewport.getAlignment();
5623 viewport.firePropertyChange("alignment", null, al);
5627 * Right justify the whole alignment.
5630 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5632 AlignmentI al = viewport.getAlignment();
5634 viewport.firePropertyChange("alignment", null, al);
5637 public void setShowSeqFeatures(boolean b)
5639 showSeqFeatures.setSelected(true);
5640 viewport.setShowSequenceFeatures(true);
5647 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5648 * awt.event.ActionEvent)
5651 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5653 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5654 alignPanel.paintAlignment(true);
5661 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5665 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5667 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5668 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5676 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5677 * .event.ActionEvent)
5680 protected void showGroupConservation_actionPerformed(ActionEvent e)
5682 viewport.setShowGroupConservation(showGroupConservation.getState());
5683 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5690 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5691 * .event.ActionEvent)
5694 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5696 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5697 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5704 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5705 * .event.ActionEvent)
5708 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5710 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5711 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5715 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5717 showSequenceLogo.setState(true);
5718 viewport.setShowSequenceLogo(true);
5719 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5720 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5724 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5726 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5733 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5734 * .event.ActionEvent)
5737 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5739 if (avc.makeGroupsFromSelection())
5741 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5742 alignPanel.updateAnnotation();
5743 alignPanel.paintAlignment(true);
5748 protected void createGroup_actionPerformed(ActionEvent e)
5750 if (avc.createGroup())
5752 alignPanel.alignmentChanged();
5757 protected void unGroup_actionPerformed(ActionEvent e)
5761 alignPanel.alignmentChanged();
5766 * make the given alignmentPanel the currently selected tab
5768 * @param alignmentPanel
5770 public void setDisplayedView(AlignmentPanel alignmentPanel)
5772 if (!viewport.getSequenceSetId().equals(
5773 alignmentPanel.av.getSequenceSetId()))
5775 throw new Error(MessageManager.getString("error.implementation_error_cannot_show_view_alignment_frame"));
5777 if (tabbedPane != null
5778 & alignPanels.indexOf(alignmentPanel) != tabbedPane
5779 .getSelectedIndex())
5781 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5786 * Action on selection of menu options to Show or Hide annotations.
5789 * @param forSequences
5790 * update sequence-related annotations
5791 * @param forAlignment
5792 * update non-sequence-related annotations
5795 protected void setAnnotationsVisibility(boolean visible,
5796 boolean forSequences, boolean forAlignment)
5798 for (AlignmentAnnotation aa : alignPanel.getAlignment()
5799 .getAlignmentAnnotation())
5801 boolean apply = (aa.sequenceRef == null && forAlignment)
5802 || (aa.sequenceRef != null && forSequences);
5805 aa.visible = visible;
5808 this.alignPanel.paintAlignment(true);
5812 * Store selected annotation sort order for the view and repaint.
5815 protected void sortAnnotations_actionPerformed()
5817 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5819 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5820 alignPanel.paintAlignment(true);
5824 class PrintThread extends Thread
5828 public PrintThread(AlignmentPanel ap)
5833 static PageFormat pf;
5838 PrinterJob printJob = PrinterJob.getPrinterJob();
5842 printJob.setPrintable(ap, pf);
5846 printJob.setPrintable(ap);
5849 if (printJob.printDialog())
5854 } catch (Exception PrintException)
5856 PrintException.printStackTrace();