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.isShowSequenceFeatures());
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);
1079 success = new Jalview2XML().SaveAlignment(this, file, shortName);
1081 statusBar.setText(MessageManager.formatMessage(
1082 "label.successfully_saved_to_file_in_format", new String[]
1083 { fileName, format }));
1088 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1090 warningMessage("Cannot save file " + fileName + " using format "
1091 + format, "Alignment output format not supported");
1092 saveAs_actionPerformed(null);
1093 // JBPNote need to have a raise_gui flag here
1097 String[] omitHidden = null;
1099 if (viewport.hasHiddenColumns())
1101 int reply = JOptionPane
1102 .showInternalConfirmDialog(
1105 .getString("label.alignment_contains_hidden_columns"),
1107 .getString("action.save_omit_hidden_columns"),
1108 JOptionPane.YES_NO_OPTION,
1109 JOptionPane.QUESTION_MESSAGE);
1111 if (reply == JOptionPane.YES_OPTION)
1113 omitHidden = viewport.getViewAsString(false);
1116 FormatAdapter f = new FormatAdapter();
1117 String output = f.formatSequences(format,
1118 viewport.getAlignment(), // class cast exceptions will
1119 // occur in the distant future
1120 omitHidden, f.getCacheSuffixDefault(format),
1121 viewport.getColumnSelection());
1131 java.io.PrintWriter out = new java.io.PrintWriter(
1132 new java.io.FileWriter(file));
1136 this.setTitle(file);
1137 statusBar.setText(MessageManager.formatMessage(
1138 "label.successfully_saved_to_file_in_format",
1140 { fileName, format }));
1141 } catch (Exception ex)
1144 ex.printStackTrace();
1151 JOptionPane.showInternalMessageDialog(this, MessageManager
1152 .formatMessage("label.couldnt_save_file", new String[]
1153 { fileName }), MessageManager
1154 .getString("label.error_saving_file"),
1155 JOptionPane.WARNING_MESSAGE);
1161 private void warningMessage(String warning, String title)
1163 if (new jalview.util.Platform().isHeadless())
1165 System.err.println("Warning: " + title + "\nWarning: " + warning);
1170 JOptionPane.showInternalMessageDialog(this, warning, title,
1171 JOptionPane.WARNING_MESSAGE);
1183 protected void outputText_actionPerformed(ActionEvent e)
1185 String[] omitHidden = null;
1187 if (viewport.hasHiddenColumns())
1189 int reply = JOptionPane
1190 .showInternalConfirmDialog(
1193 .getString("label.alignment_contains_hidden_columns"),
1195 .getString("action.save_omit_hidden_columns"),
1196 JOptionPane.YES_NO_OPTION,
1197 JOptionPane.QUESTION_MESSAGE);
1199 if (reply == JOptionPane.YES_OPTION)
1201 omitHidden = viewport.getViewAsString(false);
1205 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1206 cap.setForInput(null);
1210 cap.setText(new FormatAdapter().formatSequences(e.getActionCommand(),
1211 viewport.getAlignment(), omitHidden,
1212 viewport.getColumnSelection()));
1213 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1214 "label.alignment_output_command", new String[]
1215 { e.getActionCommand() }), 600, 500);
1216 } catch (OutOfMemoryError oom)
1218 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1231 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1233 // new HTMLOutput(alignPanel,
1234 // alignPanel.getSeqPanel().seqCanvas.getSequenceRenderer(),
1235 // alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
1236 new HtmlSvgOutput(null, alignPanel);
1240 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1242 new BioJsHTMLOutput(alignPanel,
1243 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
1245 public void createImageMap(File file, String image)
1247 alignPanel.makePNGImageMap(file, image);
1257 public void createPNG(File f)
1259 alignPanel.makePNG(f);
1269 public void createEPS(File f)
1271 alignPanel.makeEPS(f);
1274 public void createSVG(File f)
1276 alignPanel.makeSVG(f);
1279 public void pageSetup_actionPerformed(ActionEvent e)
1281 PrinterJob printJob = PrinterJob.getPrinterJob();
1282 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1292 public void printMenuItem_actionPerformed(ActionEvent e)
1294 // Putting in a thread avoids Swing painting problems
1295 PrintThread thread = new PrintThread(alignPanel);
1300 public void exportFeatures_actionPerformed(ActionEvent e)
1302 new AnnotationExporter().exportFeatures(alignPanel);
1306 public void exportAnnotations_actionPerformed(ActionEvent e)
1308 new AnnotationExporter().exportAnnotations(alignPanel);
1312 public void associatedData_actionPerformed(ActionEvent e)
1314 // Pick the tree file
1315 JalviewFileChooser chooser = new JalviewFileChooser(
1316 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1317 chooser.setFileView(new JalviewFileView());
1318 chooser.setDialogTitle(MessageManager
1319 .getString("label.load_jalview_annotations"));
1320 chooser.setToolTipText(MessageManager
1321 .getString("label.load_jalview_annotations"));
1323 int value = chooser.showOpenDialog(null);
1325 if (value == JalviewFileChooser.APPROVE_OPTION)
1327 String choice = chooser.getSelectedFile().getPath();
1328 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1329 loadJalviewDataFile(choice, null, null, null);
1335 * Close the current view or all views in the alignment frame. If the frame
1336 * only contains one view then the alignment will be removed from memory.
1338 * @param closeAllTabs
1341 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1343 if (alignPanels != null && alignPanels.size() < 2)
1345 closeAllTabs = true;
1350 if (alignPanels != null)
1354 if (this.isClosed())
1356 // really close all the windows - otherwise wait till
1357 // setClosed(true) is called
1358 for (int i = 0; i < alignPanels.size(); i++)
1360 AlignmentPanel ap = (AlignmentPanel) alignPanels.elementAt(i);
1367 closeView(alignPanel);
1373 this.setClosed(true);
1375 } catch (Exception ex)
1377 ex.printStackTrace();
1382 * close alignPanel2 and shuffle tabs appropriately.
1384 * @param alignPanel2
1386 public void closeView(AlignmentPanel alignPanel2)
1388 int index = tabbedPane.getSelectedIndex();
1389 int closedindex = tabbedPane.indexOfComponent(alignPanel2);
1390 alignPanels.removeElement(alignPanel2);
1392 // if (viewport == alignPanel2.av)
1396 alignPanel2.closePanel();
1399 tabbedPane.removeTabAt(closedindex);
1400 tabbedPane.validate();
1402 if (index > closedindex || index == tabbedPane.getTabCount())
1404 // modify currently selected tab index if necessary.
1408 this.tabSelectionChanged(index);
1414 void updateEditMenuBar()
1417 if (viewport.historyList.size() > 0)
1419 undoMenuItem.setEnabled(true);
1420 CommandI command = viewport.historyList.peek();
1421 undoMenuItem.setText(MessageManager.formatMessage(
1422 "label.undo_command", new String[]
1423 { command.getDescription() }));
1427 undoMenuItem.setEnabled(false);
1428 undoMenuItem.setText(MessageManager.getString("action.undo"));
1431 if (viewport.redoList.size() > 0)
1433 redoMenuItem.setEnabled(true);
1435 CommandI command = viewport.redoList.peek();
1436 redoMenuItem.setText(MessageManager.formatMessage(
1437 "label.redo_command", new String[]
1438 { command.getDescription() }));
1442 redoMenuItem.setEnabled(false);
1443 redoMenuItem.setText(MessageManager.getString("action.redo"));
1447 public void addHistoryItem(CommandI command)
1449 if (command.getSize() > 0)
1451 viewport.historyList.push(command);
1452 viewport.redoList.clear();
1453 updateEditMenuBar();
1454 viewport.updateHiddenColumns();
1455 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1456 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1457 // viewport.getColumnSelection()
1458 // .getHiddenColumns().size() > 0);
1464 * @return alignment objects for all views
1466 AlignmentI[] getViewAlignments()
1468 if (alignPanels != null)
1470 Enumeration e = alignPanels.elements();
1471 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1472 for (int i = 0; e.hasMoreElements(); i++)
1474 als[i] = ((AlignmentPanel) e.nextElement()).av.getAlignment();
1478 if (viewport != null)
1480 return new AlignmentI[]
1481 { viewport.getAlignment() };
1493 protected void undoMenuItem_actionPerformed(ActionEvent e)
1495 if (viewport.historyList.empty())
1499 CommandI command = viewport.historyList.pop();
1500 viewport.redoList.push(command);
1501 command.undoCommand(getViewAlignments());
1503 AlignViewport originalSource = getOriginatingSource(command);
1504 updateEditMenuBar();
1506 if (originalSource != null)
1508 if (originalSource != viewport)
1511 .warn("Implementation worry: mismatch of viewport origin for undo");
1513 originalSource.updateHiddenColumns();
1514 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1516 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1517 // viewport.getColumnSelection()
1518 // .getHiddenColumns().size() > 0);
1519 originalSource.firePropertyChange("alignment", null, originalSource
1520 .getAlignment().getSequences());
1531 protected void redoMenuItem_actionPerformed(ActionEvent e)
1533 if (viewport.redoList.size() < 1)
1538 CommandI command = viewport.redoList.pop();
1539 viewport.historyList.push(command);
1540 command.doCommand(getViewAlignments());
1542 AlignViewport originalSource = getOriginatingSource(command);
1543 updateEditMenuBar();
1545 if (originalSource != null)
1548 if (originalSource != viewport)
1551 .warn("Implementation worry: mismatch of viewport origin for redo");
1553 originalSource.updateHiddenColumns();
1554 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1556 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1557 // viewport.getColumnSelection()
1558 // .getHiddenColumns().size() > 0);
1559 originalSource.firePropertyChange("alignment", null, originalSource
1560 .getAlignment().getSequences());
1564 AlignViewport getOriginatingSource(CommandI command)
1566 AlignViewport originalSource = null;
1567 // For sequence removal and addition, we need to fire
1568 // the property change event FROM the viewport where the
1569 // original alignment was altered
1570 AlignmentI al = null;
1571 if (command instanceof EditCommand)
1573 EditCommand editCommand = (EditCommand) command;
1574 al = editCommand.getAlignment();
1575 Vector comps = (Vector) PaintRefresher.components.get(viewport
1576 .getSequenceSetId());
1578 for (int i = 0; i < comps.size(); i++)
1580 if (comps.elementAt(i) instanceof AlignmentPanel)
1582 if (al == ((AlignmentPanel) comps.elementAt(i)).av.getAlignment())
1584 originalSource = ((AlignmentPanel) comps.elementAt(i)).av;
1591 if (originalSource == null)
1593 // The original view is closed, we must validate
1594 // the current view against the closed view first
1597 PaintRefresher.validateSequences(al, viewport.getAlignment());
1600 originalSource = viewport;
1603 return originalSource;
1612 public void moveSelectedSequences(boolean up)
1614 SequenceGroup sg = viewport.getSelectionGroup();
1620 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1621 viewport.getHiddenRepSequences(), up);
1622 alignPanel.paintAlignment(true);
1625 synchronized void slideSequences(boolean right, int size)
1627 List<SequenceI> sg = new Vector();
1628 if (viewport.cursorMode)
1630 sg.add(viewport.getAlignment().getSequenceAt(
1631 alignPanel.getSeqPanel().seqCanvas.cursorY));
1633 else if (viewport.getSelectionGroup() != null
1634 && viewport.getSelectionGroup().getSize() != viewport
1635 .getAlignment().getHeight())
1637 sg = viewport.getSelectionGroup().getSequences(
1638 viewport.getHiddenRepSequences());
1646 Vector invertGroup = new Vector();
1648 for (int i = 0; i < viewport.getAlignment().getHeight(); i++)
1650 if (!sg.contains(viewport.getAlignment().getSequenceAt(i)))
1652 invertGroup.add(viewport.getAlignment().getSequenceAt(i));
1656 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1658 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1659 for (int i = 0; i < invertGroup.size(); i++)
1661 seqs2[i] = (SequenceI) invertGroup.elementAt(i);
1664 SlideSequencesCommand ssc;
1667 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1668 size, viewport.getGapCharacter());
1672 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1673 size, viewport.getGapCharacter());
1676 int groupAdjustment = 0;
1677 if (ssc.getGapsInsertedBegin() && right)
1679 if (viewport.cursorMode)
1681 alignPanel.getSeqPanel().moveCursor(size, 0);
1685 groupAdjustment = size;
1688 else if (!ssc.getGapsInsertedBegin() && !right)
1690 if (viewport.cursorMode)
1692 alignPanel.getSeqPanel().moveCursor(-size, 0);
1696 groupAdjustment = -size;
1700 if (groupAdjustment != 0)
1702 viewport.getSelectionGroup().setStartRes(
1703 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1704 viewport.getSelectionGroup().setEndRes(
1705 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1708 boolean appendHistoryItem = false;
1709 if (viewport.historyList != null && viewport.historyList.size() > 0
1710 && viewport.historyList.peek() instanceof SlideSequencesCommand)
1712 appendHistoryItem = ssc
1713 .appendSlideCommand((SlideSequencesCommand) viewport.historyList
1717 if (!appendHistoryItem)
1719 addHistoryItem(ssc);
1732 protected void copy_actionPerformed(ActionEvent e)
1735 if (viewport.getSelectionGroup() == null)
1739 // TODO: preserve the ordering of displayed alignment annotation in any
1740 // internal paste (particularly sequence associated annotation)
1741 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1742 String[] omitHidden = null;
1744 if (viewport.hasHiddenColumns())
1746 omitHidden = viewport.getViewAsString(true);
1749 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1752 StringSelection ss = new StringSelection(output);
1756 jalview.gui.Desktop.internalCopy = true;
1757 // Its really worth setting the clipboard contents
1758 // to empty before setting the large StringSelection!!
1759 Toolkit.getDefaultToolkit().getSystemClipboard()
1760 .setContents(new StringSelection(""), null);
1762 Toolkit.getDefaultToolkit().getSystemClipboard()
1763 .setContents(ss, Desktop.instance);
1764 } catch (OutOfMemoryError er)
1766 new OOMWarning("copying region", er);
1770 ArrayList<int[]> hiddenColumns = null;
1771 if (viewport.hasHiddenColumns())
1773 hiddenColumns = new ArrayList<int[]>();
1774 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1775 .getSelectionGroup().getEndRes();
1776 for (int[] region : viewport.getColumnSelection().getHiddenColumns())
1778 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1780 hiddenColumns.add(new int[]
1781 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1786 Desktop.jalviewClipboard = new Object[]
1787 { seqs, viewport.getAlignment().getDataset(), hiddenColumns };
1788 statusBar.setText(MessageManager.formatMessage(
1789 "label.copied_sequences_to_clipboard", new String[]
1790 { Integer.valueOf(seqs.length).toString() }));
1800 protected void pasteNew_actionPerformed(ActionEvent e)
1812 protected void pasteThis_actionPerformed(ActionEvent e)
1818 * Paste contents of Jalview clipboard
1820 * @param newAlignment
1821 * true to paste to a new alignment, otherwise add to this.
1823 void paste(boolean newAlignment)
1825 boolean externalPaste = true;
1828 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1829 Transferable contents = c.getContents(this);
1831 if (contents == null)
1839 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1840 if (str.length() < 1)
1845 format = new IdentifyFile().Identify(str, "Paste");
1847 } catch (OutOfMemoryError er)
1849 new OOMWarning("Out of memory pasting sequences!!", er);
1853 SequenceI[] sequences;
1854 boolean annotationAdded = false;
1855 AlignmentI alignment = null;
1857 if (Desktop.jalviewClipboard != null)
1859 // The clipboard was filled from within Jalview, we must use the
1861 // And dataset from the copied alignment
1862 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1863 // be doubly sure that we create *new* sequence objects.
1864 sequences = new SequenceI[newseq.length];
1865 for (int i = 0; i < newseq.length; i++)
1867 sequences[i] = new Sequence(newseq[i]);
1869 alignment = new Alignment(sequences);
1870 externalPaste = false;
1874 // parse the clipboard as an alignment.
1875 alignment = new FormatAdapter().readFile(str, "Paste", format);
1876 sequences = alignment.getSequencesArray();
1880 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1886 if (Desktop.jalviewClipboard != null)
1888 // dataset is inherited
1889 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1893 // new dataset is constructed
1894 alignment.setDataset(null);
1896 alwidth = alignment.getWidth() + 1;
1900 AlignmentI pastedal = alignment; // preserve pasted alignment object
1901 // Add pasted sequences and dataset into existing alignment.
1902 alignment = viewport.getAlignment();
1903 alwidth = alignment.getWidth() + 1;
1904 // decide if we need to import sequences from an existing dataset
1905 boolean importDs = Desktop.jalviewClipboard != null
1906 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1907 // importDs==true instructs us to copy over new dataset sequences from
1908 // an existing alignment
1909 Vector newDs = (importDs) ? new Vector() : null; // used to create
1910 // minimum dataset set
1912 for (int i = 0; i < sequences.length; i++)
1916 newDs.addElement(null);
1918 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
1920 if (importDs && ds != null)
1922 if (!newDs.contains(ds))
1924 newDs.setElementAt(ds, i);
1925 ds = new Sequence(ds);
1926 // update with new dataset sequence
1927 sequences[i].setDatasetSequence(ds);
1931 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
1936 // copy and derive new dataset sequence
1937 sequences[i] = sequences[i].deriveSequence();
1938 alignment.getDataset().addSequence(
1939 sequences[i].getDatasetSequence());
1940 // TODO: avoid creation of duplicate dataset sequences with a
1941 // 'contains' method using SequenceI.equals()/SequenceI.contains()
1943 alignment.addSequence(sequences[i]); // merges dataset
1947 newDs.clear(); // tidy up
1949 if (alignment.getAlignmentAnnotation() != null)
1951 for (AlignmentAnnotation alan : alignment
1952 .getAlignmentAnnotation())
1954 if (alan.graphGroup > fgroup)
1956 fgroup = alan.graphGroup;
1960 if (pastedal.getAlignmentAnnotation() != null)
1962 // Add any annotation attached to alignment.
1963 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
1964 for (int i = 0; i < alann.length; i++)
1966 annotationAdded = true;
1967 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
1969 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
1970 if (newann.graphGroup > -1)
1972 if (newGraphGroups.size() <= newann.graphGroup
1973 || newGraphGroups.get(newann.graphGroup) == null)
1975 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
1977 newGraphGroups.add(q, null);
1979 newGraphGroups.set(newann.graphGroup, new Integer(
1982 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
1986 newann.padAnnotation(alwidth);
1987 alignment.addAnnotation(newann);
1997 addHistoryItem(new EditCommand(
1998 MessageManager.getString("label.add_sequences"),
2000 sequences, 0, alignment.getWidth(), alignment));
2002 // Add any annotations attached to sequences
2003 for (int i = 0; i < sequences.length; i++)
2005 if (sequences[i].getAnnotation() != null)
2007 AlignmentAnnotation newann;
2008 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2010 annotationAdded = true;
2011 newann = sequences[i].getAnnotation()[a];
2012 newann.adjustForAlignment();
2013 newann.padAnnotation(alwidth);
2014 if (newann.graphGroup > -1)
2016 if (newann.graphGroup > -1)
2018 if (newGraphGroups.size() <= newann.graphGroup
2019 || newGraphGroups.get(newann.graphGroup) == null)
2021 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2023 newGraphGroups.add(q, null);
2025 newGraphGroups.set(newann.graphGroup, new Integer(
2028 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2032 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2037 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2044 // propagate alignment changed.
2045 viewport.setEndSeq(alignment.getHeight());
2046 if (annotationAdded)
2048 // Duplicate sequence annotation in all views.
2049 AlignmentI[] alview = this.getViewAlignments();
2050 for (int i = 0; i < sequences.length; i++)
2052 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2057 for (int avnum = 0; avnum < alview.length; avnum++)
2059 if (alview[avnum] != alignment)
2061 // duplicate in a view other than the one with input focus
2062 int avwidth = alview[avnum].getWidth() + 1;
2063 // this relies on sann being preserved after we
2064 // modify the sequence's annotation array for each duplication
2065 for (int a = 0; a < sann.length; a++)
2067 AlignmentAnnotation newann = new AlignmentAnnotation(
2069 sequences[i].addAlignmentAnnotation(newann);
2070 newann.padAnnotation(avwidth);
2071 alview[avnum].addAnnotation(newann); // annotation was
2072 // duplicated earlier
2073 // TODO JAL-1145 graphGroups are not updated for sequence
2074 // annotation added to several views. This may cause
2076 alview[avnum].setAnnotationIndex(newann, a);
2081 buildSortByAnnotationScoresMenu();
2083 viewport.firePropertyChange("alignment", null,
2084 alignment.getSequences());
2085 if (alignPanels != null)
2087 for (AlignmentPanel ap : ((Vector<AlignmentPanel>) alignPanels))
2089 ap.validateAnnotationDimensions(false);
2094 alignPanel.validateAnnotationDimensions(false);
2100 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2102 String newtitle = new String("Copied sequences");
2104 if (Desktop.jalviewClipboard != null
2105 && Desktop.jalviewClipboard[2] != null)
2107 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2108 for (int[] region : hc)
2110 af.viewport.hideColumns(region[0], region[1]);
2114 // >>>This is a fix for the moment, until a better solution is
2116 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2118 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
2120 // TODO: maintain provenance of an alignment, rather than just make the
2121 // title a concatenation of operations.
2124 if (title.startsWith("Copied sequences"))
2130 newtitle = newtitle.concat("- from " + title);
2135 newtitle = new String("Pasted sequences");
2138 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2143 } catch (Exception ex)
2145 ex.printStackTrace();
2146 System.out.println("Exception whilst pasting: " + ex);
2147 // could be anything being pasted in here
2153 protected void expand_newalign(ActionEvent e)
2157 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2158 .getAlignment(), -1);
2159 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2161 String newtitle = new String("Flanking alignment");
2163 if (Desktop.jalviewClipboard != null
2164 && Desktop.jalviewClipboard[2] != null)
2166 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2167 for (int region[] : hc)
2169 af.viewport.hideColumns(region[0], region[1]);
2173 // >>>This is a fix for the moment, until a better solution is
2175 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2177 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
2179 // TODO: maintain provenance of an alignment, rather than just make the
2180 // title a concatenation of operations.
2182 if (title.startsWith("Copied sequences"))
2188 newtitle = newtitle.concat("- from " + title);
2192 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2194 } catch (Exception ex)
2196 ex.printStackTrace();
2197 System.out.println("Exception whilst pasting: " + ex);
2198 // could be anything being pasted in here
2199 } catch (OutOfMemoryError oom)
2201 new OOMWarning("Viewing flanking region of alignment", oom);
2212 protected void cut_actionPerformed(ActionEvent e)
2214 copy_actionPerformed(null);
2215 delete_actionPerformed(null);
2225 protected void delete_actionPerformed(ActionEvent evt)
2228 SequenceGroup sg = viewport.getSelectionGroup();
2234 List<SequenceI> seqs = new ArrayList<SequenceI>(sg.getSize());
2236 for (int i = 0; i < sg.getSize(); i++)
2238 seq = sg.getSequenceAt(i);
2242 // If the cut affects all sequences, warn, remove highlighted columns
2243 if (sg.getSize() == viewport.getAlignment().getHeight())
2245 int confirm = JOptionPane.showConfirmDialog(this,
2246 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2247 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2248 JOptionPane.OK_CANCEL_OPTION);
2250 if (confirm == JOptionPane.CANCEL_OPTION
2251 || confirm == JOptionPane.CLOSED_OPTION)
2255 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2256 sg.getEndRes() + 1);
2259 SequenceI[] cut = new SequenceI[seqs.size()];
2260 for (int i = 0; i < seqs.size(); i++)
2262 cut[i] = seqs.get(i);
2266 * //ADD HISTORY ITEM
2268 addHistoryItem(new EditCommand(
2269 MessageManager.getString("label.cut_sequences"), Action.CUT,
2270 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2271 viewport.getAlignment()));
2273 viewport.setSelectionGroup(null);
2274 viewport.sendSelection();
2275 viewport.getAlignment().deleteGroup(sg);
2277 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2279 if (viewport.getAlignment().getHeight() < 1)
2283 this.setClosed(true);
2284 } catch (Exception ex)
2297 protected void deleteGroups_actionPerformed(ActionEvent e)
2299 if (avc.deleteGroups())
2301 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2302 alignPanel.updateAnnotation();
2303 alignPanel.paintAlignment(true);
2314 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2316 SequenceGroup sg = new SequenceGroup();
2318 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2320 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2323 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2324 viewport.setSelectionGroup(sg);
2325 viewport.sendSelection();
2326 alignPanel.paintAlignment(true);
2327 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2337 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2339 if (viewport.cursorMode)
2341 alignPanel.getSeqPanel().keyboardNo1 = null;
2342 alignPanel.getSeqPanel().keyboardNo2 = null;
2344 viewport.setSelectionGroup(null);
2345 viewport.getColumnSelection().clear();
2346 viewport.setSelectionGroup(null);
2347 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2348 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2349 alignPanel.paintAlignment(true);
2350 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2351 viewport.sendSelection();
2361 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2363 SequenceGroup sg = viewport.getSelectionGroup();
2367 selectAllSequenceMenuItem_actionPerformed(null);
2372 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2374 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2377 alignPanel.paintAlignment(true);
2378 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2379 viewport.sendSelection();
2383 public void invertColSel_actionPerformed(ActionEvent e)
2385 viewport.invertColumnSelection();
2386 alignPanel.paintAlignment(true);
2387 viewport.sendSelection();
2397 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2399 trimAlignment(true);
2409 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2411 trimAlignment(false);
2414 void trimAlignment(boolean trimLeft)
2416 ColumnSelection colSel = viewport.getColumnSelection();
2419 if (colSel.size() > 0)
2423 column = colSel.getMin();
2427 column = colSel.getMax();
2431 if (viewport.getSelectionGroup() != null)
2433 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2434 viewport.getHiddenRepSequences());
2438 seqs = viewport.getAlignment().getSequencesArray();
2441 TrimRegionCommand trimRegion;
2444 trimRegion = new TrimRegionCommand("Remove Left",
2445 TrimRegionCommand.TRIM_LEFT, seqs, column,
2446 viewport.getAlignment(), viewport.getColumnSelection(),
2447 viewport.getSelectionGroup());
2448 viewport.setStartRes(0);
2452 trimRegion = new TrimRegionCommand("Remove Right",
2453 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2454 viewport.getAlignment(), viewport.getColumnSelection(),
2455 viewport.getSelectionGroup());
2458 statusBar.setText(MessageManager.formatMessage(
2459 "label.removed_columns", new String[]
2460 { Integer.valueOf(trimRegion.getSize()).toString() }));
2462 addHistoryItem(trimRegion);
2464 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2466 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2467 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2469 viewport.getAlignment().deleteGroup(sg);
2473 viewport.firePropertyChange("alignment", null, viewport
2474 .getAlignment().getSequences());
2485 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2487 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2490 if (viewport.getSelectionGroup() != null)
2492 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2493 viewport.getHiddenRepSequences());
2494 start = viewport.getSelectionGroup().getStartRes();
2495 end = viewport.getSelectionGroup().getEndRes();
2499 seqs = viewport.getAlignment().getSequencesArray();
2502 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2503 "Remove Gapped Columns", seqs, start, end,
2504 viewport.getAlignment());
2506 addHistoryItem(removeGapCols);
2508 statusBar.setText(MessageManager.formatMessage(
2509 "label.removed_empty_columns", new String[]
2510 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2512 // This is to maintain viewport position on first residue
2513 // of first sequence
2514 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2515 int startRes = seq.findPosition(viewport.startRes);
2516 // ShiftList shifts;
2517 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2518 // edit.alColumnChanges=shifts.getInverse();
2519 // if (viewport.hasHiddenColumns)
2520 // viewport.getColumnSelection().compensateForEdits(shifts);
2521 viewport.setStartRes(seq.findIndex(startRes) - 1);
2522 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2534 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2536 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2539 if (viewport.getSelectionGroup() != null)
2541 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2542 viewport.getHiddenRepSequences());
2543 start = viewport.getSelectionGroup().getStartRes();
2544 end = viewport.getSelectionGroup().getEndRes();
2548 seqs = viewport.getAlignment().getSequencesArray();
2551 // This is to maintain viewport position on first residue
2552 // of first sequence
2553 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2554 int startRes = seq.findPosition(viewport.startRes);
2556 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2557 viewport.getAlignment()));
2559 viewport.setStartRes(seq.findIndex(startRes) - 1);
2561 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2573 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2575 viewport.setPadGaps(padGapsMenuitem.isSelected());
2576 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2582 // if (justifySeqs>0)
2584 // alignment.justify(justifySeqs!=RIGHT_JUSTIFY);
2597 public void findMenuItem_actionPerformed(ActionEvent e)
2603 public void newView_actionPerformed(ActionEvent e)
2610 * @param copyAnnotation
2611 * if true then duplicate all annnotation, groups and settings
2612 * @return new alignment panel, already displayed.
2614 public AlignmentPanel newView(boolean copyAnnotation)
2616 return newView(null, copyAnnotation);
2622 * title of newly created view
2623 * @return new alignment panel, already displayed.
2625 public AlignmentPanel newView(String viewTitle)
2627 return newView(viewTitle, true);
2633 * title of newly created view
2634 * @param copyAnnotation
2635 * if true then duplicate all annnotation, groups and settings
2636 * @return new alignment panel, already displayed.
2638 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2640 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2642 if (!copyAnnotation)
2644 // just remove all the current annotation except for the automatic stuff
2645 newap.av.getAlignment().deleteAllGroups();
2646 for (AlignmentAnnotation alan : newap.av.getAlignment()
2647 .getAlignmentAnnotation())
2649 if (!alan.autoCalculated)
2651 newap.av.getAlignment().deleteAnnotation(alan);
2657 newap.av.gatherViewsHere = false;
2659 if (viewport.viewName == null)
2661 viewport.viewName = "Original";
2664 newap.av.historyList = viewport.historyList;
2665 newap.av.redoList = viewport.redoList;
2667 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2668 // make sure the new view has a unique name - this is essential for Jalview
2670 boolean addFirstIndex = false;
2671 if (viewTitle == null || viewTitle.trim().length() == 0)
2673 viewTitle = MessageManager.getString("action.view");
2674 addFirstIndex = true;
2678 index = 1;// we count from 1 if given a specific name
2680 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2681 Vector comps = (Vector) PaintRefresher.components.get(viewport
2682 .getSequenceSetId());
2683 Vector existingNames = new Vector();
2684 for (int i = 0; i < comps.size(); i++)
2686 if (comps.elementAt(i) instanceof AlignmentPanel)
2688 AlignmentPanel ap = (AlignmentPanel) comps.elementAt(i);
2689 if (!existingNames.contains(ap.av.viewName))
2691 existingNames.addElement(ap.av.viewName);
2696 while (existingNames.contains(newViewName))
2698 newViewName = viewTitle + " " + (++index);
2701 newap.av.viewName = newViewName;
2703 addAlignmentPanel(newap, true);
2704 newap.alignmentChanged();
2706 if (alignPanels.size() == 2)
2708 viewport.gatherViewsHere = true;
2710 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2715 public void expandViews_actionPerformed(ActionEvent e)
2717 Desktop.instance.explodeViews(this);
2721 public void gatherViews_actionPerformed(ActionEvent e)
2723 Desktop.instance.gatherViews(this);
2733 public void font_actionPerformed(ActionEvent e)
2735 new FontChooser(alignPanel);
2745 protected void seqLimit_actionPerformed(ActionEvent e)
2747 viewport.setShowJVSuffix(seqLimits.isSelected());
2749 alignPanel.getIdPanel().getIdCanvas().setPreferredSize(alignPanel
2750 .calculateIdWidth());
2751 alignPanel.paintAlignment(true);
2755 public void idRightAlign_actionPerformed(ActionEvent e)
2757 viewport.setRightAlignIds(idRightAlign.isSelected());
2758 alignPanel.paintAlignment(true);
2762 public void centreColumnLabels_actionPerformed(ActionEvent e)
2764 viewport.centreColumnLabels = centreColumnLabelsMenuItem.getState();
2765 alignPanel.paintAlignment(true);
2771 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2774 protected void followHighlight_actionPerformed()
2776 if (viewport.followHighlight = this.followHighlightMenuItem.getState())
2778 alignPanel.scrollToPosition(
2779 alignPanel.getSeqPanel().seqCanvas.searchResults, false);
2790 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2792 viewport.setColourText(colourTextMenuItem.isSelected());
2793 alignPanel.paintAlignment(true);
2803 public void wrapMenuItem_actionPerformed(ActionEvent e)
2805 scaleAbove.setVisible(wrapMenuItem.isSelected());
2806 scaleLeft.setVisible(wrapMenuItem.isSelected());
2807 scaleRight.setVisible(wrapMenuItem.isSelected());
2808 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2809 alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2813 public void showAllSeqs_actionPerformed(ActionEvent e)
2815 viewport.showAllHiddenSeqs();
2819 public void showAllColumns_actionPerformed(ActionEvent e)
2821 viewport.showAllHiddenColumns();
2826 public void hideSelSequences_actionPerformed(ActionEvent e)
2828 viewport.hideAllSelectedSeqs();
2829 alignPanel.paintAlignment(true);
2833 * called by key handler and the hide all/show all menu items
2838 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2841 boolean hide = false;
2842 SequenceGroup sg = viewport.getSelectionGroup();
2843 if (!toggleSeqs && !toggleCols)
2845 // Hide everything by the current selection - this is a hack - we do the
2846 // invert and then hide
2847 // first check that there will be visible columns after the invert.
2848 if ((viewport.getColumnSelection() != null
2849 && viewport.getColumnSelection().getSelected() != null && viewport
2850 .getColumnSelection().getSelected().size() > 0)
2851 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2854 // now invert the sequence set, if required - empty selection implies
2855 // that no hiding is required.
2858 invertSequenceMenuItem_actionPerformed(null);
2859 sg = viewport.getSelectionGroup();
2863 viewport.expandColSelection(sg, true);
2864 // finally invert the column selection and get the new sequence
2866 invertColSel_actionPerformed(null);
2873 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
2875 hideSelSequences_actionPerformed(null);
2878 else if (!(toggleCols && viewport.getColumnSelection().getSelected()
2881 showAllSeqs_actionPerformed(null);
2887 if (viewport.getColumnSelection().getSelected().size() > 0)
2889 hideSelColumns_actionPerformed(null);
2892 viewport.setSelectionGroup(sg);
2897 showAllColumns_actionPerformed(null);
2906 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
2907 * event.ActionEvent)
2910 public void hideAllButSelection_actionPerformed(ActionEvent e)
2912 toggleHiddenRegions(false, false);
2919 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
2923 public void hideAllSelection_actionPerformed(ActionEvent e)
2925 SequenceGroup sg = viewport.getSelectionGroup();
2926 viewport.expandColSelection(sg, false);
2927 viewport.hideAllSelectedSeqs();
2928 viewport.hideSelectedColumns();
2929 alignPanel.paintAlignment(true);
2936 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
2940 public void showAllhidden_actionPerformed(ActionEvent e)
2942 viewport.showAllHiddenColumns();
2943 viewport.showAllHiddenSeqs();
2944 alignPanel.paintAlignment(true);
2948 public void hideSelColumns_actionPerformed(ActionEvent e)
2950 viewport.hideSelectedColumns();
2951 alignPanel.paintAlignment(true);
2955 public void hiddenMarkers_actionPerformed(ActionEvent e)
2957 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
2968 protected void scaleAbove_actionPerformed(ActionEvent e)
2970 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
2971 alignPanel.paintAlignment(true);
2981 protected void scaleLeft_actionPerformed(ActionEvent e)
2983 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
2984 alignPanel.paintAlignment(true);
2994 protected void scaleRight_actionPerformed(ActionEvent e)
2996 viewport.setScaleRightWrapped(scaleRight.isSelected());
2997 alignPanel.paintAlignment(true);
3007 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3009 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3010 alignPanel.paintAlignment(true);
3020 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3022 viewport.setShowText(viewTextMenuItem.isSelected());
3023 alignPanel.paintAlignment(true);
3033 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3035 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3036 alignPanel.paintAlignment(true);
3039 public FeatureSettings featureSettings;
3042 public void featureSettings_actionPerformed(ActionEvent e)
3044 if (featureSettings != null)
3046 featureSettings.close();
3047 featureSettings = null;
3049 if (!showSeqFeatures.isSelected())
3051 // make sure features are actually displayed
3052 showSeqFeatures.setSelected(true);
3053 showSeqFeatures_actionPerformed(null);
3055 featureSettings = new FeatureSettings(this);
3059 * Set or clear 'Show Sequence Features'
3065 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3067 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3068 alignPanel.paintAlignment(true);
3069 if (alignPanel.getOverviewPanel() != null)
3071 alignPanel.getOverviewPanel().updateOverviewImage();
3076 * Set or clear 'Show Sequence Features'
3082 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
3084 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
3086 if (viewport.isShowSequenceFeaturesHeight())
3088 // ensure we're actually displaying features
3089 viewport.setShowSequenceFeatures(true);
3090 showSeqFeatures.setSelected(true);
3092 alignPanel.paintAlignment(true);
3093 if (alignPanel.getOverviewPanel() != null)
3095 alignPanel.getOverviewPanel().updateOverviewImage();
3100 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3101 * the annotations panel as a whole.
3103 * The options to show/hide all annotations should be enabled when the panel
3104 * is shown, and disabled when the panel is hidden.
3109 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3111 final boolean setVisible = annotationPanelMenuItem.isSelected();
3112 viewport.setShowAnnotation(setVisible);
3113 alignPanel.setAnnotationVisible(setVisible);
3114 this.showAllSeqAnnotations.setEnabled(setVisible);
3115 this.hideAllSeqAnnotations.setEnabled(setVisible);
3116 this.showAllAlAnnotations.setEnabled(setVisible);
3117 this.hideAllAlAnnotations.setEnabled(setVisible);
3121 public void alignmentProperties()
3123 JEditorPane editPane = new JEditorPane("text/html", "");
3124 editPane.setEditable(false);
3125 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3127 editPane.setText(MessageManager.formatMessage("label.html_content",
3129 { contents.toString() }));
3130 JInternalFrame frame = new JInternalFrame();
3131 frame.getContentPane().add(new JScrollPane(editPane));
3133 Desktop.instance.addInternalFrame(frame, MessageManager.formatMessage(
3134 "label.alignment_properties", new String[]
3135 { getTitle() }), 500, 400);
3145 public void overviewMenuItem_actionPerformed(ActionEvent e)
3147 if (alignPanel.overviewPanel != null)
3152 JInternalFrame frame = new JInternalFrame();
3153 OverviewPanel overview = new OverviewPanel(alignPanel);
3154 frame.setContentPane(overview);
3155 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3156 "label.overview_params", new String[]
3157 { this.getTitle() }), frame.getWidth(), frame.getHeight());
3159 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3160 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3163 public void internalFrameClosed(
3164 javax.swing.event.InternalFrameEvent evt)
3166 alignPanel.setOverviewPanel(null);
3170 alignPanel.setOverviewPanel(overview);
3174 public void textColour_actionPerformed(ActionEvent e)
3176 new TextColourChooser().chooseColour(alignPanel, null);
3186 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3198 public void clustalColour_actionPerformed(ActionEvent e)
3200 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3201 viewport.getHiddenRepSequences()));
3211 public void zappoColour_actionPerformed(ActionEvent e)
3213 changeColour(new ZappoColourScheme());
3223 public void taylorColour_actionPerformed(ActionEvent e)
3225 changeColour(new TaylorColourScheme());
3235 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3237 changeColour(new HydrophobicColourScheme());
3247 public void helixColour_actionPerformed(ActionEvent e)
3249 changeColour(new HelixColourScheme());
3259 public void strandColour_actionPerformed(ActionEvent e)
3261 changeColour(new StrandColourScheme());
3271 public void turnColour_actionPerformed(ActionEvent e)
3273 changeColour(new TurnColourScheme());
3283 public void buriedColour_actionPerformed(ActionEvent e)
3285 changeColour(new BuriedColourScheme());
3295 public void nucleotideColour_actionPerformed(ActionEvent e)
3297 changeColour(new NucleotideColourScheme());
3301 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3303 changeColour(new PurinePyrimidineColourScheme());
3307 * public void covariationColour_actionPerformed(ActionEvent e) {
3309 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3313 public void annotationColour_actionPerformed(ActionEvent e)
3315 new AnnotationColourChooser(viewport, alignPanel);
3319 public void annotationColumn_actionPerformed(ActionEvent e)
3321 new AnnotationColumnChooser(viewport, alignPanel);
3325 public void rnahelicesColour_actionPerformed(ActionEvent e)
3327 new RNAHelicesColourChooser(viewport, alignPanel);
3337 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3339 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3348 public void changeColour(ColourSchemeI cs)
3350 // TODO: compare with applet and pull up to model method
3355 if (viewport.getAbovePIDThreshold())
3357 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3359 cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3363 cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3366 if (viewport.getConservationSelected())
3369 Alignment al = (Alignment) viewport.getAlignment();
3370 Conservation c = new Conservation("All",
3371 ResidueProperties.propHash, 3, al.getSequences(), 0,
3375 c.verdict(false, viewport.getConsPercGaps());
3377 cs.setConservation(c);
3379 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3384 cs.setConservation(null);
3387 cs.setConsensus(viewport.getSequenceConsensusHash());
3390 viewport.setGlobalColourScheme(cs);
3392 if (viewport.getColourAppliesToAllGroups())
3395 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3403 if (cs instanceof ClustalxColourScheme)
3405 sg.cs = new ClustalxColourScheme(sg,
3406 viewport.getHiddenRepSequences());
3408 else if (cs instanceof UserColourScheme)
3410 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
3416 sg.cs = cs.getClass().newInstance();
3417 } catch (Exception ex)
3422 if (viewport.getAbovePIDThreshold()
3423 || cs instanceof PIDColourScheme
3424 || cs instanceof Blosum62ColourScheme)
3426 sg.cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3428 sg.cs.setConsensus(AAFrequency.calculate(
3429 sg.getSequences(viewport.getHiddenRepSequences()),
3430 sg.getStartRes(), sg.getEndRes() + 1));
3434 sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3437 if (viewport.getConservationSelected())
3439 Conservation c = new Conservation("Group",
3440 ResidueProperties.propHash, 3, sg.getSequences(viewport
3441 .getHiddenRepSequences()), sg.getStartRes(),
3442 sg.getEndRes() + 1);
3444 c.verdict(false, viewport.getConsPercGaps());
3445 sg.cs.setConservation(c);
3449 sg.cs.setConservation(null);
3454 if (alignPanel.getOverviewPanel() != null)
3456 alignPanel.getOverviewPanel().updateOverviewImage();
3459 alignPanel.paintAlignment(true);
3469 protected void modifyPID_actionPerformed(ActionEvent e)
3471 if (viewport.getAbovePIDThreshold()
3472 && viewport.getGlobalColourScheme() != null)
3474 SliderPanel.setPIDSliderSource(alignPanel,
3475 viewport.getGlobalColourScheme(), "Background");
3476 SliderPanel.showPIDSlider();
3487 protected void modifyConservation_actionPerformed(ActionEvent e)
3489 if (viewport.getConservationSelected()
3490 && viewport.getGlobalColourScheme() != null)
3492 SliderPanel.setConservationSlider(alignPanel,
3493 viewport.getGlobalColourScheme(), "Background");
3494 SliderPanel.showConservationSlider();
3505 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3507 viewport.setConservationSelected(conservationMenuItem.isSelected());
3509 viewport.setAbovePIDThreshold(false);
3510 abovePIDThreshold.setSelected(false);
3512 changeColour(viewport.getGlobalColourScheme());
3514 modifyConservation_actionPerformed(null);
3524 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3526 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3528 conservationMenuItem.setSelected(false);
3529 viewport.setConservationSelected(false);
3531 changeColour(viewport.getGlobalColourScheme());
3533 modifyPID_actionPerformed(null);
3543 public void userDefinedColour_actionPerformed(ActionEvent e)
3545 if (e.getActionCommand().equals(
3546 MessageManager.getString("action.user_defined")))
3548 new UserDefinedColours(alignPanel, null);
3552 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3553 .getUserColourSchemes().get(e.getActionCommand());
3559 public void updateUserColourMenu()
3562 Component[] menuItems = colourMenu.getMenuComponents();
3563 int i, iSize = menuItems.length;
3564 for (i = 0; i < iSize; i++)
3566 if (menuItems[i].getName() != null
3567 && menuItems[i].getName().equals("USER_DEFINED"))
3569 colourMenu.remove(menuItems[i]);
3573 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3575 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3576 .getUserColourSchemes().keys();
3578 while (userColours.hasMoreElements())
3580 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3581 userColours.nextElement().toString());
3582 radioItem.setName("USER_DEFINED");
3583 radioItem.addMouseListener(new MouseAdapter()
3586 public void mousePressed(MouseEvent evt)
3588 if (evt.isControlDown()
3589 || SwingUtilities.isRightMouseButton(evt))
3591 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3593 int option = JOptionPane.showInternalConfirmDialog(
3594 jalview.gui.Desktop.desktop,
3596 .getString("label.remove_from_default_list"),
3598 .getString("label.remove_user_defined_colour"),
3599 JOptionPane.YES_NO_OPTION);
3600 if (option == JOptionPane.YES_OPTION)
3602 jalview.gui.UserDefinedColours
3603 .removeColourFromDefaults(radioItem.getText());
3604 colourMenu.remove(radioItem);
3608 radioItem.addActionListener(new ActionListener()
3611 public void actionPerformed(ActionEvent evt)
3613 userDefinedColour_actionPerformed(evt);
3620 radioItem.addActionListener(new ActionListener()
3623 public void actionPerformed(ActionEvent evt)
3625 userDefinedColour_actionPerformed(evt);
3629 colourMenu.insert(radioItem, 15);
3630 colours.add(radioItem);
3642 public void PIDColour_actionPerformed(ActionEvent e)
3644 changeColour(new PIDColourScheme());
3654 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3656 changeColour(new Blosum62ColourScheme());
3666 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3668 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3669 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3670 .getAlignment().getSequenceAt(0), null);
3671 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3672 viewport.getAlignment()));
3673 alignPanel.paintAlignment(true);
3683 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3685 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3686 AlignmentSorter.sortByID(viewport.getAlignment());
3687 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3688 viewport.getAlignment()));
3689 alignPanel.paintAlignment(true);
3699 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3701 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3702 AlignmentSorter.sortByLength(viewport.getAlignment());
3703 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3704 viewport.getAlignment()));
3705 alignPanel.paintAlignment(true);
3715 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3717 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3718 AlignmentSorter.sortByGroup(viewport.getAlignment());
3719 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3720 viewport.getAlignment()));
3722 alignPanel.paintAlignment(true);
3732 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3734 new RedundancyPanel(alignPanel, this);
3744 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3746 if ((viewport.getSelectionGroup() == null)
3747 || (viewport.getSelectionGroup().getSize() < 2))
3749 JOptionPane.showInternalMessageDialog(this, MessageManager
3750 .getString("label.you_must_select_least_two_sequences"),
3751 MessageManager.getString("label.invalid_selection"),
3752 JOptionPane.WARNING_MESSAGE);
3756 JInternalFrame frame = new JInternalFrame();
3757 frame.setContentPane(new PairwiseAlignPanel(viewport));
3758 Desktop.addInternalFrame(frame,
3759 MessageManager.getString("action.pairwise_alignment"), 600,
3771 public void PCAMenuItem_actionPerformed(ActionEvent e)
3773 if (((viewport.getSelectionGroup() != null)
3774 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3775 .getSelectionGroup().getSize() > 0))
3776 || (viewport.getAlignment().getHeight() < 4))
3779 .showInternalMessageDialog(
3782 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3784 .getString("label.sequence_selection_insufficient"),
3785 JOptionPane.WARNING_MESSAGE);
3790 new PCAPanel(alignPanel);
3794 public void autoCalculate_actionPerformed(ActionEvent e)
3796 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3797 if (viewport.autoCalculateConsensus)
3799 viewport.firePropertyChange("alignment", null, viewport
3800 .getAlignment().getSequences());
3805 public void sortByTreeOption_actionPerformed(ActionEvent e)
3807 viewport.sortByTree = sortByTree.isSelected();
3811 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3813 viewport.followSelection = listenToViewSelections.isSelected();
3823 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3825 NewTreePanel("AV", "PID", "Average distance tree using PID");
3835 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3837 NewTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3847 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3849 NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3859 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3861 NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3874 void NewTreePanel(String type, String pwType, String title)
3878 if (viewport.getSelectionGroup() != null
3879 && viewport.getSelectionGroup().getSize() > 0)
3881 if (viewport.getSelectionGroup().getSize() < 3)
3887 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3889 .getString("label.not_enough_sequences"),
3890 JOptionPane.WARNING_MESSAGE);
3894 SequenceGroup sg = viewport.getSelectionGroup();
3896 /* Decide if the selection is a column region */
3897 for (SequenceI _s : sg.getSequences())
3899 if (_s.getLength() < sg.getEndRes())
3905 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3907 .getString("label.sequences_selection_not_aligned"),
3908 JOptionPane.WARNING_MESSAGE);
3914 title = title + " on region";
3915 tp = new TreePanel(alignPanel, type, pwType);
3919 // are the visible sequences aligned?
3920 if (!viewport.getAlignment().isAligned(false))
3926 .getString("label.sequences_must_be_aligned_before_creating_tree"),
3928 .getString("label.sequences_not_aligned"),
3929 JOptionPane.WARNING_MESSAGE);
3934 if (viewport.getAlignment().getHeight() < 2)
3939 tp = new TreePanel(alignPanel, type, pwType);
3944 if (viewport.viewName != null)
3946 title += viewport.viewName + " of ";
3949 title += this.title;
3951 Desktop.addInternalFrame(tp, title, 600, 500);
3962 public void addSortByOrderMenuItem(String title,
3963 final AlignmentOrder order)
3965 final JMenuItem item = new JMenuItem(MessageManager.formatMessage("action.by_title_param", new String[]{title}));
3967 item.addActionListener(new java.awt.event.ActionListener()
3970 public void actionPerformed(ActionEvent e)
3972 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3974 // TODO: JBPNote - have to map order entries to curent SequenceI
3976 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3978 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
3981 alignPanel.paintAlignment(true);
3987 * Add a new sort by annotation score menu item
3990 * the menu to add the option to
3992 * the label used to retrieve scores for each sequence on the
3995 public void addSortByAnnotScoreMenuItem(JMenu sort,
3996 final String scoreLabel)
3998 final JMenuItem item = new JMenuItem(scoreLabel);
4000 item.addActionListener(new java.awt.event.ActionListener()
4003 public void actionPerformed(ActionEvent e)
4005 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4006 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4007 viewport.getAlignment());// ,viewport.getSelectionGroup());
4008 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4009 viewport.getAlignment()));
4010 alignPanel.paintAlignment(true);
4016 * last hash for alignment's annotation array - used to minimise cost of
4019 protected int _annotationScoreVectorHash;
4022 * search the alignment and rebuild the sort by annotation score submenu the
4023 * last alignment annotation vector hash is stored to minimize cost of
4024 * rebuilding in subsequence calls.
4028 public void buildSortByAnnotationScoresMenu()
4030 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4035 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4037 sortByAnnotScore.removeAll();
4038 // almost certainly a quicker way to do this - but we keep it simple
4039 Hashtable scoreSorts = new Hashtable();
4040 AlignmentAnnotation aann[];
4041 for (SequenceI sqa : viewport.getAlignment().getSequences())
4043 aann = sqa.getAnnotation();
4044 for (int i = 0; aann != null && i < aann.length; i++)
4046 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4048 scoreSorts.put(aann[i].label, aann[i].label);
4052 Enumeration labels = scoreSorts.keys();
4053 while (labels.hasMoreElements())
4055 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4056 (String) labels.nextElement());
4058 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4061 _annotationScoreVectorHash = viewport.getAlignment()
4062 .getAlignmentAnnotation().hashCode();
4067 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4068 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4069 * call. Listeners are added to remove the menu item when the treePanel is
4070 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4074 * Displayed tree window.
4076 * SortBy menu item title.
4079 public void buildTreeMenu()
4081 calculateTree.removeAll();
4082 // build the calculate menu
4084 for (final String type : new String[]
4087 String treecalcnm = MessageManager.getString("label.tree_calc_"
4088 + type.toLowerCase());
4089 for (final Object pwtype : ResidueProperties.scoreMatrices.keySet())
4091 JMenuItem tm = new JMenuItem();
4092 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4093 if (sm.isProtein() == !viewport.getAlignment().isNucleotide())
4095 String smn = MessageManager.getStringOrReturn(
4096 "label.score_model_", sm.getName());
4097 final String title = MessageManager.formatMessage(
4098 "label.treecalc_title", treecalcnm, smn);
4099 tm.setText(title);//
4100 tm.addActionListener(new java.awt.event.ActionListener()
4103 public void actionPerformed(ActionEvent e)
4105 NewTreePanel(type, (String) pwtype, title);
4108 calculateTree.add(tm);
4113 sortByTreeMenu.removeAll();
4115 Vector comps = (Vector) PaintRefresher.components.get(viewport
4116 .getSequenceSetId());
4117 Vector treePanels = new Vector();
4118 int i, iSize = comps.size();
4119 for (i = 0; i < iSize; i++)
4121 if (comps.elementAt(i) instanceof TreePanel)
4123 treePanels.add(comps.elementAt(i));
4127 iSize = treePanels.size();
4131 sortByTreeMenu.setVisible(false);
4135 sortByTreeMenu.setVisible(true);
4137 for (i = 0; i < treePanels.size(); i++)
4139 final TreePanel tp = (TreePanel) treePanels.elementAt(i);
4140 final JMenuItem item = new JMenuItem(tp.getTitle());
4141 final NJTree tree = ((TreePanel) treePanels.elementAt(i)).getTree();
4142 item.addActionListener(new java.awt.event.ActionListener()
4145 public void actionPerformed(ActionEvent e)
4147 tp.sortByTree_actionPerformed(null);
4148 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4153 sortByTreeMenu.add(item);
4157 public boolean sortBy(AlignmentOrder alorder, String undoname)
4159 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4160 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4161 if (undoname != null)
4163 addHistoryItem(new OrderCommand(undoname, oldOrder,
4164 viewport.getAlignment()));
4166 alignPanel.paintAlignment(true);
4171 * Work out whether the whole set of sequences or just the selected set will
4172 * be submitted for multiple alignment.
4175 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4177 // Now, check we have enough sequences
4178 AlignmentView msa = null;
4180 if ((viewport.getSelectionGroup() != null)
4181 && (viewport.getSelectionGroup().getSize() > 1))
4183 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4184 // some common interface!
4186 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4187 * SequenceI[sz = seqs.getSize(false)];
4189 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4190 * seqs.getSequenceAt(i); }
4192 msa = viewport.getAlignmentView(true);
4194 else if (viewport.getSelectionGroup() != null
4195 && viewport.getSelectionGroup().getSize() == 1)
4197 int option = JOptionPane.showConfirmDialog(this,
4198 MessageManager.getString("warn.oneseq_msainput_selection"),
4199 MessageManager.getString("label.invalid_selection"),
4200 JOptionPane.OK_CANCEL_OPTION);
4201 if (option == JOptionPane.OK_OPTION)
4203 msa = viewport.getAlignmentView(false);
4208 msa = viewport.getAlignmentView(false);
4214 * Decides what is submitted to a secondary structure prediction service: the
4215 * first sequence in the alignment, or in the current selection, or, if the
4216 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4217 * region or the whole alignment. (where the first sequence in the set is the
4218 * one that the prediction will be for).
4220 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4222 AlignmentView seqs = null;
4224 if ((viewport.getSelectionGroup() != null)
4225 && (viewport.getSelectionGroup().getSize() > 0))
4227 seqs = viewport.getAlignmentView(true);
4231 seqs = viewport.getAlignmentView(false);
4233 // limit sequences - JBPNote in future - could spawn multiple prediction
4235 // TODO: viewport.getAlignment().isAligned is a global state - the local
4236 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4237 if (!viewport.getAlignment().isAligned(false))
4239 seqs.setSequences(new SeqCigar[]
4240 { seqs.getSequences()[0] });
4241 // TODO: if seqs.getSequences().length>1 then should really have warned
4255 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
4257 // Pick the tree file
4258 JalviewFileChooser chooser = new JalviewFileChooser(
4259 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4260 chooser.setFileView(new JalviewFileView());
4261 chooser.setDialogTitle(MessageManager
4262 .getString("label.select_newick_like_tree_file"));
4263 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4265 int value = chooser.showOpenDialog(null);
4267 if (value == JalviewFileChooser.APPROVE_OPTION)
4269 String choice = chooser.getSelectedFile().getPath();
4270 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4271 jalview.io.NewickFile fin = null;
4274 fin = new jalview.io.NewickFile(choice, "File");
4275 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4276 } catch (Exception ex)
4283 .getString("label.problem_reading_tree_file"),
4284 JOptionPane.WARNING_MESSAGE);
4285 ex.printStackTrace();
4287 if (fin != null && fin.hasWarningMessage())
4289 JOptionPane.showMessageDialog(Desktop.desktop, fin
4290 .getWarningMessage(), MessageManager
4291 .getString("label.possible_problem_with_tree_file"),
4292 JOptionPane.WARNING_MESSAGE);
4298 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4300 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4303 public TreePanel ShowNewickTree(NewickFile nf, String title)
4305 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4308 public TreePanel ShowNewickTree(NewickFile nf, String title,
4309 AlignmentView input)
4311 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4314 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4315 int h, int x, int y)
4317 return ShowNewickTree(nf, title, null, w, h, x, y);
4321 * Add a treeviewer for the tree extracted from a newick file object to the
4322 * current alignment view
4329 * Associated alignment input data (or null)
4338 * @return TreePanel handle
4340 public TreePanel ShowNewickTree(NewickFile nf, String title,
4341 AlignmentView input, int w, int h, int x, int y)
4343 TreePanel tp = null;
4349 if (nf.getTree() != null)
4351 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4357 tp.setLocation(x, y);
4360 Desktop.addInternalFrame(tp, title, w, h);
4362 } catch (Exception ex)
4364 ex.printStackTrace();
4370 private boolean buildingMenu = false;
4373 * Generates menu items and listener event actions for web service clients
4376 public void BuildWebServiceMenu()
4378 while (buildingMenu)
4382 System.err.println("Waiting for building menu to finish.");
4384 } catch (Exception e)
4389 final AlignFrame me = this;
4390 buildingMenu = true;
4391 new Thread(new Runnable()
4396 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4399 System.err.println("Building ws menu again "
4400 + Thread.currentThread());
4401 // TODO: add support for context dependent disabling of services based
4403 // alignment and current selection
4404 // TODO: add additional serviceHandle parameter to specify abstract
4406 // class independently of AbstractName
4407 // TODO: add in rediscovery GUI function to restart discoverer
4408 // TODO: group services by location as well as function and/or
4410 // object broker mechanism.
4411 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4412 final IProgressIndicator af = me;
4413 final JMenu msawsmenu = new JMenu("Alignment");
4414 final JMenu secstrmenu = new JMenu(
4415 "Secondary Structure Prediction");
4416 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4417 final JMenu analymenu = new JMenu("Analysis");
4418 final JMenu dismenu = new JMenu("Protein Disorder");
4419 // final JMenu msawsmenu = new
4420 // JMenu(MessageManager.getString("label.alignment"));
4421 // final JMenu secstrmenu = new
4422 // JMenu(MessageManager.getString("label.secondary_structure_prediction"));
4423 // final JMenu seqsrchmenu = new
4424 // JMenu(MessageManager.getString("label.sequence_database_search"));
4425 // final JMenu analymenu = new
4426 // JMenu(MessageManager.getString("label.analysis"));
4427 // final JMenu dismenu = new
4428 // JMenu(MessageManager.getString("label.protein_disorder"));
4429 // JAL-940 - only show secondary structure prediction services from
4430 // the legacy server
4431 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4433 Discoverer.services != null && (Discoverer.services.size() > 0))
4435 // TODO: refactor to allow list of AbstractName/Handler bindings to
4437 // stored or retrieved from elsewhere
4438 // No MSAWS used any more:
4439 // Vector msaws = null; // (Vector)
4440 // Discoverer.services.get("MsaWS");
4441 Vector secstrpr = (Vector) Discoverer.services
4443 if (secstrpr != null)
4445 // Add any secondary structure prediction services
4446 for (int i = 0, j = secstrpr.size(); i < j; i++)
4448 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4450 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4451 .getServiceClient(sh);
4452 int p = secstrmenu.getItemCount();
4453 impl.attachWSMenuEntry(secstrmenu, me);
4454 int q = secstrmenu.getItemCount();
4455 for (int litm = p; litm < q; litm++)
4457 legacyItems.add(secstrmenu.getItem(litm));
4463 // Add all submenus in the order they should appear on the web
4465 wsmenu.add(msawsmenu);
4466 wsmenu.add(secstrmenu);
4467 wsmenu.add(dismenu);
4468 wsmenu.add(analymenu);
4469 // No search services yet
4470 // wsmenu.add(seqsrchmenu);
4472 javax.swing.SwingUtilities.invokeLater(new Runnable()
4479 webService.removeAll();
4480 // first, add discovered services onto the webservices menu
4481 if (wsmenu.size() > 0)
4483 for (int i = 0, j = wsmenu.size(); i < j; i++)
4485 webService.add(wsmenu.get(i));
4490 webService.add(me.webServiceNoServices);
4492 // TODO: move into separate menu builder class.
4493 boolean new_sspred = false;
4494 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4496 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4497 if (jws2servs != null)
4499 if (jws2servs.hasServices())
4501 jws2servs.attachWSMenuEntry(webService, me);
4502 for (Jws2Instance sv : jws2servs.getServices())
4504 if (sv.description.toLowerCase().contains("jpred"))
4506 for (JMenuItem jmi : legacyItems)
4508 jmi.setVisible(false);
4514 if (jws2servs.isRunning())
4516 JMenuItem tm = new JMenuItem(
4517 "Still discovering JABA Services");
4518 tm.setEnabled(false);
4523 build_urlServiceMenu(me.webService);
4524 build_fetchdbmenu(webService);
4525 for (JMenu item : wsmenu)
4527 if (item.getItemCount() == 0)
4529 item.setEnabled(false);
4533 item.setEnabled(true);
4536 } catch (Exception e)
4539 .debug("Exception during web service menu building process.",
4545 } catch (Exception e)
4550 buildingMenu = false;
4557 * construct any groupURL type service menu entries.
4561 private void build_urlServiceMenu(JMenu webService)
4563 // TODO: remove this code when 2.7 is released
4564 // DEBUG - alignmentView
4566 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4567 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4569 * @Override public void actionPerformed(ActionEvent e) {
4570 * jalview.datamodel.AlignmentView
4571 * .testSelectionViews(af.viewport.getAlignment(),
4572 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4574 * }); webService.add(testAlView);
4576 // TODO: refactor to RestClient discoverer and merge menu entries for
4577 // rest-style services with other types of analysis/calculation service
4578 // SHmmr test client - still being implemented.
4579 // DEBUG - alignmentView
4581 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4584 client.attachWSMenuEntry(
4585 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4591 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
4592 * chooser = new JalviewFileChooser(jalview.bin.Cache.
4593 * getProperty("LAST_DIRECTORY"));
4595 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
4596 * to Vamsas file"); chooser.setToolTipText("Export");
4598 * int value = chooser.showSaveDialog(this);
4600 * if (value == JalviewFileChooser.APPROVE_OPTION) {
4601 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
4602 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
4603 * chooser.getSelectedFile().getAbsolutePath(), this); } }
4606 * prototype of an automatically enabled/disabled analysis function
4609 protected void setShowProductsEnabled()
4611 SequenceI[] selection = viewport.getSequenceSelection();
4612 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
4613 viewport.getAlignment().getDataset()))
4615 showProducts.setEnabled(true);
4620 showProducts.setEnabled(false);
4625 * search selection for sequence xRef products and build the show products
4630 * @return true if showProducts menu should be enabled.
4632 public boolean canShowProducts(SequenceI[] selection,
4633 boolean isRegionSelection, Alignment dataset)
4635 boolean showp = false;
4638 showProducts.removeAll();
4639 final boolean dna = viewport.getAlignment().isNucleotide();
4640 final Alignment ds = dataset;
4641 String[] ptypes = (selection == null || selection.length == 0) ? null
4642 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4644 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4645 // selection, dataset, true);
4646 final SequenceI[] sel = selection;
4647 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4650 final boolean isRegSel = isRegionSelection;
4651 final AlignFrame af = this;
4652 final String source = ptypes[t];
4653 JMenuItem xtype = new JMenuItem(ptypes[t]);
4654 xtype.addActionListener(new ActionListener()
4658 public void actionPerformed(ActionEvent e)
4660 // TODO: new thread for this call with vis-delay
4661 af.showProductsFor(af.viewport.getSequenceSelection(), ds,
4662 isRegSel, dna, source);
4666 showProducts.add(xtype);
4668 showProducts.setVisible(showp);
4669 showProducts.setEnabled(showp);
4670 } catch (Exception e)
4672 jalview.bin.Cache.log
4673 .warn("canTranslate threw an exception - please report to help@jalview.org",
4680 protected void showProductsFor(SequenceI[] sel, Alignment ds,
4681 boolean isRegSel, boolean dna, String source)
4683 final boolean fisRegSel = isRegSel;
4684 final boolean fdna = dna;
4685 final String fsrc = source;
4686 final AlignFrame ths = this;
4687 final SequenceI[] fsel = sel;
4688 Runnable foo = new Runnable()
4694 final long sttime = System.currentTimeMillis();
4695 ths.setProgressBar(MessageManager.formatMessage("status.searching_for_sequences_from", new String[]{fsrc}), sttime);
4698 Alignment ds = ths.getViewport().getAlignment().getDataset(); // update
4702 Alignment prods = CrossRef
4703 .findXrefSequences(fsel, fdna, fsrc, ds);
4706 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4707 for (int s = 0; s < sprods.length; s++)
4709 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4710 if (ds.getSequences() == null
4711 || !ds.getSequences().contains(
4712 sprods[s].getDatasetSequence()))
4714 ds.addSequence(sprods[s].getDatasetSequence());
4716 sprods[s].updatePDBIds();
4718 Alignment al = new Alignment(sprods);
4719 AlignedCodonFrame[] cf = prods.getCodonFrames();
4721 for (int s = 0; cf != null && s < cf.length; s++)
4723 al.addCodonFrame(cf[s]);
4726 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4728 String newtitle = "" + ((fdna) ? "Proteins " : "Nucleotides ")
4729 + " for " + ((fisRegSel) ? "selected region of " : "")
4731 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4736 System.err.println("No Sequences generated for xRef type "
4739 } catch (Exception e)
4741 jalview.bin.Cache.log.error(
4742 "Exception when finding crossreferences", e);
4743 } catch (OutOfMemoryError e)
4745 new OOMWarning("whilst fetching crossreferences", e);
4748 jalview.bin.Cache.log.error("Error when finding crossreferences",
4751 ths.setProgressBar(MessageManager.formatMessage("status.finished_searching_for_sequences_from", new String[]{fsrc}),
4756 Thread frunner = new Thread(foo);
4760 public boolean canShowTranslationProducts(SequenceI[] selection,
4761 AlignmentI alignment)
4766 return (jalview.analysis.Dna.canTranslate(selection,
4767 viewport.getViewAsVisibleContigs(true)));
4768 } catch (Exception e)
4770 jalview.bin.Cache.log
4771 .warn("canTranslate threw an exception - please report to help@jalview.org",
4778 public void showProducts_actionPerformed(ActionEvent e)
4780 // /////////////////////////////
4781 // Collect Data to be translated/transferred
4783 SequenceI[] selection = viewport.getSequenceSelection();
4784 AlignmentI al = null;
4787 al = jalview.analysis.Dna.CdnaTranslate(selection, viewport
4788 .getViewAsVisibleContigs(true), viewport.getGapCharacter(),
4789 viewport.getAlignment().getDataset());
4790 } catch (Exception ex)
4793 jalview.bin.Cache.log.debug("Exception during translation.", ex);
4801 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation"),
4802 MessageManager.getString("label.translation_failed"),
4803 JOptionPane.WARNING_MESSAGE);
4807 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4808 Desktop.addInternalFrame(af, MessageManager.formatMessage(
4809 "label.translation_of_params", new String[]
4810 { this.getTitle() }), DEFAULT_WIDTH, DEFAULT_HEIGHT);
4815 public void showTranslation_actionPerformed(ActionEvent e)
4817 // /////////////////////////////
4818 // Collect Data to be translated/transferred
4820 SequenceI[] selection = viewport.getSequenceSelection();
4821 String[] seqstring = viewport.getViewAsString(true);
4822 AlignmentI al = null;
4825 al = jalview.analysis.Dna.CdnaTranslate(selection, seqstring,
4826 viewport.getViewAsVisibleContigs(true), viewport
4827 .getGapCharacter(), viewport.getAlignment()
4828 .getAlignmentAnnotation(), viewport.getAlignment()
4829 .getWidth(), viewport.getAlignment().getDataset());
4830 } catch (Exception ex)
4833 jalview.bin.Cache.log.error(
4834 "Exception during translation. Please report this !", ex);
4839 .getString("label.error_when_translating_sequences_submit_bug_report"),
4841 .getString("label.implementation_error")
4843 .getString("translation_failed"),
4844 JOptionPane.ERROR_MESSAGE);
4853 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation"),
4854 MessageManager.getString("label.translation_failed"),
4855 JOptionPane.WARNING_MESSAGE);
4859 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4860 Desktop.addInternalFrame(af, MessageManager.formatMessage(
4861 "label.translation_of_params", new String[]
4862 { this.getTitle() }), DEFAULT_WIDTH, DEFAULT_HEIGHT);
4867 * Try to load a features file onto the alignment.
4870 * contents or path to retrieve file
4872 * access mode of file (see jalview.io.AlignFile)
4873 * @return true if features file was parsed corectly.
4875 public boolean parseFeaturesFile(String file, String type)
4877 boolean featuresFile = false;
4880 featuresFile = new FeaturesFile(file, type).parse(viewport
4881 .getAlignment().getDataset(), alignPanel.getSeqPanel().seqCanvas
4882 .getFeatureRenderer().getFeatureColours(), false,
4883 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4884 } catch (Exception ex)
4886 ex.printStackTrace();
4891 viewport.setShowSequenceFeatures(true);
4892 showSeqFeatures.setSelected(true);
4893 if (alignPanel.getSeqPanel().seqCanvas.fr != null)
4895 // update the min/max ranges where necessary
4896 alignPanel.getSeqPanel().seqCanvas.fr.findAllFeatures(true);
4898 if (featureSettings != null)
4900 featureSettings.setTableData();
4902 alignPanel.paintAlignment(true);
4905 return featuresFile;
4909 public void dragEnter(DropTargetDragEvent evt)
4914 public void dragExit(DropTargetEvent evt)
4919 public void dragOver(DropTargetDragEvent evt)
4924 public void dropActionChanged(DropTargetDragEvent evt)
4929 public void drop(DropTargetDropEvent evt)
4931 Transferable t = evt.getTransferable();
4932 java.util.List files = null;
4936 DataFlavor uriListFlavor = new DataFlavor(
4937 "text/uri-list;class=java.lang.String");
4938 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
4940 // Works on Windows and MacOSX
4941 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4942 files = (java.util.List) t
4943 .getTransferData(DataFlavor.javaFileListFlavor);
4945 else if (t.isDataFlavorSupported(uriListFlavor))
4947 // This is used by Unix drag system
4948 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4949 String data = (String) t.getTransferData(uriListFlavor);
4950 files = new java.util.ArrayList(1);
4951 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
4952 data, "\r\n"); st.hasMoreTokens();)
4954 String s = st.nextToken();
4955 if (s.startsWith("#"))
4957 // the line is a comment (as per the RFC 2483)
4961 java.net.URI uri = new java.net.URI(s);
4962 // check to see if we can handle this kind of URI
4963 if (uri.getScheme().toLowerCase().startsWith("http"))
4965 files.add(uri.toString());
4969 // otherwise preserve old behaviour: catch all for file objects
4970 java.io.File file = new java.io.File(uri);
4971 files.add(file.toString());
4975 } catch (Exception e)
4977 e.printStackTrace();
4983 // check to see if any of these files have names matching sequences in
4985 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4986 .getAlignment().getSequencesArray());
4988 * Object[] { String,SequenceI}
4990 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
4991 ArrayList<String> filesnotmatched = new ArrayList<String>();
4992 for (int i = 0; i < files.size(); i++)
4994 String file = files.get(i).toString();
4996 String protocol = FormatAdapter.checkProtocol(file);
4997 if (protocol == jalview.io.FormatAdapter.FILE)
4999 File fl = new File(file);
5000 pdbfn = fl.getName();
5002 else if (protocol == jalview.io.FormatAdapter.URL)
5004 URL url = new URL(file);
5005 pdbfn = url.getFile();
5007 if (pdbfn.length() > 0)
5009 // attempt to find a match in the alignment
5010 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5011 int l = 0, c = pdbfn.indexOf(".");
5012 while (mtch == null && c != -1)
5017 } while ((c = pdbfn.indexOf(".", l)) > l);
5020 pdbfn = pdbfn.substring(0, l);
5022 mtch = idm.findAllIdMatches(pdbfn);
5029 type = new IdentifyFile().Identify(file, protocol);
5030 } catch (Exception ex)
5036 if (type.equalsIgnoreCase("PDB"))
5038 filesmatched.add(new Object[]
5039 { file, protocol, mtch });
5044 // File wasn't named like one of the sequences or wasn't a PDB file.
5045 filesnotmatched.add(file);
5049 if (filesmatched.size() > 0)
5051 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
5057 "label.automatically_associate_pdb_files_with_sequences_same_name",
5064 .getString("label.automatically_associate_pdb_files_by_name"),
5065 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
5068 for (Object[] fm : filesmatched)
5070 // try and associate
5071 // TODO: may want to set a standard ID naming formalism for
5072 // associating PDB files which have no IDs.
5073 for (SequenceI toassoc : (SequenceI[]) fm[2])
5075 PDBEntry pe = new AssociatePdbFileWithSeq()
5076 .associatePdbWithSeq((String) fm[0],
5077 (String) fm[1], toassoc, false,
5081 System.err.println("Associated file : "
5082 + ((String) fm[0]) + " with "
5083 + toassoc.getDisplayId(true));
5087 alignPanel.paintAlignment(true);
5091 if (filesnotmatched.size() > 0)
5094 && (Cache.getDefault(
5095 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
5098 "<html>"+MessageManager
5100 "label.ignore_unmatched_dropped_files_info",
5105 .toString() })+"</html>",
5107 .getString("label.ignore_unmatched_dropped_files"),
5108 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
5112 for (String fn : filesnotmatched)
5114 loadJalviewDataFile(fn, null, null, null);
5118 } catch (Exception ex)
5120 ex.printStackTrace();
5126 * Attempt to load a "dropped" file or URL string: First by testing whether
5127 * it's and Annotation file, then a JNet file, and finally a features file. If
5128 * all are false then the user may have dropped an alignment file onto this
5132 * either a filename or a URL string.
5134 public void loadJalviewDataFile(String file, String protocol,
5135 String format, SequenceI assocSeq)
5139 if (protocol == null)
5141 protocol = jalview.io.FormatAdapter.checkProtocol(file);
5143 // if the file isn't identified, or not positively identified as some
5144 // other filetype (PFAM is default unidentified alignment file type) then
5145 // try to parse as annotation.
5146 boolean isAnnotation = (format == null || format
5147 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
5148 .annotateAlignmentView(viewport, file, protocol)
5153 // first see if its a T-COFFEE score file
5154 TCoffeeScoreFile tcf = null;
5157 tcf = new TCoffeeScoreFile(file, protocol);
5160 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5162 tcoffeeColour.setEnabled(true);
5163 tcoffeeColour.setSelected(true);
5164 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5165 isAnnotation = true;
5167 .setText(MessageManager
5168 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5172 // some problem - if no warning its probable that the ID matching
5173 // process didn't work
5177 tcf.getWarningMessage() == null ? MessageManager
5178 .getString("label.check_file_matches_sequence_ids_alignment")
5179 : tcf.getWarningMessage(),
5181 .getString("label.problem_reading_tcoffee_score_file"),
5182 JOptionPane.WARNING_MESSAGE);
5189 } catch (Exception x)
5192 .debug("Exception when processing data source as T-COFFEE score file",
5198 // try to see if its a JNet 'concise' style annotation file *before*
5200 // try to parse it as a features file
5203 format = new IdentifyFile().Identify(file, protocol);
5205 if (format.equalsIgnoreCase("JnetFile"))
5207 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5209 new JnetAnnotationMaker().add_annotation(predictions,
5210 viewport.getAlignment(), 0, false);
5211 isAnnotation = true;
5216 * if (format.equalsIgnoreCase("PDB")) {
5218 * String pdbfn = ""; // try to match up filename with sequence id
5219 * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
5220 * new File(file); pdbfn = fl.getName(); } else if (protocol ==
5221 * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
5222 * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
5223 * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5224 * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
5225 * // attempt to find a match in the alignment SequenceI mtch =
5226 * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
5227 * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
5228 * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
5229 * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
5230 * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
5231 * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
5232 * { System.err.println("Associated file : " + file + " with " +
5233 * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
5234 * TODO: maybe need to load as normal otherwise return; } }
5236 // try to parse it as a features file
5237 boolean isGroupsFile = parseFeaturesFile(file, protocol);
5238 // if it wasn't a features file then we just treat it as a general
5239 // alignment file to load into the current view.
5242 new FileLoader().LoadFile(viewport, file, protocol, format);
5246 alignPanel.paintAlignment(true);
5254 alignPanel.adjustAnnotationHeight();
5255 viewport.updateSequenceIdColours();
5256 buildSortByAnnotationScoresMenu();
5257 alignPanel.paintAlignment(true);
5259 } catch (Exception ex)
5261 ex.printStackTrace();
5262 } catch (OutOfMemoryError oom)
5267 } catch (Exception x)
5273 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5274 : "using " + protocol + " from " + file)
5276 + (format != null ? "(parsing as '" + format
5277 + "' file)" : ""), oom, Desktop.desktop);
5282 public void tabSelectionChanged(int index)
5286 alignPanel = (AlignmentPanel) alignPanels.elementAt(index);
5287 viewport = alignPanel.av;
5288 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5289 setMenusFromViewport(viewport);
5294 public void tabbedPane_mousePressed(MouseEvent e)
5296 if (SwingUtilities.isRightMouseButton(e))
5298 String reply = JOptionPane.showInternalInputDialog(this,
5299 MessageManager.getString("label.enter_view_name"),
5300 MessageManager.getString("label.enter_view_name"),
5301 JOptionPane.QUESTION_MESSAGE);
5305 viewport.viewName = reply;
5306 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5311 public AlignViewport getCurrentView()
5317 * Open the dialog for regex description parsing.
5320 protected void extractScores_actionPerformed(ActionEvent e)
5322 ParseProperties pp = new jalview.analysis.ParseProperties(
5323 viewport.getAlignment());
5324 // TODO: verify regex and introduce GUI dialog for version 2.5
5325 // if (pp.getScoresFromDescription("col", "score column ",
5326 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5328 if (pp.getScoresFromDescription("description column",
5329 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5331 buildSortByAnnotationScoresMenu();
5339 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5343 protected void showDbRefs_actionPerformed(ActionEvent e)
5345 viewport.setShowDbRefs(showDbRefsMenuitem.isSelected());
5351 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5355 protected void showNpFeats_actionPerformed(ActionEvent e)
5357 viewport.setShowNpFeats(showNpFeatsMenuitem.isSelected());
5361 * find the viewport amongst the tabs in this alignment frame and close that
5366 public boolean closeView(AlignViewport av)
5370 this.closeMenuItem_actionPerformed(false);
5373 Component[] comp = tabbedPane.getComponents();
5374 for (int i = 0; comp != null && i < comp.length; i++)
5376 if (comp[i] instanceof AlignmentPanel)
5378 if (((AlignmentPanel) comp[i]).av == av)
5381 closeView((AlignmentPanel) comp[i]);
5389 protected void build_fetchdbmenu(JMenu webService)
5391 // Temporary hack - DBRef Fetcher always top level ws entry.
5392 // TODO We probably want to store a sequence database checklist in
5393 // preferences and have checkboxes.. rather than individual sources selected
5395 final JMenu rfetch = new JMenu(
5396 MessageManager.getString("action.fetch_db_references"));
5397 rfetch.setToolTipText(MessageManager
5398 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5399 webService.add(rfetch);
5401 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5402 MessageManager.getString("option.trim_retrieved_seqs"));
5403 trimrs.setToolTipText(MessageManager
5404 .getString("label.trim_retrieved_sequences"));
5405 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5406 trimrs.addActionListener(new ActionListener()
5409 public void actionPerformed(ActionEvent e)
5411 trimrs.setSelected(trimrs.isSelected());
5412 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5413 Boolean.valueOf(trimrs.isSelected()).toString());
5417 JMenuItem fetchr = new JMenuItem(
5418 MessageManager.getString("label.standard_databases"));
5419 fetchr.setToolTipText(MessageManager
5420 .getString("label.fetch_embl_uniprot"));
5421 fetchr.addActionListener(new ActionListener()
5425 public void actionPerformed(ActionEvent e)
5427 new Thread(new Runnable()
5433 new jalview.ws.DBRefFetcher(alignPanel.av
5434 .getSequenceSelection(), alignPanel.alignFrame)
5435 .fetchDBRefs(false);
5443 final AlignFrame me = this;
5444 new Thread(new Runnable()
5449 final jalview.ws.SequenceFetcher sf = SequenceFetcher
5450 .getSequenceFetcherSingleton(me);
5451 javax.swing.SwingUtilities.invokeLater(new Runnable()
5456 String[] dbclasses = sf.getOrderedSupportedSources();
5457 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5458 // jalview.util.QuickSort.sort(otherdb, otherdb);
5459 List<DbSourceProxy> otherdb;
5460 JMenu dfetch = new JMenu();
5461 JMenu ifetch = new JMenu();
5462 JMenuItem fetchr = null;
5463 int comp = 0, icomp = 0, mcomp = 15;
5464 String mname = null;
5466 for (String dbclass : dbclasses)
5468 otherdb = sf.getSourceProxy(dbclass);
5469 // add a single entry for this class, or submenu allowing 'fetch
5471 if (otherdb == null || otherdb.size() < 1)
5475 // List<DbSourceProxy> dbs=otherdb;
5476 // otherdb=new ArrayList<DbSourceProxy>();
5477 // for (DbSourceProxy db:dbs)
5479 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5483 mname = "From " + dbclass;
5485 if (otherdb.size() == 1)
5487 final DbSourceProxy[] dassource = otherdb
5488 .toArray(new DbSourceProxy[0]);
5489 DbSourceProxy src = otherdb.get(0);
5490 fetchr = new JMenuItem(src.getDbSource());
5491 fetchr.addActionListener(new ActionListener()
5495 public void actionPerformed(ActionEvent e)
5497 new Thread(new Runnable()
5503 new jalview.ws.DBRefFetcher(alignPanel.av
5504 .getSequenceSelection(),
5505 alignPanel.alignFrame, dassource)
5506 .fetchDBRefs(false);
5512 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from", new String[]{src.getDbName()})));
5518 final DbSourceProxy[] dassource = otherdb
5519 .toArray(new DbSourceProxy[0]);
5521 DbSourceProxy src = otherdb.get(0);
5522 fetchr = new JMenuItem(MessageManager.formatMessage(
5523 "label.fetch_all_param", new String[]
5524 { src.getDbSource() }));
5525 fetchr.addActionListener(new ActionListener()
5528 public void actionPerformed(ActionEvent e)
5530 new Thread(new Runnable()
5536 new jalview.ws.DBRefFetcher(alignPanel.av
5537 .getSequenceSelection(),
5538 alignPanel.alignFrame, dassource)
5539 .fetchDBRefs(false);
5545 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from_all_sources", new String[]{Integer.valueOf(otherdb.size()).toString(), src.getDbSource(), src.getDbName()})));
5548 // and then build the rest of the individual menus
5549 ifetch = new JMenu(MessageManager.formatMessage("label.source_from_db_source", new String[]{src.getDbSource()}));
5551 String imname = null;
5553 for (DbSourceProxy sproxy : otherdb)
5555 String dbname = sproxy.getDbName();
5556 String sname = dbname.length() > 5 ? dbname.substring(0,
5557 5) + "..." : dbname;
5558 String msname = dbname.length() > 10 ? dbname.substring(
5559 0, 10) + "..." : dbname;
5562 imname = MessageManager.formatMessage("label.from_msname", new String[]{sname});
5564 fetchr = new JMenuItem(msname);
5565 final DbSourceProxy[] dassrc =
5567 fetchr.addActionListener(new ActionListener()
5571 public void actionPerformed(ActionEvent e)
5573 new Thread(new Runnable()
5579 new jalview.ws.DBRefFetcher(alignPanel.av
5580 .getSequenceSelection(),
5581 alignPanel.alignFrame, dassrc)
5582 .fetchDBRefs(false);
5588 fetchr.setToolTipText("<html>"
5589 + MessageManager.formatMessage("label.fetch_retrieve_from", new String[]{dbname}));
5592 if (++icomp >= mcomp || i == (otherdb.size()))
5594 ifetch.setText(MessageManager.formatMessage(
5595 "label.source_to_target", imname, sname));
5597 ifetch = new JMenu();
5605 if (comp >= mcomp || dbi >= (dbclasses.length))
5607 dfetch.setText(MessageManager.formatMessage(
5608 "label.source_to_target", mname, dbclass));
5610 dfetch = new JMenu();
5623 * Left justify the whole alignment.
5626 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5628 AlignmentI al = viewport.getAlignment();
5630 viewport.firePropertyChange("alignment", null, al);
5634 * Right justify the whole alignment.
5637 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5639 AlignmentI al = viewport.getAlignment();
5641 viewport.firePropertyChange("alignment", null, al);
5644 public void setShowSeqFeatures(boolean b)
5646 showSeqFeatures.setSelected(true);
5647 viewport.setShowSequenceFeatures(true);
5654 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5655 * awt.event.ActionEvent)
5658 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5660 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5661 alignPanel.paintAlignment(true);
5668 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5672 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5674 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5675 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5683 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5684 * .event.ActionEvent)
5687 protected void showGroupConservation_actionPerformed(ActionEvent e)
5689 viewport.setShowGroupConservation(showGroupConservation.getState());
5690 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5697 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5698 * .event.ActionEvent)
5701 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5703 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5704 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5711 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5712 * .event.ActionEvent)
5715 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5717 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5718 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5722 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5724 showSequenceLogo.setState(true);
5725 viewport.setShowSequenceLogo(true);
5726 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5727 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5731 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5733 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5740 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5741 * .event.ActionEvent)
5744 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5746 if (avc.makeGroupsFromSelection())
5748 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5749 alignPanel.updateAnnotation();
5750 alignPanel.paintAlignment(true);
5753 public void clearAlignmentSeqRep()
5755 // TODO refactor alignmentseqrep to controller
5756 if (viewport.getAlignment().hasSeqrep()) {
5757 viewport.getAlignment().setSeqrep(null);
5758 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5759 alignPanel.updateAnnotation();
5760 alignPanel.paintAlignment(true);
5765 protected void createGroup_actionPerformed(ActionEvent e)
5767 if (avc.createGroup())
5769 alignPanel.alignmentChanged();
5774 protected void unGroup_actionPerformed(ActionEvent e)
5778 alignPanel.alignmentChanged();
5783 * make the given alignmentPanel the currently selected tab
5785 * @param alignmentPanel
5787 public void setDisplayedView(AlignmentPanel alignmentPanel)
5789 if (!viewport.getSequenceSetId().equals(
5790 alignmentPanel.av.getSequenceSetId()))
5792 throw new Error(MessageManager.getString("error.implementation_error_cannot_show_view_alignment_frame"));
5794 if (tabbedPane != null
5795 & alignPanels.indexOf(alignmentPanel) != tabbedPane
5796 .getSelectedIndex())
5798 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5803 * Action on selection of menu options to Show or Hide annotations.
5806 * @param forSequences
5807 * update sequence-related annotations
5808 * @param forAlignment
5809 * update non-sequence-related annotations
5812 protected void setAnnotationsVisibility(boolean visible,
5813 boolean forSequences, boolean forAlignment)
5815 for (AlignmentAnnotation aa : alignPanel.getAlignment()
5816 .getAlignmentAnnotation())
5818 boolean apply = (aa.sequenceRef == null && forAlignment)
5819 || (aa.sequenceRef != null && forSequences);
5822 aa.visible = visible;
5825 alignPanel.validateAnnotationDimensions(false);
5826 alignPanel.alignmentChanged();
5830 * Store selected annotation sort order for the view and repaint.
5833 protected void sortAnnotations_actionPerformed()
5835 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5837 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5838 alignPanel.paintAlignment(true);
5843 * @return alignment panels in this alignemnt frame
5845 public List<AlignmentViewPanel> getAlignPanels()
5847 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5851 class PrintThread extends Thread
5855 public PrintThread(AlignmentPanel ap)
5860 static PageFormat pf;
5865 PrinterJob printJob = PrinterJob.getPrinterJob();
5869 printJob.setPrintable(ap, pf);
5873 printJob.setPrintable(ap);
5876 if (printJob.printDialog())
5881 } catch (Exception PrintException)
5883 PrintException.printStackTrace();