2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3 * Copyright (C) 2014 The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AAFrequency;
24 import jalview.analysis.AlignmentSorter;
25 import jalview.analysis.AlignmentUtils;
26 import jalview.analysis.Conservation;
27 import jalview.analysis.CrossRef;
28 import jalview.analysis.NJTree;
29 import jalview.analysis.ParseProperties;
30 import jalview.analysis.SequenceIdMatcher;
31 import jalview.api.AlignViewControllerGuiI;
32 import jalview.api.AlignViewControllerI;
33 import jalview.api.AlignmentViewPanel;
34 import jalview.api.analysis.ScoreModelI;
35 import jalview.bin.Cache;
36 import jalview.commands.CommandI;
37 import jalview.commands.EditCommand;
38 import jalview.commands.EditCommand.Action;
39 import jalview.commands.OrderCommand;
40 import jalview.commands.RemoveGapColCommand;
41 import jalview.commands.RemoveGapsCommand;
42 import jalview.commands.SlideSequencesCommand;
43 import jalview.commands.TrimRegionCommand;
44 import jalview.datamodel.AlignedCodonFrame;
45 import jalview.datamodel.Alignment;
46 import jalview.datamodel.AlignmentAnnotation;
47 import jalview.datamodel.AlignmentI;
48 import jalview.datamodel.AlignmentOrder;
49 import jalview.datamodel.AlignmentView;
50 import jalview.datamodel.ColumnSelection;
51 import jalview.datamodel.PDBEntry;
52 import jalview.datamodel.SeqCigar;
53 import jalview.datamodel.Sequence;
54 import jalview.datamodel.SequenceGroup;
55 import jalview.datamodel.SequenceI;
56 import jalview.io.AlignmentProperties;
57 import jalview.io.AnnotationFile;
58 import jalview.io.BioJsHTMLOutput;
59 import jalview.io.FeaturesFile;
60 import jalview.io.FileLoader;
61 import jalview.io.FormatAdapter;
62 import jalview.io.HtmlSvgOutput;
63 import jalview.io.IdentifyFile;
64 import jalview.io.JalviewFileChooser;
65 import jalview.io.JalviewFileView;
66 import jalview.io.JnetAnnotationMaker;
67 import jalview.io.NewickFile;
68 import jalview.io.TCoffeeScoreFile;
69 import jalview.jbgui.GAlignFrame;
70 import jalview.schemes.Blosum62ColourScheme;
71 import jalview.schemes.BuriedColourScheme;
72 import jalview.schemes.ClustalxColourScheme;
73 import jalview.schemes.ColourSchemeI;
74 import jalview.schemes.ColourSchemeProperty;
75 import jalview.schemes.HelixColourScheme;
76 import jalview.schemes.HydrophobicColourScheme;
77 import jalview.schemes.NucleotideColourScheme;
78 import jalview.schemes.PIDColourScheme;
79 import jalview.schemes.PurinePyrimidineColourScheme;
80 import jalview.schemes.RNAHelicesColourChooser;
81 import jalview.schemes.ResidueProperties;
82 import jalview.schemes.StrandColourScheme;
83 import jalview.schemes.TCoffeeColourScheme;
84 import jalview.schemes.TaylorColourScheme;
85 import jalview.schemes.TurnColourScheme;
86 import jalview.schemes.UserColourScheme;
87 import jalview.schemes.ZappoColourScheme;
88 import jalview.util.MessageManager;
89 import jalview.ws.jws1.Discoverer;
90 import jalview.ws.jws2.Jws2Discoverer;
91 import jalview.ws.jws2.jabaws2.Jws2Instance;
92 import jalview.ws.seqfetcher.DbSourceProxy;
94 import java.awt.BorderLayout;
95 import java.awt.Component;
96 import java.awt.GridLayout;
97 import java.awt.Rectangle;
98 import java.awt.Toolkit;
99 import java.awt.datatransfer.Clipboard;
100 import java.awt.datatransfer.DataFlavor;
101 import java.awt.datatransfer.StringSelection;
102 import java.awt.datatransfer.Transferable;
103 import java.awt.dnd.DnDConstants;
104 import java.awt.dnd.DropTargetDragEvent;
105 import java.awt.dnd.DropTargetDropEvent;
106 import java.awt.dnd.DropTargetEvent;
107 import java.awt.dnd.DropTargetListener;
108 import java.awt.event.ActionEvent;
109 import java.awt.event.ActionListener;
110 import java.awt.event.KeyAdapter;
111 import java.awt.event.KeyEvent;
112 import java.awt.event.MouseAdapter;
113 import java.awt.event.MouseEvent;
114 import java.awt.print.PageFormat;
115 import java.awt.print.PrinterJob;
116 import java.beans.PropertyChangeEvent;
119 import java.util.ArrayList;
120 import java.util.Arrays;
121 import java.util.Enumeration;
122 import java.util.Hashtable;
123 import java.util.List;
124 import java.util.Vector;
126 import javax.swing.JButton;
127 import javax.swing.JCheckBoxMenuItem;
128 import javax.swing.JEditorPane;
129 import javax.swing.JInternalFrame;
130 import javax.swing.JLabel;
131 import javax.swing.JLayeredPane;
132 import javax.swing.JMenu;
133 import javax.swing.JMenuItem;
134 import javax.swing.JOptionPane;
135 import javax.swing.JPanel;
136 import javax.swing.JProgressBar;
137 import javax.swing.JRadioButtonMenuItem;
138 import javax.swing.JScrollPane;
139 import javax.swing.SwingUtilities;
145 * @version $Revision$
147 public class AlignFrame extends GAlignFrame implements DropTargetListener,
148 IProgressIndicator, AlignViewControllerGuiI
152 public static final int DEFAULT_WIDTH = 700;
155 public static final int DEFAULT_HEIGHT = 500;
157 public AlignmentPanel alignPanel;
159 AlignViewport viewport;
161 public AlignViewControllerI avc;
163 Vector alignPanels = new Vector();
166 * Last format used to load or save alignments in this window
168 String currentFileFormat = null;
171 * Current filename for this alignment
173 String fileName = null;
176 * Creates a new AlignFrame object with specific width and height.
182 public AlignFrame(AlignmentI al, int width, int height)
184 this(al, null, width, height);
188 * Creates a new AlignFrame object with specific width, height and
194 * @param sequenceSetId
196 public AlignFrame(AlignmentI al, int width, int height,
197 String sequenceSetId)
199 this(al, null, width, height, sequenceSetId);
203 * Creates a new AlignFrame object with specific width, height and
209 * @param sequenceSetId
212 public AlignFrame(AlignmentI al, int width, int height,
213 String sequenceSetId, String viewId)
215 this(al, null, width, height, sequenceSetId, viewId);
219 * new alignment window with hidden columns
223 * @param hiddenColumns
224 * ColumnSelection or null
226 * Width of alignment frame
230 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
231 int width, int height)
233 this(al, hiddenColumns, width, height, null);
237 * Create alignment frame for al with hiddenColumns, a specific width and
238 * height, and specific sequenceId
241 * @param hiddenColumns
244 * @param sequenceSetId
247 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
248 int width, int height, String sequenceSetId)
250 this(al, hiddenColumns, width, height, sequenceSetId, null);
254 * Create alignment frame for al with hiddenColumns, a specific width and
255 * height, and specific sequenceId
258 * @param hiddenColumns
261 * @param sequenceSetId
266 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
267 int width, int height, String sequenceSetId, String viewId)
269 setSize(width, height);
271 if (al.getDataset() == null)
276 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
278 alignPanel = new AlignmentPanel(this, viewport);
281 addAlignmentPanel(alignPanel, true);
286 * Make a new AlignFrame from existing alignmentPanels
293 public AlignFrame(AlignmentPanel ap)
297 addAlignmentPanel(ap, false);
302 * initalise the alignframe from the underlying viewport data and the
307 avc = new jalview.controller.AlignViewController(this, viewport,
309 if (viewport.getAlignmentConservationAnnotation() == null)
311 BLOSUM62Colour.setEnabled(false);
312 conservationMenuItem.setEnabled(false);
313 modifyConservation.setEnabled(false);
314 // PIDColour.setEnabled(false);
315 // abovePIDThreshold.setEnabled(false);
316 // modifyPID.setEnabled(false);
319 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
322 if (sortby.equals("Id"))
324 sortIDMenuItem_actionPerformed(null);
326 else if (sortby.equals("Pairwise Identity"))
328 sortPairwiseMenuItem_actionPerformed(null);
331 if (Desktop.desktop != null)
333 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
334 addServiceListeners();
335 setGUINucleotide(viewport.getAlignment().isNucleotide());
338 setMenusFromViewport(viewport);
339 buildSortByAnnotationScoresMenu();
342 if (viewport.wrapAlignment)
344 wrapMenuItem_actionPerformed(null);
347 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
349 this.overviewMenuItem_actionPerformed(null);
357 * Change the filename and format for the alignment, and enable the 'reload'
358 * button functionality.
365 public void setFileName(String file, String format)
368 currentFileFormat = format;
369 reload.setEnabled(true);
372 void addKeyListener()
374 addKeyListener(new KeyAdapter()
377 public void keyPressed(KeyEvent evt)
379 if (viewport.cursorMode
380 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
381 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
382 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
383 && Character.isDigit(evt.getKeyChar()))
385 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
388 switch (evt.getKeyCode())
391 case 27: // escape key
392 deselectAllSequenceMenuItem_actionPerformed(null);
396 case KeyEvent.VK_DOWN:
397 if (evt.isAltDown() || !viewport.cursorMode)
399 moveSelectedSequences(false);
401 if (viewport.cursorMode)
403 alignPanel.getSeqPanel().moveCursor(0, 1);
408 if (evt.isAltDown() || !viewport.cursorMode)
410 moveSelectedSequences(true);
412 if (viewport.cursorMode)
414 alignPanel.getSeqPanel().moveCursor(0, -1);
419 case KeyEvent.VK_LEFT:
420 if (evt.isAltDown() || !viewport.cursorMode)
422 slideSequences(false, alignPanel.getSeqPanel().getKeyboardNo1());
426 alignPanel.getSeqPanel().moveCursor(-1, 0);
431 case KeyEvent.VK_RIGHT:
432 if (evt.isAltDown() || !viewport.cursorMode)
434 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
438 alignPanel.getSeqPanel().moveCursor(1, 0);
442 case KeyEvent.VK_SPACE:
443 if (viewport.cursorMode)
445 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
446 || evt.isShiftDown() || evt.isAltDown());
450 // case KeyEvent.VK_A:
451 // if (viewport.cursorMode)
453 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
454 // //System.out.println("A");
458 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
459 * System.out.println("closing bracket"); } break;
461 case KeyEvent.VK_DELETE:
462 case KeyEvent.VK_BACK_SPACE:
463 if (!viewport.cursorMode)
465 cut_actionPerformed(null);
469 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
470 || evt.isShiftDown() || evt.isAltDown());
476 if (viewport.cursorMode)
478 alignPanel.getSeqPanel().setCursorRow();
482 if (viewport.cursorMode && !evt.isControlDown())
484 alignPanel.getSeqPanel().setCursorColumn();
488 if (viewport.cursorMode)
490 alignPanel.getSeqPanel().setCursorPosition();
494 case KeyEvent.VK_ENTER:
495 case KeyEvent.VK_COMMA:
496 if (viewport.cursorMode)
498 alignPanel.getSeqPanel().setCursorRowAndColumn();
503 if (viewport.cursorMode)
505 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
509 if (viewport.cursorMode)
511 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
516 viewport.cursorMode = !viewport.cursorMode;
517 statusBar.setText(MessageManager.formatMessage(
518 "label.keyboard_editing_mode", new String[]
519 { (viewport.cursorMode ? "on" : "off") }));
520 if (viewport.cursorMode)
522 alignPanel.getSeqPanel().seqCanvas.cursorX = viewport.startRes;
523 alignPanel.getSeqPanel().seqCanvas.cursorY = viewport.startSeq;
525 alignPanel.getSeqPanel().seqCanvas.repaint();
531 Help.showHelpWindow();
532 } catch (Exception ex)
534 ex.printStackTrace();
539 boolean toggleSeqs = !evt.isControlDown();
540 boolean toggleCols = !evt.isShiftDown();
541 toggleHiddenRegions(toggleSeqs, toggleCols);
544 case KeyEvent.VK_PAGE_UP:
545 if (viewport.wrapAlignment)
547 alignPanel.scrollUp(true);
551 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
552 - viewport.endSeq + viewport.startSeq);
555 case KeyEvent.VK_PAGE_DOWN:
556 if (viewport.wrapAlignment)
558 alignPanel.scrollUp(false);
562 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
563 + viewport.endSeq - viewport.startSeq);
570 public void keyReleased(KeyEvent evt)
572 switch (evt.getKeyCode())
574 case KeyEvent.VK_LEFT:
575 if (evt.isAltDown() || !viewport.cursorMode)
577 viewport.firePropertyChange("alignment", null, viewport
578 .getAlignment().getSequences());
582 case KeyEvent.VK_RIGHT:
583 if (evt.isAltDown() || !viewport.cursorMode)
585 viewport.firePropertyChange("alignment", null, viewport
586 .getAlignment().getSequences());
594 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
596 ap.alignFrame = this;
597 avc = new jalview.controller.AlignViewController(this, viewport,
600 alignPanels.addElement(ap);
602 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
604 int aSize = alignPanels.size();
606 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
608 if (aSize == 1 && ap.av.viewName == null)
610 this.getContentPane().add(ap, BorderLayout.CENTER);
616 setInitialTabVisible();
619 expandViews.setEnabled(true);
620 gatherViews.setEnabled(true);
621 tabbedPane.addTab(ap.av.viewName, ap);
623 ap.setVisible(false);
628 if (ap.av.isPadGaps())
630 ap.av.getAlignment().padGaps();
632 ap.av.updateConservation(ap);
633 ap.av.updateConsensus(ap);
634 ap.av.updateStrucConsensus(ap);
638 public void setInitialTabVisible()
640 expandViews.setEnabled(true);
641 gatherViews.setEnabled(true);
642 tabbedPane.setVisible(true);
643 AlignmentPanel first = (AlignmentPanel) alignPanels.firstElement();
644 tabbedPane.addTab(first.av.viewName, first);
645 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
648 public AlignViewport getViewport()
653 /* Set up intrinsic listeners for dynamically generated GUI bits. */
654 private void addServiceListeners()
656 final java.beans.PropertyChangeListener thisListener;
657 Desktop.instance.addJalviewPropertyChangeListener("services",
658 thisListener = new java.beans.PropertyChangeListener()
661 public void propertyChange(PropertyChangeEvent evt)
663 // // System.out.println("Discoverer property change.");
664 // if (evt.getPropertyName().equals("services"))
666 SwingUtilities.invokeLater(new Runnable()
673 .println("Rebuild WS Menu for service change");
674 BuildWebServiceMenu();
681 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
684 public void internalFrameClosed(
685 javax.swing.event.InternalFrameEvent evt)
687 System.out.println("deregistering discoverer listener");
688 Desktop.instance.removeJalviewPropertyChangeListener("services",
690 closeMenuItem_actionPerformed(true);
693 // Finally, build the menu once to get current service state
694 new Thread(new Runnable()
699 BuildWebServiceMenu();
704 public void setGUINucleotide(boolean nucleotide)
706 showTranslation.setVisible(nucleotide);
707 conservationMenuItem.setEnabled(!nucleotide);
708 modifyConservation.setEnabled(!nucleotide);
709 showGroupConservation.setEnabled(!nucleotide);
710 rnahelicesColour.setEnabled(nucleotide);
711 purinePyrimidineColour.setEnabled(nucleotide);
712 // Remember AlignFrame always starts as protein
716 // calculateMenu.remove(calculateMenu.getItemCount() - 2);
721 * set up menus for the currently viewport. This may be called after any
722 * operation that affects the data in the current view (selection changed,
723 * etc) to update the menus to reflect the new state.
725 public void setMenusForViewport()
727 setMenusFromViewport(viewport);
731 * Need to call this method when tabs are selected for multiple views, or when
732 * loading from Jalview2XML.java
737 void setMenusFromViewport(AlignViewport av)
739 padGapsMenuitem.setSelected(av.isPadGaps());
740 colourTextMenuItem.setSelected(av.showColourText);
741 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
742 conservationMenuItem.setSelected(av.getConservationSelected());
743 seqLimits.setSelected(av.getShowJVSuffix());
744 idRightAlign.setSelected(av.isRightAlignIds());
745 centreColumnLabelsMenuItem.setState(av.centreColumnLabels);
746 renderGapsMenuItem.setSelected(av.renderGaps);
747 wrapMenuItem.setSelected(av.wrapAlignment);
748 scaleAbove.setVisible(av.wrapAlignment);
749 scaleLeft.setVisible(av.wrapAlignment);
750 scaleRight.setVisible(av.wrapAlignment);
751 annotationPanelMenuItem.setState(av.isShowAnnotation());
753 * Show/hide annotations only enabled if annotation panel is shown
755 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
756 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
757 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
758 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
759 viewBoxesMenuItem.setSelected(av.showBoxes);
760 viewTextMenuItem.setSelected(av.showText);
761 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
762 showGroupConsensus.setSelected(av.isShowGroupConsensus());
763 showGroupConservation.setSelected(av.isShowGroupConservation());
764 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
765 showSequenceLogo.setSelected(av.isShowSequenceLogo());
766 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
768 setColourSelected(ColourSchemeProperty.getColourName(av
769 .getGlobalColourScheme()));
771 showSeqFeatures.setSelected(av.showSequenceFeatures);
772 hiddenMarkers.setState(av.showHiddenMarkers);
773 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
774 showNpFeatsMenuitem.setSelected(av.isShowNpFeats());
775 showDbRefsMenuitem.setSelected(av.isShowDbRefs());
776 autoCalculate.setSelected(av.autoCalculateConsensus);
777 sortByTree.setSelected(av.sortByTree);
778 listenToViewSelections.setSelected(av.followSelection);
779 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
781 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
782 setShowProductsEnabled();
786 // methods for implementing IProgressIndicator
787 // need to refactor to a reusable stub class
788 Hashtable progressBars, progressBarHandlers;
793 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
796 public void setProgressBar(String message, long id)
798 if (progressBars == null)
800 progressBars = new Hashtable();
801 progressBarHandlers = new Hashtable();
804 JPanel progressPanel;
805 Long lId = new Long(id);
806 GridLayout layout = (GridLayout) statusPanel.getLayout();
807 if (progressBars.get(lId) != null)
809 progressPanel = (JPanel) progressBars.get(new Long(id));
810 statusPanel.remove(progressPanel);
811 progressBars.remove(lId);
812 progressPanel = null;
815 statusBar.setText(message);
817 if (progressBarHandlers.contains(lId))
819 progressBarHandlers.remove(lId);
821 layout.setRows(layout.getRows() - 1);
825 progressPanel = new JPanel(new BorderLayout(10, 5));
827 JProgressBar progressBar = new JProgressBar();
828 progressBar.setIndeterminate(true);
830 progressPanel.add(new JLabel(message), BorderLayout.WEST);
831 progressPanel.add(progressBar, BorderLayout.CENTER);
833 layout.setRows(layout.getRows() + 1);
834 statusPanel.add(progressPanel);
836 progressBars.put(lId, progressPanel);
839 // setMenusForViewport();
844 public void registerHandler(final long id,
845 final IProgressIndicatorHandler handler)
847 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
849 throw new Error(MessageManager.getString("error.call_setprogressbar_before_registering_handler"));
851 progressBarHandlers.put(new Long(id), handler);
852 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
853 if (handler.canCancel())
855 JButton cancel = new JButton(
856 MessageManager.getString("action.cancel"));
857 final IProgressIndicator us = this;
858 cancel.addActionListener(new ActionListener()
862 public void actionPerformed(ActionEvent e)
864 handler.cancelActivity(id);
865 us.setProgressBar(MessageManager.formatMessage("label.cancelled_params", new String[]{((JLabel) progressPanel.getComponent(0)).getText()}), id);
868 progressPanel.add(cancel, BorderLayout.EAST);
874 * @return true if any progress bars are still active
877 public boolean operationInProgress()
879 if (progressBars != null && progressBars.size() > 0)
887 public void setStatus(String text)
889 statusBar.setText(text);
893 * Added so Castor Mapping file can obtain Jalview Version
895 public String getVersion()
897 return jalview.bin.Cache.getProperty("VERSION");
900 public FeatureRenderer getFeatureRenderer()
902 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
906 public void fetchSequence_actionPerformed(ActionEvent e)
908 new SequenceFetcher(this);
912 public void addFromFile_actionPerformed(ActionEvent e)
914 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
918 public void reload_actionPerformed(ActionEvent e)
920 if (fileName != null)
922 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
923 // originating file's format
924 // TODO: work out how to recover feature settings for correct view(s) when
926 if (currentFileFormat.equals("Jalview"))
928 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
929 for (int i = 0; i < frames.length; i++)
931 if (frames[i] instanceof AlignFrame && frames[i] != this
932 && ((AlignFrame) frames[i]).fileName != null
933 && ((AlignFrame) frames[i]).fileName.equals(fileName))
937 frames[i].setSelected(true);
938 Desktop.instance.closeAssociatedWindows();
939 } catch (java.beans.PropertyVetoException ex)
945 Desktop.instance.closeAssociatedWindows();
947 FileLoader loader = new FileLoader();
948 String protocol = fileName.startsWith("http:") ? "URL" : "File";
949 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
953 Rectangle bounds = this.getBounds();
955 FileLoader loader = new FileLoader();
956 String protocol = fileName.startsWith("http:") ? "URL" : "File";
957 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
958 protocol, currentFileFormat);
960 newframe.setBounds(bounds);
961 if (featureSettings != null && featureSettings.isShowing())
963 final Rectangle fspos = featureSettings.frame.getBounds();
964 // TODO: need a 'show feature settings' function that takes bounds -
965 // need to refactor Desktop.addFrame
966 newframe.featureSettings_actionPerformed(null);
967 final FeatureSettings nfs = newframe.featureSettings;
968 SwingUtilities.invokeLater(new Runnable()
973 nfs.frame.setBounds(fspos);
976 this.featureSettings.close();
977 this.featureSettings = null;
979 this.closeMenuItem_actionPerformed(true);
985 public void addFromText_actionPerformed(ActionEvent e)
987 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
991 public void addFromURL_actionPerformed(ActionEvent e)
993 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
997 public void save_actionPerformed(ActionEvent e)
1000 || (currentFileFormat == null || !jalview.io.FormatAdapter
1001 .isValidIOFormat(currentFileFormat, true))
1002 || fileName.startsWith("http"))
1004 saveAs_actionPerformed(null);
1008 saveAlignment(fileName, currentFileFormat);
1019 public void saveAs_actionPerformed(ActionEvent e)
1021 JalviewFileChooser chooser = new JalviewFileChooser(
1022 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
1023 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
1024 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
1025 currentFileFormat, false);
1027 chooser.setFileView(new JalviewFileView());
1028 chooser.setDialogTitle(MessageManager.getString("label.save_alignment_to_file"));
1029 chooser.setToolTipText(MessageManager.getString("action.save"));
1031 int value = chooser.showSaveDialog(this);
1033 if (value == JalviewFileChooser.APPROVE_OPTION)
1035 currentFileFormat = chooser.getSelectedFormat();
1036 if (currentFileFormat == null)
1039 .showInternalMessageDialog(
1042 .getString("label.select_file_format_before_saving"),
1044 .getString("label.file_format_not_specified"),
1045 JOptionPane.WARNING_MESSAGE);
1046 value = chooser.showSaveDialog(this);
1050 fileName = chooser.getSelectedFile().getPath();
1052 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
1055 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
1056 if (currentFileFormat.indexOf(" ") > -1)
1058 currentFileFormat = currentFileFormat.substring(0,
1059 currentFileFormat.indexOf(" "));
1061 saveAlignment(fileName, currentFileFormat);
1065 public boolean saveAlignment(String file, String format)
1067 boolean success = true;
1069 if (format.equalsIgnoreCase("Jalview"))
1071 String shortName = title;
1073 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1075 shortName = shortName.substring(shortName
1076 .lastIndexOf(java.io.File.separatorChar) + 1);
1080 * First save any linked Chimera session.
1082 Desktop.instance.saveChimeraSessions(file);
1084 success = new Jalview2XML().saveAlignment(this, file, shortName);
1086 statusBar.setText(MessageManager.formatMessage(
1087 "label.successfully_saved_to_file_in_format", new Object[]
1088 { fileName, format }));
1093 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1095 warningMessage("Cannot save file " + fileName + " using format "
1096 + format, "Alignment output format not supported");
1097 saveAs_actionPerformed(null);
1098 // JBPNote need to have a raise_gui flag here
1102 String[] omitHidden = null;
1104 if (viewport.hasHiddenColumns())
1106 int reply = JOptionPane
1107 .showInternalConfirmDialog(
1110 .getString("label.alignment_contains_hidden_columns"),
1112 .getString("action.save_omit_hidden_columns"),
1113 JOptionPane.YES_NO_OPTION,
1114 JOptionPane.QUESTION_MESSAGE);
1116 if (reply == JOptionPane.YES_OPTION)
1118 omitHidden = viewport.getViewAsString(false);
1121 FormatAdapter f = new FormatAdapter();
1122 String output = f.formatSequences(format,
1123 viewport.getAlignment(), // class cast exceptions will
1124 // occur in the distant future
1125 omitHidden, f.getCacheSuffixDefault(format),
1126 viewport.getColumnSelection());
1136 java.io.PrintWriter out = new java.io.PrintWriter(
1137 new java.io.FileWriter(file));
1141 this.setTitle(file);
1142 statusBar.setText(MessageManager.formatMessage(
1143 "label.successfully_saved_to_file_in_format",
1145 { fileName, format }));
1146 } catch (Exception ex)
1149 ex.printStackTrace();
1156 JOptionPane.showInternalMessageDialog(this, MessageManager
1157 .formatMessage("label.couldnt_save_file", new String[]
1158 { fileName }), MessageManager
1159 .getString("label.error_saving_file"),
1160 JOptionPane.WARNING_MESSAGE);
1166 private void warningMessage(String warning, String title)
1168 if (new jalview.util.Platform().isHeadless())
1170 System.err.println("Warning: " + title + "\nWarning: " + warning);
1175 JOptionPane.showInternalMessageDialog(this, warning, title,
1176 JOptionPane.WARNING_MESSAGE);
1188 protected void outputText_actionPerformed(ActionEvent e)
1190 String[] omitHidden = null;
1192 if (viewport.hasHiddenColumns())
1194 int reply = JOptionPane
1195 .showInternalConfirmDialog(
1198 .getString("label.alignment_contains_hidden_columns"),
1200 .getString("action.save_omit_hidden_columns"),
1201 JOptionPane.YES_NO_OPTION,
1202 JOptionPane.QUESTION_MESSAGE);
1204 if (reply == JOptionPane.YES_OPTION)
1206 omitHidden = viewport.getViewAsString(false);
1210 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1211 cap.setForInput(null);
1215 cap.setText(new FormatAdapter().formatSequences(e.getActionCommand(),
1216 viewport.getAlignment(), omitHidden,
1217 viewport.getColumnSelection()));
1218 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1219 "label.alignment_output_command", new String[]
1220 { e.getActionCommand() }), 600, 500);
1221 } catch (OutOfMemoryError oom)
1223 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1236 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1238 // new HTMLOutput(alignPanel,
1239 // alignPanel.getSeqPanel().seqCanvas.getSequenceRenderer(),
1240 // alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
1241 new HtmlSvgOutput(null, alignPanel);
1245 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1247 new BioJsHTMLOutput(alignPanel,
1248 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
1250 public void createImageMap(File file, String image)
1252 alignPanel.makePNGImageMap(file, image);
1262 public void createPNG(File f)
1264 alignPanel.makePNG(f);
1274 public void createEPS(File f)
1276 alignPanel.makeEPS(f);
1279 public void createSVG(File f)
1281 alignPanel.makeSVG(f);
1284 public void pageSetup_actionPerformed(ActionEvent e)
1286 PrinterJob printJob = PrinterJob.getPrinterJob();
1287 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1297 public void printMenuItem_actionPerformed(ActionEvent e)
1299 // Putting in a thread avoids Swing painting problems
1300 PrintThread thread = new PrintThread(alignPanel);
1305 public void exportFeatures_actionPerformed(ActionEvent e)
1307 new AnnotationExporter().exportFeatures(alignPanel);
1311 public void exportAnnotations_actionPerformed(ActionEvent e)
1313 new AnnotationExporter().exportAnnotations(alignPanel,
1314 viewport.isShowAnnotation() ? viewport.getAlignment()
1315 .getAlignmentAnnotation() : null, viewport
1316 .getAlignment().getGroups(), ((Alignment) viewport
1317 .getAlignment()).alignmentProperties);
1321 public void associatedData_actionPerformed(ActionEvent e)
1323 // Pick the tree file
1324 JalviewFileChooser chooser = new JalviewFileChooser(
1325 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1326 chooser.setFileView(new JalviewFileView());
1327 chooser.setDialogTitle(MessageManager
1328 .getString("label.load_jalview_annotations"));
1329 chooser.setToolTipText(MessageManager
1330 .getString("label.load_jalview_annotations"));
1332 int value = chooser.showOpenDialog(null);
1334 if (value == JalviewFileChooser.APPROVE_OPTION)
1336 String choice = chooser.getSelectedFile().getPath();
1337 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1338 loadJalviewDataFile(choice, null, null, null);
1344 * Close the current view or all views in the alignment frame. If the frame
1345 * only contains one view then the alignment will be removed from memory.
1347 * @param closeAllTabs
1350 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1352 if (alignPanels != null && alignPanels.size() < 2)
1354 closeAllTabs = true;
1359 if (alignPanels != null)
1363 if (this.isClosed())
1365 // really close all the windows - otherwise wait till
1366 // setClosed(true) is called
1367 for (int i = 0; i < alignPanels.size(); i++)
1369 AlignmentPanel ap = (AlignmentPanel) alignPanels.elementAt(i);
1376 closeView(alignPanel);
1382 this.setClosed(true);
1384 } catch (Exception ex)
1386 ex.printStackTrace();
1391 * close alignPanel2 and shuffle tabs appropriately.
1393 * @param alignPanel2
1395 public void closeView(AlignmentPanel alignPanel2)
1397 int index = tabbedPane.getSelectedIndex();
1398 int closedindex = tabbedPane.indexOfComponent(alignPanel2);
1399 alignPanels.removeElement(alignPanel2);
1401 // if (viewport == alignPanel2.av)
1405 alignPanel2.closePanel();
1408 tabbedPane.removeTabAt(closedindex);
1409 tabbedPane.validate();
1411 if (index > closedindex || index == tabbedPane.getTabCount())
1413 // modify currently selected tab index if necessary.
1417 this.tabSelectionChanged(index);
1423 void updateEditMenuBar()
1426 if (viewport.historyList.size() > 0)
1428 undoMenuItem.setEnabled(true);
1429 CommandI command = viewport.historyList.peek();
1430 undoMenuItem.setText(MessageManager.formatMessage(
1431 "label.undo_command", new String[]
1432 { command.getDescription() }));
1436 undoMenuItem.setEnabled(false);
1437 undoMenuItem.setText(MessageManager.getString("action.undo"));
1440 if (viewport.redoList.size() > 0)
1442 redoMenuItem.setEnabled(true);
1444 CommandI command = viewport.redoList.peek();
1445 redoMenuItem.setText(MessageManager.formatMessage(
1446 "label.redo_command", new String[]
1447 { command.getDescription() }));
1451 redoMenuItem.setEnabled(false);
1452 redoMenuItem.setText(MessageManager.getString("action.redo"));
1456 public void addHistoryItem(CommandI command)
1458 if (command.getSize() > 0)
1460 viewport.historyList.push(command);
1461 viewport.redoList.clear();
1462 updateEditMenuBar();
1463 viewport.updateHiddenColumns();
1464 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1465 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1466 // viewport.getColumnSelection()
1467 // .getHiddenColumns().size() > 0);
1473 * @return alignment objects for all views
1475 AlignmentI[] getViewAlignments()
1477 if (alignPanels != null)
1479 Enumeration e = alignPanels.elements();
1480 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1481 for (int i = 0; e.hasMoreElements(); i++)
1483 als[i] = ((AlignmentPanel) e.nextElement()).av.getAlignment();
1487 if (viewport != null)
1489 return new AlignmentI[]
1490 { viewport.getAlignment() };
1502 protected void undoMenuItem_actionPerformed(ActionEvent e)
1504 if (viewport.historyList.empty())
1508 CommandI command = viewport.historyList.pop();
1509 viewport.redoList.push(command);
1510 command.undoCommand(getViewAlignments());
1512 AlignViewport originalSource = getOriginatingSource(command);
1513 updateEditMenuBar();
1515 if (originalSource != null)
1517 if (originalSource != viewport)
1520 .warn("Implementation worry: mismatch of viewport origin for undo");
1522 originalSource.updateHiddenColumns();
1523 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1525 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1526 // viewport.getColumnSelection()
1527 // .getHiddenColumns().size() > 0);
1528 originalSource.firePropertyChange("alignment", null, originalSource
1529 .getAlignment().getSequences());
1540 protected void redoMenuItem_actionPerformed(ActionEvent e)
1542 if (viewport.redoList.size() < 1)
1547 CommandI command = viewport.redoList.pop();
1548 viewport.historyList.push(command);
1549 command.doCommand(getViewAlignments());
1551 AlignViewport originalSource = getOriginatingSource(command);
1552 updateEditMenuBar();
1554 if (originalSource != null)
1557 if (originalSource != viewport)
1560 .warn("Implementation worry: mismatch of viewport origin for redo");
1562 originalSource.updateHiddenColumns();
1563 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1565 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1566 // viewport.getColumnSelection()
1567 // .getHiddenColumns().size() > 0);
1568 originalSource.firePropertyChange("alignment", null, originalSource
1569 .getAlignment().getSequences());
1573 AlignViewport getOriginatingSource(CommandI command)
1575 AlignViewport originalSource = null;
1576 // For sequence removal and addition, we need to fire
1577 // the property change event FROM the viewport where the
1578 // original alignment was altered
1579 AlignmentI al = null;
1580 if (command instanceof EditCommand)
1582 EditCommand editCommand = (EditCommand) command;
1583 al = editCommand.getAlignment();
1584 Vector comps = (Vector) PaintRefresher.components.get(viewport
1585 .getSequenceSetId());
1587 for (int i = 0; i < comps.size(); i++)
1589 if (comps.elementAt(i) instanceof AlignmentPanel)
1591 if (al == ((AlignmentPanel) comps.elementAt(i)).av.getAlignment())
1593 originalSource = ((AlignmentPanel) comps.elementAt(i)).av;
1600 if (originalSource == null)
1602 // The original view is closed, we must validate
1603 // the current view against the closed view first
1606 PaintRefresher.validateSequences(al, viewport.getAlignment());
1609 originalSource = viewport;
1612 return originalSource;
1621 public void moveSelectedSequences(boolean up)
1623 SequenceGroup sg = viewport.getSelectionGroup();
1629 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1630 viewport.getHiddenRepSequences(), up);
1631 alignPanel.paintAlignment(true);
1634 synchronized void slideSequences(boolean right, int size)
1636 List<SequenceI> sg = new Vector();
1637 if (viewport.cursorMode)
1639 sg.add(viewport.getAlignment().getSequenceAt(
1640 alignPanel.getSeqPanel().seqCanvas.cursorY));
1642 else if (viewport.getSelectionGroup() != null
1643 && viewport.getSelectionGroup().getSize() != viewport
1644 .getAlignment().getHeight())
1646 sg = viewport.getSelectionGroup().getSequences(
1647 viewport.getHiddenRepSequences());
1655 Vector invertGroup = new Vector();
1657 for (int i = 0; i < viewport.getAlignment().getHeight(); i++)
1659 if (!sg.contains(viewport.getAlignment().getSequenceAt(i)))
1661 invertGroup.add(viewport.getAlignment().getSequenceAt(i));
1665 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1667 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1668 for (int i = 0; i < invertGroup.size(); i++)
1670 seqs2[i] = (SequenceI) invertGroup.elementAt(i);
1673 SlideSequencesCommand ssc;
1676 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1677 size, viewport.getGapCharacter());
1681 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1682 size, viewport.getGapCharacter());
1685 int groupAdjustment = 0;
1686 if (ssc.getGapsInsertedBegin() && right)
1688 if (viewport.cursorMode)
1690 alignPanel.getSeqPanel().moveCursor(size, 0);
1694 groupAdjustment = size;
1697 else if (!ssc.getGapsInsertedBegin() && !right)
1699 if (viewport.cursorMode)
1701 alignPanel.getSeqPanel().moveCursor(-size, 0);
1705 groupAdjustment = -size;
1709 if (groupAdjustment != 0)
1711 viewport.getSelectionGroup().setStartRes(
1712 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1713 viewport.getSelectionGroup().setEndRes(
1714 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1717 boolean appendHistoryItem = false;
1718 if (viewport.historyList != null && viewport.historyList.size() > 0
1719 && viewport.historyList.peek() instanceof SlideSequencesCommand)
1721 appendHistoryItem = ssc
1722 .appendSlideCommand((SlideSequencesCommand) viewport.historyList
1726 if (!appendHistoryItem)
1728 addHistoryItem(ssc);
1741 protected void copy_actionPerformed(ActionEvent e)
1744 if (viewport.getSelectionGroup() == null)
1748 // TODO: preserve the ordering of displayed alignment annotation in any
1749 // internal paste (particularly sequence associated annotation)
1750 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1751 String[] omitHidden = null;
1753 if (viewport.hasHiddenColumns())
1755 omitHidden = viewport.getViewAsString(true);
1758 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1761 StringSelection ss = new StringSelection(output);
1765 jalview.gui.Desktop.internalCopy = true;
1766 // Its really worth setting the clipboard contents
1767 // to empty before setting the large StringSelection!!
1768 Toolkit.getDefaultToolkit().getSystemClipboard()
1769 .setContents(new StringSelection(""), null);
1771 Toolkit.getDefaultToolkit().getSystemClipboard()
1772 .setContents(ss, Desktop.instance);
1773 } catch (OutOfMemoryError er)
1775 new OOMWarning("copying region", er);
1779 Vector hiddenColumns = null;
1780 if (viewport.hasHiddenColumns())
1782 hiddenColumns = new Vector();
1783 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1784 .getSelectionGroup().getEndRes();
1785 for (int i = 0; i < viewport.getColumnSelection().getHiddenColumns()
1788 int[] region = (int[]) viewport.getColumnSelection()
1789 .getHiddenColumns().elementAt(i);
1790 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1792 hiddenColumns.addElement(new int[]
1793 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1798 Desktop.jalviewClipboard = new Object[]
1799 { seqs, viewport.getAlignment().getDataset(), hiddenColumns };
1800 statusBar.setText(MessageManager.formatMessage(
1801 "label.copied_sequences_to_clipboard", new String[]
1802 { Integer.valueOf(seqs.length).toString() }));
1812 protected void pasteNew_actionPerformed(ActionEvent e)
1824 protected void pasteThis_actionPerformed(ActionEvent e)
1830 * Paste contents of Jalview clipboard
1832 * @param newAlignment
1833 * true to paste to a new alignment, otherwise add to this.
1835 void paste(boolean newAlignment)
1837 boolean externalPaste = true;
1840 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1841 Transferable contents = c.getContents(this);
1843 if (contents == null)
1851 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1852 if (str.length() < 1)
1857 format = new IdentifyFile().Identify(str, "Paste");
1859 } catch (OutOfMemoryError er)
1861 new OOMWarning("Out of memory pasting sequences!!", er);
1865 SequenceI[] sequences;
1866 boolean annotationAdded = false;
1867 AlignmentI alignment = null;
1869 if (Desktop.jalviewClipboard != null)
1871 // The clipboard was filled from within Jalview, we must use the
1873 // And dataset from the copied alignment
1874 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1875 // be doubly sure that we create *new* sequence objects.
1876 sequences = new SequenceI[newseq.length];
1877 for (int i = 0; i < newseq.length; i++)
1879 sequences[i] = new Sequence(newseq[i]);
1881 alignment = new Alignment(sequences);
1882 externalPaste = false;
1886 // parse the clipboard as an alignment.
1887 alignment = new FormatAdapter().readFile(str, "Paste", format);
1888 sequences = alignment.getSequencesArray();
1892 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1898 if (Desktop.jalviewClipboard != null)
1900 // dataset is inherited
1901 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1905 // new dataset is constructed
1906 alignment.setDataset(null);
1908 alwidth = alignment.getWidth() + 1;
1912 AlignmentI pastedal = alignment; // preserve pasted alignment object
1913 // Add pasted sequences and dataset into existing alignment.
1914 alignment = viewport.getAlignment();
1915 alwidth = alignment.getWidth() + 1;
1916 // decide if we need to import sequences from an existing dataset
1917 boolean importDs = Desktop.jalviewClipboard != null
1918 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1919 // importDs==true instructs us to copy over new dataset sequences from
1920 // an existing alignment
1921 Vector newDs = (importDs) ? new Vector() : null; // used to create
1922 // minimum dataset set
1924 for (int i = 0; i < sequences.length; i++)
1928 newDs.addElement(null);
1930 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
1932 if (importDs && ds != null)
1934 if (!newDs.contains(ds))
1936 newDs.setElementAt(ds, i);
1937 ds = new Sequence(ds);
1938 // update with new dataset sequence
1939 sequences[i].setDatasetSequence(ds);
1943 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
1948 // copy and derive new dataset sequence
1949 sequences[i] = sequences[i].deriveSequence();
1950 alignment.getDataset().addSequence(
1951 sequences[i].getDatasetSequence());
1952 // TODO: avoid creation of duplicate dataset sequences with a
1953 // 'contains' method using SequenceI.equals()/SequenceI.contains()
1955 alignment.addSequence(sequences[i]); // merges dataset
1959 newDs.clear(); // tidy up
1961 if (alignment.getAlignmentAnnotation() != null)
1963 for (AlignmentAnnotation alan : alignment
1964 .getAlignmentAnnotation())
1966 if (alan.graphGroup > fgroup)
1968 fgroup = alan.graphGroup;
1972 if (pastedal.getAlignmentAnnotation() != null)
1974 // Add any annotation attached to alignment.
1975 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
1976 for (int i = 0; i < alann.length; i++)
1978 annotationAdded = true;
1979 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
1981 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
1982 if (newann.graphGroup > -1)
1984 if (newGraphGroups.size() <= newann.graphGroup
1985 || newGraphGroups.get(newann.graphGroup) == null)
1987 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
1989 newGraphGroups.add(q, null);
1991 newGraphGroups.set(newann.graphGroup, new Integer(
1994 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
1998 newann.padAnnotation(alwidth);
1999 alignment.addAnnotation(newann);
2009 addHistoryItem(new EditCommand(
2010 MessageManager.getString("label.add_sequences"),
2012 sequences, 0, alignment.getWidth(), alignment));
2014 // Add any annotations attached to sequences
2015 for (int i = 0; i < sequences.length; i++)
2017 if (sequences[i].getAnnotation() != null)
2019 AlignmentAnnotation newann;
2020 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2022 annotationAdded = true;
2023 newann = sequences[i].getAnnotation()[a];
2024 newann.adjustForAlignment();
2025 newann.padAnnotation(alwidth);
2026 if (newann.graphGroup > -1)
2028 if (newann.graphGroup > -1)
2030 if (newGraphGroups.size() <= newann.graphGroup
2031 || newGraphGroups.get(newann.graphGroup) == null)
2033 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2035 newGraphGroups.add(q, null);
2037 newGraphGroups.set(newann.graphGroup, new Integer(
2040 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2044 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2049 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2056 // propagate alignment changed.
2057 viewport.setEndSeq(alignment.getHeight());
2058 if (annotationAdded)
2060 // Duplicate sequence annotation in all views.
2061 AlignmentI[] alview = this.getViewAlignments();
2062 for (int i = 0; i < sequences.length; i++)
2064 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2069 for (int avnum = 0; avnum < alview.length; avnum++)
2071 if (alview[avnum] != alignment)
2073 // duplicate in a view other than the one with input focus
2074 int avwidth = alview[avnum].getWidth() + 1;
2075 // this relies on sann being preserved after we
2076 // modify the sequence's annotation array for each duplication
2077 for (int a = 0; a < sann.length; a++)
2079 AlignmentAnnotation newann = new AlignmentAnnotation(
2081 sequences[i].addAlignmentAnnotation(newann);
2082 newann.padAnnotation(avwidth);
2083 alview[avnum].addAnnotation(newann); // annotation was
2084 // duplicated earlier
2085 // TODO JAL-1145 graphGroups are not updated for sequence
2086 // annotation added to several views. This may cause
2088 alview[avnum].setAnnotationIndex(newann, a);
2093 buildSortByAnnotationScoresMenu();
2095 viewport.firePropertyChange("alignment", null,
2096 alignment.getSequences());
2097 if (alignPanels != null)
2099 for (AlignmentPanel ap : ((Vector<AlignmentPanel>) alignPanels))
2101 ap.validateAnnotationDimensions(false);
2106 alignPanel.validateAnnotationDimensions(false);
2112 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2114 String newtitle = new String("Copied sequences");
2116 if (Desktop.jalviewClipboard != null
2117 && Desktop.jalviewClipboard[2] != null)
2119 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2120 for (int i = 0; i < hc.size(); i++)
2122 int[] region = (int[]) hc.elementAt(i);
2123 af.viewport.hideColumns(region[0], region[1]);
2127 // >>>This is a fix for the moment, until a better solution is
2129 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2131 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
2133 // TODO: maintain provenance of an alignment, rather than just make the
2134 // title a concatenation of operations.
2137 if (title.startsWith("Copied sequences"))
2143 newtitle = newtitle.concat("- from " + title);
2148 newtitle = new String("Pasted sequences");
2151 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2156 } catch (Exception ex)
2158 ex.printStackTrace();
2159 System.out.println("Exception whilst pasting: " + ex);
2160 // could be anything being pasted in here
2166 protected void expand_newalign(ActionEvent e)
2170 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2171 .getAlignment(), -1);
2172 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2174 String newtitle = new String("Flanking alignment");
2176 if (Desktop.jalviewClipboard != null
2177 && Desktop.jalviewClipboard[2] != null)
2179 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2180 for (int i = 0; i < hc.size(); i++)
2182 int[] region = (int[]) hc.elementAt(i);
2183 af.viewport.hideColumns(region[0], region[1]);
2187 // >>>This is a fix for the moment, until a better solution is
2189 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2191 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
2193 // TODO: maintain provenance of an alignment, rather than just make the
2194 // title a concatenation of operations.
2196 if (title.startsWith("Copied sequences"))
2202 newtitle = newtitle.concat("- from " + title);
2206 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2208 } catch (Exception ex)
2210 ex.printStackTrace();
2211 System.out.println("Exception whilst pasting: " + ex);
2212 // could be anything being pasted in here
2213 } catch (OutOfMemoryError oom)
2215 new OOMWarning("Viewing flanking region of alignment", oom);
2226 protected void cut_actionPerformed(ActionEvent e)
2228 copy_actionPerformed(null);
2229 delete_actionPerformed(null);
2239 protected void delete_actionPerformed(ActionEvent evt)
2242 SequenceGroup sg = viewport.getSelectionGroup();
2248 List<SequenceI> seqs = new ArrayList<SequenceI>(sg.getSize());
2250 for (int i = 0; i < sg.getSize(); i++)
2252 seq = sg.getSequenceAt(i);
2256 // If the cut affects all sequences, warn, remove highlighted columns
2257 if (sg.getSize() == viewport.getAlignment().getHeight())
2259 int confirm = JOptionPane.showConfirmDialog(this,
2260 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2261 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2262 JOptionPane.OK_CANCEL_OPTION);
2264 if (confirm == JOptionPane.CANCEL_OPTION
2265 || confirm == JOptionPane.CLOSED_OPTION)
2269 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2270 sg.getEndRes() + 1);
2273 SequenceI[] cut = new SequenceI[seqs.size()];
2274 for (int i = 0; i < seqs.size(); i++)
2276 cut[i] = seqs.get(i);
2280 * //ADD HISTORY ITEM
2282 addHistoryItem(new EditCommand(
2283 MessageManager.getString("label.cut_sequences"), Action.CUT,
2284 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2285 viewport.getAlignment()));
2287 viewport.setSelectionGroup(null);
2288 viewport.sendSelection();
2289 viewport.getAlignment().deleteGroup(sg);
2291 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2293 if (viewport.getAlignment().getHeight() < 1)
2297 this.setClosed(true);
2298 } catch (Exception ex)
2311 protected void deleteGroups_actionPerformed(ActionEvent e)
2313 if (avc.deleteGroups())
2315 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2316 alignPanel.updateAnnotation();
2317 alignPanel.paintAlignment(true);
2328 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2330 SequenceGroup sg = new SequenceGroup();
2332 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2334 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2337 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2338 viewport.setSelectionGroup(sg);
2339 viewport.sendSelection();
2340 alignPanel.paintAlignment(true);
2341 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2351 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2353 if (viewport.cursorMode)
2355 alignPanel.getSeqPanel().keyboardNo1 = null;
2356 alignPanel.getSeqPanel().keyboardNo2 = null;
2358 viewport.setSelectionGroup(null);
2359 viewport.getColumnSelection().clear();
2360 viewport.setSelectionGroup(null);
2361 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2362 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2363 alignPanel.paintAlignment(true);
2364 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2365 viewport.sendSelection();
2375 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2377 SequenceGroup sg = viewport.getSelectionGroup();
2381 selectAllSequenceMenuItem_actionPerformed(null);
2386 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2388 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2391 alignPanel.paintAlignment(true);
2392 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2393 viewport.sendSelection();
2397 public void invertColSel_actionPerformed(ActionEvent e)
2399 viewport.invertColumnSelection();
2400 alignPanel.paintAlignment(true);
2401 viewport.sendSelection();
2411 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2413 trimAlignment(true);
2423 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2425 trimAlignment(false);
2428 void trimAlignment(boolean trimLeft)
2430 ColumnSelection colSel = viewport.getColumnSelection();
2433 if (colSel.size() > 0)
2437 column = colSel.getMin();
2441 column = colSel.getMax();
2445 if (viewport.getSelectionGroup() != null)
2447 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2448 viewport.getHiddenRepSequences());
2452 seqs = viewport.getAlignment().getSequencesArray();
2455 TrimRegionCommand trimRegion;
2458 trimRegion = new TrimRegionCommand("Remove Left",
2459 TrimRegionCommand.TRIM_LEFT, seqs, column,
2460 viewport.getAlignment(), viewport.getColumnSelection(),
2461 viewport.getSelectionGroup());
2462 viewport.setStartRes(0);
2466 trimRegion = new TrimRegionCommand("Remove Right",
2467 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2468 viewport.getAlignment(), viewport.getColumnSelection(),
2469 viewport.getSelectionGroup());
2472 statusBar.setText(MessageManager.formatMessage(
2473 "label.removed_columns", new String[]
2474 { Integer.valueOf(trimRegion.getSize()).toString() }));
2476 addHistoryItem(trimRegion);
2478 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2480 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2481 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2483 viewport.getAlignment().deleteGroup(sg);
2487 viewport.firePropertyChange("alignment", null, viewport
2488 .getAlignment().getSequences());
2499 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2501 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2504 if (viewport.getSelectionGroup() != null)
2506 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2507 viewport.getHiddenRepSequences());
2508 start = viewport.getSelectionGroup().getStartRes();
2509 end = viewport.getSelectionGroup().getEndRes();
2513 seqs = viewport.getAlignment().getSequencesArray();
2516 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2517 "Remove Gapped Columns", seqs, start, end,
2518 viewport.getAlignment());
2520 addHistoryItem(removeGapCols);
2522 statusBar.setText(MessageManager.formatMessage(
2523 "label.removed_empty_columns", new String[]
2524 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2526 // This is to maintain viewport position on first residue
2527 // of first sequence
2528 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2529 int startRes = seq.findPosition(viewport.startRes);
2530 // ShiftList shifts;
2531 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2532 // edit.alColumnChanges=shifts.getInverse();
2533 // if (viewport.hasHiddenColumns)
2534 // viewport.getColumnSelection().compensateForEdits(shifts);
2535 viewport.setStartRes(seq.findIndex(startRes) - 1);
2536 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2548 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2550 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2553 if (viewport.getSelectionGroup() != null)
2555 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2556 viewport.getHiddenRepSequences());
2557 start = viewport.getSelectionGroup().getStartRes();
2558 end = viewport.getSelectionGroup().getEndRes();
2562 seqs = viewport.getAlignment().getSequencesArray();
2565 // This is to maintain viewport position on first residue
2566 // of first sequence
2567 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2568 int startRes = seq.findPosition(viewport.startRes);
2570 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2571 viewport.getAlignment()));
2573 viewport.setStartRes(seq.findIndex(startRes) - 1);
2575 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2587 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2589 viewport.setPadGaps(padGapsMenuitem.isSelected());
2590 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2596 // if (justifySeqs>0)
2598 // alignment.justify(justifySeqs!=RIGHT_JUSTIFY);
2611 public void findMenuItem_actionPerformed(ActionEvent e)
2617 public void newView_actionPerformed(ActionEvent e)
2624 * @param copyAnnotation
2625 * if true then duplicate all annnotation, groups and settings
2626 * @return new alignment panel, already displayed.
2628 public AlignmentPanel newView(boolean copyAnnotation)
2630 return newView(null, copyAnnotation);
2636 * title of newly created view
2637 * @return new alignment panel, already displayed.
2639 public AlignmentPanel newView(String viewTitle)
2641 return newView(viewTitle, true);
2647 * title of newly created view
2648 * @param copyAnnotation
2649 * if true then duplicate all annnotation, groups and settings
2650 * @return new alignment panel, already displayed.
2652 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2654 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2656 if (!copyAnnotation)
2658 // just remove all the current annotation except for the automatic stuff
2659 newap.av.getAlignment().deleteAllGroups();
2660 for (AlignmentAnnotation alan : newap.av.getAlignment()
2661 .getAlignmentAnnotation())
2663 if (!alan.autoCalculated)
2665 newap.av.getAlignment().deleteAnnotation(alan);
2671 newap.av.gatherViewsHere = false;
2673 if (viewport.viewName == null)
2675 viewport.viewName = "Original";
2678 newap.av.historyList = viewport.historyList;
2679 newap.av.redoList = viewport.redoList;
2681 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2682 // make sure the new view has a unique name - this is essential for Jalview
2684 boolean addFirstIndex = false;
2685 if (viewTitle == null || viewTitle.trim().length() == 0)
2687 viewTitle = MessageManager.getString("action.view");
2688 addFirstIndex = true;
2692 index = 1;// we count from 1 if given a specific name
2694 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2695 Vector comps = (Vector) PaintRefresher.components.get(viewport
2696 .getSequenceSetId());
2697 Vector existingNames = new Vector();
2698 for (int i = 0; i < comps.size(); i++)
2700 if (comps.elementAt(i) instanceof AlignmentPanel)
2702 AlignmentPanel ap = (AlignmentPanel) comps.elementAt(i);
2703 if (!existingNames.contains(ap.av.viewName))
2705 existingNames.addElement(ap.av.viewName);
2710 while (existingNames.contains(newViewName))
2712 newViewName = viewTitle + " " + (++index);
2715 newap.av.viewName = newViewName;
2717 addAlignmentPanel(newap, true);
2718 newap.alignmentChanged();
2720 if (alignPanels.size() == 2)
2722 viewport.gatherViewsHere = true;
2724 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2729 public void expandViews_actionPerformed(ActionEvent e)
2731 Desktop.instance.explodeViews(this);
2735 public void gatherViews_actionPerformed(ActionEvent e)
2737 Desktop.instance.gatherViews(this);
2747 public void font_actionPerformed(ActionEvent e)
2749 new FontChooser(alignPanel);
2759 protected void seqLimit_actionPerformed(ActionEvent e)
2761 viewport.setShowJVSuffix(seqLimits.isSelected());
2763 alignPanel.getIdPanel().getIdCanvas().setPreferredSize(alignPanel
2764 .calculateIdWidth());
2765 alignPanel.paintAlignment(true);
2769 public void idRightAlign_actionPerformed(ActionEvent e)
2771 viewport.setRightAlignIds(idRightAlign.isSelected());
2772 alignPanel.paintAlignment(true);
2776 public void centreColumnLabels_actionPerformed(ActionEvent e)
2778 viewport.centreColumnLabels = centreColumnLabelsMenuItem.getState();
2779 alignPanel.paintAlignment(true);
2785 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2788 protected void followHighlight_actionPerformed()
2790 if (viewport.followHighlight = this.followHighlightMenuItem.getState())
2792 alignPanel.scrollToPosition(
2793 alignPanel.getSeqPanel().seqCanvas.searchResults, false);
2804 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2806 viewport.setColourText(colourTextMenuItem.isSelected());
2807 alignPanel.paintAlignment(true);
2817 public void wrapMenuItem_actionPerformed(ActionEvent e)
2819 scaleAbove.setVisible(wrapMenuItem.isSelected());
2820 scaleLeft.setVisible(wrapMenuItem.isSelected());
2821 scaleRight.setVisible(wrapMenuItem.isSelected());
2822 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2823 alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2827 public void showAllSeqs_actionPerformed(ActionEvent e)
2829 viewport.showAllHiddenSeqs();
2833 public void showAllColumns_actionPerformed(ActionEvent e)
2835 viewport.showAllHiddenColumns();
2840 public void hideSelSequences_actionPerformed(ActionEvent e)
2842 viewport.hideAllSelectedSeqs();
2843 alignPanel.paintAlignment(true);
2847 * called by key handler and the hide all/show all menu items
2852 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2855 boolean hide = false;
2856 SequenceGroup sg = viewport.getSelectionGroup();
2857 if (!toggleSeqs && !toggleCols)
2859 // Hide everything by the current selection - this is a hack - we do the
2860 // invert and then hide
2861 // first check that there will be visible columns after the invert.
2862 if ((viewport.getColumnSelection() != null
2863 && viewport.getColumnSelection().getSelected() != null && viewport
2864 .getColumnSelection().getSelected().size() > 0)
2865 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2868 // now invert the sequence set, if required - empty selection implies
2869 // that no hiding is required.
2872 invertSequenceMenuItem_actionPerformed(null);
2873 sg = viewport.getSelectionGroup();
2877 viewport.expandColSelection(sg, true);
2878 // finally invert the column selection and get the new sequence
2880 invertColSel_actionPerformed(null);
2887 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
2889 hideSelSequences_actionPerformed(null);
2892 else if (!(toggleCols && viewport.getColumnSelection().getSelected()
2895 showAllSeqs_actionPerformed(null);
2901 if (viewport.getColumnSelection().getSelected().size() > 0)
2903 hideSelColumns_actionPerformed(null);
2906 viewport.setSelectionGroup(sg);
2911 showAllColumns_actionPerformed(null);
2920 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
2921 * event.ActionEvent)
2924 public void hideAllButSelection_actionPerformed(ActionEvent e)
2926 toggleHiddenRegions(false, false);
2933 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
2937 public void hideAllSelection_actionPerformed(ActionEvent e)
2939 SequenceGroup sg = viewport.getSelectionGroup();
2940 viewport.expandColSelection(sg, false);
2941 viewport.hideAllSelectedSeqs();
2942 viewport.hideSelectedColumns();
2943 alignPanel.paintAlignment(true);
2950 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
2954 public void showAllhidden_actionPerformed(ActionEvent e)
2956 viewport.showAllHiddenColumns();
2957 viewport.showAllHiddenSeqs();
2958 alignPanel.paintAlignment(true);
2962 public void hideSelColumns_actionPerformed(ActionEvent e)
2964 viewport.hideSelectedColumns();
2965 alignPanel.paintAlignment(true);
2969 public void hiddenMarkers_actionPerformed(ActionEvent e)
2971 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
2982 protected void scaleAbove_actionPerformed(ActionEvent e)
2984 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
2985 alignPanel.paintAlignment(true);
2995 protected void scaleLeft_actionPerformed(ActionEvent e)
2997 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
2998 alignPanel.paintAlignment(true);
3008 protected void scaleRight_actionPerformed(ActionEvent e)
3010 viewport.setScaleRightWrapped(scaleRight.isSelected());
3011 alignPanel.paintAlignment(true);
3021 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3023 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3024 alignPanel.paintAlignment(true);
3034 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3036 viewport.setShowText(viewTextMenuItem.isSelected());
3037 alignPanel.paintAlignment(true);
3047 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3049 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3050 alignPanel.paintAlignment(true);
3053 public FeatureSettings featureSettings;
3056 public void featureSettings_actionPerformed(ActionEvent e)
3058 if (featureSettings != null)
3060 featureSettings.close();
3061 featureSettings = null;
3063 if (!showSeqFeatures.isSelected())
3065 // make sure features are actually displayed
3066 showSeqFeatures.setSelected(true);
3067 showSeqFeatures_actionPerformed(null);
3069 featureSettings = new FeatureSettings(this);
3073 * Set or clear 'Show Sequence Features'
3079 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3081 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3082 alignPanel.paintAlignment(true);
3083 if (alignPanel.getOverviewPanel() != null)
3085 alignPanel.getOverviewPanel().updateOverviewImage();
3090 * Set or clear 'Show Sequence Features'
3096 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
3098 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
3100 if (viewport.getShowSequenceFeaturesHeight())
3102 // ensure we're actually displaying features
3103 viewport.setShowSequenceFeatures(true);
3104 showSeqFeatures.setSelected(true);
3106 alignPanel.paintAlignment(true);
3107 if (alignPanel.getOverviewPanel() != null)
3109 alignPanel.getOverviewPanel().updateOverviewImage();
3114 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3115 * the annotations panel as a whole.
3117 * The options to show/hide all annotations should be enabled when the panel
3118 * is shown, and disabled when the panel is hidden.
3123 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3125 final boolean setVisible = annotationPanelMenuItem.isSelected();
3126 viewport.setShowAnnotation(setVisible);
3127 alignPanel.setAnnotationVisible(setVisible);
3128 this.showAllSeqAnnotations.setEnabled(setVisible);
3129 this.hideAllSeqAnnotations.setEnabled(setVisible);
3130 this.showAllAlAnnotations.setEnabled(setVisible);
3131 this.hideAllAlAnnotations.setEnabled(setVisible);
3135 public void alignmentProperties()
3137 JEditorPane editPane = new JEditorPane("text/html", "");
3138 editPane.setEditable(false);
3139 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3141 editPane.setText(MessageManager.formatMessage("label.html_content",
3143 { contents.toString() }));
3144 JInternalFrame frame = new JInternalFrame();
3145 frame.getContentPane().add(new JScrollPane(editPane));
3147 Desktop.instance.addInternalFrame(frame, MessageManager.formatMessage(
3148 "label.alignment_properties", new String[]
3149 { getTitle() }), 500, 400);
3159 public void overviewMenuItem_actionPerformed(ActionEvent e)
3161 if (alignPanel.overviewPanel != null)
3166 JInternalFrame frame = new JInternalFrame();
3167 OverviewPanel overview = new OverviewPanel(alignPanel);
3168 frame.setContentPane(overview);
3169 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3170 "label.overview_params", new String[]
3171 { this.getTitle() }), frame.getWidth(), frame.getHeight());
3173 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3174 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3177 public void internalFrameClosed(
3178 javax.swing.event.InternalFrameEvent evt)
3180 alignPanel.setOverviewPanel(null);
3184 alignPanel.setOverviewPanel(overview);
3188 public void textColour_actionPerformed(ActionEvent e)
3190 new TextColourChooser().chooseColour(alignPanel, null);
3200 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3212 public void clustalColour_actionPerformed(ActionEvent e)
3214 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3215 viewport.getHiddenRepSequences()));
3225 public void zappoColour_actionPerformed(ActionEvent e)
3227 changeColour(new ZappoColourScheme());
3237 public void taylorColour_actionPerformed(ActionEvent e)
3239 changeColour(new TaylorColourScheme());
3249 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3251 changeColour(new HydrophobicColourScheme());
3261 public void helixColour_actionPerformed(ActionEvent e)
3263 changeColour(new HelixColourScheme());
3273 public void strandColour_actionPerformed(ActionEvent e)
3275 changeColour(new StrandColourScheme());
3285 public void turnColour_actionPerformed(ActionEvent e)
3287 changeColour(new TurnColourScheme());
3297 public void buriedColour_actionPerformed(ActionEvent e)
3299 changeColour(new BuriedColourScheme());
3309 public void nucleotideColour_actionPerformed(ActionEvent e)
3311 changeColour(new NucleotideColourScheme());
3315 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3317 changeColour(new PurinePyrimidineColourScheme());
3321 * public void covariationColour_actionPerformed(ActionEvent e) {
3323 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3327 public void annotationColour_actionPerformed(ActionEvent e)
3329 new AnnotationColourChooser(viewport, alignPanel);
3333 public void rnahelicesColour_actionPerformed(ActionEvent e)
3335 new RNAHelicesColourChooser(viewport, alignPanel);
3345 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3347 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3356 public void changeColour(ColourSchemeI cs)
3358 // TODO: compare with applet and pull up to model method
3363 if (viewport.getAbovePIDThreshold())
3365 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3367 cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3371 cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3374 if (viewport.getConservationSelected())
3377 Alignment al = (Alignment) viewport.getAlignment();
3378 Conservation c = new Conservation("All",
3379 ResidueProperties.propHash, 3, al.getSequences(), 0,
3383 c.verdict(false, viewport.getConsPercGaps());
3385 cs.setConservation(c);
3387 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3392 cs.setConservation(null);
3395 cs.setConsensus(viewport.getSequenceConsensusHash());
3398 viewport.setGlobalColourScheme(cs);
3400 if (viewport.getColourAppliesToAllGroups())
3403 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3411 if (cs instanceof ClustalxColourScheme)
3413 sg.cs = new ClustalxColourScheme(sg,
3414 viewport.getHiddenRepSequences());
3416 else if (cs instanceof UserColourScheme)
3418 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
3424 sg.cs = cs.getClass().newInstance();
3425 } catch (Exception ex)
3430 if (viewport.getAbovePIDThreshold()
3431 || cs instanceof PIDColourScheme
3432 || cs instanceof Blosum62ColourScheme)
3434 sg.cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3436 sg.cs.setConsensus(AAFrequency.calculate(
3437 sg.getSequences(viewport.getHiddenRepSequences()),
3438 sg.getStartRes(), sg.getEndRes() + 1));
3442 sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3445 if (viewport.getConservationSelected())
3447 Conservation c = new Conservation("Group",
3448 ResidueProperties.propHash, 3, sg.getSequences(viewport
3449 .getHiddenRepSequences()), sg.getStartRes(),
3450 sg.getEndRes() + 1);
3452 c.verdict(false, viewport.getConsPercGaps());
3453 sg.cs.setConservation(c);
3457 sg.cs.setConservation(null);
3462 if (alignPanel.getOverviewPanel() != null)
3464 alignPanel.getOverviewPanel().updateOverviewImage();
3467 alignPanel.paintAlignment(true);
3477 protected void modifyPID_actionPerformed(ActionEvent e)
3479 if (viewport.getAbovePIDThreshold()
3480 && viewport.getGlobalColourScheme() != null)
3482 SliderPanel.setPIDSliderSource(alignPanel,
3483 viewport.getGlobalColourScheme(), "Background");
3484 SliderPanel.showPIDSlider();
3495 protected void modifyConservation_actionPerformed(ActionEvent e)
3497 if (viewport.getConservationSelected()
3498 && viewport.getGlobalColourScheme() != null)
3500 SliderPanel.setConservationSlider(alignPanel,
3501 viewport.getGlobalColourScheme(), "Background");
3502 SliderPanel.showConservationSlider();
3513 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3515 viewport.setConservationSelected(conservationMenuItem.isSelected());
3517 viewport.setAbovePIDThreshold(false);
3518 abovePIDThreshold.setSelected(false);
3520 changeColour(viewport.getGlobalColourScheme());
3522 modifyConservation_actionPerformed(null);
3532 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3534 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3536 conservationMenuItem.setSelected(false);
3537 viewport.setConservationSelected(false);
3539 changeColour(viewport.getGlobalColourScheme());
3541 modifyPID_actionPerformed(null);
3551 public void userDefinedColour_actionPerformed(ActionEvent e)
3553 if (e.getActionCommand().equals(
3554 MessageManager.getString("action.user_defined")))
3556 new UserDefinedColours(alignPanel, null);
3560 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3561 .getUserColourSchemes().get(e.getActionCommand());
3567 public void updateUserColourMenu()
3570 Component[] menuItems = colourMenu.getMenuComponents();
3571 int i, iSize = menuItems.length;
3572 for (i = 0; i < iSize; i++)
3574 if (menuItems[i].getName() != null
3575 && menuItems[i].getName().equals("USER_DEFINED"))
3577 colourMenu.remove(menuItems[i]);
3581 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3583 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3584 .getUserColourSchemes().keys();
3586 while (userColours.hasMoreElements())
3588 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3589 userColours.nextElement().toString());
3590 radioItem.setName("USER_DEFINED");
3591 radioItem.addMouseListener(new MouseAdapter()
3594 public void mousePressed(MouseEvent evt)
3596 if (evt.isControlDown()
3597 || SwingUtilities.isRightMouseButton(evt))
3599 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3601 int option = JOptionPane.showInternalConfirmDialog(
3602 jalview.gui.Desktop.desktop,
3604 .getString("label.remove_from_default_list"),
3606 .getString("label.remove_user_defined_colour"),
3607 JOptionPane.YES_NO_OPTION);
3608 if (option == JOptionPane.YES_OPTION)
3610 jalview.gui.UserDefinedColours
3611 .removeColourFromDefaults(radioItem.getText());
3612 colourMenu.remove(radioItem);
3616 radioItem.addActionListener(new ActionListener()
3619 public void actionPerformed(ActionEvent evt)
3621 userDefinedColour_actionPerformed(evt);
3628 radioItem.addActionListener(new ActionListener()
3631 public void actionPerformed(ActionEvent evt)
3633 userDefinedColour_actionPerformed(evt);
3637 colourMenu.insert(radioItem, 15);
3638 colours.add(radioItem);
3650 public void PIDColour_actionPerformed(ActionEvent e)
3652 changeColour(new PIDColourScheme());
3662 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3664 changeColour(new Blosum62ColourScheme());
3674 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3676 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3677 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3678 .getAlignment().getSequenceAt(0), null);
3679 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3680 viewport.getAlignment()));
3681 alignPanel.paintAlignment(true);
3691 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3693 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3694 AlignmentSorter.sortByID(viewport.getAlignment());
3695 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3696 viewport.getAlignment()));
3697 alignPanel.paintAlignment(true);
3707 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3709 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3710 AlignmentSorter.sortByLength(viewport.getAlignment());
3711 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3712 viewport.getAlignment()));
3713 alignPanel.paintAlignment(true);
3723 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3725 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3726 AlignmentSorter.sortByGroup(viewport.getAlignment());
3727 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3728 viewport.getAlignment()));
3730 alignPanel.paintAlignment(true);
3740 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3742 new RedundancyPanel(alignPanel, this);
3752 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3754 if ((viewport.getSelectionGroup() == null)
3755 || (viewport.getSelectionGroup().getSize() < 2))
3757 JOptionPane.showInternalMessageDialog(this, MessageManager
3758 .getString("label.you_must_select_least_two_sequences"),
3759 MessageManager.getString("label.invalid_selection"),
3760 JOptionPane.WARNING_MESSAGE);
3764 JInternalFrame frame = new JInternalFrame();
3765 frame.setContentPane(new PairwiseAlignPanel(viewport));
3766 Desktop.addInternalFrame(frame,
3767 MessageManager.getString("action.pairwise_alignment"), 600,
3779 public void PCAMenuItem_actionPerformed(ActionEvent e)
3781 if (((viewport.getSelectionGroup() != null)
3782 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3783 .getSelectionGroup().getSize() > 0))
3784 || (viewport.getAlignment().getHeight() < 4))
3787 .showInternalMessageDialog(
3790 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3792 .getString("label.sequence_selection_insufficient"),
3793 JOptionPane.WARNING_MESSAGE);
3798 new PCAPanel(alignPanel);
3802 public void autoCalculate_actionPerformed(ActionEvent e)
3804 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3805 if (viewport.autoCalculateConsensus)
3807 viewport.firePropertyChange("alignment", null, viewport
3808 .getAlignment().getSequences());
3813 public void sortByTreeOption_actionPerformed(ActionEvent e)
3815 viewport.sortByTree = sortByTree.isSelected();
3819 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3821 viewport.followSelection = listenToViewSelections.isSelected();
3831 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3833 NewTreePanel("AV", "PID", "Average distance tree using PID");
3843 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3845 NewTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3855 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3857 NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3867 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3869 NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3882 void NewTreePanel(String type, String pwType, String title)
3886 if (viewport.getSelectionGroup() != null
3887 && viewport.getSelectionGroup().getSize() > 0)
3889 if (viewport.getSelectionGroup().getSize() < 3)
3895 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3897 .getString("label.not_enough_sequences"),
3898 JOptionPane.WARNING_MESSAGE);
3902 SequenceGroup sg = viewport.getSelectionGroup();
3904 /* Decide if the selection is a column region */
3905 for (SequenceI _s : sg.getSequences())
3907 if (_s.getLength() < sg.getEndRes())
3913 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3915 .getString("label.sequences_selection_not_aligned"),
3916 JOptionPane.WARNING_MESSAGE);
3922 title = title + " on region";
3923 tp = new TreePanel(alignPanel, type, pwType);
3927 // are the visible sequences aligned?
3928 if (!viewport.getAlignment().isAligned(false))
3934 .getString("label.sequences_must_be_aligned_before_creating_tree"),
3936 .getString("label.sequences_not_aligned"),
3937 JOptionPane.WARNING_MESSAGE);
3942 if (viewport.getAlignment().getHeight() < 2)
3947 tp = new TreePanel(alignPanel, type, pwType);
3952 if (viewport.viewName != null)
3954 title += viewport.viewName + " of ";
3957 title += this.title;
3959 Desktop.addInternalFrame(tp, title, 600, 500);
3970 public void addSortByOrderMenuItem(String title,
3971 final AlignmentOrder order)
3973 final JMenuItem item = new JMenuItem(MessageManager.formatMessage("action.by_title_param", new String[]{title}));
3975 item.addActionListener(new java.awt.event.ActionListener()
3978 public void actionPerformed(ActionEvent e)
3980 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3982 // TODO: JBPNote - have to map order entries to curent SequenceI
3984 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3986 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
3989 alignPanel.paintAlignment(true);
3995 * Add a new sort by annotation score menu item
3998 * the menu to add the option to
4000 * the label used to retrieve scores for each sequence on the
4003 public void addSortByAnnotScoreMenuItem(JMenu sort,
4004 final String scoreLabel)
4006 final JMenuItem item = new JMenuItem(scoreLabel);
4008 item.addActionListener(new java.awt.event.ActionListener()
4011 public void actionPerformed(ActionEvent e)
4013 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4014 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4015 viewport.getAlignment());// ,viewport.getSelectionGroup());
4016 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4017 viewport.getAlignment()));
4018 alignPanel.paintAlignment(true);
4024 * last hash for alignment's annotation array - used to minimise cost of
4027 protected int _annotationScoreVectorHash;
4030 * search the alignment and rebuild the sort by annotation score submenu the
4031 * last alignment annotation vector hash is stored to minimize cost of
4032 * rebuilding in subsequence calls.
4036 public void buildSortByAnnotationScoresMenu()
4038 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4043 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4045 sortByAnnotScore.removeAll();
4046 // almost certainly a quicker way to do this - but we keep it simple
4047 Hashtable scoreSorts = new Hashtable();
4048 AlignmentAnnotation aann[];
4049 for (SequenceI sqa : viewport.getAlignment().getSequences())
4051 aann = sqa.getAnnotation();
4052 for (int i = 0; aann != null && i < aann.length; i++)
4054 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4056 scoreSorts.put(aann[i].label, aann[i].label);
4060 Enumeration labels = scoreSorts.keys();
4061 while (labels.hasMoreElements())
4063 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4064 (String) labels.nextElement());
4066 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4069 _annotationScoreVectorHash = viewport.getAlignment()
4070 .getAlignmentAnnotation().hashCode();
4075 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4076 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4077 * call. Listeners are added to remove the menu item when the treePanel is
4078 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4082 * Displayed tree window.
4084 * SortBy menu item title.
4087 public void buildTreeMenu()
4089 calculateTree.removeAll();
4090 // build the calculate menu
4092 for (final String type : new String[]
4095 String treecalcnm = MessageManager.getString("label.tree_calc_"
4096 + type.toLowerCase());
4097 for (final Object pwtype : ResidueProperties.scoreMatrices.keySet())
4099 JMenuItem tm = new JMenuItem();
4100 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4101 if (sm.isProtein() == !viewport.getAlignment().isNucleotide())
4103 String smn = MessageManager.getStringOrReturn(
4104 "label.score_model_", sm.getName());
4105 final String title = MessageManager.formatMessage(
4106 "label.treecalc_title", treecalcnm, smn);
4107 tm.setText(title);//
4108 tm.addActionListener(new java.awt.event.ActionListener()
4111 public void actionPerformed(ActionEvent e)
4113 NewTreePanel(type, (String) pwtype, title);
4116 calculateTree.add(tm);
4121 sortByTreeMenu.removeAll();
4123 Vector comps = (Vector) PaintRefresher.components.get(viewport
4124 .getSequenceSetId());
4125 Vector treePanels = new Vector();
4126 int i, iSize = comps.size();
4127 for (i = 0; i < iSize; i++)
4129 if (comps.elementAt(i) instanceof TreePanel)
4131 treePanels.add(comps.elementAt(i));
4135 iSize = treePanels.size();
4139 sortByTreeMenu.setVisible(false);
4143 sortByTreeMenu.setVisible(true);
4145 for (i = 0; i < treePanels.size(); i++)
4147 final TreePanel tp = (TreePanel) treePanels.elementAt(i);
4148 final JMenuItem item = new JMenuItem(tp.getTitle());
4149 final NJTree tree = ((TreePanel) treePanels.elementAt(i)).getTree();
4150 item.addActionListener(new java.awt.event.ActionListener()
4153 public void actionPerformed(ActionEvent e)
4155 tp.sortByTree_actionPerformed(null);
4156 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4161 sortByTreeMenu.add(item);
4165 public boolean sortBy(AlignmentOrder alorder, String undoname)
4167 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4168 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4169 if (undoname != null)
4171 addHistoryItem(new OrderCommand(undoname, oldOrder,
4172 viewport.getAlignment()));
4174 alignPanel.paintAlignment(true);
4179 * Work out whether the whole set of sequences or just the selected set will
4180 * be submitted for multiple alignment.
4183 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4185 // Now, check we have enough sequences
4186 AlignmentView msa = null;
4188 if ((viewport.getSelectionGroup() != null)
4189 && (viewport.getSelectionGroup().getSize() > 1))
4191 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4192 // some common interface!
4194 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4195 * SequenceI[sz = seqs.getSize(false)];
4197 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4198 * seqs.getSequenceAt(i); }
4200 msa = viewport.getAlignmentView(true);
4202 else if (viewport.getSelectionGroup() != null
4203 && viewport.getSelectionGroup().getSize() == 1)
4205 int option = JOptionPane.showConfirmDialog(this,
4206 MessageManager.getString("warn.oneseq_msainput_selection"),
4207 MessageManager.getString("label.invalid_selection"),
4208 JOptionPane.OK_CANCEL_OPTION);
4209 if (option == JOptionPane.OK_OPTION)
4211 msa = viewport.getAlignmentView(false);
4216 msa = viewport.getAlignmentView(false);
4222 * Decides what is submitted to a secondary structure prediction service: the
4223 * first sequence in the alignment, or in the current selection, or, if the
4224 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4225 * region or the whole alignment. (where the first sequence in the set is the
4226 * one that the prediction will be for).
4228 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4230 AlignmentView seqs = null;
4232 if ((viewport.getSelectionGroup() != null)
4233 && (viewport.getSelectionGroup().getSize() > 0))
4235 seqs = viewport.getAlignmentView(true);
4239 seqs = viewport.getAlignmentView(false);
4241 // limit sequences - JBPNote in future - could spawn multiple prediction
4243 // TODO: viewport.getAlignment().isAligned is a global state - the local
4244 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4245 if (!viewport.getAlignment().isAligned(false))
4247 seqs.setSequences(new SeqCigar[]
4248 { seqs.getSequences()[0] });
4249 // TODO: if seqs.getSequences().length>1 then should really have warned
4263 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
4265 // Pick the tree file
4266 JalviewFileChooser chooser = new JalviewFileChooser(
4267 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4268 chooser.setFileView(new JalviewFileView());
4269 chooser.setDialogTitle(MessageManager
4270 .getString("label.select_newick_like_tree_file"));
4271 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4273 int value = chooser.showOpenDialog(null);
4275 if (value == JalviewFileChooser.APPROVE_OPTION)
4277 String choice = chooser.getSelectedFile().getPath();
4278 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4279 jalview.io.NewickFile fin = null;
4282 fin = new jalview.io.NewickFile(choice, "File");
4283 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4284 } catch (Exception ex)
4291 .getString("label.problem_reading_tree_file"),
4292 JOptionPane.WARNING_MESSAGE);
4293 ex.printStackTrace();
4295 if (fin != null && fin.hasWarningMessage())
4297 JOptionPane.showMessageDialog(Desktop.desktop, fin
4298 .getWarningMessage(), MessageManager
4299 .getString("label.possible_problem_with_tree_file"),
4300 JOptionPane.WARNING_MESSAGE);
4306 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4308 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4311 public TreePanel ShowNewickTree(NewickFile nf, String title)
4313 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4316 public TreePanel ShowNewickTree(NewickFile nf, String title,
4317 AlignmentView input)
4319 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4322 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4323 int h, int x, int y)
4325 return ShowNewickTree(nf, title, null, w, h, x, y);
4329 * Add a treeviewer for the tree extracted from a newick file object to the
4330 * current alignment view
4337 * Associated alignment input data (or null)
4346 * @return TreePanel handle
4348 public TreePanel ShowNewickTree(NewickFile nf, String title,
4349 AlignmentView input, int w, int h, int x, int y)
4351 TreePanel tp = null;
4357 if (nf.getTree() != null)
4359 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4365 tp.setLocation(x, y);
4368 Desktop.addInternalFrame(tp, title, w, h);
4370 } catch (Exception ex)
4372 ex.printStackTrace();
4378 private boolean buildingMenu = false;
4381 * Generates menu items and listener event actions for web service clients
4384 public void BuildWebServiceMenu()
4386 while (buildingMenu)
4390 System.err.println("Waiting for building menu to finish.");
4392 } catch (Exception e)
4397 final AlignFrame me = this;
4398 buildingMenu = true;
4399 new Thread(new Runnable()
4404 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4407 System.err.println("Building ws menu again "
4408 + Thread.currentThread());
4409 // TODO: add support for context dependent disabling of services based
4411 // alignment and current selection
4412 // TODO: add additional serviceHandle parameter to specify abstract
4414 // class independently of AbstractName
4415 // TODO: add in rediscovery GUI function to restart discoverer
4416 // TODO: group services by location as well as function and/or
4418 // object broker mechanism.
4419 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4420 final IProgressIndicator af = me;
4421 final JMenu msawsmenu = new JMenu("Alignment");
4422 final JMenu secstrmenu = new JMenu(
4423 "Secondary Structure Prediction");
4424 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4425 final JMenu analymenu = new JMenu("Analysis");
4426 final JMenu dismenu = new JMenu("Protein Disorder");
4427 // final JMenu msawsmenu = new
4428 // JMenu(MessageManager.getString("label.alignment"));
4429 // final JMenu secstrmenu = new
4430 // JMenu(MessageManager.getString("label.secondary_structure_prediction"));
4431 // final JMenu seqsrchmenu = new
4432 // JMenu(MessageManager.getString("label.sequence_database_search"));
4433 // final JMenu analymenu = new
4434 // JMenu(MessageManager.getString("label.analysis"));
4435 // final JMenu dismenu = new
4436 // JMenu(MessageManager.getString("label.protein_disorder"));
4437 // JAL-940 - only show secondary structure prediction services from
4438 // the legacy server
4439 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4441 Discoverer.services != null && (Discoverer.services.size() > 0))
4443 // TODO: refactor to allow list of AbstractName/Handler bindings to
4445 // stored or retrieved from elsewhere
4446 // No MSAWS used any more:
4447 // Vector msaws = null; // (Vector)
4448 // Discoverer.services.get("MsaWS");
4449 Vector secstrpr = (Vector) Discoverer.services
4451 if (secstrpr != null)
4453 // Add any secondary structure prediction services
4454 for (int i = 0, j = secstrpr.size(); i < j; i++)
4456 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4458 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4459 .getServiceClient(sh);
4460 int p = secstrmenu.getItemCount();
4461 impl.attachWSMenuEntry(secstrmenu, me);
4462 int q = secstrmenu.getItemCount();
4463 for (int litm = p; litm < q; litm++)
4465 legacyItems.add(secstrmenu.getItem(litm));
4471 // Add all submenus in the order they should appear on the web
4473 wsmenu.add(msawsmenu);
4474 wsmenu.add(secstrmenu);
4475 wsmenu.add(dismenu);
4476 wsmenu.add(analymenu);
4477 // No search services yet
4478 // wsmenu.add(seqsrchmenu);
4480 javax.swing.SwingUtilities.invokeLater(new Runnable()
4487 webService.removeAll();
4488 // first, add discovered services onto the webservices menu
4489 if (wsmenu.size() > 0)
4491 for (int i = 0, j = wsmenu.size(); i < j; i++)
4493 webService.add(wsmenu.get(i));
4498 webService.add(me.webServiceNoServices);
4500 // TODO: move into separate menu builder class.
4501 boolean new_sspred = false;
4502 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4504 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4505 if (jws2servs != null)
4507 if (jws2servs.hasServices())
4509 jws2servs.attachWSMenuEntry(webService, me);
4510 for (Jws2Instance sv : jws2servs.getServices())
4512 if (sv.description.toLowerCase().contains("jpred"))
4514 for (JMenuItem jmi : legacyItems)
4516 jmi.setVisible(false);
4522 if (jws2servs.isRunning())
4524 JMenuItem tm = new JMenuItem(
4525 "Still discovering JABA Services");
4526 tm.setEnabled(false);
4531 build_urlServiceMenu(me.webService);
4532 build_fetchdbmenu(webService);
4533 for (JMenu item : wsmenu)
4535 if (item.getItemCount() == 0)
4537 item.setEnabled(false);
4541 item.setEnabled(true);
4544 } catch (Exception e)
4547 .debug("Exception during web service menu building process.",
4553 } catch (Exception e)
4558 buildingMenu = false;
4565 * construct any groupURL type service menu entries.
4569 private void build_urlServiceMenu(JMenu webService)
4571 // TODO: remove this code when 2.7 is released
4572 // DEBUG - alignmentView
4574 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4575 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4577 * @Override public void actionPerformed(ActionEvent e) {
4578 * jalview.datamodel.AlignmentView
4579 * .testSelectionViews(af.viewport.getAlignment(),
4580 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4582 * }); webService.add(testAlView);
4584 // TODO: refactor to RestClient discoverer and merge menu entries for
4585 // rest-style services with other types of analysis/calculation service
4586 // SHmmr test client - still being implemented.
4587 // DEBUG - alignmentView
4589 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4592 client.attachWSMenuEntry(
4593 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4599 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
4600 * chooser = new JalviewFileChooser(jalview.bin.Cache.
4601 * getProperty("LAST_DIRECTORY"));
4603 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
4604 * to Vamsas file"); chooser.setToolTipText("Export");
4606 * int value = chooser.showSaveDialog(this);
4608 * if (value == JalviewFileChooser.APPROVE_OPTION) {
4609 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
4610 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
4611 * chooser.getSelectedFile().getAbsolutePath(), this); } }
4614 * prototype of an automatically enabled/disabled analysis function
4617 protected void setShowProductsEnabled()
4619 SequenceI[] selection = viewport.getSequenceSelection();
4620 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
4621 viewport.getAlignment().getDataset()))
4623 showProducts.setEnabled(true);
4628 showProducts.setEnabled(false);
4633 * search selection for sequence xRef products and build the show products
4638 * @return true if showProducts menu should be enabled.
4640 public boolean canShowProducts(SequenceI[] selection,
4641 boolean isRegionSelection, Alignment dataset)
4643 boolean showp = false;
4646 showProducts.removeAll();
4647 final boolean dna = viewport.getAlignment().isNucleotide();
4648 final Alignment ds = dataset;
4649 String[] ptypes = (selection == null || selection.length == 0) ? null
4650 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4652 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4653 // selection, dataset, true);
4654 final SequenceI[] sel = selection;
4655 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4658 final boolean isRegSel = isRegionSelection;
4659 final AlignFrame af = this;
4660 final String source = ptypes[t];
4661 JMenuItem xtype = new JMenuItem(ptypes[t]);
4662 xtype.addActionListener(new ActionListener()
4666 public void actionPerformed(ActionEvent e)
4668 // TODO: new thread for this call with vis-delay
4669 af.showProductsFor(af.viewport.getSequenceSelection(), ds,
4670 isRegSel, dna, source);
4674 showProducts.add(xtype);
4676 showProducts.setVisible(showp);
4677 showProducts.setEnabled(showp);
4678 } catch (Exception e)
4680 jalview.bin.Cache.log
4681 .warn("canTranslate threw an exception - please report to help@jalview.org",
4688 protected void showProductsFor(SequenceI[] sel, Alignment ds,
4689 boolean isRegSel, boolean dna, String source)
4691 final boolean fisRegSel = isRegSel;
4692 final boolean fdna = dna;
4693 final String fsrc = source;
4694 final AlignFrame ths = this;
4695 final SequenceI[] fsel = sel;
4696 Runnable foo = new Runnable()
4702 final long sttime = System.currentTimeMillis();
4703 ths.setProgressBar(MessageManager.formatMessage("status.searching_for_sequences_from", new String[]{fsrc}), sttime);
4706 Alignment ds = ths.getViewport().getAlignment().getDataset(); // update
4710 Alignment prods = CrossRef
4711 .findXrefSequences(fsel, fdna, fsrc, ds);
4714 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4715 for (int s = 0; s < sprods.length; s++)
4717 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4718 if (ds.getSequences() == null
4719 || !ds.getSequences().contains(
4720 sprods[s].getDatasetSequence()))
4722 ds.addSequence(sprods[s].getDatasetSequence());
4724 sprods[s].updatePDBIds();
4726 Alignment al = new Alignment(sprods);
4727 AlignedCodonFrame[] cf = prods.getCodonFrames();
4729 for (int s = 0; cf != null && s < cf.length; s++)
4731 al.addCodonFrame(cf[s]);
4734 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4736 String newtitle = "" + ((fdna) ? "Proteins " : "Nucleotides ")
4737 + " for " + ((fisRegSel) ? "selected region of " : "")
4739 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4744 System.err.println("No Sequences generated for xRef type "
4747 } catch (Exception e)
4749 jalview.bin.Cache.log.error(
4750 "Exception when finding crossreferences", e);
4751 } catch (OutOfMemoryError e)
4753 new OOMWarning("whilst fetching crossreferences", e);
4756 jalview.bin.Cache.log.error("Error when finding crossreferences",
4759 ths.setProgressBar(MessageManager.formatMessage("status.finished_searching_for_sequences_from", new String[]{fsrc}),
4764 Thread frunner = new Thread(foo);
4768 public boolean canShowTranslationProducts(SequenceI[] selection,
4769 AlignmentI alignment)
4774 return (jalview.analysis.Dna.canTranslate(selection,
4775 viewport.getViewAsVisibleContigs(true)));
4776 } catch (Exception e)
4778 jalview.bin.Cache.log
4779 .warn("canTranslate threw an exception - please report to help@jalview.org",
4786 public void showProducts_actionPerformed(ActionEvent e)
4788 // /////////////////////////////
4789 // Collect Data to be translated/transferred
4791 SequenceI[] selection = viewport.getSequenceSelection();
4792 AlignmentI al = null;
4795 al = jalview.analysis.Dna.CdnaTranslate(selection, viewport
4796 .getViewAsVisibleContigs(true), viewport.getGapCharacter(),
4797 viewport.getAlignment().getDataset());
4798 } catch (Exception ex)
4801 jalview.bin.Cache.log.debug("Exception during translation.", ex);
4809 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation"),
4810 MessageManager.getString("label.translation_failed"),
4811 JOptionPane.WARNING_MESSAGE);
4815 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4816 Desktop.addInternalFrame(af, MessageManager.formatMessage(
4817 "label.translation_of_params", new String[]
4818 { this.getTitle() }), DEFAULT_WIDTH, DEFAULT_HEIGHT);
4823 public void showTranslation_actionPerformed(ActionEvent e)
4825 // /////////////////////////////
4826 // Collect Data to be translated/transferred
4828 SequenceI[] selection = viewport.getSequenceSelection();
4829 String[] seqstring = viewport.getViewAsString(true);
4830 AlignmentI al = null;
4833 al = jalview.analysis.Dna.CdnaTranslate(selection, seqstring,
4834 viewport.getViewAsVisibleContigs(true), viewport
4835 .getGapCharacter(), viewport.getAlignment()
4836 .getAlignmentAnnotation(), viewport.getAlignment()
4837 .getWidth(), viewport.getAlignment().getDataset());
4838 } catch (Exception ex)
4841 jalview.bin.Cache.log.error(
4842 "Exception during translation. Please report this !", ex);
4847 .getString("label.error_when_translating_sequences_submit_bug_report"),
4849 .getString("label.implementation_error")
4851 .getString("translation_failed"),
4852 JOptionPane.ERROR_MESSAGE);
4861 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation"),
4862 MessageManager.getString("label.translation_failed"),
4863 JOptionPane.WARNING_MESSAGE);
4867 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4868 Desktop.addInternalFrame(af, MessageManager.formatMessage(
4869 "label.translation_of_params", new String[]
4870 { this.getTitle() }), DEFAULT_WIDTH, DEFAULT_HEIGHT);
4875 * Try to load a features file onto the alignment.
4878 * contents or path to retrieve file
4880 * access mode of file (see jalview.io.AlignFile)
4881 * @return true if features file was parsed corectly.
4883 public boolean parseFeaturesFile(String file, String type)
4885 boolean featuresFile = false;
4888 featuresFile = new FeaturesFile(file, type).parse(viewport
4889 .getAlignment().getDataset(), alignPanel.getSeqPanel().seqCanvas
4890 .getFeatureRenderer().featureColours, false,
4891 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4892 } catch (Exception ex)
4894 ex.printStackTrace();
4899 viewport.showSequenceFeatures = true;
4900 showSeqFeatures.setSelected(true);
4901 if (alignPanel.getSeqPanel().seqCanvas.fr != null)
4903 // update the min/max ranges where necessary
4904 alignPanel.getSeqPanel().seqCanvas.fr.findAllFeatures(true);
4906 if (featureSettings != null)
4908 featureSettings.setTableData();
4910 alignPanel.paintAlignment(true);
4913 return featuresFile;
4917 public void dragEnter(DropTargetDragEvent evt)
4922 public void dragExit(DropTargetEvent evt)
4927 public void dragOver(DropTargetDragEvent evt)
4932 public void dropActionChanged(DropTargetDragEvent evt)
4937 public void drop(DropTargetDropEvent evt)
4939 Transferable t = evt.getTransferable();
4940 java.util.List files = null;
4944 DataFlavor uriListFlavor = new DataFlavor(
4945 "text/uri-list;class=java.lang.String");
4946 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
4948 // Works on Windows and MacOSX
4949 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4950 files = (java.util.List) t
4951 .getTransferData(DataFlavor.javaFileListFlavor);
4953 else if (t.isDataFlavorSupported(uriListFlavor))
4955 // This is used by Unix drag system
4956 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4957 String data = (String) t.getTransferData(uriListFlavor);
4958 files = new java.util.ArrayList(1);
4959 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
4960 data, "\r\n"); st.hasMoreTokens();)
4962 String s = st.nextToken();
4963 if (s.startsWith("#"))
4965 // the line is a comment (as per the RFC 2483)
4969 java.net.URI uri = new java.net.URI(s);
4970 // check to see if we can handle this kind of URI
4971 if (uri.getScheme().toLowerCase().startsWith("http"))
4973 files.add(uri.toString());
4977 // otherwise preserve old behaviour: catch all for file objects
4978 java.io.File file = new java.io.File(uri);
4979 files.add(file.toString());
4983 } catch (Exception e)
4985 e.printStackTrace();
4991 // check to see if any of these files have names matching sequences in
4993 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4994 .getAlignment().getSequencesArray());
4996 * Object[] { String,SequenceI}
4998 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
4999 ArrayList<String> filesnotmatched = new ArrayList<String>();
5000 for (int i = 0; i < files.size(); i++)
5002 String file = files.get(i).toString();
5004 String protocol = FormatAdapter.checkProtocol(file);
5005 if (protocol == jalview.io.FormatAdapter.FILE)
5007 File fl = new File(file);
5008 pdbfn = fl.getName();
5010 else if (protocol == jalview.io.FormatAdapter.URL)
5012 URL url = new URL(file);
5013 pdbfn = url.getFile();
5015 if (pdbfn.length() > 0)
5017 // attempt to find a match in the alignment
5018 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5019 int l = 0, c = pdbfn.indexOf(".");
5020 while (mtch == null && c != -1)
5025 } while ((c = pdbfn.indexOf(".", l)) > l);
5028 pdbfn = pdbfn.substring(0, l);
5030 mtch = idm.findAllIdMatches(pdbfn);
5037 type = new IdentifyFile().Identify(file, protocol);
5038 } catch (Exception ex)
5044 if (type.equalsIgnoreCase("PDB"))
5046 filesmatched.add(new Object[]
5047 { file, protocol, mtch });
5052 // File wasn't named like one of the sequences or wasn't a PDB file.
5053 filesnotmatched.add(file);
5057 if (filesmatched.size() > 0)
5059 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
5065 "label.automatically_associate_pdb_files_with_sequences_same_name",
5072 .getString("label.automatically_associate_pdb_files_by_name"),
5073 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
5076 for (Object[] fm : filesmatched)
5078 // try and associate
5079 // TODO: may want to set a standard ID naming formalism for
5080 // associating PDB files which have no IDs.
5081 for (SequenceI toassoc : (SequenceI[]) fm[2])
5083 PDBEntry pe = new AssociatePdbFileWithSeq()
5084 .associatePdbWithSeq((String) fm[0],
5085 (String) fm[1], toassoc, false,
5089 System.err.println("Associated file : "
5090 + ((String) fm[0]) + " with "
5091 + toassoc.getDisplayId(true));
5095 alignPanel.paintAlignment(true);
5099 if (filesnotmatched.size() > 0)
5102 && (Cache.getDefault(
5103 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
5106 "<html>"+MessageManager
5108 "label.ignore_unmatched_dropped_files_info",
5113 .toString() })+"</html>",
5115 .getString("label.ignore_unmatched_dropped_files"),
5116 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
5120 for (String fn : filesnotmatched)
5122 loadJalviewDataFile(fn, null, null, null);
5126 } catch (Exception ex)
5128 ex.printStackTrace();
5134 * Attempt to load a "dropped" file or URL string: First by testing whether
5135 * it's and Annotation file, then a JNet file, and finally a features file. If
5136 * all are false then the user may have dropped an alignment file onto this
5140 * either a filename or a URL string.
5142 public void loadJalviewDataFile(String file, String protocol,
5143 String format, SequenceI assocSeq)
5147 if (protocol == null)
5149 protocol = jalview.io.FormatAdapter.checkProtocol(file);
5151 // if the file isn't identified, or not positively identified as some
5152 // other filetype (PFAM is default unidentified alignment file type) then
5153 // try to parse as annotation.
5154 boolean isAnnotation = (format == null || format
5155 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
5156 .readAnnotationFile(viewport.getAlignment(), file, protocol)
5161 // first see if its a T-COFFEE score file
5162 TCoffeeScoreFile tcf = null;
5165 tcf = new TCoffeeScoreFile(file, protocol);
5168 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5170 tcoffeeColour.setEnabled(true);
5171 tcoffeeColour.setSelected(true);
5172 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5173 isAnnotation = true;
5175 .setText(MessageManager
5176 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5180 // some problem - if no warning its probable that the ID matching
5181 // process didn't work
5185 tcf.getWarningMessage() == null ? MessageManager
5186 .getString("label.check_file_matches_sequence_ids_alignment")
5187 : tcf.getWarningMessage(),
5189 .getString("label.problem_reading_tcoffee_score_file"),
5190 JOptionPane.WARNING_MESSAGE);
5197 } catch (Exception x)
5200 .debug("Exception when processing data source as T-COFFEE score file",
5206 // try to see if its a JNet 'concise' style annotation file *before*
5208 // try to parse it as a features file
5211 format = new IdentifyFile().Identify(file, protocol);
5213 if (format.equalsIgnoreCase("JnetFile"))
5215 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5217 new JnetAnnotationMaker().add_annotation(predictions,
5218 viewport.getAlignment(), 0, false);
5219 isAnnotation = true;
5224 * if (format.equalsIgnoreCase("PDB")) {
5226 * String pdbfn = ""; // try to match up filename with sequence id
5227 * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
5228 * new File(file); pdbfn = fl.getName(); } else if (protocol ==
5229 * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
5230 * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
5231 * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5232 * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
5233 * // attempt to find a match in the alignment SequenceI mtch =
5234 * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
5235 * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
5236 * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
5237 * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
5238 * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
5239 * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
5240 * { System.err.println("Associated file : " + file + " with " +
5241 * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
5242 * TODO: maybe need to load as normal otherwise return; } }
5244 // try to parse it as a features file
5245 boolean isGroupsFile = parseFeaturesFile(file, protocol);
5246 // if it wasn't a features file then we just treat it as a general
5247 // alignment file to load into the current view.
5250 new FileLoader().LoadFile(viewport, file, protocol, format);
5254 alignPanel.paintAlignment(true);
5262 alignPanel.adjustAnnotationHeight();
5263 viewport.updateSequenceIdColours();
5264 buildSortByAnnotationScoresMenu();
5265 alignPanel.paintAlignment(true);
5267 } catch (Exception ex)
5269 ex.printStackTrace();
5270 } catch (OutOfMemoryError oom)
5275 } catch (Exception x)
5281 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5282 : "using " + protocol + " from " + file)
5284 + (format != null ? "(parsing as '" + format
5285 + "' file)" : ""), oom, Desktop.desktop);
5290 public void tabSelectionChanged(int index)
5294 alignPanel = (AlignmentPanel) alignPanels.elementAt(index);
5295 viewport = alignPanel.av;
5296 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5297 setMenusFromViewport(viewport);
5302 public void tabbedPane_mousePressed(MouseEvent e)
5304 if (SwingUtilities.isRightMouseButton(e))
5306 String reply = JOptionPane.showInternalInputDialog(this,
5307 MessageManager.getString("label.enter_view_name"),
5308 MessageManager.getString("label.enter_view_name"),
5309 JOptionPane.QUESTION_MESSAGE);
5313 viewport.viewName = reply;
5314 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5319 public AlignViewport getCurrentView()
5325 * Open the dialog for regex description parsing.
5328 protected void extractScores_actionPerformed(ActionEvent e)
5330 ParseProperties pp = new jalview.analysis.ParseProperties(
5331 viewport.getAlignment());
5332 // TODO: verify regex and introduce GUI dialog for version 2.5
5333 // if (pp.getScoresFromDescription("col", "score column ",
5334 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5336 if (pp.getScoresFromDescription("description column",
5337 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5339 buildSortByAnnotationScoresMenu();
5347 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5351 protected void showDbRefs_actionPerformed(ActionEvent e)
5353 viewport.setShowDbRefs(showDbRefsMenuitem.isSelected());
5359 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5363 protected void showNpFeats_actionPerformed(ActionEvent e)
5365 viewport.setShowNpFeats(showNpFeatsMenuitem.isSelected());
5369 * find the viewport amongst the tabs in this alignment frame and close that
5374 public boolean closeView(AlignViewport av)
5378 this.closeMenuItem_actionPerformed(false);
5381 Component[] comp = tabbedPane.getComponents();
5382 for (int i = 0; comp != null && i < comp.length; i++)
5384 if (comp[i] instanceof AlignmentPanel)
5386 if (((AlignmentPanel) comp[i]).av == av)
5389 closeView((AlignmentPanel) comp[i]);
5397 protected void build_fetchdbmenu(JMenu webService)
5399 // Temporary hack - DBRef Fetcher always top level ws entry.
5400 // TODO We probably want to store a sequence database checklist in
5401 // preferences and have checkboxes.. rather than individual sources selected
5403 final JMenu rfetch = new JMenu(
5404 MessageManager.getString("action.fetch_db_references"));
5405 rfetch.setToolTipText(MessageManager
5406 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5407 webService.add(rfetch);
5409 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5410 MessageManager.getString("option.trim_retrieved_seqs"));
5411 trimrs.setToolTipText(MessageManager
5412 .getString("label.trim_retrieved_sequences"));
5413 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5414 trimrs.addActionListener(new ActionListener()
5417 public void actionPerformed(ActionEvent e)
5419 trimrs.setSelected(trimrs.isSelected());
5420 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5421 Boolean.valueOf(trimrs.isSelected()).toString());
5425 JMenuItem fetchr = new JMenuItem(
5426 MessageManager.getString("label.standard_databases"));
5427 fetchr.setToolTipText(MessageManager
5428 .getString("label.fetch_embl_uniprot"));
5429 fetchr.addActionListener(new ActionListener()
5433 public void actionPerformed(ActionEvent e)
5435 new Thread(new Runnable()
5441 new jalview.ws.DBRefFetcher(alignPanel.av
5442 .getSequenceSelection(), alignPanel.alignFrame)
5443 .fetchDBRefs(false);
5451 final AlignFrame me = this;
5452 new Thread(new Runnable()
5457 final jalview.ws.SequenceFetcher sf = SequenceFetcher
5458 .getSequenceFetcherSingleton(me);
5459 javax.swing.SwingUtilities.invokeLater(new Runnable()
5464 String[] dbclasses = sf.getOrderedSupportedSources();
5465 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5466 // jalview.util.QuickSort.sort(otherdb, otherdb);
5467 List<DbSourceProxy> otherdb;
5468 JMenu dfetch = new JMenu();
5469 JMenu ifetch = new JMenu();
5470 JMenuItem fetchr = null;
5471 int comp = 0, icomp = 0, mcomp = 15;
5472 String mname = null;
5474 for (String dbclass : dbclasses)
5476 otherdb = sf.getSourceProxy(dbclass);
5477 // add a single entry for this class, or submenu allowing 'fetch
5479 if (otherdb == null || otherdb.size() < 1)
5483 // List<DbSourceProxy> dbs=otherdb;
5484 // otherdb=new ArrayList<DbSourceProxy>();
5485 // for (DbSourceProxy db:dbs)
5487 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5491 mname = "From " + dbclass;
5493 if (otherdb.size() == 1)
5495 final DbSourceProxy[] dassource = otherdb
5496 .toArray(new DbSourceProxy[0]);
5497 DbSourceProxy src = otherdb.get(0);
5498 fetchr = new JMenuItem(src.getDbSource());
5499 fetchr.addActionListener(new ActionListener()
5503 public void actionPerformed(ActionEvent e)
5505 new Thread(new Runnable()
5511 new jalview.ws.DBRefFetcher(alignPanel.av
5512 .getSequenceSelection(),
5513 alignPanel.alignFrame, dassource)
5514 .fetchDBRefs(false);
5520 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from", new String[]{src.getDbName()})));
5526 final DbSourceProxy[] dassource = otherdb
5527 .toArray(new DbSourceProxy[0]);
5529 DbSourceProxy src = otherdb.get(0);
5530 fetchr = new JMenuItem(MessageManager.formatMessage(
5531 "label.fetch_all_param", new String[]
5532 { src.getDbSource() }));
5533 fetchr.addActionListener(new ActionListener()
5536 public void actionPerformed(ActionEvent e)
5538 new Thread(new Runnable()
5544 new jalview.ws.DBRefFetcher(alignPanel.av
5545 .getSequenceSelection(),
5546 alignPanel.alignFrame, dassource)
5547 .fetchDBRefs(false);
5553 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from_all_sources", new String[]{Integer.valueOf(otherdb.size()).toString(), src.getDbSource(), src.getDbName()})));
5556 // and then build the rest of the individual menus
5557 ifetch = new JMenu(MessageManager.formatMessage("label.source_from_db_source", new String[]{src.getDbSource()}));
5559 String imname = null;
5561 for (DbSourceProxy sproxy : otherdb)
5563 String dbname = sproxy.getDbName();
5564 String sname = dbname.length() > 5 ? dbname.substring(0,
5565 5) + "..." : dbname;
5566 String msname = dbname.length() > 10 ? dbname.substring(
5567 0, 10) + "..." : dbname;
5570 imname = MessageManager.formatMessage("label.from_msname", new String[]{sname});
5572 fetchr = new JMenuItem(msname);
5573 final DbSourceProxy[] dassrc =
5575 fetchr.addActionListener(new ActionListener()
5579 public void actionPerformed(ActionEvent e)
5581 new Thread(new Runnable()
5587 new jalview.ws.DBRefFetcher(alignPanel.av
5588 .getSequenceSelection(),
5589 alignPanel.alignFrame, dassrc)
5590 .fetchDBRefs(false);
5596 fetchr.setToolTipText("<html>"
5597 + MessageManager.formatMessage("label.fetch_retrieve_from", new String[]{dbname}));
5600 if (++icomp >= mcomp || i == (otherdb.size()))
5602 ifetch.setText(MessageManager.formatMessage(
5603 "label.source_to_target", imname, sname));
5605 ifetch = new JMenu();
5613 if (comp >= mcomp || dbi >= (dbclasses.length))
5615 dfetch.setText(MessageManager.formatMessage(
5616 "label.source_to_target", mname, dbclass));
5618 dfetch = new JMenu();
5631 * Left justify the whole alignment.
5634 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5636 AlignmentI al = viewport.getAlignment();
5638 viewport.firePropertyChange("alignment", null, al);
5642 * Right justify the whole alignment.
5645 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5647 AlignmentI al = viewport.getAlignment();
5649 viewport.firePropertyChange("alignment", null, al);
5652 public void setShowSeqFeatures(boolean b)
5654 showSeqFeatures.setSelected(true);
5655 viewport.setShowSequenceFeatures(true);
5662 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5663 * awt.event.ActionEvent)
5666 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5668 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5669 alignPanel.paintAlignment(true);
5676 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5680 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5682 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5683 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5691 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5692 * .event.ActionEvent)
5695 protected void showGroupConservation_actionPerformed(ActionEvent e)
5697 viewport.setShowGroupConservation(showGroupConservation.getState());
5698 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5705 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5706 * .event.ActionEvent)
5709 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5711 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5712 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5719 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5720 * .event.ActionEvent)
5723 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5725 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5726 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5730 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5732 showSequenceLogo.setState(true);
5733 viewport.setShowSequenceLogo(true);
5734 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5735 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5739 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5741 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5748 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5749 * .event.ActionEvent)
5752 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5754 if (avc.makeGroupsFromSelection())
5756 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5757 alignPanel.updateAnnotation();
5758 alignPanel.paintAlignment(true);
5763 protected void createGroup_actionPerformed(ActionEvent e)
5765 if (avc.createGroup())
5767 alignPanel.alignmentChanged();
5772 protected void unGroup_actionPerformed(ActionEvent e)
5776 alignPanel.alignmentChanged();
5781 * make the given alignmentPanel the currently selected tab
5783 * @param alignmentPanel
5785 public void setDisplayedView(AlignmentPanel alignmentPanel)
5787 if (!viewport.getSequenceSetId().equals(
5788 alignmentPanel.av.getSequenceSetId()))
5790 throw new Error(MessageManager.getString("error.implementation_error_cannot_show_view_alignment_frame"));
5792 if (tabbedPane != null
5793 & alignPanels.indexOf(alignmentPanel) != tabbedPane
5794 .getSelectedIndex())
5796 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5801 * Action on selection of menu options to Show or Hide annotations.
5804 * @param forSequences
5805 * update sequence-related annotations
5806 * @param forAlignment
5807 * update non-sequence-related annotations
5810 protected void setAnnotationsVisibility(boolean visible,
5811 boolean forSequences, boolean forAlignment)
5813 for (AlignmentAnnotation aa : alignPanel.getAlignment()
5814 .getAlignmentAnnotation())
5816 boolean apply = (aa.sequenceRef == null && forAlignment)
5817 || (aa.sequenceRef != null && forSequences);
5820 aa.visible = visible;
5823 alignPanel.validateAnnotationDimensions(false);
5824 alignPanel.alignmentChanged();
5828 * Store selected annotation sort order for the view and repaint.
5831 protected void sortAnnotations_actionPerformed()
5833 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5835 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5836 alignPanel.paintAlignment(true);
5841 * @return alignment panels in this alignemnt frame
5843 public List<AlignmentViewPanel> getAlignPanels()
5845 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5849 class PrintThread extends Thread
5853 public PrintThread(AlignmentPanel ap)
5858 static PageFormat pf;
5863 PrinterJob printJob = PrinterJob.getPrinterJob();
5867 printJob.setPrintable(ap, pf);
5871 printJob.setPrintable(ap);
5874 if (printJob.printDialog())
5879 } catch (Exception PrintException)
5881 PrintException.printStackTrace();