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.HTMLOutput;
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.seqPanel.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.seqPanel.moveCursor(0, 1);
408 if (evt.isAltDown() || !viewport.cursorMode)
410 moveSelectedSequences(true);
412 if (viewport.cursorMode)
414 alignPanel.seqPanel.moveCursor(0, -1);
419 case KeyEvent.VK_LEFT:
420 if (evt.isAltDown() || !viewport.cursorMode)
422 slideSequences(false, alignPanel.seqPanel.getKeyboardNo1());
426 alignPanel.seqPanel.moveCursor(-1, 0);
431 case KeyEvent.VK_RIGHT:
432 if (evt.isAltDown() || !viewport.cursorMode)
434 slideSequences(true, alignPanel.seqPanel.getKeyboardNo1());
438 alignPanel.seqPanel.moveCursor(1, 0);
442 case KeyEvent.VK_SPACE:
443 if (viewport.cursorMode)
445 alignPanel.seqPanel.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.seqPanel.deleteGapAtCursor(evt.isControlDown()
470 || evt.isShiftDown() || evt.isAltDown());
476 if (viewport.cursorMode)
478 alignPanel.seqPanel.setCursorRow();
482 if (viewport.cursorMode && !evt.isControlDown())
484 alignPanel.seqPanel.setCursorColumn();
488 if (viewport.cursorMode)
490 alignPanel.seqPanel.setCursorPosition();
494 case KeyEvent.VK_ENTER:
495 case KeyEvent.VK_COMMA:
496 if (viewport.cursorMode)
498 alignPanel.seqPanel.setCursorRowAndColumn();
503 if (viewport.cursorMode)
505 alignPanel.seqPanel.setSelectionAreaAtCursor(true);
509 if (viewport.cursorMode)
511 alignPanel.seqPanel.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.seqPanel.seqCanvas.cursorX = viewport.startRes;
523 alignPanel.seqPanel.seqCanvas.cursorY = viewport.startSeq;
525 alignPanel.seqPanel.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.rightAlignIds);
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.showAnnotation);
753 * Show/hide annotations only enabled if annotation panel is shown
755 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
756 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
757 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
758 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
759 viewBoxesMenuItem.setSelected(av.showBoxes);
760 viewTextMenuItem.setSelected(av.showText);
761 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
762 showGroupConsensus.setSelected(av.isShowGroupConsensus());
763 showGroupConservation.setSelected(av.isShowGroupConservation());
764 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
765 showSequenceLogo.setSelected(av.isShowSequenceLogo());
766 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
768 setColourSelected(ColourSchemeProperty.getColourName(av
769 .getGlobalColourScheme()));
771 showSeqFeatures.setSelected(av.showSequenceFeatures);
772 hiddenMarkers.setState(av.showHiddenMarkers);
773 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
774 showNpFeatsMenuitem.setSelected(av.isShowNpFeats());
775 showDbRefsMenuitem.setSelected(av.isShowDbRefs());
776 autoCalculate.setSelected(av.autoCalculateConsensus);
777 sortByTree.setSelected(av.sortByTree);
778 listenToViewSelections.setSelected(av.followSelection);
779 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
781 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
782 setShowProductsEnabled();
786 // methods for implementing IProgressIndicator
787 // need to refactor to a reusable stub class
788 Hashtable progressBars, progressBarHandlers;
793 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
796 public void setProgressBar(String message, long id)
798 if (progressBars == null)
800 progressBars = new Hashtable();
801 progressBarHandlers = new Hashtable();
804 JPanel progressPanel;
805 Long lId = new Long(id);
806 GridLayout layout = (GridLayout) statusPanel.getLayout();
807 if (progressBars.get(lId) != null)
809 progressPanel = (JPanel) progressBars.get(new Long(id));
810 statusPanel.remove(progressPanel);
811 progressBars.remove(lId);
812 progressPanel = null;
815 statusBar.setText(message);
817 if (progressBarHandlers.contains(lId))
819 progressBarHandlers.remove(lId);
821 layout.setRows(layout.getRows() - 1);
825 progressPanel = new JPanel(new BorderLayout(10, 5));
827 JProgressBar progressBar = new JProgressBar();
828 progressBar.setIndeterminate(true);
830 progressPanel.add(new JLabel(message), BorderLayout.WEST);
831 progressPanel.add(progressBar, BorderLayout.CENTER);
833 layout.setRows(layout.getRows() + 1);
834 statusPanel.add(progressPanel);
836 progressBars.put(lId, progressPanel);
839 // setMenusForViewport();
844 public void registerHandler(final long id,
845 final IProgressIndicatorHandler handler)
847 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
849 throw new Error(MessageManager.getString("error.call_setprogressbar_before_registering_handler"));
851 progressBarHandlers.put(new Long(id), handler);
852 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
853 if (handler.canCancel())
855 JButton cancel = new JButton(
856 MessageManager.getString("action.cancel"));
857 final IProgressIndicator us = this;
858 cancel.addActionListener(new ActionListener()
862 public void actionPerformed(ActionEvent e)
864 handler.cancelActivity(id);
865 us.setProgressBar(MessageManager.formatMessage("label.cancelled_params", new String[]{((JLabel) progressPanel.getComponent(0)).getText()}), id);
868 progressPanel.add(cancel, BorderLayout.EAST);
874 * @return true if any progress bars are still active
877 public boolean operationInProgress()
879 if (progressBars != null && progressBars.size() > 0)
887 public void setStatus(String text)
889 statusBar.setText(text);
893 * Added so Castor Mapping file can obtain Jalview Version
895 public String getVersion()
897 return jalview.bin.Cache.getProperty("VERSION");
900 public FeatureRenderer getFeatureRenderer()
902 return alignPanel.seqPanel.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.seqPanel.seqCanvas.getSequenceRenderer(),
1235 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
1239 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1241 new BioJsHTMLOutput(alignPanel,
1242 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
1244 public void createImageMap(File file, String image)
1246 alignPanel.makePNGImageMap(file, image);
1256 public void createPNG(File f)
1258 alignPanel.makePNG(f);
1268 public void createEPS(File f)
1270 alignPanel.makeEPS(f);
1273 public void createSVG(File f)
1275 alignPanel.makeSVG(f);
1278 public void pageSetup_actionPerformed(ActionEvent e)
1280 PrinterJob printJob = PrinterJob.getPrinterJob();
1281 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1291 public void printMenuItem_actionPerformed(ActionEvent e)
1293 // Putting in a thread avoids Swing painting problems
1294 PrintThread thread = new PrintThread(alignPanel);
1299 public void exportFeatures_actionPerformed(ActionEvent e)
1301 new AnnotationExporter().exportFeatures(alignPanel);
1305 public void exportAnnotations_actionPerformed(ActionEvent e)
1307 new AnnotationExporter().exportAnnotations(alignPanel,
1308 viewport.showAnnotation ? viewport.getAlignment()
1309 .getAlignmentAnnotation() : null, viewport
1310 .getAlignment().getGroups(), ((Alignment) viewport
1311 .getAlignment()).alignmentProperties);
1315 public void associatedData_actionPerformed(ActionEvent e)
1317 // Pick the tree file
1318 JalviewFileChooser chooser = new JalviewFileChooser(
1319 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1320 chooser.setFileView(new JalviewFileView());
1321 chooser.setDialogTitle(MessageManager
1322 .getString("label.load_jalview_annotations"));
1323 chooser.setToolTipText(MessageManager
1324 .getString("label.load_jalview_annotations"));
1326 int value = chooser.showOpenDialog(null);
1328 if (value == JalviewFileChooser.APPROVE_OPTION)
1330 String choice = chooser.getSelectedFile().getPath();
1331 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1332 loadJalviewDataFile(choice, null, null, null);
1338 * Close the current view or all views in the alignment frame. If the frame
1339 * only contains one view then the alignment will be removed from memory.
1341 * @param closeAllTabs
1344 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1346 if (alignPanels != null && alignPanels.size() < 2)
1348 closeAllTabs = true;
1353 if (alignPanels != null)
1357 if (this.isClosed())
1359 // really close all the windows - otherwise wait till
1360 // setClosed(true) is called
1361 for (int i = 0; i < alignPanels.size(); i++)
1363 AlignmentPanel ap = (AlignmentPanel) alignPanels.elementAt(i);
1370 closeView(alignPanel);
1376 this.setClosed(true);
1378 } catch (Exception ex)
1380 ex.printStackTrace();
1385 * close alignPanel2 and shuffle tabs appropriately.
1387 * @param alignPanel2
1389 public void closeView(AlignmentPanel alignPanel2)
1391 int index = tabbedPane.getSelectedIndex();
1392 int closedindex = tabbedPane.indexOfComponent(alignPanel2);
1393 alignPanels.removeElement(alignPanel2);
1395 // if (viewport == alignPanel2.av)
1399 alignPanel2.closePanel();
1402 tabbedPane.removeTabAt(closedindex);
1403 tabbedPane.validate();
1405 if (index > closedindex || index == tabbedPane.getTabCount())
1407 // modify currently selected tab index if necessary.
1411 this.tabSelectionChanged(index);
1417 void updateEditMenuBar()
1420 if (viewport.historyList.size() > 0)
1422 undoMenuItem.setEnabled(true);
1423 CommandI command = viewport.historyList.peek();
1424 undoMenuItem.setText(MessageManager.formatMessage(
1425 "label.undo_command", new String[]
1426 { command.getDescription() }));
1430 undoMenuItem.setEnabled(false);
1431 undoMenuItem.setText(MessageManager.getString("action.undo"));
1434 if (viewport.redoList.size() > 0)
1436 redoMenuItem.setEnabled(true);
1438 CommandI command = viewport.redoList.peek();
1439 redoMenuItem.setText(MessageManager.formatMessage(
1440 "label.redo_command", new String[]
1441 { command.getDescription() }));
1445 redoMenuItem.setEnabled(false);
1446 redoMenuItem.setText(MessageManager.getString("action.redo"));
1450 public void addHistoryItem(CommandI command)
1452 if (command.getSize() > 0)
1454 viewport.historyList.push(command);
1455 viewport.redoList.clear();
1456 updateEditMenuBar();
1457 viewport.updateHiddenColumns();
1458 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1459 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1460 // viewport.getColumnSelection()
1461 // .getHiddenColumns().size() > 0);
1467 * @return alignment objects for all views
1469 AlignmentI[] getViewAlignments()
1471 if (alignPanels != null)
1473 Enumeration e = alignPanels.elements();
1474 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1475 for (int i = 0; e.hasMoreElements(); i++)
1477 als[i] = ((AlignmentPanel) e.nextElement()).av.getAlignment();
1481 if (viewport != null)
1483 return new AlignmentI[]
1484 { viewport.getAlignment() };
1496 protected void undoMenuItem_actionPerformed(ActionEvent e)
1498 if (viewport.historyList.empty())
1502 CommandI command = viewport.historyList.pop();
1503 viewport.redoList.push(command);
1504 command.undoCommand(getViewAlignments());
1506 AlignViewport originalSource = getOriginatingSource(command);
1507 updateEditMenuBar();
1509 if (originalSource != null)
1511 if (originalSource != viewport)
1514 .warn("Implementation worry: mismatch of viewport origin for undo");
1516 originalSource.updateHiddenColumns();
1517 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1519 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1520 // viewport.getColumnSelection()
1521 // .getHiddenColumns().size() > 0);
1522 originalSource.firePropertyChange("alignment", null, originalSource
1523 .getAlignment().getSequences());
1534 protected void redoMenuItem_actionPerformed(ActionEvent e)
1536 if (viewport.redoList.size() < 1)
1541 CommandI command = viewport.redoList.pop();
1542 viewport.historyList.push(command);
1543 command.doCommand(getViewAlignments());
1545 AlignViewport originalSource = getOriginatingSource(command);
1546 updateEditMenuBar();
1548 if (originalSource != null)
1551 if (originalSource != viewport)
1554 .warn("Implementation worry: mismatch of viewport origin for redo");
1556 originalSource.updateHiddenColumns();
1557 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1559 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1560 // viewport.getColumnSelection()
1561 // .getHiddenColumns().size() > 0);
1562 originalSource.firePropertyChange("alignment", null, originalSource
1563 .getAlignment().getSequences());
1567 AlignViewport getOriginatingSource(CommandI command)
1569 AlignViewport originalSource = null;
1570 // For sequence removal and addition, we need to fire
1571 // the property change event FROM the viewport where the
1572 // original alignment was altered
1573 AlignmentI al = null;
1574 if (command instanceof EditCommand)
1576 EditCommand editCommand = (EditCommand) command;
1577 al = editCommand.getAlignment();
1578 Vector comps = (Vector) PaintRefresher.components.get(viewport
1579 .getSequenceSetId());
1581 for (int i = 0; i < comps.size(); i++)
1583 if (comps.elementAt(i) instanceof AlignmentPanel)
1585 if (al == ((AlignmentPanel) comps.elementAt(i)).av.getAlignment())
1587 originalSource = ((AlignmentPanel) comps.elementAt(i)).av;
1594 if (originalSource == null)
1596 // The original view is closed, we must validate
1597 // the current view against the closed view first
1600 PaintRefresher.validateSequences(al, viewport.getAlignment());
1603 originalSource = viewport;
1606 return originalSource;
1615 public void moveSelectedSequences(boolean up)
1617 SequenceGroup sg = viewport.getSelectionGroup();
1623 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1624 viewport.getHiddenRepSequences(), up);
1625 alignPanel.paintAlignment(true);
1628 synchronized void slideSequences(boolean right, int size)
1630 List<SequenceI> sg = new Vector();
1631 if (viewport.cursorMode)
1633 sg.add(viewport.getAlignment().getSequenceAt(
1634 alignPanel.seqPanel.seqCanvas.cursorY));
1636 else if (viewport.getSelectionGroup() != null
1637 && viewport.getSelectionGroup().getSize() != viewport
1638 .getAlignment().getHeight())
1640 sg = viewport.getSelectionGroup().getSequences(
1641 viewport.getHiddenRepSequences());
1649 Vector invertGroup = new Vector();
1651 for (int i = 0; i < viewport.getAlignment().getHeight(); i++)
1653 if (!sg.contains(viewport.getAlignment().getSequenceAt(i)))
1655 invertGroup.add(viewport.getAlignment().getSequenceAt(i));
1659 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1661 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1662 for (int i = 0; i < invertGroup.size(); i++)
1664 seqs2[i] = (SequenceI) invertGroup.elementAt(i);
1667 SlideSequencesCommand ssc;
1670 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1671 size, viewport.getGapCharacter());
1675 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1676 size, viewport.getGapCharacter());
1679 int groupAdjustment = 0;
1680 if (ssc.getGapsInsertedBegin() && right)
1682 if (viewport.cursorMode)
1684 alignPanel.seqPanel.moveCursor(size, 0);
1688 groupAdjustment = size;
1691 else if (!ssc.getGapsInsertedBegin() && !right)
1693 if (viewport.cursorMode)
1695 alignPanel.seqPanel.moveCursor(-size, 0);
1699 groupAdjustment = -size;
1703 if (groupAdjustment != 0)
1705 viewport.getSelectionGroup().setStartRes(
1706 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1707 viewport.getSelectionGroup().setEndRes(
1708 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1711 boolean appendHistoryItem = false;
1712 if (viewport.historyList != null && viewport.historyList.size() > 0
1713 && viewport.historyList.peek() instanceof SlideSequencesCommand)
1715 appendHistoryItem = ssc
1716 .appendSlideCommand((SlideSequencesCommand) viewport.historyList
1720 if (!appendHistoryItem)
1722 addHistoryItem(ssc);
1735 protected void copy_actionPerformed(ActionEvent e)
1738 if (viewport.getSelectionGroup() == null)
1742 // TODO: preserve the ordering of displayed alignment annotation in any
1743 // internal paste (particularly sequence associated annotation)
1744 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1745 String[] omitHidden = null;
1747 if (viewport.hasHiddenColumns())
1749 omitHidden = viewport.getViewAsString(true);
1752 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1755 StringSelection ss = new StringSelection(output);
1759 jalview.gui.Desktop.internalCopy = true;
1760 // Its really worth setting the clipboard contents
1761 // to empty before setting the large StringSelection!!
1762 Toolkit.getDefaultToolkit().getSystemClipboard()
1763 .setContents(new StringSelection(""), null);
1765 Toolkit.getDefaultToolkit().getSystemClipboard()
1766 .setContents(ss, Desktop.instance);
1767 } catch (OutOfMemoryError er)
1769 new OOMWarning("copying region", er);
1773 Vector hiddenColumns = null;
1774 if (viewport.hasHiddenColumns())
1776 hiddenColumns = new Vector();
1777 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1778 .getSelectionGroup().getEndRes();
1779 for (int i = 0; i < viewport.getColumnSelection().getHiddenColumns()
1782 int[] region = (int[]) viewport.getColumnSelection()
1783 .getHiddenColumns().elementAt(i);
1784 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1786 hiddenColumns.addElement(new int[]
1787 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1792 Desktop.jalviewClipboard = new Object[]
1793 { seqs, viewport.getAlignment().getDataset(), hiddenColumns };
1794 statusBar.setText(MessageManager.formatMessage(
1795 "label.copied_sequences_to_clipboard", new String[]
1796 { Integer.valueOf(seqs.length).toString() }));
1806 protected void pasteNew_actionPerformed(ActionEvent e)
1818 protected void pasteThis_actionPerformed(ActionEvent e)
1824 * Paste contents of Jalview clipboard
1826 * @param newAlignment
1827 * true to paste to a new alignment, otherwise add to this.
1829 void paste(boolean newAlignment)
1831 boolean externalPaste = true;
1834 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1835 Transferable contents = c.getContents(this);
1837 if (contents == null)
1845 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1846 if (str.length() < 1)
1851 format = new IdentifyFile().Identify(str, "Paste");
1853 } catch (OutOfMemoryError er)
1855 new OOMWarning("Out of memory pasting sequences!!", er);
1859 SequenceI[] sequences;
1860 boolean annotationAdded = false;
1861 AlignmentI alignment = null;
1863 if (Desktop.jalviewClipboard != null)
1865 // The clipboard was filled from within Jalview, we must use the
1867 // And dataset from the copied alignment
1868 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1869 // be doubly sure that we create *new* sequence objects.
1870 sequences = new SequenceI[newseq.length];
1871 for (int i = 0; i < newseq.length; i++)
1873 sequences[i] = new Sequence(newseq[i]);
1875 alignment = new Alignment(sequences);
1876 externalPaste = false;
1880 // parse the clipboard as an alignment.
1881 alignment = new FormatAdapter().readFile(str, "Paste", format);
1882 sequences = alignment.getSequencesArray();
1886 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1892 if (Desktop.jalviewClipboard != null)
1894 // dataset is inherited
1895 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1899 // new dataset is constructed
1900 alignment.setDataset(null);
1902 alwidth = alignment.getWidth() + 1;
1906 AlignmentI pastedal = alignment; // preserve pasted alignment object
1907 // Add pasted sequences and dataset into existing alignment.
1908 alignment = viewport.getAlignment();
1909 alwidth = alignment.getWidth() + 1;
1910 // decide if we need to import sequences from an existing dataset
1911 boolean importDs = Desktop.jalviewClipboard != null
1912 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1913 // importDs==true instructs us to copy over new dataset sequences from
1914 // an existing alignment
1915 Vector newDs = (importDs) ? new Vector() : null; // used to create
1916 // minimum dataset set
1918 for (int i = 0; i < sequences.length; i++)
1922 newDs.addElement(null);
1924 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
1926 if (importDs && ds != null)
1928 if (!newDs.contains(ds))
1930 newDs.setElementAt(ds, i);
1931 ds = new Sequence(ds);
1932 // update with new dataset sequence
1933 sequences[i].setDatasetSequence(ds);
1937 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
1942 // copy and derive new dataset sequence
1943 sequences[i] = sequences[i].deriveSequence();
1944 alignment.getDataset().addSequence(
1945 sequences[i].getDatasetSequence());
1946 // TODO: avoid creation of duplicate dataset sequences with a
1947 // 'contains' method using SequenceI.equals()/SequenceI.contains()
1949 alignment.addSequence(sequences[i]); // merges dataset
1953 newDs.clear(); // tidy up
1955 if (alignment.getAlignmentAnnotation() != null)
1957 for (AlignmentAnnotation alan : alignment
1958 .getAlignmentAnnotation())
1960 if (alan.graphGroup > fgroup)
1962 fgroup = alan.graphGroup;
1966 if (pastedal.getAlignmentAnnotation() != null)
1968 // Add any annotation attached to alignment.
1969 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
1970 for (int i = 0; i < alann.length; i++)
1972 annotationAdded = true;
1973 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
1975 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
1976 if (newann.graphGroup > -1)
1978 if (newGraphGroups.size() <= newann.graphGroup
1979 || newGraphGroups.get(newann.graphGroup) == null)
1981 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
1983 newGraphGroups.add(q, null);
1985 newGraphGroups.set(newann.graphGroup, new Integer(
1988 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
1992 newann.padAnnotation(alwidth);
1993 alignment.addAnnotation(newann);
2003 addHistoryItem(new EditCommand(
2004 MessageManager.getString("label.add_sequences"),
2006 sequences, 0, alignment.getWidth(), alignment));
2008 // Add any annotations attached to sequences
2009 for (int i = 0; i < sequences.length; i++)
2011 if (sequences[i].getAnnotation() != null)
2013 AlignmentAnnotation newann;
2014 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2016 annotationAdded = true;
2017 newann = sequences[i].getAnnotation()[a];
2018 newann.adjustForAlignment();
2019 newann.padAnnotation(alwidth);
2020 if (newann.graphGroup > -1)
2022 if (newann.graphGroup > -1)
2024 if (newGraphGroups.size() <= newann.graphGroup
2025 || newGraphGroups.get(newann.graphGroup) == null)
2027 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2029 newGraphGroups.add(q, null);
2031 newGraphGroups.set(newann.graphGroup, new Integer(
2034 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2038 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2043 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2050 // propagate alignment changed.
2051 viewport.setEndSeq(alignment.getHeight());
2052 if (annotationAdded)
2054 // Duplicate sequence annotation in all views.
2055 AlignmentI[] alview = this.getViewAlignments();
2056 for (int i = 0; i < sequences.length; i++)
2058 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2063 for (int avnum = 0; avnum < alview.length; avnum++)
2065 if (alview[avnum] != alignment)
2067 // duplicate in a view other than the one with input focus
2068 int avwidth = alview[avnum].getWidth() + 1;
2069 // this relies on sann being preserved after we
2070 // modify the sequence's annotation array for each duplication
2071 for (int a = 0; a < sann.length; a++)
2073 AlignmentAnnotation newann = new AlignmentAnnotation(
2075 sequences[i].addAlignmentAnnotation(newann);
2076 newann.padAnnotation(avwidth);
2077 alview[avnum].addAnnotation(newann); // annotation was
2078 // duplicated earlier
2079 // TODO JAL-1145 graphGroups are not updated for sequence
2080 // annotation added to several views. This may cause
2082 alview[avnum].setAnnotationIndex(newann, a);
2087 buildSortByAnnotationScoresMenu();
2089 viewport.firePropertyChange("alignment", null,
2090 alignment.getSequences());
2091 if (alignPanels != null)
2093 for (AlignmentPanel ap : ((Vector<AlignmentPanel>) alignPanels))
2095 ap.validateAnnotationDimensions(false);
2100 alignPanel.validateAnnotationDimensions(false);
2106 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2108 String newtitle = new String("Copied sequences");
2110 if (Desktop.jalviewClipboard != null
2111 && Desktop.jalviewClipboard[2] != null)
2113 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2114 for (int i = 0; i < hc.size(); i++)
2116 int[] region = (int[]) hc.elementAt(i);
2117 af.viewport.hideColumns(region[0], region[1]);
2121 // >>>This is a fix for the moment, until a better solution is
2123 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
2125 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
2127 // TODO: maintain provenance of an alignment, rather than just make the
2128 // title a concatenation of operations.
2131 if (title.startsWith("Copied sequences"))
2137 newtitle = newtitle.concat("- from " + title);
2142 newtitle = new String("Pasted sequences");
2145 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2150 } catch (Exception ex)
2152 ex.printStackTrace();
2153 System.out.println("Exception whilst pasting: " + ex);
2154 // could be anything being pasted in here
2160 protected void expand_newalign(ActionEvent e)
2164 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2165 .getAlignment(), -1);
2166 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2168 String newtitle = new String("Flanking alignment");
2170 if (Desktop.jalviewClipboard != null
2171 && Desktop.jalviewClipboard[2] != null)
2173 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2174 for (int i = 0; i < hc.size(); i++)
2176 int[] region = (int[]) hc.elementAt(i);
2177 af.viewport.hideColumns(region[0], region[1]);
2181 // >>>This is a fix for the moment, until a better solution is
2183 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
2185 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
2187 // TODO: maintain provenance of an alignment, rather than just make the
2188 // title a concatenation of operations.
2190 if (title.startsWith("Copied sequences"))
2196 newtitle = newtitle.concat("- from " + title);
2200 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2202 } catch (Exception ex)
2204 ex.printStackTrace();
2205 System.out.println("Exception whilst pasting: " + ex);
2206 // could be anything being pasted in here
2207 } catch (OutOfMemoryError oom)
2209 new OOMWarning("Viewing flanking region of alignment", oom);
2220 protected void cut_actionPerformed(ActionEvent e)
2222 copy_actionPerformed(null);
2223 delete_actionPerformed(null);
2233 protected void delete_actionPerformed(ActionEvent evt)
2236 SequenceGroup sg = viewport.getSelectionGroup();
2242 List<SequenceI> seqs = new ArrayList<SequenceI>(sg.getSize());
2244 for (int i = 0; i < sg.getSize(); i++)
2246 seq = sg.getSequenceAt(i);
2250 // If the cut affects all sequences, warn, remove highlighted columns
2251 if (sg.getSize() == viewport.getAlignment().getHeight())
2253 int confirm = JOptionPane.showConfirmDialog(this,
2254 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2255 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2256 JOptionPane.OK_CANCEL_OPTION);
2258 if (confirm == JOptionPane.CANCEL_OPTION
2259 || confirm == JOptionPane.CLOSED_OPTION)
2263 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2264 sg.getEndRes() + 1);
2267 SequenceI[] cut = new SequenceI[seqs.size()];
2268 for (int i = 0; i < seqs.size(); i++)
2270 cut[i] = seqs.get(i);
2274 * //ADD HISTORY ITEM
2276 addHistoryItem(new EditCommand(
2277 MessageManager.getString("label.cut_sequences"), Action.CUT,
2278 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2279 viewport.getAlignment()));
2281 viewport.setSelectionGroup(null);
2282 viewport.sendSelection();
2283 viewport.getAlignment().deleteGroup(sg);
2285 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2287 if (viewport.getAlignment().getHeight() < 1)
2291 this.setClosed(true);
2292 } catch (Exception ex)
2305 protected void deleteGroups_actionPerformed(ActionEvent e)
2307 if (avc.deleteGroups())
2309 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2310 alignPanel.updateAnnotation();
2311 alignPanel.paintAlignment(true);
2322 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2324 SequenceGroup sg = new SequenceGroup();
2326 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2328 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2331 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2332 viewport.setSelectionGroup(sg);
2333 viewport.sendSelection();
2334 alignPanel.paintAlignment(true);
2335 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2345 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2347 if (viewport.cursorMode)
2349 alignPanel.seqPanel.keyboardNo1 = null;
2350 alignPanel.seqPanel.keyboardNo2 = null;
2352 viewport.setSelectionGroup(null);
2353 viewport.getColumnSelection().clear();
2354 viewport.setSelectionGroup(null);
2355 alignPanel.seqPanel.seqCanvas.highlightSearchResults(null);
2356 alignPanel.idPanel.idCanvas.searchResults = null;
2357 alignPanel.paintAlignment(true);
2358 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2359 viewport.sendSelection();
2369 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2371 SequenceGroup sg = viewport.getSelectionGroup();
2375 selectAllSequenceMenuItem_actionPerformed(null);
2380 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2382 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2385 alignPanel.paintAlignment(true);
2386 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2387 viewport.sendSelection();
2391 public void invertColSel_actionPerformed(ActionEvent e)
2393 viewport.invertColumnSelection();
2394 alignPanel.paintAlignment(true);
2395 viewport.sendSelection();
2405 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2407 trimAlignment(true);
2417 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2419 trimAlignment(false);
2422 void trimAlignment(boolean trimLeft)
2424 ColumnSelection colSel = viewport.getColumnSelection();
2427 if (colSel.size() > 0)
2431 column = colSel.getMin();
2435 column = colSel.getMax();
2439 if (viewport.getSelectionGroup() != null)
2441 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2442 viewport.getHiddenRepSequences());
2446 seqs = viewport.getAlignment().getSequencesArray();
2449 TrimRegionCommand trimRegion;
2452 trimRegion = new TrimRegionCommand("Remove Left",
2453 TrimRegionCommand.TRIM_LEFT, seqs, column,
2454 viewport.getAlignment(), viewport.getColumnSelection(),
2455 viewport.getSelectionGroup());
2456 viewport.setStartRes(0);
2460 trimRegion = new TrimRegionCommand("Remove Right",
2461 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2462 viewport.getAlignment(), viewport.getColumnSelection(),
2463 viewport.getSelectionGroup());
2466 statusBar.setText(MessageManager.formatMessage(
2467 "label.removed_columns", new String[]
2468 { Integer.valueOf(trimRegion.getSize()).toString() }));
2470 addHistoryItem(trimRegion);
2472 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2474 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2475 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2477 viewport.getAlignment().deleteGroup(sg);
2481 viewport.firePropertyChange("alignment", null, viewport
2482 .getAlignment().getSequences());
2493 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2495 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2498 if (viewport.getSelectionGroup() != null)
2500 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2501 viewport.getHiddenRepSequences());
2502 start = viewport.getSelectionGroup().getStartRes();
2503 end = viewport.getSelectionGroup().getEndRes();
2507 seqs = viewport.getAlignment().getSequencesArray();
2510 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2511 "Remove Gapped Columns", seqs, start, end,
2512 viewport.getAlignment());
2514 addHistoryItem(removeGapCols);
2516 statusBar.setText(MessageManager.formatMessage(
2517 "label.removed_empty_columns", new String[]
2518 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2520 // This is to maintain viewport position on first residue
2521 // of first sequence
2522 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2523 int startRes = seq.findPosition(viewport.startRes);
2524 // ShiftList shifts;
2525 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2526 // edit.alColumnChanges=shifts.getInverse();
2527 // if (viewport.hasHiddenColumns)
2528 // viewport.getColumnSelection().compensateForEdits(shifts);
2529 viewport.setStartRes(seq.findIndex(startRes) - 1);
2530 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2542 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2544 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2547 if (viewport.getSelectionGroup() != null)
2549 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2550 viewport.getHiddenRepSequences());
2551 start = viewport.getSelectionGroup().getStartRes();
2552 end = viewport.getSelectionGroup().getEndRes();
2556 seqs = viewport.getAlignment().getSequencesArray();
2559 // This is to maintain viewport position on first residue
2560 // of first sequence
2561 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2562 int startRes = seq.findPosition(viewport.startRes);
2564 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2565 viewport.getAlignment()));
2567 viewport.setStartRes(seq.findIndex(startRes) - 1);
2569 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2581 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2583 viewport.setPadGaps(padGapsMenuitem.isSelected());
2584 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2590 // if (justifySeqs>0)
2592 // alignment.justify(justifySeqs!=RIGHT_JUSTIFY);
2605 public void findMenuItem_actionPerformed(ActionEvent e)
2611 public void newView_actionPerformed(ActionEvent e)
2618 * @param copyAnnotation
2619 * if true then duplicate all annnotation, groups and settings
2620 * @return new alignment panel, already displayed.
2622 public AlignmentPanel newView(boolean copyAnnotation)
2624 return newView(null, copyAnnotation);
2630 * title of newly created view
2631 * @return new alignment panel, already displayed.
2633 public AlignmentPanel newView(String viewTitle)
2635 return newView(viewTitle, true);
2641 * title of newly created view
2642 * @param copyAnnotation
2643 * if true then duplicate all annnotation, groups and settings
2644 * @return new alignment panel, already displayed.
2646 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2648 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2650 if (!copyAnnotation)
2652 // just remove all the current annotation except for the automatic stuff
2653 newap.av.getAlignment().deleteAllGroups();
2654 for (AlignmentAnnotation alan : newap.av.getAlignment()
2655 .getAlignmentAnnotation())
2657 if (!alan.autoCalculated)
2659 newap.av.getAlignment().deleteAnnotation(alan);
2665 newap.av.gatherViewsHere = false;
2667 if (viewport.viewName == null)
2669 viewport.viewName = "Original";
2672 newap.av.historyList = viewport.historyList;
2673 newap.av.redoList = viewport.redoList;
2675 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2676 // make sure the new view has a unique name - this is essential for Jalview
2678 boolean addFirstIndex = false;
2679 if (viewTitle == null || viewTitle.trim().length() == 0)
2681 viewTitle = MessageManager.getString("action.view");
2682 addFirstIndex = true;
2686 index = 1;// we count from 1 if given a specific name
2688 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2689 Vector comps = (Vector) PaintRefresher.components.get(viewport
2690 .getSequenceSetId());
2691 Vector existingNames = new Vector();
2692 for (int i = 0; i < comps.size(); i++)
2694 if (comps.elementAt(i) instanceof AlignmentPanel)
2696 AlignmentPanel ap = (AlignmentPanel) comps.elementAt(i);
2697 if (!existingNames.contains(ap.av.viewName))
2699 existingNames.addElement(ap.av.viewName);
2704 while (existingNames.contains(newViewName))
2706 newViewName = viewTitle + " " + (++index);
2709 newap.av.viewName = newViewName;
2711 addAlignmentPanel(newap, true);
2712 newap.alignmentChanged();
2714 if (alignPanels.size() == 2)
2716 viewport.gatherViewsHere = true;
2718 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2723 public void expandViews_actionPerformed(ActionEvent e)
2725 Desktop.instance.explodeViews(this);
2729 public void gatherViews_actionPerformed(ActionEvent e)
2731 Desktop.instance.gatherViews(this);
2741 public void font_actionPerformed(ActionEvent e)
2743 new FontChooser(alignPanel);
2753 protected void seqLimit_actionPerformed(ActionEvent e)
2755 viewport.setShowJVSuffix(seqLimits.isSelected());
2757 alignPanel.idPanel.idCanvas.setPreferredSize(alignPanel
2758 .calculateIdWidth());
2759 alignPanel.paintAlignment(true);
2763 public void idRightAlign_actionPerformed(ActionEvent e)
2765 viewport.rightAlignIds = idRightAlign.isSelected();
2766 alignPanel.paintAlignment(true);
2770 public void centreColumnLabels_actionPerformed(ActionEvent e)
2772 viewport.centreColumnLabels = centreColumnLabelsMenuItem.getState();
2773 alignPanel.paintAlignment(true);
2779 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2782 protected void followHighlight_actionPerformed()
2784 if (viewport.followHighlight = this.followHighlightMenuItem.getState())
2786 alignPanel.scrollToPosition(
2787 alignPanel.seqPanel.seqCanvas.searchResults, false);
2798 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2800 viewport.setColourText(colourTextMenuItem.isSelected());
2801 alignPanel.paintAlignment(true);
2811 public void wrapMenuItem_actionPerformed(ActionEvent e)
2813 scaleAbove.setVisible(wrapMenuItem.isSelected());
2814 scaleLeft.setVisible(wrapMenuItem.isSelected());
2815 scaleRight.setVisible(wrapMenuItem.isSelected());
2816 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2817 alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2821 public void showAllSeqs_actionPerformed(ActionEvent e)
2823 viewport.showAllHiddenSeqs();
2827 public void showAllColumns_actionPerformed(ActionEvent e)
2829 viewport.showAllHiddenColumns();
2834 public void hideSelSequences_actionPerformed(ActionEvent e)
2836 viewport.hideAllSelectedSeqs();
2837 alignPanel.paintAlignment(true);
2841 * called by key handler and the hide all/show all menu items
2846 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2849 boolean hide = false;
2850 SequenceGroup sg = viewport.getSelectionGroup();
2851 if (!toggleSeqs && !toggleCols)
2853 // Hide everything by the current selection - this is a hack - we do the
2854 // invert and then hide
2855 // first check that there will be visible columns after the invert.
2856 if ((viewport.getColumnSelection() != null
2857 && viewport.getColumnSelection().getSelected() != null && viewport
2858 .getColumnSelection().getSelected().size() > 0)
2859 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2862 // now invert the sequence set, if required - empty selection implies
2863 // that no hiding is required.
2866 invertSequenceMenuItem_actionPerformed(null);
2867 sg = viewport.getSelectionGroup();
2871 viewport.expandColSelection(sg, true);
2872 // finally invert the column selection and get the new sequence
2874 invertColSel_actionPerformed(null);
2881 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
2883 hideSelSequences_actionPerformed(null);
2886 else if (!(toggleCols && viewport.getColumnSelection().getSelected()
2889 showAllSeqs_actionPerformed(null);
2895 if (viewport.getColumnSelection().getSelected().size() > 0)
2897 hideSelColumns_actionPerformed(null);
2900 viewport.setSelectionGroup(sg);
2905 showAllColumns_actionPerformed(null);
2914 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
2915 * event.ActionEvent)
2918 public void hideAllButSelection_actionPerformed(ActionEvent e)
2920 toggleHiddenRegions(false, false);
2927 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
2931 public void hideAllSelection_actionPerformed(ActionEvent e)
2933 SequenceGroup sg = viewport.getSelectionGroup();
2934 viewport.expandColSelection(sg, false);
2935 viewport.hideAllSelectedSeqs();
2936 viewport.hideSelectedColumns();
2937 alignPanel.paintAlignment(true);
2944 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
2948 public void showAllhidden_actionPerformed(ActionEvent e)
2950 viewport.showAllHiddenColumns();
2951 viewport.showAllHiddenSeqs();
2952 alignPanel.paintAlignment(true);
2956 public void hideSelColumns_actionPerformed(ActionEvent e)
2958 viewport.hideSelectedColumns();
2959 alignPanel.paintAlignment(true);
2963 public void hiddenMarkers_actionPerformed(ActionEvent e)
2965 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
2976 protected void scaleAbove_actionPerformed(ActionEvent e)
2978 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
2979 alignPanel.paintAlignment(true);
2989 protected void scaleLeft_actionPerformed(ActionEvent e)
2991 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
2992 alignPanel.paintAlignment(true);
3002 protected void scaleRight_actionPerformed(ActionEvent e)
3004 viewport.setScaleRightWrapped(scaleRight.isSelected());
3005 alignPanel.paintAlignment(true);
3015 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3017 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3018 alignPanel.paintAlignment(true);
3028 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3030 viewport.setShowText(viewTextMenuItem.isSelected());
3031 alignPanel.paintAlignment(true);
3041 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3043 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3044 alignPanel.paintAlignment(true);
3047 public FeatureSettings featureSettings;
3050 public void featureSettings_actionPerformed(ActionEvent e)
3052 if (featureSettings != null)
3054 featureSettings.close();
3055 featureSettings = null;
3057 if (!showSeqFeatures.isSelected())
3059 // make sure features are actually displayed
3060 showSeqFeatures.setSelected(true);
3061 showSeqFeatures_actionPerformed(null);
3063 featureSettings = new FeatureSettings(this);
3067 * Set or clear 'Show Sequence Features'
3073 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3075 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3076 alignPanel.paintAlignment(true);
3077 if (alignPanel.getOverviewPanel() != null)
3079 alignPanel.getOverviewPanel().updateOverviewImage();
3084 * Set or clear 'Show Sequence Features'
3090 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
3092 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
3094 if (viewport.getShowSequenceFeaturesHeight())
3096 // ensure we're actually displaying features
3097 viewport.setShowSequenceFeatures(true);
3098 showSeqFeatures.setSelected(true);
3100 alignPanel.paintAlignment(true);
3101 if (alignPanel.getOverviewPanel() != null)
3103 alignPanel.getOverviewPanel().updateOverviewImage();
3108 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3109 * the annotations panel as a whole.
3111 * The options to show/hide all annotations should be enabled when the panel
3112 * is shown, and disabled when the panel is hidden.
3117 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3119 final boolean setVisible = annotationPanelMenuItem.isSelected();
3120 viewport.setShowAnnotation(setVisible);
3121 alignPanel.setAnnotationVisible(setVisible);
3122 this.showAllSeqAnnotations.setEnabled(setVisible);
3123 this.hideAllSeqAnnotations.setEnabled(setVisible);
3124 this.showAllAlAnnotations.setEnabled(setVisible);
3125 this.hideAllAlAnnotations.setEnabled(setVisible);
3129 public void alignmentProperties()
3131 JEditorPane editPane = new JEditorPane("text/html", "");
3132 editPane.setEditable(false);
3133 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3135 editPane.setText(MessageManager.formatMessage("label.html_content",
3137 { contents.toString() }));
3138 JInternalFrame frame = new JInternalFrame();
3139 frame.getContentPane().add(new JScrollPane(editPane));
3141 Desktop.instance.addInternalFrame(frame, MessageManager.formatMessage(
3142 "label.alignment_properties", new String[]
3143 { getTitle() }), 500, 400);
3153 public void overviewMenuItem_actionPerformed(ActionEvent e)
3155 if (alignPanel.overviewPanel != null)
3160 JInternalFrame frame = new JInternalFrame();
3161 OverviewPanel overview = new OverviewPanel(alignPanel);
3162 frame.setContentPane(overview);
3163 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3164 "label.overview_params", new String[]
3165 { this.getTitle() }), frame.getWidth(), frame.getHeight());
3167 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3168 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3171 public void internalFrameClosed(
3172 javax.swing.event.InternalFrameEvent evt)
3174 alignPanel.setOverviewPanel(null);
3178 alignPanel.setOverviewPanel(overview);
3182 public void textColour_actionPerformed(ActionEvent e)
3184 new TextColourChooser().chooseColour(alignPanel, null);
3194 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3206 public void clustalColour_actionPerformed(ActionEvent e)
3208 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3209 viewport.getHiddenRepSequences()));
3219 public void zappoColour_actionPerformed(ActionEvent e)
3221 changeColour(new ZappoColourScheme());
3231 public void taylorColour_actionPerformed(ActionEvent e)
3233 changeColour(new TaylorColourScheme());
3243 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3245 changeColour(new HydrophobicColourScheme());
3255 public void helixColour_actionPerformed(ActionEvent e)
3257 changeColour(new HelixColourScheme());
3267 public void strandColour_actionPerformed(ActionEvent e)
3269 changeColour(new StrandColourScheme());
3279 public void turnColour_actionPerformed(ActionEvent e)
3281 changeColour(new TurnColourScheme());
3291 public void buriedColour_actionPerformed(ActionEvent e)
3293 changeColour(new BuriedColourScheme());
3303 public void nucleotideColour_actionPerformed(ActionEvent e)
3305 changeColour(new NucleotideColourScheme());
3309 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3311 changeColour(new PurinePyrimidineColourScheme());
3315 * public void covariationColour_actionPerformed(ActionEvent e) {
3317 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3321 public void annotationColour_actionPerformed(ActionEvent e)
3323 new AnnotationColourChooser(viewport, alignPanel);
3327 public void rnahelicesColour_actionPerformed(ActionEvent e)
3329 new RNAHelicesColourChooser(viewport, alignPanel);
3339 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3341 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3350 public void changeColour(ColourSchemeI cs)
3352 // TODO: compare with applet and pull up to model method
3357 if (viewport.getAbovePIDThreshold())
3359 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3361 cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3365 cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3368 if (viewport.getConservationSelected())
3371 Alignment al = (Alignment) viewport.getAlignment();
3372 Conservation c = new Conservation("All",
3373 ResidueProperties.propHash, 3, al.getSequences(), 0,
3377 c.verdict(false, viewport.getConsPercGaps());
3379 cs.setConservation(c);
3381 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3386 cs.setConservation(null);
3389 cs.setConsensus(viewport.getSequenceConsensusHash());
3392 viewport.setGlobalColourScheme(cs);
3394 if (viewport.getColourAppliesToAllGroups())
3397 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3405 if (cs instanceof ClustalxColourScheme)
3407 sg.cs = new ClustalxColourScheme(sg,
3408 viewport.getHiddenRepSequences());
3410 else if (cs instanceof UserColourScheme)
3412 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
3418 sg.cs = cs.getClass().newInstance();
3419 } catch (Exception ex)
3424 if (viewport.getAbovePIDThreshold()
3425 || cs instanceof PIDColourScheme
3426 || cs instanceof Blosum62ColourScheme)
3428 sg.cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3430 sg.cs.setConsensus(AAFrequency.calculate(
3431 sg.getSequences(viewport.getHiddenRepSequences()),
3432 sg.getStartRes(), sg.getEndRes() + 1));
3436 sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3439 if (viewport.getConservationSelected())
3441 Conservation c = new Conservation("Group",
3442 ResidueProperties.propHash, 3, sg.getSequences(viewport
3443 .getHiddenRepSequences()), sg.getStartRes(),
3444 sg.getEndRes() + 1);
3446 c.verdict(false, viewport.getConsPercGaps());
3447 sg.cs.setConservation(c);
3451 sg.cs.setConservation(null);
3456 if (alignPanel.getOverviewPanel() != null)
3458 alignPanel.getOverviewPanel().updateOverviewImage();
3461 alignPanel.paintAlignment(true);
3471 protected void modifyPID_actionPerformed(ActionEvent e)
3473 if (viewport.getAbovePIDThreshold()
3474 && viewport.getGlobalColourScheme() != null)
3476 SliderPanel.setPIDSliderSource(alignPanel,
3477 viewport.getGlobalColourScheme(), "Background");
3478 SliderPanel.showPIDSlider();
3489 protected void modifyConservation_actionPerformed(ActionEvent e)
3491 if (viewport.getConservationSelected()
3492 && viewport.getGlobalColourScheme() != null)
3494 SliderPanel.setConservationSlider(alignPanel,
3495 viewport.getGlobalColourScheme(), "Background");
3496 SliderPanel.showConservationSlider();
3507 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3509 viewport.setConservationSelected(conservationMenuItem.isSelected());
3511 viewport.setAbovePIDThreshold(false);
3512 abovePIDThreshold.setSelected(false);
3514 changeColour(viewport.getGlobalColourScheme());
3516 modifyConservation_actionPerformed(null);
3526 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3528 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3530 conservationMenuItem.setSelected(false);
3531 viewport.setConservationSelected(false);
3533 changeColour(viewport.getGlobalColourScheme());
3535 modifyPID_actionPerformed(null);
3545 public void userDefinedColour_actionPerformed(ActionEvent e)
3547 if (e.getActionCommand().equals(
3548 MessageManager.getString("action.user_defined")))
3550 new UserDefinedColours(alignPanel, null);
3554 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3555 .getUserColourSchemes().get(e.getActionCommand());
3561 public void updateUserColourMenu()
3564 Component[] menuItems = colourMenu.getMenuComponents();
3565 int i, iSize = menuItems.length;
3566 for (i = 0; i < iSize; i++)
3568 if (menuItems[i].getName() != null
3569 && menuItems[i].getName().equals("USER_DEFINED"))
3571 colourMenu.remove(menuItems[i]);
3575 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3577 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3578 .getUserColourSchemes().keys();
3580 while (userColours.hasMoreElements())
3582 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3583 userColours.nextElement().toString());
3584 radioItem.setName("USER_DEFINED");
3585 radioItem.addMouseListener(new MouseAdapter()
3588 public void mousePressed(MouseEvent evt)
3590 if (evt.isControlDown()
3591 || SwingUtilities.isRightMouseButton(evt))
3593 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3595 int option = JOptionPane.showInternalConfirmDialog(
3596 jalview.gui.Desktop.desktop,
3598 .getString("label.remove_from_default_list"),
3600 .getString("label.remove_user_defined_colour"),
3601 JOptionPane.YES_NO_OPTION);
3602 if (option == JOptionPane.YES_OPTION)
3604 jalview.gui.UserDefinedColours
3605 .removeColourFromDefaults(radioItem.getText());
3606 colourMenu.remove(radioItem);
3610 radioItem.addActionListener(new ActionListener()
3613 public void actionPerformed(ActionEvent evt)
3615 userDefinedColour_actionPerformed(evt);
3622 radioItem.addActionListener(new ActionListener()
3625 public void actionPerformed(ActionEvent evt)
3627 userDefinedColour_actionPerformed(evt);
3631 colourMenu.insert(radioItem, 15);
3632 colours.add(radioItem);
3644 public void PIDColour_actionPerformed(ActionEvent e)
3646 changeColour(new PIDColourScheme());
3656 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3658 changeColour(new Blosum62ColourScheme());
3668 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3670 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3671 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3672 .getAlignment().getSequenceAt(0), null);
3673 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3674 viewport.getAlignment()));
3675 alignPanel.paintAlignment(true);
3685 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3687 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3688 AlignmentSorter.sortByID(viewport.getAlignment());
3689 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3690 viewport.getAlignment()));
3691 alignPanel.paintAlignment(true);
3701 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3703 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3704 AlignmentSorter.sortByLength(viewport.getAlignment());
3705 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3706 viewport.getAlignment()));
3707 alignPanel.paintAlignment(true);
3717 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3719 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3720 AlignmentSorter.sortByGroup(viewport.getAlignment());
3721 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3722 viewport.getAlignment()));
3724 alignPanel.paintAlignment(true);
3734 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3736 new RedundancyPanel(alignPanel, this);
3746 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3748 if ((viewport.getSelectionGroup() == null)
3749 || (viewport.getSelectionGroup().getSize() < 2))
3751 JOptionPane.showInternalMessageDialog(this, MessageManager
3752 .getString("label.you_must_select_least_two_sequences"),
3753 MessageManager.getString("label.invalid_selection"),
3754 JOptionPane.WARNING_MESSAGE);
3758 JInternalFrame frame = new JInternalFrame();
3759 frame.setContentPane(new PairwiseAlignPanel(viewport));
3760 Desktop.addInternalFrame(frame,
3761 MessageManager.getString("action.pairwise_alignment"), 600,
3773 public void PCAMenuItem_actionPerformed(ActionEvent e)
3775 if (((viewport.getSelectionGroup() != null)
3776 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3777 .getSelectionGroup().getSize() > 0))
3778 || (viewport.getAlignment().getHeight() < 4))
3781 .showInternalMessageDialog(
3784 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3786 .getString("label.sequence_selection_insufficient"),
3787 JOptionPane.WARNING_MESSAGE);
3792 new PCAPanel(alignPanel);
3796 public void autoCalculate_actionPerformed(ActionEvent e)
3798 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3799 if (viewport.autoCalculateConsensus)
3801 viewport.firePropertyChange("alignment", null, viewport
3802 .getAlignment().getSequences());
3807 public void sortByTreeOption_actionPerformed(ActionEvent e)
3809 viewport.sortByTree = sortByTree.isSelected();
3813 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3815 viewport.followSelection = listenToViewSelections.isSelected();
3825 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3827 NewTreePanel("AV", "PID", "Average distance tree using PID");
3837 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3839 NewTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3849 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3851 NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3861 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3863 NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3876 void NewTreePanel(String type, String pwType, String title)
3880 if (viewport.getSelectionGroup() != null
3881 && viewport.getSelectionGroup().getSize() > 0)
3883 if (viewport.getSelectionGroup().getSize() < 3)
3889 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3891 .getString("label.not_enough_sequences"),
3892 JOptionPane.WARNING_MESSAGE);
3896 SequenceGroup sg = viewport.getSelectionGroup();
3898 /* Decide if the selection is a column region */
3899 for (SequenceI _s : sg.getSequences())
3901 if (_s.getLength() < sg.getEndRes())
3907 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3909 .getString("label.sequences_selection_not_aligned"),
3910 JOptionPane.WARNING_MESSAGE);
3916 title = title + " on region";
3917 tp = new TreePanel(alignPanel, type, pwType);
3921 // are the visible sequences aligned?
3922 if (!viewport.getAlignment().isAligned(false))
3928 .getString("label.sequences_must_be_aligned_before_creating_tree"),
3930 .getString("label.sequences_not_aligned"),
3931 JOptionPane.WARNING_MESSAGE);
3936 if (viewport.getAlignment().getHeight() < 2)
3941 tp = new TreePanel(alignPanel, type, pwType);
3946 if (viewport.viewName != null)
3948 title += viewport.viewName + " of ";
3951 title += this.title;
3953 Desktop.addInternalFrame(tp, title, 600, 500);
3964 public void addSortByOrderMenuItem(String title,
3965 final AlignmentOrder order)
3967 final JMenuItem item = new JMenuItem(MessageManager.formatMessage("action.by_title_param", new String[]{title}));
3969 item.addActionListener(new java.awt.event.ActionListener()
3972 public void actionPerformed(ActionEvent e)
3974 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3976 // TODO: JBPNote - have to map order entries to curent SequenceI
3978 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3980 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
3983 alignPanel.paintAlignment(true);
3989 * Add a new sort by annotation score menu item
3992 * the menu to add the option to
3994 * the label used to retrieve scores for each sequence on the
3997 public void addSortByAnnotScoreMenuItem(JMenu sort,
3998 final String scoreLabel)
4000 final JMenuItem item = new JMenuItem(scoreLabel);
4002 item.addActionListener(new java.awt.event.ActionListener()
4005 public void actionPerformed(ActionEvent e)
4007 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4008 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4009 viewport.getAlignment());// ,viewport.getSelectionGroup());
4010 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4011 viewport.getAlignment()));
4012 alignPanel.paintAlignment(true);
4018 * last hash for alignment's annotation array - used to minimise cost of
4021 protected int _annotationScoreVectorHash;
4024 * search the alignment and rebuild the sort by annotation score submenu the
4025 * last alignment annotation vector hash is stored to minimize cost of
4026 * rebuilding in subsequence calls.
4030 public void buildSortByAnnotationScoresMenu()
4032 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4037 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4039 sortByAnnotScore.removeAll();
4040 // almost certainly a quicker way to do this - but we keep it simple
4041 Hashtable scoreSorts = new Hashtable();
4042 AlignmentAnnotation aann[];
4043 for (SequenceI sqa : viewport.getAlignment().getSequences())
4045 aann = sqa.getAnnotation();
4046 for (int i = 0; aann != null && i < aann.length; i++)
4048 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4050 scoreSorts.put(aann[i].label, aann[i].label);
4054 Enumeration labels = scoreSorts.keys();
4055 while (labels.hasMoreElements())
4057 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4058 (String) labels.nextElement());
4060 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4063 _annotationScoreVectorHash = viewport.getAlignment()
4064 .getAlignmentAnnotation().hashCode();
4069 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4070 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4071 * call. Listeners are added to remove the menu item when the treePanel is
4072 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4076 * Displayed tree window.
4078 * SortBy menu item title.
4081 public void buildTreeMenu()
4083 calculateTree.removeAll();
4084 // build the calculate menu
4086 for (final String type : new String[]
4089 String treecalcnm = MessageManager.getString("label.tree_calc_"
4090 + type.toLowerCase());
4091 for (final Object pwtype : ResidueProperties.scoreMatrices.keySet())
4093 JMenuItem tm = new JMenuItem();
4094 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4095 if (sm.isProtein() == !viewport.getAlignment().isNucleotide())
4097 String smn = MessageManager.getStringOrReturn(
4098 "label.score_model_", sm.getName());
4099 final String title = MessageManager.formatMessage(
4100 "label.treecalc_title", treecalcnm, smn);
4101 tm.setText(title);//
4102 tm.addActionListener(new java.awt.event.ActionListener()
4105 public void actionPerformed(ActionEvent e)
4107 NewTreePanel(type, (String) pwtype, title);
4110 calculateTree.add(tm);
4115 sortByTreeMenu.removeAll();
4117 Vector comps = (Vector) PaintRefresher.components.get(viewport
4118 .getSequenceSetId());
4119 Vector treePanels = new Vector();
4120 int i, iSize = comps.size();
4121 for (i = 0; i < iSize; i++)
4123 if (comps.elementAt(i) instanceof TreePanel)
4125 treePanels.add(comps.elementAt(i));
4129 iSize = treePanels.size();
4133 sortByTreeMenu.setVisible(false);
4137 sortByTreeMenu.setVisible(true);
4139 for (i = 0; i < treePanels.size(); i++)
4141 final TreePanel tp = (TreePanel) treePanels.elementAt(i);
4142 final JMenuItem item = new JMenuItem(tp.getTitle());
4143 final NJTree tree = ((TreePanel) treePanels.elementAt(i)).getTree();
4144 item.addActionListener(new java.awt.event.ActionListener()
4147 public void actionPerformed(ActionEvent e)
4149 tp.sortByTree_actionPerformed(null);
4150 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4155 sortByTreeMenu.add(item);
4159 public boolean sortBy(AlignmentOrder alorder, String undoname)
4161 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4162 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4163 if (undoname != null)
4165 addHistoryItem(new OrderCommand(undoname, oldOrder,
4166 viewport.getAlignment()));
4168 alignPanel.paintAlignment(true);
4173 * Work out whether the whole set of sequences or just the selected set will
4174 * be submitted for multiple alignment.
4177 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4179 // Now, check we have enough sequences
4180 AlignmentView msa = null;
4182 if ((viewport.getSelectionGroup() != null)
4183 && (viewport.getSelectionGroup().getSize() > 1))
4185 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4186 // some common interface!
4188 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4189 * SequenceI[sz = seqs.getSize(false)];
4191 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4192 * seqs.getSequenceAt(i); }
4194 msa = viewport.getAlignmentView(true);
4196 else if (viewport.getSelectionGroup() != null
4197 && viewport.getSelectionGroup().getSize() == 1)
4199 int option = JOptionPane
4202 "More than one sequece group selection is required for this Job, click \n'Cancel' to edit your selection or 'Ok' to submit the entire sequence.",
4203 "Invalid selection",
4204 JOptionPane.OK_CANCEL_OPTION);
4205 if (option == JOptionPane.OK_OPTION)
4207 msa = viewport.getAlignmentView(false);
4214 * Vector seqs = viewport.getAlignment().getSequences();
4216 * if (seqs.size() > 1) { msa = new SequenceI[seqs.size()];
4218 * for (int i = 0; i < seqs.size(); i++) { msa[i] = (SequenceI)
4219 * seqs.elementAt(i); } }
4221 msa = viewport.getAlignmentView(false);
4227 * Decides what is submitted to a secondary structure prediction service: the
4228 * first sequence in the alignment, or in the current selection, or, if the
4229 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4230 * region or the whole alignment. (where the first sequence in the set is the
4231 * one that the prediction will be for).
4233 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4235 AlignmentView seqs = null;
4237 if ((viewport.getSelectionGroup() != null)
4238 && (viewport.getSelectionGroup().getSize() > 0))
4240 seqs = viewport.getAlignmentView(true);
4244 seqs = viewport.getAlignmentView(false);
4246 // limit sequences - JBPNote in future - could spawn multiple prediction
4248 // TODO: viewport.getAlignment().isAligned is a global state - the local
4249 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4250 if (!viewport.getAlignment().isAligned(false))
4252 seqs.setSequences(new SeqCigar[]
4253 { seqs.getSequences()[0] });
4254 // TODO: if seqs.getSequences().length>1 then should really have warned
4268 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
4270 // Pick the tree file
4271 JalviewFileChooser chooser = new JalviewFileChooser(
4272 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4273 chooser.setFileView(new JalviewFileView());
4274 chooser.setDialogTitle(MessageManager
4275 .getString("label.select_newick_like_tree_file"));
4276 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4278 int value = chooser.showOpenDialog(null);
4280 if (value == JalviewFileChooser.APPROVE_OPTION)
4282 String choice = chooser.getSelectedFile().getPath();
4283 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4284 jalview.io.NewickFile fin = null;
4287 fin = new jalview.io.NewickFile(choice, "File");
4288 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4289 } catch (Exception ex)
4296 .getString("label.problem_reading_tree_file"),
4297 JOptionPane.WARNING_MESSAGE);
4298 ex.printStackTrace();
4300 if (fin != null && fin.hasWarningMessage())
4302 JOptionPane.showMessageDialog(Desktop.desktop, fin
4303 .getWarningMessage(), MessageManager
4304 .getString("label.possible_problem_with_tree_file"),
4305 JOptionPane.WARNING_MESSAGE);
4311 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4313 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4316 public TreePanel ShowNewickTree(NewickFile nf, String title)
4318 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4321 public TreePanel ShowNewickTree(NewickFile nf, String title,
4322 AlignmentView input)
4324 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4327 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4328 int h, int x, int y)
4330 return ShowNewickTree(nf, title, null, w, h, x, y);
4334 * Add a treeviewer for the tree extracted from a newick file object to the
4335 * current alignment view
4342 * Associated alignment input data (or null)
4351 * @return TreePanel handle
4353 public TreePanel ShowNewickTree(NewickFile nf, String title,
4354 AlignmentView input, int w, int h, int x, int y)
4356 TreePanel tp = null;
4362 if (nf.getTree() != null)
4364 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4370 tp.setLocation(x, y);
4373 Desktop.addInternalFrame(tp, title, w, h);
4375 } catch (Exception ex)
4377 ex.printStackTrace();
4383 private boolean buildingMenu = false;
4386 * Generates menu items and listener event actions for web service clients
4389 public void BuildWebServiceMenu()
4391 while (buildingMenu)
4395 System.err.println("Waiting for building menu to finish.");
4397 } catch (Exception e)
4402 final AlignFrame me = this;
4403 buildingMenu = true;
4404 new Thread(new Runnable()
4409 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4412 System.err.println("Building ws menu again "
4413 + Thread.currentThread());
4414 // TODO: add support for context dependent disabling of services based
4416 // alignment and current selection
4417 // TODO: add additional serviceHandle parameter to specify abstract
4419 // class independently of AbstractName
4420 // TODO: add in rediscovery GUI function to restart discoverer
4421 // TODO: group services by location as well as function and/or
4423 // object broker mechanism.
4424 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4425 final IProgressIndicator af = me;
4426 final JMenu msawsmenu = new JMenu("Alignment");
4427 final JMenu secstrmenu = new JMenu(
4428 "Secondary Structure Prediction");
4429 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4430 final JMenu analymenu = new JMenu("Analysis");
4431 final JMenu dismenu = new JMenu("Protein Disorder");
4432 // final JMenu msawsmenu = new
4433 // JMenu(MessageManager.getString("label.alignment"));
4434 // final JMenu secstrmenu = new
4435 // JMenu(MessageManager.getString("label.secondary_structure_prediction"));
4436 // final JMenu seqsrchmenu = new
4437 // JMenu(MessageManager.getString("label.sequence_database_search"));
4438 // final JMenu analymenu = new
4439 // JMenu(MessageManager.getString("label.analysis"));
4440 // final JMenu dismenu = new
4441 // JMenu(MessageManager.getString("label.protein_disorder"));
4442 // JAL-940 - only show secondary structure prediction services from
4443 // the legacy server
4444 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4446 Discoverer.services != null && (Discoverer.services.size() > 0))
4448 // TODO: refactor to allow list of AbstractName/Handler bindings to
4450 // stored or retrieved from elsewhere
4451 // No MSAWS used any more:
4452 // Vector msaws = null; // (Vector)
4453 // Discoverer.services.get("MsaWS");
4454 Vector secstrpr = (Vector) Discoverer.services
4456 if (secstrpr != null)
4458 // Add any secondary structure prediction services
4459 for (int i = 0, j = secstrpr.size(); i < j; i++)
4461 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4463 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4464 .getServiceClient(sh);
4465 int p = secstrmenu.getItemCount();
4466 impl.attachWSMenuEntry(secstrmenu, me);
4467 int q = secstrmenu.getItemCount();
4468 for (int litm = p; litm < q; litm++)
4470 legacyItems.add(secstrmenu.getItem(litm));
4476 // Add all submenus in the order they should appear on the web
4478 wsmenu.add(msawsmenu);
4479 wsmenu.add(secstrmenu);
4480 wsmenu.add(dismenu);
4481 wsmenu.add(analymenu);
4482 // No search services yet
4483 // wsmenu.add(seqsrchmenu);
4485 javax.swing.SwingUtilities.invokeLater(new Runnable()
4492 webService.removeAll();
4493 // first, add discovered services onto the webservices menu
4494 if (wsmenu.size() > 0)
4496 for (int i = 0, j = wsmenu.size(); i < j; i++)
4498 webService.add(wsmenu.get(i));
4503 webService.add(me.webServiceNoServices);
4505 // TODO: move into separate menu builder class.
4506 boolean new_sspred = false;
4507 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4509 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4510 if (jws2servs != null)
4512 if (jws2servs.hasServices())
4514 jws2servs.attachWSMenuEntry(webService, me);
4515 for (Jws2Instance sv : jws2servs.getServices())
4517 if (sv.description.toLowerCase().contains("jpred"))
4519 for (JMenuItem jmi : legacyItems)
4521 jmi.setVisible(false);
4527 if (jws2servs.isRunning())
4529 JMenuItem tm = new JMenuItem(
4530 "Still discovering JABA Services");
4531 tm.setEnabled(false);
4536 build_urlServiceMenu(me.webService);
4537 build_fetchdbmenu(webService);
4538 for (JMenu item : wsmenu)
4540 if (item.getItemCount() == 0)
4542 item.setEnabled(false);
4546 item.setEnabled(true);
4549 } catch (Exception e)
4552 .debug("Exception during web service menu building process.",
4558 } catch (Exception e)
4563 buildingMenu = false;
4570 * construct any groupURL type service menu entries.
4574 private void build_urlServiceMenu(JMenu webService)
4576 // TODO: remove this code when 2.7 is released
4577 // DEBUG - alignmentView
4579 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4580 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4582 * @Override public void actionPerformed(ActionEvent e) {
4583 * jalview.datamodel.AlignmentView
4584 * .testSelectionViews(af.viewport.getAlignment(),
4585 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4587 * }); webService.add(testAlView);
4589 // TODO: refactor to RestClient discoverer and merge menu entries for
4590 // rest-style services with other types of analysis/calculation service
4591 // SHmmr test client - still being implemented.
4592 // DEBUG - alignmentView
4594 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4597 client.attachWSMenuEntry(
4598 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4604 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
4605 * chooser = new JalviewFileChooser(jalview.bin.Cache.
4606 * getProperty("LAST_DIRECTORY"));
4608 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
4609 * to Vamsas file"); chooser.setToolTipText("Export");
4611 * int value = chooser.showSaveDialog(this);
4613 * if (value == JalviewFileChooser.APPROVE_OPTION) {
4614 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
4615 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
4616 * chooser.getSelectedFile().getAbsolutePath(), this); } }
4619 * prototype of an automatically enabled/disabled analysis function
4622 protected void setShowProductsEnabled()
4624 SequenceI[] selection = viewport.getSequenceSelection();
4625 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
4626 viewport.getAlignment().getDataset()))
4628 showProducts.setEnabled(true);
4633 showProducts.setEnabled(false);
4638 * search selection for sequence xRef products and build the show products
4643 * @return true if showProducts menu should be enabled.
4645 public boolean canShowProducts(SequenceI[] selection,
4646 boolean isRegionSelection, Alignment dataset)
4648 boolean showp = false;
4651 showProducts.removeAll();
4652 final boolean dna = viewport.getAlignment().isNucleotide();
4653 final Alignment ds = dataset;
4654 String[] ptypes = (selection == null || selection.length == 0) ? null
4655 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4657 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4658 // selection, dataset, true);
4659 final SequenceI[] sel = selection;
4660 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4663 final boolean isRegSel = isRegionSelection;
4664 final AlignFrame af = this;
4665 final String source = ptypes[t];
4666 JMenuItem xtype = new JMenuItem(ptypes[t]);
4667 xtype.addActionListener(new ActionListener()
4671 public void actionPerformed(ActionEvent e)
4673 // TODO: new thread for this call with vis-delay
4674 af.showProductsFor(af.viewport.getSequenceSelection(), ds,
4675 isRegSel, dna, source);
4679 showProducts.add(xtype);
4681 showProducts.setVisible(showp);
4682 showProducts.setEnabled(showp);
4683 } catch (Exception e)
4685 jalview.bin.Cache.log
4686 .warn("canTranslate threw an exception - please report to help@jalview.org",
4693 protected void showProductsFor(SequenceI[] sel, Alignment ds,
4694 boolean isRegSel, boolean dna, String source)
4696 final boolean fisRegSel = isRegSel;
4697 final boolean fdna = dna;
4698 final String fsrc = source;
4699 final AlignFrame ths = this;
4700 final SequenceI[] fsel = sel;
4701 Runnable foo = new Runnable()
4707 final long sttime = System.currentTimeMillis();
4708 ths.setProgressBar(MessageManager.formatMessage("status.searching_for_sequences_from", new String[]{fsrc}), sttime);
4711 Alignment ds = ths.getViewport().getAlignment().getDataset(); // update
4715 Alignment prods = CrossRef
4716 .findXrefSequences(fsel, fdna, fsrc, ds);
4719 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4720 for (int s = 0; s < sprods.length; s++)
4722 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4723 if (ds.getSequences() == null
4724 || !ds.getSequences().contains(
4725 sprods[s].getDatasetSequence()))
4727 ds.addSequence(sprods[s].getDatasetSequence());
4729 sprods[s].updatePDBIds();
4731 Alignment al = new Alignment(sprods);
4732 AlignedCodonFrame[] cf = prods.getCodonFrames();
4734 for (int s = 0; cf != null && s < cf.length; s++)
4736 al.addCodonFrame(cf[s]);
4739 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4741 String newtitle = "" + ((fdna) ? "Proteins " : "Nucleotides ")
4742 + " for " + ((fisRegSel) ? "selected region of " : "")
4744 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4749 System.err.println("No Sequences generated for xRef type "
4752 } catch (Exception e)
4754 jalview.bin.Cache.log.error(
4755 "Exception when finding crossreferences", e);
4756 } catch (OutOfMemoryError e)
4758 new OOMWarning("whilst fetching crossreferences", e);
4761 jalview.bin.Cache.log.error("Error when finding crossreferences",
4764 ths.setProgressBar(MessageManager.formatMessage("status.finished_searching_for_sequences_from", new String[]{fsrc}),
4769 Thread frunner = new Thread(foo);
4773 public boolean canShowTranslationProducts(SequenceI[] selection,
4774 AlignmentI alignment)
4779 return (jalview.analysis.Dna.canTranslate(selection,
4780 viewport.getViewAsVisibleContigs(true)));
4781 } catch (Exception e)
4783 jalview.bin.Cache.log
4784 .warn("canTranslate threw an exception - please report to help@jalview.org",
4791 public void showProducts_actionPerformed(ActionEvent e)
4793 // /////////////////////////////
4794 // Collect Data to be translated/transferred
4796 SequenceI[] selection = viewport.getSequenceSelection();
4797 AlignmentI al = null;
4800 al = jalview.analysis.Dna.CdnaTranslate(selection, viewport
4801 .getViewAsVisibleContigs(true), viewport.getGapCharacter(),
4802 viewport.getAlignment().getDataset());
4803 } catch (Exception ex)
4806 jalview.bin.Cache.log.debug("Exception during translation.", ex);
4814 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation"),
4815 MessageManager.getString("label.translation_failed"),
4816 JOptionPane.WARNING_MESSAGE);
4820 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4821 Desktop.addInternalFrame(af, MessageManager.formatMessage(
4822 "label.translation_of_params", new String[]
4823 { this.getTitle() }), DEFAULT_WIDTH, DEFAULT_HEIGHT);
4828 public void showTranslation_actionPerformed(ActionEvent e)
4830 // /////////////////////////////
4831 // Collect Data to be translated/transferred
4833 SequenceI[] selection = viewport.getSequenceSelection();
4834 String[] seqstring = viewport.getViewAsString(true);
4835 AlignmentI al = null;
4838 al = jalview.analysis.Dna.CdnaTranslate(selection, seqstring,
4839 viewport.getViewAsVisibleContigs(true), viewport
4840 .getGapCharacter(), viewport.getAlignment()
4841 .getAlignmentAnnotation(), viewport.getAlignment()
4842 .getWidth(), viewport.getAlignment().getDataset());
4843 } catch (Exception ex)
4846 jalview.bin.Cache.log.error(
4847 "Exception during translation. Please report this !", ex);
4852 .getString("label.error_when_translating_sequences_submit_bug_report"),
4854 .getString("label.implementation_error")
4856 .getString("translation_failed"),
4857 JOptionPane.ERROR_MESSAGE);
4866 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation"),
4867 MessageManager.getString("label.translation_failed"),
4868 JOptionPane.WARNING_MESSAGE);
4872 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4873 Desktop.addInternalFrame(af, MessageManager.formatMessage(
4874 "label.translation_of_params", new String[]
4875 { this.getTitle() }), DEFAULT_WIDTH, DEFAULT_HEIGHT);
4880 * Try to load a features file onto the alignment.
4883 * contents or path to retrieve file
4885 * access mode of file (see jalview.io.AlignFile)
4886 * @return true if features file was parsed corectly.
4888 public boolean parseFeaturesFile(String file, String type)
4890 boolean featuresFile = false;
4893 featuresFile = new FeaturesFile(file, type).parse(viewport
4894 .getAlignment().getDataset(), alignPanel.seqPanel.seqCanvas
4895 .getFeatureRenderer().featureColours, false,
4896 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4897 } catch (Exception ex)
4899 ex.printStackTrace();
4904 viewport.showSequenceFeatures = true;
4905 showSeqFeatures.setSelected(true);
4906 if (alignPanel.seqPanel.seqCanvas.fr != null)
4908 // update the min/max ranges where necessary
4909 alignPanel.seqPanel.seqCanvas.fr.findAllFeatures(true);
4911 if (featureSettings != null)
4913 featureSettings.setTableData();
4915 alignPanel.paintAlignment(true);
4918 return featuresFile;
4922 public void dragEnter(DropTargetDragEvent evt)
4927 public void dragExit(DropTargetEvent evt)
4932 public void dragOver(DropTargetDragEvent evt)
4937 public void dropActionChanged(DropTargetDragEvent evt)
4942 public void drop(DropTargetDropEvent evt)
4944 Transferable t = evt.getTransferable();
4945 java.util.List files = null;
4949 DataFlavor uriListFlavor = new DataFlavor(
4950 "text/uri-list;class=java.lang.String");
4951 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
4953 // Works on Windows and MacOSX
4954 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4955 files = (java.util.List) t
4956 .getTransferData(DataFlavor.javaFileListFlavor);
4958 else if (t.isDataFlavorSupported(uriListFlavor))
4960 // This is used by Unix drag system
4961 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4962 String data = (String) t.getTransferData(uriListFlavor);
4963 files = new java.util.ArrayList(1);
4964 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
4965 data, "\r\n"); st.hasMoreTokens();)
4967 String s = st.nextToken();
4968 if (s.startsWith("#"))
4970 // the line is a comment (as per the RFC 2483)
4974 java.net.URI uri = new java.net.URI(s);
4975 // check to see if we can handle this kind of URI
4976 if (uri.getScheme().toLowerCase().startsWith("http"))
4978 files.add(uri.toString());
4982 // otherwise preserve old behaviour: catch all for file objects
4983 java.io.File file = new java.io.File(uri);
4984 files.add(file.toString());
4988 } catch (Exception e)
4990 e.printStackTrace();
4996 // check to see if any of these files have names matching sequences in
4998 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4999 .getAlignment().getSequencesArray());
5001 * Object[] { String,SequenceI}
5003 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
5004 ArrayList<String> filesnotmatched = new ArrayList<String>();
5005 for (int i = 0; i < files.size(); i++)
5007 String file = files.get(i).toString();
5009 String protocol = FormatAdapter.checkProtocol(file);
5010 if (protocol == jalview.io.FormatAdapter.FILE)
5012 File fl = new File(file);
5013 pdbfn = fl.getName();
5015 else if (protocol == jalview.io.FormatAdapter.URL)
5017 URL url = new URL(file);
5018 pdbfn = url.getFile();
5020 if (pdbfn.length() > 0)
5022 // attempt to find a match in the alignment
5023 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5024 int l = 0, c = pdbfn.indexOf(".");
5025 while (mtch == null && c != -1)
5030 } while ((c = pdbfn.indexOf(".", l)) > l);
5033 pdbfn = pdbfn.substring(0, l);
5035 mtch = idm.findAllIdMatches(pdbfn);
5042 type = new IdentifyFile().Identify(file, protocol);
5043 } catch (Exception ex)
5049 if (type.equalsIgnoreCase("PDB"))
5051 filesmatched.add(new Object[]
5052 { file, protocol, mtch });
5057 // File wasn't named like one of the sequences or wasn't a PDB file.
5058 filesnotmatched.add(file);
5062 if (filesmatched.size() > 0)
5064 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
5070 "label.automatically_associate_pdb_files_with_sequences_same_name",
5077 .getString("label.automatically_associate_pdb_files_by_name"),
5078 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
5081 for (Object[] fm : filesmatched)
5083 // try and associate
5084 // TODO: may want to set a standard ID naming formalism for
5085 // associating PDB files which have no IDs.
5086 for (SequenceI toassoc : (SequenceI[]) fm[2])
5088 PDBEntry pe = new AssociatePdbFileWithSeq()
5089 .associatePdbWithSeq((String) fm[0],
5090 (String) fm[1], toassoc, false,
5094 System.err.println("Associated file : "
5095 + ((String) fm[0]) + " with "
5096 + toassoc.getDisplayId(true));
5100 alignPanel.paintAlignment(true);
5104 if (filesnotmatched.size() > 0)
5107 && (Cache.getDefault(
5108 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
5111 "<html>"+MessageManager
5113 "label.ignore_unmatched_dropped_files_info",
5118 .toString() })+"</html>",
5120 .getString("label.ignore_unmatched_dropped_files"),
5121 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
5125 for (String fn : filesnotmatched)
5127 loadJalviewDataFile(fn, null, null, null);
5131 } catch (Exception ex)
5133 ex.printStackTrace();
5139 * Attempt to load a "dropped" file or URL string: First by testing whether
5140 * it's and Annotation file, then a JNet file, and finally a features file. If
5141 * all are false then the user may have dropped an alignment file onto this
5145 * either a filename or a URL string.
5147 public void loadJalviewDataFile(String file, String protocol,
5148 String format, SequenceI assocSeq)
5152 if (protocol == null)
5154 protocol = jalview.io.FormatAdapter.checkProtocol(file);
5156 // if the file isn't identified, or not positively identified as some
5157 // other filetype (PFAM is default unidentified alignment file type) then
5158 // try to parse as annotation.
5159 boolean isAnnotation = (format == null || format
5160 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
5161 .readAnnotationFile(viewport.getAlignment(), file, protocol)
5166 // first see if its a T-COFFEE score file
5167 TCoffeeScoreFile tcf = null;
5170 tcf = new TCoffeeScoreFile(file, protocol);
5173 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5175 tcoffeeColour.setEnabled(true);
5176 tcoffeeColour.setSelected(true);
5177 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5178 isAnnotation = true;
5180 .setText(MessageManager
5181 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5185 // some problem - if no warning its probable that the ID matching
5186 // process didn't work
5190 tcf.getWarningMessage() == null ? MessageManager
5191 .getString("label.check_file_matches_sequence_ids_alignment")
5192 : tcf.getWarningMessage(),
5194 .getString("label.problem_reading_tcoffee_score_file"),
5195 JOptionPane.WARNING_MESSAGE);
5202 } catch (Exception x)
5205 .debug("Exception when processing data source as T-COFFEE score file",
5211 // try to see if its a JNet 'concise' style annotation file *before*
5213 // try to parse it as a features file
5216 format = new IdentifyFile().Identify(file, protocol);
5218 if (format.equalsIgnoreCase("JnetFile"))
5220 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5222 new JnetAnnotationMaker().add_annotation(predictions,
5223 viewport.getAlignment(), 0, false);
5224 isAnnotation = true;
5229 * if (format.equalsIgnoreCase("PDB")) {
5231 * String pdbfn = ""; // try to match up filename with sequence id
5232 * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
5233 * new File(file); pdbfn = fl.getName(); } else if (protocol ==
5234 * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
5235 * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
5236 * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5237 * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
5238 * // attempt to find a match in the alignment SequenceI mtch =
5239 * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
5240 * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
5241 * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
5242 * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
5243 * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
5244 * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
5245 * { System.err.println("Associated file : " + file + " with " +
5246 * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
5247 * TODO: maybe need to load as normal otherwise return; } }
5249 // try to parse it as a features file
5250 boolean isGroupsFile = parseFeaturesFile(file, protocol);
5251 // if it wasn't a features file then we just treat it as a general
5252 // alignment file to load into the current view.
5255 new FileLoader().LoadFile(viewport, file, protocol, format);
5259 alignPanel.paintAlignment(true);
5267 alignPanel.adjustAnnotationHeight();
5268 viewport.updateSequenceIdColours();
5269 buildSortByAnnotationScoresMenu();
5270 alignPanel.paintAlignment(true);
5272 } catch (Exception ex)
5274 ex.printStackTrace();
5275 } catch (OutOfMemoryError oom)
5280 } catch (Exception x)
5286 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5287 : "using " + protocol + " from " + file)
5289 + (format != null ? "(parsing as '" + format
5290 + "' file)" : ""), oom, Desktop.desktop);
5295 public void tabSelectionChanged(int index)
5299 alignPanel = (AlignmentPanel) alignPanels.elementAt(index);
5300 viewport = alignPanel.av;
5301 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5302 setMenusFromViewport(viewport);
5307 public void tabbedPane_mousePressed(MouseEvent e)
5309 if (SwingUtilities.isRightMouseButton(e))
5311 String reply = JOptionPane.showInternalInputDialog(this,
5312 MessageManager.getString("label.enter_view_name"),
5313 MessageManager.getString("label.enter_view_name"),
5314 JOptionPane.QUESTION_MESSAGE);
5318 viewport.viewName = reply;
5319 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5324 public AlignViewport getCurrentView()
5330 * Open the dialog for regex description parsing.
5333 protected void extractScores_actionPerformed(ActionEvent e)
5335 ParseProperties pp = new jalview.analysis.ParseProperties(
5336 viewport.getAlignment());
5337 // TODO: verify regex and introduce GUI dialog for version 2.5
5338 // if (pp.getScoresFromDescription("col", "score column ",
5339 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5341 if (pp.getScoresFromDescription("description column",
5342 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5344 buildSortByAnnotationScoresMenu();
5352 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5356 protected void showDbRefs_actionPerformed(ActionEvent e)
5358 viewport.setShowDbRefs(showDbRefsMenuitem.isSelected());
5364 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5368 protected void showNpFeats_actionPerformed(ActionEvent e)
5370 viewport.setShowNpFeats(showNpFeatsMenuitem.isSelected());
5374 * find the viewport amongst the tabs in this alignment frame and close that
5379 public boolean closeView(AlignViewport av)
5383 this.closeMenuItem_actionPerformed(false);
5386 Component[] comp = tabbedPane.getComponents();
5387 for (int i = 0; comp != null && i < comp.length; i++)
5389 if (comp[i] instanceof AlignmentPanel)
5391 if (((AlignmentPanel) comp[i]).av == av)
5394 closeView((AlignmentPanel) comp[i]);
5402 protected void build_fetchdbmenu(JMenu webService)
5404 // Temporary hack - DBRef Fetcher always top level ws entry.
5405 // TODO We probably want to store a sequence database checklist in
5406 // preferences and have checkboxes.. rather than individual sources selected
5408 final JMenu rfetch = new JMenu(
5409 MessageManager.getString("action.fetch_db_references"));
5410 rfetch.setToolTipText(MessageManager
5411 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5412 webService.add(rfetch);
5414 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5415 MessageManager.getString("option.trim_retrieved_seqs"));
5416 trimrs.setToolTipText(MessageManager
5417 .getString("label.trim_retrieved_sequences"));
5418 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5419 trimrs.addActionListener(new ActionListener()
5422 public void actionPerformed(ActionEvent e)
5424 trimrs.setSelected(trimrs.isSelected());
5425 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5426 Boolean.valueOf(trimrs.isSelected()).toString());
5430 JMenuItem fetchr = new JMenuItem(
5431 MessageManager.getString("label.standard_databases"));
5432 fetchr.setToolTipText(MessageManager
5433 .getString("label.fetch_embl_uniprot"));
5434 fetchr.addActionListener(new ActionListener()
5438 public void actionPerformed(ActionEvent e)
5440 new Thread(new Runnable()
5446 new jalview.ws.DBRefFetcher(alignPanel.av
5447 .getSequenceSelection(), alignPanel.alignFrame)
5448 .fetchDBRefs(false);
5456 final AlignFrame me = this;
5457 new Thread(new Runnable()
5462 final jalview.ws.SequenceFetcher sf = SequenceFetcher
5463 .getSequenceFetcherSingleton(me);
5464 javax.swing.SwingUtilities.invokeLater(new Runnable()
5469 String[] dbclasses = sf.getOrderedSupportedSources();
5470 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5471 // jalview.util.QuickSort.sort(otherdb, otherdb);
5472 List<DbSourceProxy> otherdb;
5473 JMenu dfetch = new JMenu();
5474 JMenu ifetch = new JMenu();
5475 JMenuItem fetchr = null;
5476 int comp = 0, icomp = 0, mcomp = 15;
5477 String mname = null;
5479 for (String dbclass : dbclasses)
5481 otherdb = sf.getSourceProxy(dbclass);
5482 // add a single entry for this class, or submenu allowing 'fetch
5484 if (otherdb == null || otherdb.size() < 1)
5488 // List<DbSourceProxy> dbs=otherdb;
5489 // otherdb=new ArrayList<DbSourceProxy>();
5490 // for (DbSourceProxy db:dbs)
5492 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5496 mname = "From " + dbclass;
5498 if (otherdb.size() == 1)
5500 final DbSourceProxy[] dassource = otherdb
5501 .toArray(new DbSourceProxy[0]);
5502 DbSourceProxy src = otherdb.get(0);
5503 fetchr = new JMenuItem(src.getDbSource());
5504 fetchr.addActionListener(new ActionListener()
5508 public void actionPerformed(ActionEvent e)
5510 new Thread(new Runnable()
5516 new jalview.ws.DBRefFetcher(alignPanel.av
5517 .getSequenceSelection(),
5518 alignPanel.alignFrame, dassource)
5519 .fetchDBRefs(false);
5525 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from", new String[]{src.getDbName()})));
5531 final DbSourceProxy[] dassource = otherdb
5532 .toArray(new DbSourceProxy[0]);
5534 DbSourceProxy src = otherdb.get(0);
5535 fetchr = new JMenuItem(MessageManager.formatMessage(
5536 "label.fetch_all_param", new String[]
5537 { src.getDbSource() }));
5538 fetchr.addActionListener(new ActionListener()
5541 public void actionPerformed(ActionEvent e)
5543 new Thread(new Runnable()
5549 new jalview.ws.DBRefFetcher(alignPanel.av
5550 .getSequenceSelection(),
5551 alignPanel.alignFrame, dassource)
5552 .fetchDBRefs(false);
5558 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from_all_sources", new String[]{Integer.valueOf(otherdb.size()).toString(), src.getDbSource(), src.getDbName()})));
5561 // and then build the rest of the individual menus
5562 ifetch = new JMenu(MessageManager.formatMessage("label.source_from_db_source", new String[]{src.getDbSource()}));
5564 String imname = null;
5566 for (DbSourceProxy sproxy : otherdb)
5568 String dbname = sproxy.getDbName();
5569 String sname = dbname.length() > 5 ? dbname.substring(0,
5570 5) + "..." : dbname;
5571 String msname = dbname.length() > 10 ? dbname.substring(
5572 0, 10) + "..." : dbname;
5575 imname = MessageManager.formatMessage("label.from_msname", new String[]{sname});
5577 fetchr = new JMenuItem(msname);
5578 final DbSourceProxy[] dassrc =
5580 fetchr.addActionListener(new ActionListener()
5584 public void actionPerformed(ActionEvent e)
5586 new Thread(new Runnable()
5592 new jalview.ws.DBRefFetcher(alignPanel.av
5593 .getSequenceSelection(),
5594 alignPanel.alignFrame, dassrc)
5595 .fetchDBRefs(false);
5601 fetchr.setToolTipText("<html>"
5602 + MessageManager.formatMessage("label.fetch_retrieve_from", new String[]{dbname}));
5605 if (++icomp >= mcomp || i == (otherdb.size()))
5607 ifetch.setText(MessageManager.formatMessage(
5608 "label.source_to_target", imname, sname));
5610 ifetch = new JMenu();
5618 if (comp >= mcomp || dbi >= (dbclasses.length))
5620 dfetch.setText(MessageManager.formatMessage(
5621 "label.source_to_target", mname, dbclass));
5623 dfetch = new JMenu();
5636 * Left justify the whole alignment.
5639 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5641 AlignmentI al = viewport.getAlignment();
5643 viewport.firePropertyChange("alignment", null, al);
5647 * Right justify the whole alignment.
5650 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5652 AlignmentI al = viewport.getAlignment();
5654 viewport.firePropertyChange("alignment", null, al);
5657 public void setShowSeqFeatures(boolean b)
5659 showSeqFeatures.setSelected(true);
5660 viewport.setShowSequenceFeatures(true);
5667 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5668 * awt.event.ActionEvent)
5671 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5673 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5674 alignPanel.paintAlignment(true);
5681 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5685 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5687 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5688 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5696 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5697 * .event.ActionEvent)
5700 protected void showGroupConservation_actionPerformed(ActionEvent e)
5702 viewport.setShowGroupConservation(showGroupConservation.getState());
5703 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5710 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5711 * .event.ActionEvent)
5714 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5716 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5717 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5724 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5725 * .event.ActionEvent)
5728 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5730 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5731 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5735 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5737 showSequenceLogo.setState(true);
5738 viewport.setShowSequenceLogo(true);
5739 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5740 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5744 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5746 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5753 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5754 * .event.ActionEvent)
5757 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5759 if (avc.makeGroupsFromSelection())
5761 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5762 alignPanel.updateAnnotation();
5763 alignPanel.paintAlignment(true);
5768 protected void createGroup_actionPerformed(ActionEvent e)
5770 if (avc.createGroup())
5772 alignPanel.alignmentChanged();
5777 protected void unGroup_actionPerformed(ActionEvent e)
5781 alignPanel.alignmentChanged();
5786 * make the given alignmentPanel the currently selected tab
5788 * @param alignmentPanel
5790 public void setDisplayedView(AlignmentPanel alignmentPanel)
5792 if (!viewport.getSequenceSetId().equals(
5793 alignmentPanel.av.getSequenceSetId()))
5795 throw new Error(MessageManager.getString("error.implementation_error_cannot_show_view_alignment_frame"));
5797 if (tabbedPane != null
5798 & alignPanels.indexOf(alignmentPanel) != tabbedPane
5799 .getSelectedIndex())
5801 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5806 * Action on selection of menu options to Show or Hide annotations.
5809 * @param forSequences
5810 * update sequence-related annotations
5811 * @param forAlignment
5812 * update non-sequence-related annotations
5815 protected void setAnnotationsVisibility(boolean visible,
5816 boolean forSequences, boolean forAlignment)
5818 for (AlignmentAnnotation aa : alignPanel.getAlignment()
5819 .getAlignmentAnnotation())
5821 boolean apply = (aa.sequenceRef == null && forAlignment)
5822 || (aa.sequenceRef != null && forSequences);
5825 aa.visible = visible;
5828 alignPanel.validateAnnotationDimensions(false);
5829 alignPanel.alignmentChanged();
5833 * Store selected annotation sort order for the view and repaint.
5836 protected void sortAnnotations_actionPerformed()
5838 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5840 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5841 alignPanel.paintAlignment(true);
5846 * @return alignment panels in this alignemnt frame
5848 public List<AlignmentViewPanel> getAlignPanels()
5850 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5854 class PrintThread extends Thread
5858 public PrintThread(AlignmentPanel ap)
5863 static PageFormat pf;
5868 PrinterJob printJob = PrinterJob.getPrinterJob();
5872 printJob.setPrintable(ap, pf);
5876 printJob.setPrintable(ap);
5879 if (printJob.printDialog())
5884 } catch (Exception PrintException)
5886 PrintException.printStackTrace();