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.AnnotationSorter.SortOrder;
27 import jalview.analysis.Conservation;
28 import jalview.analysis.CrossRef;
29 import jalview.analysis.NJTree;
30 import jalview.analysis.ParseProperties;
31 import jalview.analysis.SequenceIdMatcher;
32 import jalview.api.AlignViewControllerGuiI;
33 import jalview.api.AlignViewControllerI;
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.OrderCommand;
39 import jalview.commands.RemoveGapColCommand;
40 import jalview.commands.RemoveGapsCommand;
41 import jalview.commands.SlideSequencesCommand;
42 import jalview.commands.TrimRegionCommand;
43 import jalview.datamodel.AlignedCodonFrame;
44 import jalview.datamodel.Alignment;
45 import jalview.datamodel.AlignmentAnnotation;
46 import jalview.datamodel.AlignmentI;
47 import jalview.datamodel.AlignmentOrder;
48 import jalview.datamodel.AlignmentView;
49 import jalview.datamodel.ColumnSelection;
50 import jalview.datamodel.PDBEntry;
51 import jalview.datamodel.SeqCigar;
52 import jalview.datamodel.Sequence;
53 import jalview.datamodel.SequenceGroup;
54 import jalview.datamodel.SequenceI;
55 import jalview.io.AlignmentProperties;
56 import jalview.io.AnnotationFile;
57 import jalview.io.FeaturesFile;
58 import jalview.io.FileLoader;
59 import jalview.io.FormatAdapter;
60 import jalview.io.HTMLOutput;
61 import jalview.io.IdentifyFile;
62 import jalview.io.JalviewFileChooser;
63 import jalview.io.JalviewFileView;
64 import jalview.io.JnetAnnotationMaker;
65 import jalview.io.NewickFile;
66 import jalview.io.TCoffeeScoreFile;
67 import jalview.jbgui.GAlignFrame;
68 import jalview.schemes.Blosum62ColourScheme;
69 import jalview.schemes.BuriedColourScheme;
70 import jalview.schemes.ClustalxColourScheme;
71 import jalview.schemes.ColourSchemeI;
72 import jalview.schemes.ColourSchemeProperty;
73 import jalview.schemes.HelixColourScheme;
74 import jalview.schemes.HydrophobicColourScheme;
75 import jalview.schemes.NucleotideColourScheme;
76 import jalview.schemes.PIDColourScheme;
77 import jalview.schemes.PurinePyrimidineColourScheme;
78 import jalview.schemes.RNAHelicesColourChooser;
79 import jalview.schemes.ResidueProperties;
80 import jalview.schemes.StrandColourScheme;
81 import jalview.schemes.TCoffeeColourScheme;
82 import jalview.schemes.TaylorColourScheme;
83 import jalview.schemes.TurnColourScheme;
84 import jalview.schemes.UserColourScheme;
85 import jalview.schemes.ZappoColourScheme;
86 import jalview.util.MessageManager;
87 import jalview.ws.jws1.Discoverer;
88 import jalview.ws.jws2.Jws2Discoverer;
89 import jalview.ws.jws2.jabaws2.Jws2Instance;
90 import jalview.ws.seqfetcher.DbSourceProxy;
92 import java.awt.BorderLayout;
93 import java.awt.Component;
94 import java.awt.GridLayout;
95 import java.awt.Rectangle;
96 import java.awt.Toolkit;
97 import java.awt.datatransfer.Clipboard;
98 import java.awt.datatransfer.DataFlavor;
99 import java.awt.datatransfer.StringSelection;
100 import java.awt.datatransfer.Transferable;
101 import java.awt.dnd.DnDConstants;
102 import java.awt.dnd.DropTargetDragEvent;
103 import java.awt.dnd.DropTargetDropEvent;
104 import java.awt.dnd.DropTargetEvent;
105 import java.awt.dnd.DropTargetListener;
106 import java.awt.event.ActionEvent;
107 import java.awt.event.ActionListener;
108 import java.awt.event.KeyAdapter;
109 import java.awt.event.KeyEvent;
110 import java.awt.event.MouseAdapter;
111 import java.awt.event.MouseEvent;
112 import java.awt.print.PageFormat;
113 import java.awt.print.PrinterJob;
114 import java.beans.PropertyChangeEvent;
117 import java.util.ArrayList;
118 import java.util.Enumeration;
119 import java.util.Hashtable;
120 import java.util.List;
121 import java.util.Vector;
123 import javax.swing.JButton;
124 import javax.swing.JCheckBoxMenuItem;
125 import javax.swing.JEditorPane;
126 import javax.swing.JInternalFrame;
127 import javax.swing.JLabel;
128 import javax.swing.JLayeredPane;
129 import javax.swing.JMenu;
130 import javax.swing.JMenuItem;
131 import javax.swing.JOptionPane;
132 import javax.swing.JPanel;
133 import javax.swing.JProgressBar;
134 import javax.swing.JRadioButtonMenuItem;
135 import javax.swing.JScrollPane;
136 import javax.swing.SwingUtilities;
142 * @version $Revision$
144 public class AlignFrame extends GAlignFrame implements DropTargetListener,
145 IProgressIndicator, AlignViewControllerGuiI
149 public static final int DEFAULT_WIDTH = 700;
152 public static final int DEFAULT_HEIGHT = 500;
154 public AlignmentPanel alignPanel;
156 AlignViewport viewport;
158 public AlignViewControllerI avc;
160 Vector alignPanels = new Vector();
163 * Last format used to load or save alignments in this window
165 String currentFileFormat = null;
168 * Current filename for this alignment
170 String fileName = null;
173 * Creates a new AlignFrame object with specific width and height.
179 public AlignFrame(AlignmentI al, int width, int height)
181 this(al, null, width, height);
185 * Creates a new AlignFrame object with specific width, height and
191 * @param sequenceSetId
193 public AlignFrame(AlignmentI al, int width, int height,
194 String sequenceSetId)
196 this(al, null, width, height, sequenceSetId);
200 * Creates a new AlignFrame object with specific width, height and
206 * @param sequenceSetId
209 public AlignFrame(AlignmentI al, int width, int height,
210 String sequenceSetId, String viewId)
212 this(al, null, width, height, sequenceSetId, viewId);
216 * new alignment window with hidden columns
220 * @param hiddenColumns
221 * ColumnSelection or null
223 * Width of alignment frame
227 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
228 int width, int height)
230 this(al, hiddenColumns, width, height, null);
234 * Create alignment frame for al with hiddenColumns, a specific width and
235 * height, and specific sequenceId
238 * @param hiddenColumns
241 * @param sequenceSetId
244 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
245 int width, int height, String sequenceSetId)
247 this(al, hiddenColumns, width, height, sequenceSetId, null);
251 * Create alignment frame for al with hiddenColumns, a specific width and
252 * height, and specific sequenceId
255 * @param hiddenColumns
258 * @param sequenceSetId
263 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
264 int width, int height, String sequenceSetId, String viewId)
266 setSize(width, height);
268 if (al.getDataset() == null)
273 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
275 alignPanel = new AlignmentPanel(this, viewport);
278 addAlignmentPanel(alignPanel, true);
283 * Make a new AlignFrame from exisiting alignmentPanels
290 public AlignFrame(AlignmentPanel ap)
294 addAlignmentPanel(ap, false);
299 * initalise the alignframe from the underlying viewport data and the
304 avc = new jalview.controller.AlignViewController(this, viewport,
306 if (viewport.getAlignmentConservationAnnotation() == null)
308 BLOSUM62Colour.setEnabled(false);
309 conservationMenuItem.setEnabled(false);
310 modifyConservation.setEnabled(false);
311 // PIDColour.setEnabled(false);
312 // abovePIDThreshold.setEnabled(false);
313 // modifyPID.setEnabled(false);
316 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
319 if (sortby.equals("Id"))
321 sortIDMenuItem_actionPerformed(null);
323 else if (sortby.equals("Pairwise Identity"))
325 sortPairwiseMenuItem_actionPerformed(null);
328 if (Desktop.desktop != null)
330 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
331 addServiceListeners();
332 setGUINucleotide(viewport.getAlignment().isNucleotide());
335 setMenusFromViewport(viewport);
336 buildSortByAnnotationScoresMenu();
339 if (viewport.wrapAlignment)
341 wrapMenuItem_actionPerformed(null);
344 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
346 this.overviewMenuItem_actionPerformed(null);
354 * Change the filename and format for the alignment, and enable the 'reload'
355 * button functionality.
362 public void setFileName(String file, String format)
365 currentFileFormat = format;
366 reload.setEnabled(true);
369 void addKeyListener()
371 addKeyListener(new KeyAdapter()
374 public void keyPressed(KeyEvent evt)
376 if (viewport.cursorMode
377 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
378 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
379 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
380 && Character.isDigit(evt.getKeyChar()))
382 alignPanel.seqPanel.numberPressed(evt.getKeyChar());
385 switch (evt.getKeyCode())
388 case 27: // escape key
389 deselectAllSequenceMenuItem_actionPerformed(null);
393 case KeyEvent.VK_DOWN:
394 if (evt.isAltDown() || !viewport.cursorMode)
396 moveSelectedSequences(false);
398 if (viewport.cursorMode)
400 alignPanel.seqPanel.moveCursor(0, 1);
405 if (evt.isAltDown() || !viewport.cursorMode)
407 moveSelectedSequences(true);
409 if (viewport.cursorMode)
411 alignPanel.seqPanel.moveCursor(0, -1);
416 case KeyEvent.VK_LEFT:
417 if (evt.isAltDown() || !viewport.cursorMode)
419 slideSequences(false, alignPanel.seqPanel.getKeyboardNo1());
423 alignPanel.seqPanel.moveCursor(-1, 0);
428 case KeyEvent.VK_RIGHT:
429 if (evt.isAltDown() || !viewport.cursorMode)
431 slideSequences(true, alignPanel.seqPanel.getKeyboardNo1());
435 alignPanel.seqPanel.moveCursor(1, 0);
439 case KeyEvent.VK_SPACE:
440 if (viewport.cursorMode)
442 alignPanel.seqPanel.insertGapAtCursor(evt.isControlDown()
443 || evt.isShiftDown() || evt.isAltDown());
447 // case KeyEvent.VK_A:
448 // if (viewport.cursorMode)
450 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
451 // //System.out.println("A");
455 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
456 * System.out.println("closing bracket"); } break;
458 case KeyEvent.VK_DELETE:
459 case KeyEvent.VK_BACK_SPACE:
460 if (!viewport.cursorMode)
462 cut_actionPerformed(null);
466 alignPanel.seqPanel.deleteGapAtCursor(evt.isControlDown()
467 || evt.isShiftDown() || evt.isAltDown());
473 if (viewport.cursorMode)
475 alignPanel.seqPanel.setCursorRow();
479 if (viewport.cursorMode && !evt.isControlDown())
481 alignPanel.seqPanel.setCursorColumn();
485 if (viewport.cursorMode)
487 alignPanel.seqPanel.setCursorPosition();
491 case KeyEvent.VK_ENTER:
492 case KeyEvent.VK_COMMA:
493 if (viewport.cursorMode)
495 alignPanel.seqPanel.setCursorRowAndColumn();
500 if (viewport.cursorMode)
502 alignPanel.seqPanel.setSelectionAreaAtCursor(true);
506 if (viewport.cursorMode)
508 alignPanel.seqPanel.setSelectionAreaAtCursor(false);
513 viewport.cursorMode = !viewport.cursorMode;
514 statusBar.setText(MessageManager.formatMessage(
515 "label.keyboard_editing_mode", new String[]
516 { (viewport.cursorMode ? "on" : "off") }));
517 if (viewport.cursorMode)
519 alignPanel.seqPanel.seqCanvas.cursorX = viewport.startRes;
520 alignPanel.seqPanel.seqCanvas.cursorY = viewport.startSeq;
522 alignPanel.seqPanel.seqCanvas.repaint();
528 Help.showHelpWindow();
529 } catch (Exception ex)
531 ex.printStackTrace();
536 boolean toggleSeqs = !evt.isControlDown();
537 boolean toggleCols = !evt.isShiftDown();
538 toggleHiddenRegions(toggleSeqs, toggleCols);
541 case KeyEvent.VK_PAGE_UP:
542 if (viewport.wrapAlignment)
544 alignPanel.scrollUp(true);
548 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
549 - viewport.endSeq + viewport.startSeq);
552 case KeyEvent.VK_PAGE_DOWN:
553 if (viewport.wrapAlignment)
555 alignPanel.scrollUp(false);
559 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
560 + viewport.endSeq - viewport.startSeq);
567 public void keyReleased(KeyEvent evt)
569 switch (evt.getKeyCode())
571 case KeyEvent.VK_LEFT:
572 if (evt.isAltDown() || !viewport.cursorMode)
574 viewport.firePropertyChange("alignment", null, viewport
575 .getAlignment().getSequences());
579 case KeyEvent.VK_RIGHT:
580 if (evt.isAltDown() || !viewport.cursorMode)
582 viewport.firePropertyChange("alignment", null, viewport
583 .getAlignment().getSequences());
591 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
593 ap.alignFrame = this;
594 avc = new jalview.controller.AlignViewController(this, viewport,
597 alignPanels.addElement(ap);
599 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
601 int aSize = alignPanels.size();
603 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
605 if (aSize == 1 && ap.av.viewName == null)
607 this.getContentPane().add(ap, BorderLayout.CENTER);
613 setInitialTabVisible();
616 expandViews.setEnabled(true);
617 gatherViews.setEnabled(true);
618 tabbedPane.addTab(ap.av.viewName, ap);
620 ap.setVisible(false);
625 if (ap.av.isPadGaps())
627 ap.av.getAlignment().padGaps();
629 ap.av.updateConservation(ap);
630 ap.av.updateConsensus(ap);
631 ap.av.updateStrucConsensus(ap);
635 public void setInitialTabVisible()
637 expandViews.setEnabled(true);
638 gatherViews.setEnabled(true);
639 tabbedPane.setVisible(true);
640 AlignmentPanel first = (AlignmentPanel) alignPanels.firstElement();
641 tabbedPane.addTab(first.av.viewName, first);
642 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
645 public AlignViewport getViewport()
650 /* Set up intrinsic listeners for dynamically generated GUI bits. */
651 private void addServiceListeners()
653 final java.beans.PropertyChangeListener thisListener;
654 Desktop.instance.addJalviewPropertyChangeListener("services",
655 thisListener = new java.beans.PropertyChangeListener()
658 public void propertyChange(PropertyChangeEvent evt)
660 // // System.out.println("Discoverer property change.");
661 // if (evt.getPropertyName().equals("services"))
663 SwingUtilities.invokeLater(new Runnable()
670 .println("Rebuild WS Menu for service change");
671 BuildWebServiceMenu();
678 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
681 public void internalFrameClosed(
682 javax.swing.event.InternalFrameEvent evt)
684 System.out.println("deregistering discoverer listener");
685 Desktop.instance.removeJalviewPropertyChangeListener("services",
687 closeMenuItem_actionPerformed(true);
690 // Finally, build the menu once to get current service state
691 new Thread(new Runnable()
696 BuildWebServiceMenu();
701 public void setGUINucleotide(boolean nucleotide)
703 showTranslation.setVisible(nucleotide);
704 conservationMenuItem.setEnabled(!nucleotide);
705 modifyConservation.setEnabled(!nucleotide);
706 showGroupConservation.setEnabled(!nucleotide);
707 rnahelicesColour.setEnabled(nucleotide);
708 purinePyrimidineColour.setEnabled(nucleotide);
709 // Remember AlignFrame always starts as protein
713 // calculateMenu.remove(calculateMenu.getItemCount() - 2);
718 * set up menus for the currently viewport. This may be called after any
719 * operation that affects the data in the current view (selection changed,
720 * etc) to update the menus to reflect the new state.
722 public void setMenusForViewport()
724 setMenusFromViewport(viewport);
728 * Need to call this method when tabs are selected for multiple views, or when
729 * loading from Jalview2XML.java
734 void setMenusFromViewport(AlignViewport av)
736 padGapsMenuitem.setSelected(av.isPadGaps());
737 colourTextMenuItem.setSelected(av.showColourText);
738 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
739 conservationMenuItem.setSelected(av.getConservationSelected());
740 seqLimits.setSelected(av.getShowJVSuffix());
741 idRightAlign.setSelected(av.rightAlignIds);
742 centreColumnLabelsMenuItem.setState(av.centreColumnLabels);
743 renderGapsMenuItem.setSelected(av.renderGaps);
744 wrapMenuItem.setSelected(av.wrapAlignment);
745 scaleAbove.setVisible(av.wrapAlignment);
746 scaleLeft.setVisible(av.wrapAlignment);
747 scaleRight.setVisible(av.wrapAlignment);
748 annotationPanelMenuItem.setState(av.showAnnotation);
750 * Show/hide all annotations only enabled if annotation panel is shown
752 showAllAnnotations.setEnabled(annotationPanelMenuItem.getState());
753 hideAllAnnotations.setEnabled(annotationPanelMenuItem.getState());
754 viewBoxesMenuItem.setSelected(av.showBoxes);
755 viewTextMenuItem.setSelected(av.showText);
756 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
757 showGroupConsensus.setSelected(av.isShowGroupConsensus());
758 showGroupConservation.setSelected(av.isShowGroupConservation());
759 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
760 showSequenceLogo.setSelected(av.isShowSequenceLogo());
761 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
763 setColourSelected(ColourSchemeProperty.getColourName(av
764 .getGlobalColourScheme()));
766 showSeqFeatures.setSelected(av.showSequenceFeatures);
767 hiddenMarkers.setState(av.showHiddenMarkers);
768 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
769 showNpFeatsMenuitem.setSelected(av.isShowNpFeats());
770 showDbRefsMenuitem.setSelected(av.isShowDbRefs());
771 autoCalculate.setSelected(av.autoCalculateConsensus);
772 sortByTree.setSelected(av.sortByTree);
773 listenToViewSelections.setSelected(av.followSelection);
774 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
776 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
777 setShowProductsEnabled();
781 // methods for implementing IProgressIndicator
782 // need to refactor to a reusable stub class
783 Hashtable progressBars, progressBarHandlers;
788 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
791 public void setProgressBar(String message, long id)
793 if (progressBars == null)
795 progressBars = new Hashtable();
796 progressBarHandlers = new Hashtable();
799 JPanel progressPanel;
800 Long lId = new Long(id);
801 GridLayout layout = (GridLayout) statusPanel.getLayout();
802 if (progressBars.get(lId) != null)
804 progressPanel = (JPanel) progressBars.get(new Long(id));
805 statusPanel.remove(progressPanel);
806 progressBars.remove(lId);
807 progressPanel = null;
810 statusBar.setText(message);
812 if (progressBarHandlers.contains(lId))
814 progressBarHandlers.remove(lId);
816 layout.setRows(layout.getRows() - 1);
820 progressPanel = new JPanel(new BorderLayout(10, 5));
822 JProgressBar progressBar = new JProgressBar();
823 progressBar.setIndeterminate(true);
825 progressPanel.add(new JLabel(message), BorderLayout.WEST);
826 progressPanel.add(progressBar, BorderLayout.CENTER);
828 layout.setRows(layout.getRows() + 1);
829 statusPanel.add(progressPanel);
831 progressBars.put(lId, progressPanel);
834 // setMenusForViewport();
839 public void registerHandler(final long id,
840 final IProgressIndicatorHandler handler)
842 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
844 throw new Error(MessageManager.getString("error.call_setprogressbar_before_registering_handler"));
846 progressBarHandlers.put(new Long(id), handler);
847 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
848 if (handler.canCancel())
850 JButton cancel = new JButton(
851 MessageManager.getString("action.cancel"));
852 final IProgressIndicator us = this;
853 cancel.addActionListener(new ActionListener()
857 public void actionPerformed(ActionEvent e)
859 handler.cancelActivity(id);
860 us.setProgressBar(MessageManager.formatMessage("label.cancelled_params", new String[]{((JLabel) progressPanel.getComponent(0)).getText()}), id);
863 progressPanel.add(cancel, BorderLayout.EAST);
869 * @return true if any progress bars are still active
872 public boolean operationInProgress()
874 if (progressBars != null && progressBars.size() > 0)
882 public void setStatus(String text)
884 statusBar.setText(text);
888 * Added so Castor Mapping file can obtain Jalview Version
890 public String getVersion()
892 return jalview.bin.Cache.getProperty("VERSION");
895 public FeatureRenderer getFeatureRenderer()
897 return alignPanel.seqPanel.seqCanvas.getFeatureRenderer();
901 public void fetchSequence_actionPerformed(ActionEvent e)
903 new SequenceFetcher(this);
907 public void addFromFile_actionPerformed(ActionEvent e)
909 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
913 public void reload_actionPerformed(ActionEvent e)
915 if (fileName != null)
917 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
918 // originating file's format
919 // TODO: work out how to recover feature settings for correct view(s) when
921 if (currentFileFormat.equals("Jalview"))
923 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
924 for (int i = 0; i < frames.length; i++)
926 if (frames[i] instanceof AlignFrame && frames[i] != this
927 && ((AlignFrame) frames[i]).fileName != null
928 && ((AlignFrame) frames[i]).fileName.equals(fileName))
932 frames[i].setSelected(true);
933 Desktop.instance.closeAssociatedWindows();
934 } catch (java.beans.PropertyVetoException ex)
940 Desktop.instance.closeAssociatedWindows();
942 FileLoader loader = new FileLoader();
943 String protocol = fileName.startsWith("http:") ? "URL" : "File";
944 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
948 Rectangle bounds = this.getBounds();
950 FileLoader loader = new FileLoader();
951 String protocol = fileName.startsWith("http:") ? "URL" : "File";
952 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
953 protocol, currentFileFormat);
955 newframe.setBounds(bounds);
956 if (featureSettings != null && featureSettings.isShowing())
958 final Rectangle fspos = featureSettings.frame.getBounds();
959 // TODO: need a 'show feature settings' function that takes bounds -
960 // need to refactor Desktop.addFrame
961 newframe.featureSettings_actionPerformed(null);
962 final FeatureSettings nfs = newframe.featureSettings;
963 SwingUtilities.invokeLater(new Runnable()
968 nfs.frame.setBounds(fspos);
971 this.featureSettings.close();
972 this.featureSettings = null;
974 this.closeMenuItem_actionPerformed(true);
980 public void addFromText_actionPerformed(ActionEvent e)
982 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
986 public void addFromURL_actionPerformed(ActionEvent e)
988 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
992 public void save_actionPerformed(ActionEvent e)
995 || (currentFileFormat == null || !jalview.io.FormatAdapter
996 .isValidIOFormat(currentFileFormat, true))
997 || fileName.startsWith("http"))
999 saveAs_actionPerformed(null);
1003 saveAlignment(fileName, currentFileFormat);
1014 public void saveAs_actionPerformed(ActionEvent e)
1016 JalviewFileChooser chooser = new JalviewFileChooser(
1017 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
1018 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
1019 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
1020 currentFileFormat, false);
1022 chooser.setFileView(new JalviewFileView());
1023 chooser.setDialogTitle(MessageManager.getString("label.save_alignment_to_file"));
1024 chooser.setToolTipText(MessageManager.getString("action.save"));
1026 int value = chooser.showSaveDialog(this);
1028 if (value == JalviewFileChooser.APPROVE_OPTION)
1030 currentFileFormat = chooser.getSelectedFormat();
1031 if (currentFileFormat == null)
1034 .showInternalMessageDialog(
1037 .getString("label.select_file_format_before_saving"),
1039 .getString("label.file_format_not_specified"),
1040 JOptionPane.WARNING_MESSAGE);
1041 value = chooser.showSaveDialog(this);
1045 fileName = chooser.getSelectedFile().getPath();
1047 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
1050 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
1051 if (currentFileFormat.indexOf(" ") > -1)
1053 currentFileFormat = currentFileFormat.substring(0,
1054 currentFileFormat.indexOf(" "));
1056 saveAlignment(fileName, currentFileFormat);
1060 public boolean saveAlignment(String file, String format)
1062 boolean success = true;
1064 if (format.equalsIgnoreCase("Jalview"))
1066 String shortName = title;
1068 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1070 shortName = shortName.substring(shortName
1071 .lastIndexOf(java.io.File.separatorChar) + 1);
1074 success = new Jalview2XML().SaveAlignment(this, file, shortName);
1076 statusBar.setText(MessageManager.formatMessage(
1077 "label.successfully_saved_to_file_in_format", new String[]
1078 { fileName, format }));
1083 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1085 warningMessage("Cannot save file " + fileName + " using format "
1086 + format, "Alignment output format not supported");
1087 saveAs_actionPerformed(null);
1088 // JBPNote need to have a raise_gui flag here
1092 String[] omitHidden = null;
1094 if (viewport.hasHiddenColumns())
1096 int reply = JOptionPane
1097 .showInternalConfirmDialog(
1100 .getString("label.alignment_contains_hidden_columns"),
1102 .getString("action.save_omit_hidden_columns"),
1103 JOptionPane.YES_NO_OPTION,
1104 JOptionPane.QUESTION_MESSAGE);
1106 if (reply == JOptionPane.YES_OPTION)
1108 omitHidden = viewport.getViewAsString(false);
1111 FormatAdapter f = new FormatAdapter();
1112 String output = f.formatSequences(format,
1113 viewport.getAlignment(), // class cast exceptions will
1114 // occur in the distant future
1115 omitHidden, f.getCacheSuffixDefault(format),
1116 viewport.getColumnSelection());
1126 java.io.PrintWriter out = new java.io.PrintWriter(
1127 new java.io.FileWriter(file));
1131 this.setTitle(file);
1132 statusBar.setText(MessageManager.formatMessage(
1133 "label.successfully_saved_to_file_in_format",
1135 { fileName, format }));
1136 } catch (Exception ex)
1139 ex.printStackTrace();
1146 JOptionPane.showInternalMessageDialog(this, MessageManager
1147 .formatMessage("label.couldnt_save_file", new String[]
1148 { fileName }), MessageManager
1149 .getString("label.error_saving_file"),
1150 JOptionPane.WARNING_MESSAGE);
1156 private void warningMessage(String warning, String title)
1158 if (new jalview.util.Platform().isHeadless())
1160 System.err.println("Warning: " + title + "\nWarning: " + warning);
1165 JOptionPane.showInternalMessageDialog(this, warning, title,
1166 JOptionPane.WARNING_MESSAGE);
1178 protected void outputText_actionPerformed(ActionEvent e)
1180 String[] omitHidden = null;
1182 if (viewport.hasHiddenColumns())
1184 int reply = JOptionPane
1185 .showInternalConfirmDialog(
1188 .getString("label.alignment_contains_hidden_columns"),
1190 .getString("action.save_omit_hidden_columns"),
1191 JOptionPane.YES_NO_OPTION,
1192 JOptionPane.QUESTION_MESSAGE);
1194 if (reply == JOptionPane.YES_OPTION)
1196 omitHidden = viewport.getViewAsString(false);
1200 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1201 cap.setForInput(null);
1205 cap.setText(new FormatAdapter().formatSequences(e.getActionCommand(),
1206 viewport.getAlignment(), omitHidden,
1207 viewport.getColumnSelection()));
1208 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1209 "label.alignment_output_command", new String[]
1210 { e.getActionCommand() }), 600, 500);
1211 } catch (OutOfMemoryError oom)
1213 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1226 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1228 new HTMLOutput(alignPanel,
1229 alignPanel.seqPanel.seqCanvas.getSequenceRenderer(),
1230 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
1233 public void createImageMap(File file, String image)
1235 alignPanel.makePNGImageMap(file, image);
1245 public void createPNG(File f)
1247 alignPanel.makePNG(f);
1257 public void createEPS(File f)
1259 alignPanel.makeEPS(f);
1263 public void pageSetup_actionPerformed(ActionEvent e)
1265 PrinterJob printJob = PrinterJob.getPrinterJob();
1266 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1276 public void printMenuItem_actionPerformed(ActionEvent e)
1278 // Putting in a thread avoids Swing painting problems
1279 PrintThread thread = new PrintThread(alignPanel);
1284 public void exportFeatures_actionPerformed(ActionEvent e)
1286 new AnnotationExporter().exportFeatures(alignPanel);
1290 public void exportAnnotations_actionPerformed(ActionEvent e)
1292 new AnnotationExporter().exportAnnotations(alignPanel,
1293 viewport.showAnnotation ? viewport.getAlignment()
1294 .getAlignmentAnnotation() : null, viewport
1295 .getAlignment().getGroups(), ((Alignment) viewport
1296 .getAlignment()).alignmentProperties);
1300 public void associatedData_actionPerformed(ActionEvent e)
1302 // Pick the tree file
1303 JalviewFileChooser chooser = new JalviewFileChooser(
1304 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1305 chooser.setFileView(new JalviewFileView());
1306 chooser.setDialogTitle(MessageManager
1307 .getString("label.load_jalview_annotations"));
1308 chooser.setToolTipText(MessageManager
1309 .getString("label.load_jalview_annotations"));
1311 int value = chooser.showOpenDialog(null);
1313 if (value == JalviewFileChooser.APPROVE_OPTION)
1315 String choice = chooser.getSelectedFile().getPath();
1316 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1317 loadJalviewDataFile(choice, null, null, null);
1323 * Close the current view or all views in the alignment frame. If the frame
1324 * only contains one view then the alignment will be removed from memory.
1326 * @param closeAllTabs
1329 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1331 if (alignPanels != null && alignPanels.size() < 2)
1333 closeAllTabs = true;
1338 if (alignPanels != null)
1342 if (this.isClosed())
1344 // really close all the windows - otherwise wait till
1345 // setClosed(true) is called
1346 for (int i = 0; i < alignPanels.size(); i++)
1348 AlignmentPanel ap = (AlignmentPanel) alignPanels.elementAt(i);
1355 closeView(alignPanel);
1361 this.setClosed(true);
1363 } catch (Exception ex)
1365 ex.printStackTrace();
1370 * close alignPanel2 and shuffle tabs appropriately.
1372 * @param alignPanel2
1374 public void closeView(AlignmentPanel alignPanel2)
1376 int index = tabbedPane.getSelectedIndex();
1377 int closedindex = tabbedPane.indexOfComponent(alignPanel2);
1378 alignPanels.removeElement(alignPanel2);
1380 // if (viewport == alignPanel2.av)
1384 alignPanel2.closePanel();
1387 tabbedPane.removeTabAt(closedindex);
1388 tabbedPane.validate();
1390 if (index > closedindex || index == tabbedPane.getTabCount())
1392 // modify currently selected tab index if necessary.
1396 this.tabSelectionChanged(index);
1402 void updateEditMenuBar()
1405 if (viewport.historyList.size() > 0)
1407 undoMenuItem.setEnabled(true);
1408 CommandI command = (CommandI) viewport.historyList.peek();
1409 undoMenuItem.setText(MessageManager.formatMessage(
1410 "label.undo_command", new String[]
1411 { command.getDescription() }));
1415 undoMenuItem.setEnabled(false);
1416 undoMenuItem.setText(MessageManager.getString("action.undo"));
1419 if (viewport.redoList.size() > 0)
1421 redoMenuItem.setEnabled(true);
1423 CommandI command = (CommandI) viewport.redoList.peek();
1424 redoMenuItem.setText(MessageManager.formatMessage(
1425 "label.redo_command", new String[]
1426 { command.getDescription() }));
1430 redoMenuItem.setEnabled(false);
1431 redoMenuItem.setText(MessageManager.getString("action.redo"));
1435 public void addHistoryItem(CommandI command)
1437 if (command.getSize() > 0)
1439 viewport.historyList.push(command);
1440 viewport.redoList.clear();
1441 updateEditMenuBar();
1442 viewport.updateHiddenColumns();
1443 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1444 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1445 // viewport.getColumnSelection()
1446 // .getHiddenColumns().size() > 0);
1452 * @return alignment objects for all views
1454 AlignmentI[] getViewAlignments()
1456 if (alignPanels != null)
1458 Enumeration e = alignPanels.elements();
1459 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1460 for (int i = 0; e.hasMoreElements(); i++)
1462 als[i] = ((AlignmentPanel) e.nextElement()).av.getAlignment();
1466 if (viewport != null)
1468 return new AlignmentI[]
1469 { viewport.getAlignment() };
1481 protected void undoMenuItem_actionPerformed(ActionEvent e)
1483 if (viewport.historyList.empty())
1487 CommandI command = (CommandI) viewport.historyList.pop();
1488 viewport.redoList.push(command);
1489 command.undoCommand(getViewAlignments());
1491 AlignViewport originalSource = getOriginatingSource(command);
1492 updateEditMenuBar();
1494 if (originalSource != null)
1496 if (originalSource != viewport)
1499 .warn("Implementation worry: mismatch of viewport origin for undo");
1501 originalSource.updateHiddenColumns();
1502 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1504 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1505 // viewport.getColumnSelection()
1506 // .getHiddenColumns().size() > 0);
1507 originalSource.firePropertyChange("alignment", null, originalSource
1508 .getAlignment().getSequences());
1519 protected void redoMenuItem_actionPerformed(ActionEvent e)
1521 if (viewport.redoList.size() < 1)
1526 CommandI command = (CommandI) viewport.redoList.pop();
1527 viewport.historyList.push(command);
1528 command.doCommand(getViewAlignments());
1530 AlignViewport originalSource = getOriginatingSource(command);
1531 updateEditMenuBar();
1533 if (originalSource != null)
1536 if (originalSource != viewport)
1539 .warn("Implementation worry: mismatch of viewport origin for redo");
1541 originalSource.updateHiddenColumns();
1542 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1544 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1545 // viewport.getColumnSelection()
1546 // .getHiddenColumns().size() > 0);
1547 originalSource.firePropertyChange("alignment", null, originalSource
1548 .getAlignment().getSequences());
1552 AlignViewport getOriginatingSource(CommandI command)
1554 AlignViewport originalSource = null;
1555 // For sequence removal and addition, we need to fire
1556 // the property change event FROM the viewport where the
1557 // original alignment was altered
1558 AlignmentI al = null;
1559 if (command instanceof EditCommand)
1561 EditCommand editCommand = (EditCommand) command;
1562 al = editCommand.getAlignment();
1563 Vector comps = (Vector) PaintRefresher.components.get(viewport
1564 .getSequenceSetId());
1566 for (int i = 0; i < comps.size(); i++)
1568 if (comps.elementAt(i) instanceof AlignmentPanel)
1570 if (al == ((AlignmentPanel) comps.elementAt(i)).av.getAlignment())
1572 originalSource = ((AlignmentPanel) comps.elementAt(i)).av;
1579 if (originalSource == null)
1581 // The original view is closed, we must validate
1582 // the current view against the closed view first
1585 PaintRefresher.validateSequences(al, viewport.getAlignment());
1588 originalSource = viewport;
1591 return originalSource;
1600 public void moveSelectedSequences(boolean up)
1602 SequenceGroup sg = viewport.getSelectionGroup();
1608 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1609 viewport.getHiddenRepSequences(), up);
1610 alignPanel.paintAlignment(true);
1613 synchronized void slideSequences(boolean right, int size)
1615 List<SequenceI> sg = new Vector();
1616 if (viewport.cursorMode)
1618 sg.add(viewport.getAlignment().getSequenceAt(
1619 alignPanel.seqPanel.seqCanvas.cursorY));
1621 else if (viewport.getSelectionGroup() != null
1622 && viewport.getSelectionGroup().getSize() != viewport
1623 .getAlignment().getHeight())
1625 sg = viewport.getSelectionGroup().getSequences(
1626 viewport.getHiddenRepSequences());
1634 Vector invertGroup = new Vector();
1636 for (int i = 0; i < viewport.getAlignment().getHeight(); i++)
1638 if (!sg.contains(viewport.getAlignment().getSequenceAt(i)))
1640 invertGroup.add(viewport.getAlignment().getSequenceAt(i));
1644 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1646 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1647 for (int i = 0; i < invertGroup.size(); i++)
1649 seqs2[i] = (SequenceI) invertGroup.elementAt(i);
1652 SlideSequencesCommand ssc;
1655 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1656 size, viewport.getGapCharacter());
1660 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1661 size, viewport.getGapCharacter());
1664 int groupAdjustment = 0;
1665 if (ssc.getGapsInsertedBegin() && right)
1667 if (viewport.cursorMode)
1669 alignPanel.seqPanel.moveCursor(size, 0);
1673 groupAdjustment = size;
1676 else if (!ssc.getGapsInsertedBegin() && !right)
1678 if (viewport.cursorMode)
1680 alignPanel.seqPanel.moveCursor(-size, 0);
1684 groupAdjustment = -size;
1688 if (groupAdjustment != 0)
1690 viewport.getSelectionGroup().setStartRes(
1691 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1692 viewport.getSelectionGroup().setEndRes(
1693 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1696 boolean appendHistoryItem = false;
1697 if (viewport.historyList != null && viewport.historyList.size() > 0
1698 && viewport.historyList.peek() instanceof SlideSequencesCommand)
1700 appendHistoryItem = ssc
1701 .appendSlideCommand((SlideSequencesCommand) viewport.historyList
1705 if (!appendHistoryItem)
1707 addHistoryItem(ssc);
1720 protected void copy_actionPerformed(ActionEvent e)
1723 if (viewport.getSelectionGroup() == null)
1727 // TODO: preserve the ordering of displayed alignment annotation in any
1728 // internal paste (particularly sequence associated annotation)
1729 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1730 String[] omitHidden = null;
1732 if (viewport.hasHiddenColumns())
1734 omitHidden = viewport.getViewAsString(true);
1737 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1740 StringSelection ss = new StringSelection(output);
1744 jalview.gui.Desktop.internalCopy = true;
1745 // Its really worth setting the clipboard contents
1746 // to empty before setting the large StringSelection!!
1747 Toolkit.getDefaultToolkit().getSystemClipboard()
1748 .setContents(new StringSelection(""), null);
1750 Toolkit.getDefaultToolkit().getSystemClipboard()
1751 .setContents(ss, Desktop.instance);
1752 } catch (OutOfMemoryError er)
1754 new OOMWarning("copying region", er);
1758 Vector hiddenColumns = null;
1759 if (viewport.hasHiddenColumns())
1761 hiddenColumns = new Vector();
1762 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1763 .getSelectionGroup().getEndRes();
1764 for (int i = 0; i < viewport.getColumnSelection().getHiddenColumns()
1767 int[] region = (int[]) viewport.getColumnSelection()
1768 .getHiddenColumns().elementAt(i);
1769 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1771 hiddenColumns.addElement(new int[]
1772 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1777 Desktop.jalviewClipboard = new Object[]
1778 { seqs, viewport.getAlignment().getDataset(), hiddenColumns };
1779 statusBar.setText(MessageManager.formatMessage(
1780 "label.copied_sequences_to_clipboard", new String[]
1781 { Integer.valueOf(seqs.length).toString() }));
1791 protected void pasteNew_actionPerformed(ActionEvent e)
1803 protected void pasteThis_actionPerformed(ActionEvent e)
1809 * Paste contents of Jalview clipboard
1811 * @param newAlignment
1812 * true to paste to a new alignment, otherwise add to this.
1814 void paste(boolean newAlignment)
1816 boolean externalPaste = true;
1819 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1820 Transferable contents = c.getContents(this);
1822 if (contents == null)
1830 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1831 if (str.length() < 1)
1836 format = new IdentifyFile().Identify(str, "Paste");
1838 } catch (OutOfMemoryError er)
1840 new OOMWarning("Out of memory pasting sequences!!", er);
1844 SequenceI[] sequences;
1845 boolean annotationAdded = false;
1846 AlignmentI alignment = null;
1848 if (Desktop.jalviewClipboard != null)
1850 // The clipboard was filled from within Jalview, we must use the
1852 // And dataset from the copied alignment
1853 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1854 // be doubly sure that we create *new* sequence objects.
1855 sequences = new SequenceI[newseq.length];
1856 for (int i = 0; i < newseq.length; i++)
1858 sequences[i] = new Sequence(newseq[i]);
1860 alignment = new Alignment(sequences);
1861 externalPaste = false;
1865 // parse the clipboard as an alignment.
1866 alignment = new FormatAdapter().readFile(str, "Paste", format);
1867 sequences = alignment.getSequencesArray();
1871 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1877 if (Desktop.jalviewClipboard != null)
1879 // dataset is inherited
1880 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1884 // new dataset is constructed
1885 alignment.setDataset(null);
1887 alwidth = alignment.getWidth() + 1;
1891 AlignmentI pastedal = alignment; // preserve pasted alignment object
1892 // Add pasted sequences and dataset into existing alignment.
1893 alignment = viewport.getAlignment();
1894 alwidth = alignment.getWidth() + 1;
1895 // decide if we need to import sequences from an existing dataset
1896 boolean importDs = Desktop.jalviewClipboard != null
1897 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1898 // importDs==true instructs us to copy over new dataset sequences from
1899 // an existing alignment
1900 Vector newDs = (importDs) ? new Vector() : null; // used to create
1901 // minimum dataset set
1903 for (int i = 0; i < sequences.length; i++)
1907 newDs.addElement(null);
1909 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
1911 if (importDs && ds != null)
1913 if (!newDs.contains(ds))
1915 newDs.setElementAt(ds, i);
1916 ds = new Sequence(ds);
1917 // update with new dataset sequence
1918 sequences[i].setDatasetSequence(ds);
1922 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
1927 // copy and derive new dataset sequence
1928 sequences[i] = sequences[i].deriveSequence();
1929 alignment.getDataset().addSequence(
1930 sequences[i].getDatasetSequence());
1931 // TODO: avoid creation of duplicate dataset sequences with a
1932 // 'contains' method using SequenceI.equals()/SequenceI.contains()
1934 alignment.addSequence(sequences[i]); // merges dataset
1938 newDs.clear(); // tidy up
1940 if (alignment.getAlignmentAnnotation() != null)
1942 for (AlignmentAnnotation alan : alignment
1943 .getAlignmentAnnotation())
1945 if (alan.graphGroup > fgroup)
1947 fgroup = alan.graphGroup;
1951 if (pastedal.getAlignmentAnnotation() != null)
1953 // Add any annotation attached to alignment.
1954 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
1955 for (int i = 0; i < alann.length; i++)
1957 annotationAdded = true;
1958 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
1960 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
1961 if (newann.graphGroup > -1)
1963 if (newGraphGroups.size() <= newann.graphGroup
1964 || newGraphGroups.get(newann.graphGroup) == null)
1966 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
1968 newGraphGroups.add(q, null);
1970 newGraphGroups.set(newann.graphGroup, new Integer(
1973 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
1977 newann.padAnnotation(alwidth);
1978 alignment.addAnnotation(newann);
1988 addHistoryItem(new EditCommand(MessageManager.getString("label.add_sequences"), EditCommand.PASTE,
1989 sequences, 0, alignment.getWidth(), alignment));
1991 // Add any annotations attached to sequences
1992 for (int i = 0; i < sequences.length; i++)
1994 if (sequences[i].getAnnotation() != null)
1996 AlignmentAnnotation newann;
1997 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
1999 annotationAdded = true;
2000 newann = sequences[i].getAnnotation()[a];
2001 newann.adjustForAlignment();
2002 newann.padAnnotation(alwidth);
2003 if (newann.graphGroup > -1)
2005 if (newann.graphGroup > -1)
2007 if (newGraphGroups.size() <= newann.graphGroup
2008 || newGraphGroups.get(newann.graphGroup) == null)
2010 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2012 newGraphGroups.add(q, null);
2014 newGraphGroups.set(newann.graphGroup, new Integer(
2017 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2021 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2026 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2033 // propagate alignment changed.
2034 viewport.setEndSeq(alignment.getHeight());
2035 if (annotationAdded)
2037 // Duplicate sequence annotation in all views.
2038 AlignmentI[] alview = this.getViewAlignments();
2039 for (int i = 0; i < sequences.length; i++)
2041 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2046 for (int avnum = 0; avnum < alview.length; avnum++)
2048 if (alview[avnum] != alignment)
2050 // duplicate in a view other than the one with input focus
2051 int avwidth = alview[avnum].getWidth() + 1;
2052 // this relies on sann being preserved after we
2053 // modify the sequence's annotation array for each duplication
2054 for (int a = 0; a < sann.length; a++)
2056 AlignmentAnnotation newann = new AlignmentAnnotation(
2058 sequences[i].addAlignmentAnnotation(newann);
2059 newann.padAnnotation(avwidth);
2060 alview[avnum].addAnnotation(newann); // annotation was
2061 // duplicated earlier
2062 // TODO JAL-1145 graphGroups are not updated for sequence
2063 // annotation added to several views. This may cause
2065 alview[avnum].setAnnotationIndex(newann, a);
2070 buildSortByAnnotationScoresMenu();
2072 viewport.firePropertyChange("alignment", null,
2073 alignment.getSequences());
2074 if (alignPanels != null)
2076 for (AlignmentPanel ap : ((Vector<AlignmentPanel>) alignPanels))
2078 ap.validateAnnotationDimensions(false);
2083 alignPanel.validateAnnotationDimensions(false);
2089 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2091 String newtitle = new String("Copied sequences");
2093 if (Desktop.jalviewClipboard != null
2094 && Desktop.jalviewClipboard[2] != null)
2096 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2097 for (int i = 0; i < hc.size(); i++)
2099 int[] region = (int[]) hc.elementAt(i);
2100 af.viewport.hideColumns(region[0], region[1]);
2104 // >>>This is a fix for the moment, until a better solution is
2106 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
2108 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
2110 // TODO: maintain provenance of an alignment, rather than just make the
2111 // title a concatenation of operations.
2114 if (title.startsWith("Copied sequences"))
2120 newtitle = newtitle.concat("- from " + title);
2125 newtitle = new String("Pasted sequences");
2128 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2133 } catch (Exception ex)
2135 ex.printStackTrace();
2136 System.out.println("Exception whilst pasting: " + ex);
2137 // could be anything being pasted in here
2143 protected void expand_newalign(ActionEvent e)
2147 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2148 .getAlignment(), -1);
2149 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2151 String newtitle = new String("Flanking alignment");
2153 if (Desktop.jalviewClipboard != null
2154 && Desktop.jalviewClipboard[2] != null)
2156 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2157 for (int i = 0; i < hc.size(); i++)
2159 int[] region = (int[]) hc.elementAt(i);
2160 af.viewport.hideColumns(region[0], region[1]);
2164 // >>>This is a fix for the moment, until a better solution is
2166 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
2168 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
2170 // TODO: maintain provenance of an alignment, rather than just make the
2171 // title a concatenation of operations.
2173 if (title.startsWith("Copied sequences"))
2179 newtitle = newtitle.concat("- from " + title);
2183 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2185 } catch (Exception ex)
2187 ex.printStackTrace();
2188 System.out.println("Exception whilst pasting: " + ex);
2189 // could be anything being pasted in here
2190 } catch (OutOfMemoryError oom)
2192 new OOMWarning("Viewing flanking region of alignment", oom);
2203 protected void cut_actionPerformed(ActionEvent e)
2205 copy_actionPerformed(null);
2206 delete_actionPerformed(null);
2216 protected void delete_actionPerformed(ActionEvent evt)
2219 SequenceGroup sg = viewport.getSelectionGroup();
2225 List<SequenceI> seqs = new ArrayList<SequenceI>(sg.getSize());
2227 for (int i = 0; i < sg.getSize(); i++)
2229 seq = sg.getSequenceAt(i);
2233 // If the cut affects all sequences, warn, remove highlighted columns
2234 if (sg.getSize() == viewport.getAlignment().getHeight())
2236 int confirm = JOptionPane.showConfirmDialog(this,
2237 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2238 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2239 JOptionPane.OK_CANCEL_OPTION);
2241 if (confirm == JOptionPane.CANCEL_OPTION
2242 || confirm == JOptionPane.CLOSED_OPTION)
2246 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2247 sg.getEndRes() + 1);
2250 SequenceI[] cut = new SequenceI[seqs.size()];
2251 for (int i = 0; i < seqs.size(); i++)
2253 cut[i] = seqs.get(i);
2257 * //ADD HISTORY ITEM
2259 addHistoryItem(new EditCommand(MessageManager.getString("label.cut_sequences"), EditCommand.CUT, cut,
2260 sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2261 viewport.getAlignment()));
2263 viewport.setSelectionGroup(null);
2264 viewport.sendSelection();
2265 viewport.getAlignment().deleteGroup(sg);
2267 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2269 if (viewport.getAlignment().getHeight() < 1)
2273 this.setClosed(true);
2274 } catch (Exception ex)
2287 protected void deleteGroups_actionPerformed(ActionEvent e)
2289 if (avc.deleteGroups())
2291 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2292 alignPanel.updateAnnotation();
2293 alignPanel.paintAlignment(true);
2304 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2306 SequenceGroup sg = new SequenceGroup();
2308 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2310 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2313 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2314 viewport.setSelectionGroup(sg);
2315 viewport.sendSelection();
2316 alignPanel.paintAlignment(true);
2317 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2327 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2329 if (viewport.cursorMode)
2331 alignPanel.seqPanel.keyboardNo1 = null;
2332 alignPanel.seqPanel.keyboardNo2 = null;
2334 viewport.setSelectionGroup(null);
2335 viewport.getColumnSelection().clear();
2336 viewport.setSelectionGroup(null);
2337 alignPanel.seqPanel.seqCanvas.highlightSearchResults(null);
2338 alignPanel.idPanel.idCanvas.searchResults = null;
2339 alignPanel.paintAlignment(true);
2340 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2341 viewport.sendSelection();
2351 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2353 SequenceGroup sg = viewport.getSelectionGroup();
2357 selectAllSequenceMenuItem_actionPerformed(null);
2362 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2364 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2367 alignPanel.paintAlignment(true);
2368 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2369 viewport.sendSelection();
2373 public void invertColSel_actionPerformed(ActionEvent e)
2375 viewport.invertColumnSelection();
2376 alignPanel.paintAlignment(true);
2377 viewport.sendSelection();
2387 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2389 trimAlignment(true);
2399 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2401 trimAlignment(false);
2404 void trimAlignment(boolean trimLeft)
2406 ColumnSelection colSel = viewport.getColumnSelection();
2409 if (colSel.size() > 0)
2413 column = colSel.getMin();
2417 column = colSel.getMax();
2421 if (viewport.getSelectionGroup() != null)
2423 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2424 viewport.getHiddenRepSequences());
2428 seqs = viewport.getAlignment().getSequencesArray();
2431 TrimRegionCommand trimRegion;
2434 trimRegion = new TrimRegionCommand("Remove Left",
2435 TrimRegionCommand.TRIM_LEFT, seqs, column,
2436 viewport.getAlignment(), viewport.getColumnSelection(),
2437 viewport.getSelectionGroup());
2438 viewport.setStartRes(0);
2442 trimRegion = new TrimRegionCommand("Remove Right",
2443 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2444 viewport.getAlignment(), viewport.getColumnSelection(),
2445 viewport.getSelectionGroup());
2448 statusBar.setText(MessageManager.formatMessage(
2449 "label.removed_columns", new String[]
2450 { Integer.valueOf(trimRegion.getSize()).toString() }));
2452 addHistoryItem(trimRegion);
2454 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2456 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2457 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2459 viewport.getAlignment().deleteGroup(sg);
2463 viewport.firePropertyChange("alignment", null, viewport
2464 .getAlignment().getSequences());
2475 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2477 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2480 if (viewport.getSelectionGroup() != null)
2482 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2483 viewport.getHiddenRepSequences());
2484 start = viewport.getSelectionGroup().getStartRes();
2485 end = viewport.getSelectionGroup().getEndRes();
2489 seqs = viewport.getAlignment().getSequencesArray();
2492 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2493 "Remove Gapped Columns", seqs, start, end,
2494 viewport.getAlignment());
2496 addHistoryItem(removeGapCols);
2498 statusBar.setText(MessageManager.formatMessage(
2499 "label.removed_empty_columns", new String[]
2500 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2502 // This is to maintain viewport position on first residue
2503 // of first sequence
2504 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2505 int startRes = seq.findPosition(viewport.startRes);
2506 // ShiftList shifts;
2507 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2508 // edit.alColumnChanges=shifts.getInverse();
2509 // if (viewport.hasHiddenColumns)
2510 // viewport.getColumnSelection().compensateForEdits(shifts);
2511 viewport.setStartRes(seq.findIndex(startRes) - 1);
2512 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2524 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2526 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2529 if (viewport.getSelectionGroup() != null)
2531 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2532 viewport.getHiddenRepSequences());
2533 start = viewport.getSelectionGroup().getStartRes();
2534 end = viewport.getSelectionGroup().getEndRes();
2538 seqs = viewport.getAlignment().getSequencesArray();
2541 // This is to maintain viewport position on first residue
2542 // of first sequence
2543 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2544 int startRes = seq.findPosition(viewport.startRes);
2546 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2547 viewport.getAlignment()));
2549 viewport.setStartRes(seq.findIndex(startRes) - 1);
2551 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2563 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2565 viewport.setPadGaps(padGapsMenuitem.isSelected());
2566 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2572 // if (justifySeqs>0)
2574 // alignment.justify(justifySeqs!=RIGHT_JUSTIFY);
2587 public void findMenuItem_actionPerformed(ActionEvent e)
2593 public void newView_actionPerformed(ActionEvent e)
2600 * @param copyAnnotation
2601 * if true then duplicate all annnotation, groups and settings
2602 * @return new alignment panel, already displayed.
2604 public AlignmentPanel newView(boolean copyAnnotation)
2606 return newView(null, copyAnnotation);
2612 * title of newly created view
2613 * @return new alignment panel, already displayed.
2615 public AlignmentPanel newView(String viewTitle)
2617 return newView(viewTitle, true);
2623 * title of newly created view
2624 * @param copyAnnotation
2625 * if true then duplicate all annnotation, groups and settings
2626 * @return new alignment panel, already displayed.
2628 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2630 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2632 if (!copyAnnotation)
2634 // just remove all the current annotation except for the automatic stuff
2635 newap.av.getAlignment().deleteAllGroups();
2636 for (AlignmentAnnotation alan : newap.av.getAlignment()
2637 .getAlignmentAnnotation())
2639 if (!alan.autoCalculated)
2641 newap.av.getAlignment().deleteAnnotation(alan);
2647 newap.av.gatherViewsHere = false;
2649 if (viewport.viewName == null)
2651 viewport.viewName = "Original";
2654 newap.av.historyList = viewport.historyList;
2655 newap.av.redoList = viewport.redoList;
2657 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2658 // make sure the new view has a unique name - this is essential for Jalview
2660 boolean addFirstIndex = false;
2661 if (viewTitle == null || viewTitle.trim().length() == 0)
2663 viewTitle = MessageManager.getString("action.view");
2664 addFirstIndex = true;
2668 index = 1;// we count from 1 if given a specific name
2670 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2671 Vector comps = (Vector) PaintRefresher.components.get(viewport
2672 .getSequenceSetId());
2673 Vector existingNames = new Vector();
2674 for (int i = 0; i < comps.size(); i++)
2676 if (comps.elementAt(i) instanceof AlignmentPanel)
2678 AlignmentPanel ap = (AlignmentPanel) comps.elementAt(i);
2679 if (!existingNames.contains(ap.av.viewName))
2681 existingNames.addElement(ap.av.viewName);
2686 while (existingNames.contains(newViewName))
2688 newViewName = viewTitle + " " + (++index);
2691 newap.av.viewName = newViewName;
2693 addAlignmentPanel(newap, true);
2694 newap.alignmentChanged();
2696 if (alignPanels.size() == 2)
2698 viewport.gatherViewsHere = true;
2700 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2705 public void expandViews_actionPerformed(ActionEvent e)
2707 Desktop.instance.explodeViews(this);
2711 public void gatherViews_actionPerformed(ActionEvent e)
2713 Desktop.instance.gatherViews(this);
2723 public void font_actionPerformed(ActionEvent e)
2725 new FontChooser(alignPanel);
2735 protected void seqLimit_actionPerformed(ActionEvent e)
2737 viewport.setShowJVSuffix(seqLimits.isSelected());
2739 alignPanel.idPanel.idCanvas.setPreferredSize(alignPanel
2740 .calculateIdWidth());
2741 alignPanel.paintAlignment(true);
2745 public void idRightAlign_actionPerformed(ActionEvent e)
2747 viewport.rightAlignIds = idRightAlign.isSelected();
2748 alignPanel.paintAlignment(true);
2752 public void centreColumnLabels_actionPerformed(ActionEvent e)
2754 viewport.centreColumnLabels = centreColumnLabelsMenuItem.getState();
2755 alignPanel.paintAlignment(true);
2761 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2764 protected void followHighlight_actionPerformed()
2766 if (viewport.followHighlight = this.followHighlightMenuItem.getState())
2768 alignPanel.scrollToPosition(
2769 alignPanel.seqPanel.seqCanvas.searchResults, false);
2780 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2782 viewport.setColourText(colourTextMenuItem.isSelected());
2783 alignPanel.paintAlignment(true);
2793 public void wrapMenuItem_actionPerformed(ActionEvent e)
2795 scaleAbove.setVisible(wrapMenuItem.isSelected());
2796 scaleLeft.setVisible(wrapMenuItem.isSelected());
2797 scaleRight.setVisible(wrapMenuItem.isSelected());
2798 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2799 alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2803 public void showAllSeqs_actionPerformed(ActionEvent e)
2805 viewport.showAllHiddenSeqs();
2809 public void showAllColumns_actionPerformed(ActionEvent e)
2811 viewport.showAllHiddenColumns();
2816 public void hideSelSequences_actionPerformed(ActionEvent e)
2818 viewport.hideAllSelectedSeqs();
2819 alignPanel.paintAlignment(true);
2823 * called by key handler and the hide all/show all menu items
2828 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2831 boolean hide = false;
2832 SequenceGroup sg = viewport.getSelectionGroup();
2833 if (!toggleSeqs && !toggleCols)
2835 // Hide everything by the current selection - this is a hack - we do the
2836 // invert and then hide
2837 // first check that there will be visible columns after the invert.
2838 if ((viewport.getColumnSelection() != null
2839 && viewport.getColumnSelection().getSelected() != null && viewport
2840 .getColumnSelection().getSelected().size() > 0)
2841 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2844 // now invert the sequence set, if required - empty selection implies
2845 // that no hiding is required.
2848 invertSequenceMenuItem_actionPerformed(null);
2849 sg = viewport.getSelectionGroup();
2853 viewport.expandColSelection(sg, true);
2854 // finally invert the column selection and get the new sequence
2856 invertColSel_actionPerformed(null);
2863 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
2865 hideSelSequences_actionPerformed(null);
2868 else if (!(toggleCols && viewport.getColumnSelection().getSelected()
2871 showAllSeqs_actionPerformed(null);
2877 if (viewport.getColumnSelection().getSelected().size() > 0)
2879 hideSelColumns_actionPerformed(null);
2882 viewport.setSelectionGroup(sg);
2887 showAllColumns_actionPerformed(null);
2896 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
2897 * event.ActionEvent)
2900 public void hideAllButSelection_actionPerformed(ActionEvent e)
2902 toggleHiddenRegions(false, false);
2909 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
2913 public void hideAllSelection_actionPerformed(ActionEvent e)
2915 SequenceGroup sg = viewport.getSelectionGroup();
2916 viewport.expandColSelection(sg, false);
2917 viewport.hideAllSelectedSeqs();
2918 viewport.hideSelectedColumns();
2919 alignPanel.paintAlignment(true);
2926 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
2930 public void showAllhidden_actionPerformed(ActionEvent e)
2932 viewport.showAllHiddenColumns();
2933 viewport.showAllHiddenSeqs();
2934 alignPanel.paintAlignment(true);
2938 public void hideSelColumns_actionPerformed(ActionEvent e)
2940 viewport.hideSelectedColumns();
2941 alignPanel.paintAlignment(true);
2945 public void hiddenMarkers_actionPerformed(ActionEvent e)
2947 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
2958 protected void scaleAbove_actionPerformed(ActionEvent e)
2960 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
2961 alignPanel.paintAlignment(true);
2971 protected void scaleLeft_actionPerformed(ActionEvent e)
2973 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
2974 alignPanel.paintAlignment(true);
2984 protected void scaleRight_actionPerformed(ActionEvent e)
2986 viewport.setScaleRightWrapped(scaleRight.isSelected());
2987 alignPanel.paintAlignment(true);
2997 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
2999 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3000 alignPanel.paintAlignment(true);
3010 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3012 viewport.setShowText(viewTextMenuItem.isSelected());
3013 alignPanel.paintAlignment(true);
3023 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3025 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3026 alignPanel.paintAlignment(true);
3029 public FeatureSettings featureSettings;
3032 public void featureSettings_actionPerformed(ActionEvent e)
3034 if (featureSettings != null)
3036 featureSettings.close();
3037 featureSettings = null;
3039 if (!showSeqFeatures.isSelected())
3041 // make sure features are actually displayed
3042 showSeqFeatures.setSelected(true);
3043 showSeqFeatures_actionPerformed(null);
3045 featureSettings = new FeatureSettings(this);
3049 * Set or clear 'Show Sequence Features'
3055 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3057 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3058 alignPanel.paintAlignment(true);
3059 if (alignPanel.getOverviewPanel() != null)
3061 alignPanel.getOverviewPanel().updateOverviewImage();
3066 * Set or clear 'Show Sequence Features'
3072 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
3074 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
3076 if (viewport.getShowSequenceFeaturesHeight())
3078 // ensure we're actually displaying features
3079 viewport.setShowSequenceFeatures(true);
3080 showSeqFeatures.setSelected(true);
3082 alignPanel.paintAlignment(true);
3083 if (alignPanel.getOverviewPanel() != null)
3085 alignPanel.getOverviewPanel().updateOverviewImage();
3090 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3091 * the annotations panel as a whole.
3093 * The options to show/hide all annotations should be enabled when the panel
3094 * is shown, and disabled when the panel is hidden.
3099 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3101 final boolean setVisible = annotationPanelMenuItem.isSelected();
3102 viewport.setShowAnnotation(setVisible);
3103 alignPanel.setAnnotationVisible(setVisible);
3104 this.showAllAnnotations.setEnabled(setVisible);
3105 this.hideAllAnnotations.setEnabled(setVisible);
3109 public void alignmentProperties()
3111 JEditorPane editPane = new JEditorPane("text/html", "");
3112 editPane.setEditable(false);
3113 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3115 editPane.setText(MessageManager.formatMessage("label.html_content",
3117 { contents.toString() }));
3118 JInternalFrame frame = new JInternalFrame();
3119 frame.getContentPane().add(new JScrollPane(editPane));
3121 Desktop.instance.addInternalFrame(frame, MessageManager.formatMessage(
3122 "label.alignment_properties", new String[]
3123 { getTitle() }), 500, 400);
3133 public void overviewMenuItem_actionPerformed(ActionEvent e)
3135 if (alignPanel.overviewPanel != null)
3140 JInternalFrame frame = new JInternalFrame();
3141 OverviewPanel overview = new OverviewPanel(alignPanel);
3142 frame.setContentPane(overview);
3143 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3144 "label.overview_params", new String[]
3145 { this.getTitle() }), frame.getWidth(), frame.getHeight());
3147 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3148 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3151 public void internalFrameClosed(
3152 javax.swing.event.InternalFrameEvent evt)
3154 alignPanel.setOverviewPanel(null);
3158 alignPanel.setOverviewPanel(overview);
3162 public void textColour_actionPerformed(ActionEvent e)
3164 new TextColourChooser().chooseColour(alignPanel, null);
3174 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3186 public void clustalColour_actionPerformed(ActionEvent e)
3188 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3189 viewport.getHiddenRepSequences()));
3199 public void zappoColour_actionPerformed(ActionEvent e)
3201 changeColour(new ZappoColourScheme());
3211 public void taylorColour_actionPerformed(ActionEvent e)
3213 changeColour(new TaylorColourScheme());
3223 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3225 changeColour(new HydrophobicColourScheme());
3235 public void helixColour_actionPerformed(ActionEvent e)
3237 changeColour(new HelixColourScheme());
3247 public void strandColour_actionPerformed(ActionEvent e)
3249 changeColour(new StrandColourScheme());
3259 public void turnColour_actionPerformed(ActionEvent e)
3261 changeColour(new TurnColourScheme());
3271 public void buriedColour_actionPerformed(ActionEvent e)
3273 changeColour(new BuriedColourScheme());
3283 public void nucleotideColour_actionPerformed(ActionEvent e)
3285 changeColour(new NucleotideColourScheme());
3289 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3291 changeColour(new PurinePyrimidineColourScheme());
3295 * public void covariationColour_actionPerformed(ActionEvent e) {
3297 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3301 public void annotationColour_actionPerformed(ActionEvent e)
3303 new AnnotationColourChooser(viewport, alignPanel);
3307 public void rnahelicesColour_actionPerformed(ActionEvent e)
3309 new RNAHelicesColourChooser(viewport, alignPanel);
3319 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3321 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3330 public void changeColour(ColourSchemeI cs)
3332 // TODO: compare with applet and pull up to model method
3337 if (viewport.getAbovePIDThreshold())
3339 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3341 cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3345 cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3348 if (viewport.getConservationSelected())
3351 Alignment al = (Alignment) viewport.getAlignment();
3352 Conservation c = new Conservation("All",
3353 ResidueProperties.propHash, 3, al.getSequences(), 0,
3357 c.verdict(false, viewport.getConsPercGaps());
3359 cs.setConservation(c);
3361 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3366 cs.setConservation(null);
3369 cs.setConsensus(viewport.getSequenceConsensusHash());
3372 viewport.setGlobalColourScheme(cs);
3374 if (viewport.getColourAppliesToAllGroups())
3377 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3385 if (cs instanceof ClustalxColourScheme)
3387 sg.cs = new ClustalxColourScheme(sg,
3388 viewport.getHiddenRepSequences());
3390 else if (cs instanceof UserColourScheme)
3392 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
3398 sg.cs = cs.getClass().newInstance();
3399 } catch (Exception ex)
3404 if (viewport.getAbovePIDThreshold()
3405 || cs instanceof PIDColourScheme
3406 || cs instanceof Blosum62ColourScheme)
3408 sg.cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3410 sg.cs.setConsensus(AAFrequency.calculate(
3411 sg.getSequences(viewport.getHiddenRepSequences()),
3412 sg.getStartRes(), sg.getEndRes() + 1));
3416 sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3419 if (viewport.getConservationSelected())
3421 Conservation c = new Conservation("Group",
3422 ResidueProperties.propHash, 3, sg.getSequences(viewport
3423 .getHiddenRepSequences()), sg.getStartRes(),
3424 sg.getEndRes() + 1);
3426 c.verdict(false, viewport.getConsPercGaps());
3427 sg.cs.setConservation(c);
3431 sg.cs.setConservation(null);
3436 if (alignPanel.getOverviewPanel() != null)
3438 alignPanel.getOverviewPanel().updateOverviewImage();
3441 alignPanel.paintAlignment(true);
3451 protected void modifyPID_actionPerformed(ActionEvent e)
3453 if (viewport.getAbovePIDThreshold()
3454 && viewport.getGlobalColourScheme() != null)
3456 SliderPanel.setPIDSliderSource(alignPanel,
3457 viewport.getGlobalColourScheme(), "Background");
3458 SliderPanel.showPIDSlider();
3469 protected void modifyConservation_actionPerformed(ActionEvent e)
3471 if (viewport.getConservationSelected()
3472 && viewport.getGlobalColourScheme() != null)
3474 SliderPanel.setConservationSlider(alignPanel,
3475 viewport.getGlobalColourScheme(), "Background");
3476 SliderPanel.showConservationSlider();
3487 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3489 viewport.setConservationSelected(conservationMenuItem.isSelected());
3491 viewport.setAbovePIDThreshold(false);
3492 abovePIDThreshold.setSelected(false);
3494 changeColour(viewport.getGlobalColourScheme());
3496 modifyConservation_actionPerformed(null);
3506 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3508 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3510 conservationMenuItem.setSelected(false);
3511 viewport.setConservationSelected(false);
3513 changeColour(viewport.getGlobalColourScheme());
3515 modifyPID_actionPerformed(null);
3525 public void userDefinedColour_actionPerformed(ActionEvent e)
3527 if (e.getActionCommand().equals(
3528 MessageManager.getString("action.user_defined")))
3530 new UserDefinedColours(alignPanel, null);
3534 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3535 .getUserColourSchemes().get(e.getActionCommand());
3541 public void updateUserColourMenu()
3544 Component[] menuItems = colourMenu.getMenuComponents();
3545 int i, iSize = menuItems.length;
3546 for (i = 0; i < iSize; i++)
3548 if (menuItems[i].getName() != null
3549 && menuItems[i].getName().equals("USER_DEFINED"))
3551 colourMenu.remove(menuItems[i]);
3555 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3557 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3558 .getUserColourSchemes().keys();
3560 while (userColours.hasMoreElements())
3562 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3563 userColours.nextElement().toString());
3564 radioItem.setName("USER_DEFINED");
3565 radioItem.addMouseListener(new MouseAdapter()
3568 public void mousePressed(MouseEvent evt)
3570 if (evt.isControlDown()
3571 || SwingUtilities.isRightMouseButton(evt))
3573 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3575 int option = JOptionPane.showInternalConfirmDialog(
3576 jalview.gui.Desktop.desktop,
3578 .getString("label.remove_from_default_list"),
3580 .getString("label.remove_user_defined_colour"),
3581 JOptionPane.YES_NO_OPTION);
3582 if (option == JOptionPane.YES_OPTION)
3584 jalview.gui.UserDefinedColours
3585 .removeColourFromDefaults(radioItem.getText());
3586 colourMenu.remove(radioItem);
3590 radioItem.addActionListener(new ActionListener()
3593 public void actionPerformed(ActionEvent evt)
3595 userDefinedColour_actionPerformed(evt);
3602 radioItem.addActionListener(new ActionListener()
3605 public void actionPerformed(ActionEvent evt)
3607 userDefinedColour_actionPerformed(evt);
3611 colourMenu.insert(radioItem, 15);
3612 colours.add(radioItem);
3624 public void PIDColour_actionPerformed(ActionEvent e)
3626 changeColour(new PIDColourScheme());
3636 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3638 changeColour(new Blosum62ColourScheme());
3648 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3650 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3651 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3652 .getAlignment().getSequenceAt(0), null);
3653 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3654 viewport.getAlignment()));
3655 alignPanel.paintAlignment(true);
3665 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3667 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3668 AlignmentSorter.sortByID(viewport.getAlignment());
3669 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3670 viewport.getAlignment()));
3671 alignPanel.paintAlignment(true);
3681 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3683 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3684 AlignmentSorter.sortByLength(viewport.getAlignment());
3685 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3686 viewport.getAlignment()));
3687 alignPanel.paintAlignment(true);
3697 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3699 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3700 AlignmentSorter.sortByGroup(viewport.getAlignment());
3701 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3702 viewport.getAlignment()));
3704 alignPanel.paintAlignment(true);
3714 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3716 new RedundancyPanel(alignPanel, this);
3726 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3728 if ((viewport.getSelectionGroup() == null)
3729 || (viewport.getSelectionGroup().getSize() < 2))
3731 JOptionPane.showInternalMessageDialog(this, MessageManager
3732 .getString("label.you_must_select_least_two_sequences"),
3733 MessageManager.getString("label.invalid_selection"),
3734 JOptionPane.WARNING_MESSAGE);
3738 JInternalFrame frame = new JInternalFrame();
3739 frame.setContentPane(new PairwiseAlignPanel(viewport));
3740 Desktop.addInternalFrame(frame,
3741 MessageManager.getString("action.pairwise_alignment"), 600,
3753 public void PCAMenuItem_actionPerformed(ActionEvent e)
3755 if (((viewport.getSelectionGroup() != null)
3756 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3757 .getSelectionGroup().getSize() > 0))
3758 || (viewport.getAlignment().getHeight() < 4))
3761 .showInternalMessageDialog(
3764 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3766 .getString("label.sequence_selection_insufficient"),
3767 JOptionPane.WARNING_MESSAGE);
3772 new PCAPanel(alignPanel);
3776 public void autoCalculate_actionPerformed(ActionEvent e)
3778 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3779 if (viewport.autoCalculateConsensus)
3781 viewport.firePropertyChange("alignment", null, viewport
3782 .getAlignment().getSequences());
3787 public void sortByTreeOption_actionPerformed(ActionEvent e)
3789 viewport.sortByTree = sortByTree.isSelected();
3793 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3795 viewport.followSelection = listenToViewSelections.isSelected();
3805 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3807 NewTreePanel("AV", "PID", "Average distance tree using PID");
3817 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3819 NewTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3829 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3831 NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3841 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3843 NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3856 void NewTreePanel(String type, String pwType, String title)
3860 if (viewport.getSelectionGroup() != null
3861 && viewport.getSelectionGroup().getSize() > 0)
3863 if (viewport.getSelectionGroup().getSize() < 3)
3869 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3871 .getString("label.not_enough_sequences"),
3872 JOptionPane.WARNING_MESSAGE);
3876 SequenceGroup sg = viewport.getSelectionGroup();
3878 /* Decide if the selection is a column region */
3879 for (SequenceI _s : sg.getSequences())
3881 if (_s.getLength() < sg.getEndRes())
3887 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3889 .getString("label.sequences_selection_not_aligned"),
3890 JOptionPane.WARNING_MESSAGE);
3896 title = title + " on region";
3897 tp = new TreePanel(alignPanel, type, pwType);
3901 // are the visible sequences aligned?
3902 if (!viewport.getAlignment().isAligned(false))
3908 .getString("label.sequences_must_be_aligned_before_creating_tree"),
3910 .getString("label.sequences_not_aligned"),
3911 JOptionPane.WARNING_MESSAGE);
3916 if (viewport.getAlignment().getHeight() < 2)
3921 tp = new TreePanel(alignPanel, type, pwType);
3926 if (viewport.viewName != null)
3928 title += viewport.viewName + " of ";
3931 title += this.title;
3933 Desktop.addInternalFrame(tp, title, 600, 500);
3944 public void addSortByOrderMenuItem(String title,
3945 final AlignmentOrder order)
3947 final JMenuItem item = new JMenuItem(MessageManager.formatMessage("action.by_title_param", new String[]{title}));
3949 item.addActionListener(new java.awt.event.ActionListener()
3952 public void actionPerformed(ActionEvent e)
3954 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3956 // TODO: JBPNote - have to map order entries to curent SequenceI
3958 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3960 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
3963 alignPanel.paintAlignment(true);
3969 * Add a new sort by annotation score menu item
3972 * the menu to add the option to
3974 * the label used to retrieve scores for each sequence on the
3977 public void addSortByAnnotScoreMenuItem(JMenu sort,
3978 final String scoreLabel)
3980 final JMenuItem item = new JMenuItem(scoreLabel);
3982 item.addActionListener(new java.awt.event.ActionListener()
3985 public void actionPerformed(ActionEvent e)
3987 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3988 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3989 viewport.getAlignment());// ,viewport.getSelectionGroup());
3990 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3991 viewport.getAlignment()));
3992 alignPanel.paintAlignment(true);
3998 * last hash for alignment's annotation array - used to minimise cost of
4001 protected int _annotationScoreVectorHash;
4004 * search the alignment and rebuild the sort by annotation score submenu the
4005 * last alignment annotation vector hash is stored to minimize cost of
4006 * rebuilding in subsequence calls.
4010 public void buildSortByAnnotationScoresMenu()
4012 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4017 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4019 sortByAnnotScore.removeAll();
4020 // almost certainly a quicker way to do this - but we keep it simple
4021 Hashtable scoreSorts = new Hashtable();
4022 AlignmentAnnotation aann[];
4023 for (SequenceI sqa : viewport.getAlignment().getSequences())
4025 aann = sqa.getAnnotation();
4026 for (int i = 0; aann != null && i < aann.length; i++)
4028 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4030 scoreSorts.put(aann[i].label, aann[i].label);
4034 Enumeration labels = scoreSorts.keys();
4035 while (labels.hasMoreElements())
4037 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4038 (String) labels.nextElement());
4040 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4043 _annotationScoreVectorHash = viewport.getAlignment()
4044 .getAlignmentAnnotation().hashCode();
4049 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4050 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4051 * call. Listeners are added to remove the menu item when the treePanel is
4052 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4056 * Displayed tree window.
4058 * SortBy menu item title.
4061 public void buildTreeMenu()
4063 calculateTree.removeAll();
4064 // build the calculate menu
4066 for (final String type : new String[]
4069 String treecalcnm = MessageManager.getString("label.tree_calc_"
4070 + type.toLowerCase());
4071 for (final Object pwtype : ResidueProperties.scoreMatrices.keySet())
4073 JMenuItem tm = new JMenuItem();
4074 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4075 if (sm.isProtein() == !viewport.getAlignment().isNucleotide())
4077 String smn = MessageManager.getStringOrReturn(
4078 "label.score_model_", sm.getName());
4079 final String title = MessageManager.formatMessage(
4080 "label.treecalc_title", treecalcnm, smn);
4081 tm.setText(title);//
4082 tm.addActionListener(new java.awt.event.ActionListener()
4085 public void actionPerformed(ActionEvent e)
4087 NewTreePanel(type, (String) pwtype, title);
4090 calculateTree.add(tm);
4095 sortByTreeMenu.removeAll();
4097 Vector comps = (Vector) PaintRefresher.components.get(viewport
4098 .getSequenceSetId());
4099 Vector treePanels = new Vector();
4100 int i, iSize = comps.size();
4101 for (i = 0; i < iSize; i++)
4103 if (comps.elementAt(i) instanceof TreePanel)
4105 treePanels.add(comps.elementAt(i));
4109 iSize = treePanels.size();
4113 sortByTreeMenu.setVisible(false);
4117 sortByTreeMenu.setVisible(true);
4119 for (i = 0; i < treePanels.size(); i++)
4121 final TreePanel tp = (TreePanel) treePanels.elementAt(i);
4122 final JMenuItem item = new JMenuItem(tp.getTitle());
4123 final NJTree tree = ((TreePanel) treePanels.elementAt(i)).getTree();
4124 item.addActionListener(new java.awt.event.ActionListener()
4127 public void actionPerformed(ActionEvent e)
4129 tp.sortByTree_actionPerformed(null);
4130 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4135 sortByTreeMenu.add(item);
4139 public boolean sortBy(AlignmentOrder alorder, String undoname)
4141 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4142 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4143 if (undoname != null)
4145 addHistoryItem(new OrderCommand(undoname, oldOrder,
4146 viewport.getAlignment()));
4148 alignPanel.paintAlignment(true);
4153 * Work out whether the whole set of sequences or just the selected set will
4154 * be submitted for multiple alignment.
4157 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4159 // Now, check we have enough sequences
4160 AlignmentView msa = null;
4162 if ((viewport.getSelectionGroup() != null)
4163 && (viewport.getSelectionGroup().getSize() > 1))
4165 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4166 // some common interface!
4168 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4169 * SequenceI[sz = seqs.getSize(false)];
4171 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4172 * seqs.getSequenceAt(i); }
4174 msa = viewport.getAlignmentView(true);
4179 * Vector seqs = viewport.getAlignment().getSequences();
4181 * if (seqs.size() > 1) { msa = new SequenceI[seqs.size()];
4183 * for (int i = 0; i < seqs.size(); i++) { msa[i] = (SequenceI)
4184 * seqs.elementAt(i); } }
4186 msa = viewport.getAlignmentView(false);
4192 * Decides what is submitted to a secondary structure prediction service: the
4193 * first sequence in the alignment, or in the current selection, or, if the
4194 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4195 * region or the whole alignment. (where the first sequence in the set is the
4196 * one that the prediction will be for).
4198 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4200 AlignmentView seqs = null;
4202 if ((viewport.getSelectionGroup() != null)
4203 && (viewport.getSelectionGroup().getSize() > 0))
4205 seqs = viewport.getAlignmentView(true);
4209 seqs = viewport.getAlignmentView(false);
4211 // limit sequences - JBPNote in future - could spawn multiple prediction
4213 // TODO: viewport.getAlignment().isAligned is a global state - the local
4214 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4215 if (!viewport.getAlignment().isAligned(false))
4217 seqs.setSequences(new SeqCigar[]
4218 { seqs.getSequences()[0] });
4219 // TODO: if seqs.getSequences().length>1 then should really have warned
4233 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
4235 // Pick the tree file
4236 JalviewFileChooser chooser = new JalviewFileChooser(
4237 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4238 chooser.setFileView(new JalviewFileView());
4239 chooser.setDialogTitle(MessageManager
4240 .getString("label.select_newick_like_tree_file"));
4241 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4243 int value = chooser.showOpenDialog(null);
4245 if (value == JalviewFileChooser.APPROVE_OPTION)
4247 String choice = chooser.getSelectedFile().getPath();
4248 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4249 jalview.io.NewickFile fin = null;
4252 fin = new jalview.io.NewickFile(choice, "File");
4253 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4254 } catch (Exception ex)
4261 .getString("label.problem_reading_tree_file"),
4262 JOptionPane.WARNING_MESSAGE);
4263 ex.printStackTrace();
4265 if (fin != null && fin.hasWarningMessage())
4267 JOptionPane.showMessageDialog(Desktop.desktop, fin
4268 .getWarningMessage(), MessageManager
4269 .getString("label.possible_problem_with_tree_file"),
4270 JOptionPane.WARNING_MESSAGE);
4276 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4278 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4281 public TreePanel ShowNewickTree(NewickFile nf, String title)
4283 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4286 public TreePanel ShowNewickTree(NewickFile nf, String title,
4287 AlignmentView input)
4289 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4292 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4293 int h, int x, int y)
4295 return ShowNewickTree(nf, title, null, w, h, x, y);
4299 * Add a treeviewer for the tree extracted from a newick file object to the
4300 * current alignment view
4307 * Associated alignment input data (or null)
4316 * @return TreePanel handle
4318 public TreePanel ShowNewickTree(NewickFile nf, String title,
4319 AlignmentView input, int w, int h, int x, int y)
4321 TreePanel tp = null;
4327 if (nf.getTree() != null)
4329 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4335 tp.setLocation(x, y);
4338 Desktop.addInternalFrame(tp, title, w, h);
4340 } catch (Exception ex)
4342 ex.printStackTrace();
4348 private boolean buildingMenu = false;
4351 * Generates menu items and listener event actions for web service clients
4354 public void BuildWebServiceMenu()
4356 while (buildingMenu)
4360 System.err.println("Waiting for building menu to finish.");
4362 } catch (Exception e)
4367 final AlignFrame me = this;
4368 buildingMenu = true;
4369 new Thread(new Runnable()
4374 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4377 System.err.println("Building ws menu again "
4378 + Thread.currentThread());
4379 // TODO: add support for context dependent disabling of services based
4381 // alignment and current selection
4382 // TODO: add additional serviceHandle parameter to specify abstract
4384 // class independently of AbstractName
4385 // TODO: add in rediscovery GUI function to restart discoverer
4386 // TODO: group services by location as well as function and/or
4388 // object broker mechanism.
4389 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4390 final IProgressIndicator af = me;
4391 final JMenu msawsmenu = new JMenu("Alignment");
4392 final JMenu secstrmenu = new JMenu(
4393 "Secondary Structure Prediction");
4394 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4395 final JMenu analymenu = new JMenu("Analysis");
4396 final JMenu dismenu = new JMenu("Protein Disorder");
4397 // final JMenu msawsmenu = new
4398 // JMenu(MessageManager.getString("label.alignment"));
4399 // final JMenu secstrmenu = new
4400 // JMenu(MessageManager.getString("label.secondary_structure_prediction"));
4401 // final JMenu seqsrchmenu = new
4402 // JMenu(MessageManager.getString("label.sequence_database_search"));
4403 // final JMenu analymenu = new
4404 // JMenu(MessageManager.getString("label.analysis"));
4405 // final JMenu dismenu = new
4406 // JMenu(MessageManager.getString("label.protein_disorder"));
4407 // JAL-940 - only show secondary structure prediction services from
4408 // the legacy server
4409 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4411 Discoverer.services != null && (Discoverer.services.size() > 0))
4413 // TODO: refactor to allow list of AbstractName/Handler bindings to
4415 // stored or retrieved from elsewhere
4416 // No MSAWS used any more:
4417 // Vector msaws = null; // (Vector)
4418 // Discoverer.services.get("MsaWS");
4419 Vector secstrpr = (Vector) Discoverer.services
4421 if (secstrpr != null)
4423 // Add any secondary structure prediction services
4424 for (int i = 0, j = secstrpr.size(); i < j; i++)
4426 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4428 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4429 .getServiceClient(sh);
4430 int p = secstrmenu.getItemCount();
4431 impl.attachWSMenuEntry(secstrmenu, me);
4432 int q = secstrmenu.getItemCount();
4433 for (int litm = p; litm < q; litm++)
4435 legacyItems.add(secstrmenu.getItem(litm));
4441 // Add all submenus in the order they should appear on the web
4443 wsmenu.add(msawsmenu);
4444 wsmenu.add(secstrmenu);
4445 wsmenu.add(dismenu);
4446 wsmenu.add(analymenu);
4447 // No search services yet
4448 // wsmenu.add(seqsrchmenu);
4450 javax.swing.SwingUtilities.invokeLater(new Runnable()
4457 webService.removeAll();
4458 // first, add discovered services onto the webservices menu
4459 if (wsmenu.size() > 0)
4461 for (int i = 0, j = wsmenu.size(); i < j; i++)
4463 webService.add(wsmenu.get(i));
4468 webService.add(me.webServiceNoServices);
4470 // TODO: move into separate menu builder class.
4471 boolean new_sspred = false;
4472 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4474 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4475 if (jws2servs != null)
4477 if (jws2servs.hasServices())
4479 jws2servs.attachWSMenuEntry(webService, me);
4480 for (Jws2Instance sv : jws2servs.getServices())
4482 if (sv.description.toLowerCase().contains("jpred"))
4484 for (JMenuItem jmi : legacyItems)
4486 jmi.setVisible(false);
4492 if (jws2servs.isRunning())
4494 JMenuItem tm = new JMenuItem(
4495 "Still discovering JABA Services");
4496 tm.setEnabled(false);
4501 build_urlServiceMenu(me.webService);
4502 build_fetchdbmenu(webService);
4503 for (JMenu item : wsmenu)
4505 if (item.getItemCount() == 0)
4507 item.setEnabled(false);
4511 item.setEnabled(true);
4514 } catch (Exception e)
4517 .debug("Exception during web service menu building process.",
4523 } catch (Exception e)
4528 buildingMenu = false;
4535 * construct any groupURL type service menu entries.
4539 private void build_urlServiceMenu(JMenu webService)
4541 // TODO: remove this code when 2.7 is released
4542 // DEBUG - alignmentView
4544 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4545 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4547 * @Override public void actionPerformed(ActionEvent e) {
4548 * jalview.datamodel.AlignmentView
4549 * .testSelectionViews(af.viewport.getAlignment(),
4550 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4552 * }); webService.add(testAlView);
4554 // TODO: refactor to RestClient discoverer and merge menu entries for
4555 // rest-style services with other types of analysis/calculation service
4556 // SHmmr test client - still being implemented.
4557 // DEBUG - alignmentView
4559 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4562 client.attachWSMenuEntry(
4563 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4569 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
4570 * chooser = new JalviewFileChooser(jalview.bin.Cache.
4571 * getProperty("LAST_DIRECTORY"));
4573 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
4574 * to Vamsas file"); chooser.setToolTipText("Export");
4576 * int value = chooser.showSaveDialog(this);
4578 * if (value == JalviewFileChooser.APPROVE_OPTION) {
4579 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
4580 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
4581 * chooser.getSelectedFile().getAbsolutePath(), this); } }
4584 * prototype of an automatically enabled/disabled analysis function
4587 protected void setShowProductsEnabled()
4589 SequenceI[] selection = viewport.getSequenceSelection();
4590 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
4591 viewport.getAlignment().getDataset()))
4593 showProducts.setEnabled(true);
4598 showProducts.setEnabled(false);
4603 * search selection for sequence xRef products and build the show products
4608 * @return true if showProducts menu should be enabled.
4610 public boolean canShowProducts(SequenceI[] selection,
4611 boolean isRegionSelection, Alignment dataset)
4613 boolean showp = false;
4616 showProducts.removeAll();
4617 final boolean dna = viewport.getAlignment().isNucleotide();
4618 final Alignment ds = dataset;
4619 String[] ptypes = (selection == null || selection.length == 0) ? null
4620 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4622 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4623 // selection, dataset, true);
4624 final SequenceI[] sel = selection;
4625 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4628 final boolean isRegSel = isRegionSelection;
4629 final AlignFrame af = this;
4630 final String source = ptypes[t];
4631 JMenuItem xtype = new JMenuItem(ptypes[t]);
4632 xtype.addActionListener(new ActionListener()
4636 public void actionPerformed(ActionEvent e)
4638 // TODO: new thread for this call with vis-delay
4639 af.showProductsFor(af.viewport.getSequenceSelection(), ds,
4640 isRegSel, dna, source);
4644 showProducts.add(xtype);
4646 showProducts.setVisible(showp);
4647 showProducts.setEnabled(showp);
4648 } catch (Exception e)
4650 jalview.bin.Cache.log
4651 .warn("canTranslate threw an exception - please report to help@jalview.org",
4658 protected void showProductsFor(SequenceI[] sel, Alignment ds,
4659 boolean isRegSel, boolean dna, String source)
4661 final boolean fisRegSel = isRegSel;
4662 final boolean fdna = dna;
4663 final String fsrc = source;
4664 final AlignFrame ths = this;
4665 final SequenceI[] fsel = sel;
4666 Runnable foo = new Runnable()
4672 final long sttime = System.currentTimeMillis();
4673 ths.setProgressBar(MessageManager.formatMessage("status.searching_for_sequences_from", new String[]{fsrc}), sttime);
4676 Alignment ds = ths.getViewport().getAlignment().getDataset(); // update
4680 Alignment prods = CrossRef
4681 .findXrefSequences(fsel, fdna, fsrc, ds);
4684 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4685 for (int s = 0; s < sprods.length; s++)
4687 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4688 if (ds.getSequences() == null
4689 || !ds.getSequences().contains(
4690 sprods[s].getDatasetSequence()))
4692 ds.addSequence(sprods[s].getDatasetSequence());
4694 sprods[s].updatePDBIds();
4696 Alignment al = new Alignment(sprods);
4697 AlignedCodonFrame[] cf = prods.getCodonFrames();
4699 for (int s = 0; cf != null && s < cf.length; s++)
4701 al.addCodonFrame(cf[s]);
4704 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4706 String newtitle = "" + ((fdna) ? "Proteins " : "Nucleotides ")
4707 + " for " + ((fisRegSel) ? "selected region of " : "")
4709 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4714 System.err.println("No Sequences generated for xRef type "
4717 } catch (Exception e)
4719 jalview.bin.Cache.log.error(
4720 "Exception when finding crossreferences", e);
4721 } catch (OutOfMemoryError e)
4723 new OOMWarning("whilst fetching crossreferences", e);
4726 jalview.bin.Cache.log.error("Error when finding crossreferences",
4729 ths.setProgressBar(MessageManager.formatMessage("status.finished_searching_for_sequences_from", new String[]{fsrc}),
4734 Thread frunner = new Thread(foo);
4738 public boolean canShowTranslationProducts(SequenceI[] selection,
4739 AlignmentI alignment)
4744 return (jalview.analysis.Dna.canTranslate(selection,
4745 viewport.getViewAsVisibleContigs(true)));
4746 } catch (Exception e)
4748 jalview.bin.Cache.log
4749 .warn("canTranslate threw an exception - please report to help@jalview.org",
4756 public void showProducts_actionPerformed(ActionEvent e)
4758 // /////////////////////////////
4759 // Collect Data to be translated/transferred
4761 SequenceI[] selection = viewport.getSequenceSelection();
4762 AlignmentI al = null;
4765 al = jalview.analysis.Dna.CdnaTranslate(selection, viewport
4766 .getViewAsVisibleContigs(true), viewport.getGapCharacter(),
4767 viewport.getAlignment().getDataset());
4768 } catch (Exception ex)
4771 jalview.bin.Cache.log.debug("Exception during translation.", ex);
4779 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation"),
4780 MessageManager.getString("label.translation_failed"),
4781 JOptionPane.WARNING_MESSAGE);
4785 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4786 Desktop.addInternalFrame(af, MessageManager.formatMessage(
4787 "label.translation_of_params", new String[]
4788 { this.getTitle() }), DEFAULT_WIDTH, DEFAULT_HEIGHT);
4793 public void showTranslation_actionPerformed(ActionEvent e)
4795 // /////////////////////////////
4796 // Collect Data to be translated/transferred
4798 SequenceI[] selection = viewport.getSequenceSelection();
4799 String[] seqstring = viewport.getViewAsString(true);
4800 AlignmentI al = null;
4803 al = jalview.analysis.Dna.CdnaTranslate(selection, seqstring,
4804 viewport.getViewAsVisibleContigs(true), viewport
4805 .getGapCharacter(), viewport.getAlignment()
4806 .getAlignmentAnnotation(), viewport.getAlignment()
4807 .getWidth(), viewport.getAlignment().getDataset());
4808 } catch (Exception ex)
4811 jalview.bin.Cache.log.error(
4812 "Exception during translation. Please report this !", ex);
4817 .getString("label.error_when_translating_sequences_submit_bug_report"),
4819 .getString("label.implementation_error")
4821 .getString("translation_failed"),
4822 JOptionPane.ERROR_MESSAGE);
4831 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation"),
4832 MessageManager.getString("label.translation_failed"),
4833 JOptionPane.WARNING_MESSAGE);
4837 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4838 Desktop.addInternalFrame(af, MessageManager.formatMessage(
4839 "label.translation_of_params", new String[]
4840 { this.getTitle() }), DEFAULT_WIDTH, DEFAULT_HEIGHT);
4845 * Try to load a features file onto the alignment.
4848 * contents or path to retrieve file
4850 * access mode of file (see jalview.io.AlignFile)
4851 * @return true if features file was parsed corectly.
4853 public boolean parseFeaturesFile(String file, String type)
4855 boolean featuresFile = false;
4858 featuresFile = new FeaturesFile(file, type).parse(viewport
4859 .getAlignment().getDataset(), alignPanel.seqPanel.seqCanvas
4860 .getFeatureRenderer().featureColours, false,
4861 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4862 } catch (Exception ex)
4864 ex.printStackTrace();
4869 viewport.showSequenceFeatures = true;
4870 showSeqFeatures.setSelected(true);
4871 if (alignPanel.seqPanel.seqCanvas.fr != null)
4873 // update the min/max ranges where necessary
4874 alignPanel.seqPanel.seqCanvas.fr.findAllFeatures(true);
4876 if (featureSettings != null)
4878 featureSettings.setTableData();
4880 alignPanel.paintAlignment(true);
4883 return featuresFile;
4887 public void dragEnter(DropTargetDragEvent evt)
4892 public void dragExit(DropTargetEvent evt)
4897 public void dragOver(DropTargetDragEvent evt)
4902 public void dropActionChanged(DropTargetDragEvent evt)
4907 public void drop(DropTargetDropEvent evt)
4909 Transferable t = evt.getTransferable();
4910 java.util.List files = null;
4914 DataFlavor uriListFlavor = new DataFlavor(
4915 "text/uri-list;class=java.lang.String");
4916 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
4918 // Works on Windows and MacOSX
4919 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4920 files = (java.util.List) t
4921 .getTransferData(DataFlavor.javaFileListFlavor);
4923 else if (t.isDataFlavorSupported(uriListFlavor))
4925 // This is used by Unix drag system
4926 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4927 String data = (String) t.getTransferData(uriListFlavor);
4928 files = new java.util.ArrayList(1);
4929 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
4930 data, "\r\n"); st.hasMoreTokens();)
4932 String s = st.nextToken();
4933 if (s.startsWith("#"))
4935 // the line is a comment (as per the RFC 2483)
4939 java.net.URI uri = new java.net.URI(s);
4940 // check to see if we can handle this kind of URI
4941 if (uri.getScheme().toLowerCase().startsWith("http"))
4943 files.add(uri.toString());
4947 // otherwise preserve old behaviour: catch all for file objects
4948 java.io.File file = new java.io.File(uri);
4949 files.add(file.toString());
4953 } catch (Exception e)
4955 e.printStackTrace();
4961 // check to see if any of these files have names matching sequences in
4963 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4964 .getAlignment().getSequencesArray());
4966 * Object[] { String,SequenceI}
4968 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
4969 ArrayList<String> filesnotmatched = new ArrayList<String>();
4970 for (int i = 0; i < files.size(); i++)
4972 String file = files.get(i).toString();
4974 String protocol = FormatAdapter.checkProtocol(file);
4975 if (protocol == jalview.io.FormatAdapter.FILE)
4977 File fl = new File(file);
4978 pdbfn = fl.getName();
4980 else if (protocol == jalview.io.FormatAdapter.URL)
4982 URL url = new URL(file);
4983 pdbfn = url.getFile();
4985 if (pdbfn.length() > 0)
4987 // attempt to find a match in the alignment
4988 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4989 int l = 0, c = pdbfn.indexOf(".");
4990 while (mtch == null && c != -1)
4995 } while ((c = pdbfn.indexOf(".", l)) > l);
4998 pdbfn = pdbfn.substring(0, l);
5000 mtch = idm.findAllIdMatches(pdbfn);
5007 type = new IdentifyFile().Identify(file, protocol);
5008 } catch (Exception ex)
5014 if (type.equalsIgnoreCase("PDB"))
5016 filesmatched.add(new Object[]
5017 { file, protocol, mtch });
5022 // File wasn't named like one of the sequences or wasn't a PDB file.
5023 filesnotmatched.add(file);
5027 if (filesmatched.size() > 0)
5029 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
5035 "label.automatically_associate_pdb_files_with_sequences_same_name",
5042 .getString("label.automatically_associate_pdb_files_by_name"),
5043 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
5046 for (Object[] fm : filesmatched)
5048 // try and associate
5049 // TODO: may want to set a standard ID naming formalism for
5050 // associating PDB files which have no IDs.
5051 for (SequenceI toassoc : (SequenceI[]) fm[2])
5053 PDBEntry pe = new AssociatePdbFileWithSeq()
5054 .associatePdbWithSeq((String) fm[0],
5055 (String) fm[1], toassoc, false);
5058 System.err.println("Associated file : "
5059 + ((String) fm[0]) + " with "
5060 + toassoc.getDisplayId(true));
5064 alignPanel.paintAlignment(true);
5068 if (filesnotmatched.size() > 0)
5071 && (Cache.getDefault(
5072 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
5075 "<html>"+MessageManager
5077 "label.ignore_unmatched_dropped_files_info",
5082 .toString() })+"</html>",
5084 .getString("label.ignore_unmatched_dropped_files"),
5085 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
5089 for (String fn : filesnotmatched)
5091 loadJalviewDataFile(fn, null, null, null);
5095 } catch (Exception ex)
5097 ex.printStackTrace();
5103 * Attempt to load a "dropped" file or URL string: First by testing whether
5104 * it's and Annotation file, then a JNet file, and finally a features file. If
5105 * all are false then the user may have dropped an alignment file onto this
5109 * either a filename or a URL string.
5111 public void loadJalviewDataFile(String file, String protocol,
5112 String format, SequenceI assocSeq)
5116 if (protocol == null)
5118 protocol = jalview.io.FormatAdapter.checkProtocol(file);
5120 // if the file isn't identified, or not positively identified as some
5121 // other filetype (PFAM is default unidentified alignment file type) then
5122 // try to parse as annotation.
5123 boolean isAnnotation = (format == null || format
5124 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
5125 .readAnnotationFile(viewport.getAlignment(), file, protocol)
5130 // first see if its a T-COFFEE score file
5131 TCoffeeScoreFile tcf = null;
5134 tcf = new TCoffeeScoreFile(file, protocol);
5137 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5139 tcoffeeColour.setEnabled(true);
5140 tcoffeeColour.setSelected(true);
5141 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5142 isAnnotation = true;
5144 .setText(MessageManager
5145 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5149 // some problem - if no warning its probable that the ID matching
5150 // process didn't work
5154 tcf.getWarningMessage() == null ? MessageManager
5155 .getString("label.check_file_matches_sequence_ids_alignment")
5156 : tcf.getWarningMessage(),
5158 .getString("label.problem_reading_tcoffee_score_file"),
5159 JOptionPane.WARNING_MESSAGE);
5166 } catch (Exception x)
5169 .debug("Exception when processing data source as T-COFFEE score file",
5175 // try to see if its a JNet 'concise' style annotation file *before*
5177 // try to parse it as a features file
5180 format = new IdentifyFile().Identify(file, protocol);
5182 if (format.equalsIgnoreCase("JnetFile"))
5184 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5186 new JnetAnnotationMaker().add_annotation(predictions,
5187 viewport.getAlignment(), 0, false);
5188 isAnnotation = true;
5193 * if (format.equalsIgnoreCase("PDB")) {
5195 * String pdbfn = ""; // try to match up filename with sequence id
5196 * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
5197 * new File(file); pdbfn = fl.getName(); } else if (protocol ==
5198 * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
5199 * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
5200 * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5201 * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
5202 * // attempt to find a match in the alignment SequenceI mtch =
5203 * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
5204 * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
5205 * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
5206 * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
5207 * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
5208 * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
5209 * { System.err.println("Associated file : " + file + " with " +
5210 * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
5211 * TODO: maybe need to load as normal otherwise return; } }
5213 // try to parse it as a features file
5214 boolean isGroupsFile = parseFeaturesFile(file, protocol);
5215 // if it wasn't a features file then we just treat it as a general
5216 // alignment file to load into the current view.
5219 new FileLoader().LoadFile(viewport, file, protocol, format);
5223 alignPanel.paintAlignment(true);
5231 alignPanel.adjustAnnotationHeight();
5232 viewport.updateSequenceIdColours();
5233 buildSortByAnnotationScoresMenu();
5234 alignPanel.paintAlignment(true);
5236 } catch (Exception ex)
5238 ex.printStackTrace();
5239 } catch (OutOfMemoryError oom)
5244 } catch (Exception x)
5250 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5251 : "using " + protocol + " from " + file)
5253 + (format != null ? "(parsing as '" + format
5254 + "' file)" : ""), oom, Desktop.desktop);
5259 public void tabSelectionChanged(int index)
5263 alignPanel = (AlignmentPanel) alignPanels.elementAt(index);
5264 viewport = alignPanel.av;
5265 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5266 setMenusFromViewport(viewport);
5271 public void tabbedPane_mousePressed(MouseEvent e)
5273 if (SwingUtilities.isRightMouseButton(e))
5275 String reply = JOptionPane.showInternalInputDialog(this,
5276 MessageManager.getString("label.enter_view_name"),
5277 MessageManager.getString("label.enter_view_name"),
5278 JOptionPane.QUESTION_MESSAGE);
5282 viewport.viewName = reply;
5283 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5288 public AlignViewport getCurrentView()
5294 * Open the dialog for regex description parsing.
5297 protected void extractScores_actionPerformed(ActionEvent e)
5299 ParseProperties pp = new jalview.analysis.ParseProperties(
5300 viewport.getAlignment());
5301 // TODO: verify regex and introduce GUI dialog for version 2.5
5302 // if (pp.getScoresFromDescription("col", "score column ",
5303 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5305 if (pp.getScoresFromDescription("description column",
5306 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5308 buildSortByAnnotationScoresMenu();
5316 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5320 protected void showDbRefs_actionPerformed(ActionEvent e)
5322 viewport.setShowDbRefs(showDbRefsMenuitem.isSelected());
5328 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5332 protected void showNpFeats_actionPerformed(ActionEvent e)
5334 viewport.setShowNpFeats(showNpFeatsMenuitem.isSelected());
5338 * find the viewport amongst the tabs in this alignment frame and close that
5343 public boolean closeView(AlignViewport av)
5347 this.closeMenuItem_actionPerformed(false);
5350 Component[] comp = tabbedPane.getComponents();
5351 for (int i = 0; comp != null && i < comp.length; i++)
5353 if (comp[i] instanceof AlignmentPanel)
5355 if (((AlignmentPanel) comp[i]).av == av)
5358 closeView((AlignmentPanel) comp[i]);
5366 protected void build_fetchdbmenu(JMenu webService)
5368 // Temporary hack - DBRef Fetcher always top level ws entry.
5369 // TODO We probably want to store a sequence database checklist in
5370 // preferences and have checkboxes.. rather than individual sources selected
5372 final JMenu rfetch = new JMenu(
5373 MessageManager.getString("action.fetch_db_references"));
5374 rfetch.setToolTipText(MessageManager
5375 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5376 webService.add(rfetch);
5378 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5379 MessageManager.getString("option.trim_retrieved_seqs"));
5380 trimrs.setToolTipText(MessageManager
5381 .getString("label.trim_retrieved_sequences"));
5382 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5383 trimrs.addActionListener(new ActionListener()
5386 public void actionPerformed(ActionEvent e)
5388 trimrs.setSelected(trimrs.isSelected());
5389 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5390 Boolean.valueOf(trimrs.isSelected()).toString());
5394 JMenuItem fetchr = new JMenuItem(
5395 MessageManager.getString("label.standard_databases"));
5396 fetchr.setToolTipText(MessageManager
5397 .getString("label.fetch_embl_uniprot"));
5398 fetchr.addActionListener(new ActionListener()
5402 public void actionPerformed(ActionEvent e)
5404 new Thread(new Runnable()
5410 new jalview.ws.DBRefFetcher(alignPanel.av
5411 .getSequenceSelection(), alignPanel.alignFrame)
5412 .fetchDBRefs(false);
5420 final AlignFrame me = this;
5421 new Thread(new Runnable()
5426 final jalview.ws.SequenceFetcher sf = SequenceFetcher
5427 .getSequenceFetcherSingleton(me);
5428 javax.swing.SwingUtilities.invokeLater(new Runnable()
5433 String[] dbclasses = sf.getOrderedSupportedSources();
5434 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5435 // jalview.util.QuickSort.sort(otherdb, otherdb);
5436 List<DbSourceProxy> otherdb;
5437 JMenu dfetch = new JMenu();
5438 JMenu ifetch = new JMenu();
5439 JMenuItem fetchr = null;
5440 int comp = 0, icomp = 0, mcomp = 15;
5441 String mname = null;
5443 for (String dbclass : dbclasses)
5445 otherdb = sf.getSourceProxy(dbclass);
5446 // add a single entry for this class, or submenu allowing 'fetch
5448 if (otherdb == null || otherdb.size() < 1)
5452 // List<DbSourceProxy> dbs=otherdb;
5453 // otherdb=new ArrayList<DbSourceProxy>();
5454 // for (DbSourceProxy db:dbs)
5456 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5460 mname = "From " + dbclass;
5462 if (otherdb.size() == 1)
5464 final DbSourceProxy[] dassource = otherdb
5465 .toArray(new DbSourceProxy[0]);
5466 DbSourceProxy src = otherdb.get(0);
5467 fetchr = new JMenuItem(src.getDbSource());
5468 fetchr.addActionListener(new ActionListener()
5472 public void actionPerformed(ActionEvent e)
5474 new Thread(new Runnable()
5480 new jalview.ws.DBRefFetcher(alignPanel.av
5481 .getSequenceSelection(),
5482 alignPanel.alignFrame, dassource)
5483 .fetchDBRefs(false);
5489 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from", new String[]{src.getDbName()})));
5495 final DbSourceProxy[] dassource = otherdb
5496 .toArray(new DbSourceProxy[0]);
5498 DbSourceProxy src = otherdb.get(0);
5499 fetchr = new JMenuItem(MessageManager.formatMessage(
5500 "label.fetch_all_param", new String[]
5501 { src.getDbSource() }));
5502 fetchr.addActionListener(new ActionListener()
5505 public void actionPerformed(ActionEvent e)
5507 new Thread(new Runnable()
5513 new jalview.ws.DBRefFetcher(alignPanel.av
5514 .getSequenceSelection(),
5515 alignPanel.alignFrame, dassource)
5516 .fetchDBRefs(false);
5522 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from_all_sources", new String[]{Integer.valueOf(otherdb.size()).toString(), src.getDbSource(), src.getDbName()})));
5525 // and then build the rest of the individual menus
5526 ifetch = new JMenu(MessageManager.formatMessage("label.source_from_db_source", new String[]{src.getDbSource()}));
5528 String imname = null;
5530 for (DbSourceProxy sproxy : otherdb)
5532 String dbname = sproxy.getDbName();
5533 String sname = dbname.length() > 5 ? dbname.substring(0,
5534 5) + "..." : dbname;
5535 String msname = dbname.length() > 10 ? dbname.substring(
5536 0, 10) + "..." : dbname;
5539 imname = MessageManager.formatMessage("label.from_msname", new String[]{sname});
5541 fetchr = new JMenuItem(msname);
5542 final DbSourceProxy[] dassrc =
5544 fetchr.addActionListener(new ActionListener()
5548 public void actionPerformed(ActionEvent e)
5550 new Thread(new Runnable()
5556 new jalview.ws.DBRefFetcher(alignPanel.av
5557 .getSequenceSelection(),
5558 alignPanel.alignFrame, dassrc)
5559 .fetchDBRefs(false);
5565 fetchr.setToolTipText("<html>"
5566 + MessageManager.formatMessage("label.fetch_retrieve_from", new String[]{dbname}));
5569 if (++icomp >= mcomp || i == (otherdb.size()))
5571 ifetch.setText(MessageManager.formatMessage(
5572 "label.source_to_target", imname, sname));
5574 ifetch = new JMenu();
5582 if (comp >= mcomp || dbi >= (dbclasses.length))
5584 dfetch.setText(MessageManager.formatMessage(
5585 "label.source_to_target", mname, dbclass));
5587 dfetch = new JMenu();
5600 * Left justify the whole alignment.
5603 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5605 AlignmentI al = viewport.getAlignment();
5607 viewport.firePropertyChange("alignment", null, al);
5611 * Right justify the whole alignment.
5614 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5616 AlignmentI al = viewport.getAlignment();
5618 viewport.firePropertyChange("alignment", null, al);
5621 public void setShowSeqFeatures(boolean b)
5623 showSeqFeatures.setSelected(true);
5624 viewport.setShowSequenceFeatures(true);
5631 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5632 * awt.event.ActionEvent)
5635 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5637 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5638 alignPanel.paintAlignment(true);
5645 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5649 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5651 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5652 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5660 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5661 * .event.ActionEvent)
5664 protected void showGroupConservation_actionPerformed(ActionEvent e)
5666 viewport.setShowGroupConservation(showGroupConservation.getState());
5667 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5674 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5675 * .event.ActionEvent)
5678 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5680 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5681 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5688 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5689 * .event.ActionEvent)
5692 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5694 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5695 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5699 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5701 showSequenceLogo.setState(true);
5702 viewport.setShowSequenceLogo(true);
5703 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5704 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5708 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5710 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5717 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5718 * .event.ActionEvent)
5721 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5723 if (avc.makeGroupsFromSelection())
5725 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5726 alignPanel.updateAnnotation();
5727 alignPanel.paintAlignment(true);
5732 protected void createGroup_actionPerformed(ActionEvent e)
5734 if (avc.createGroup())
5736 alignPanel.alignmentChanged();
5741 protected void unGroup_actionPerformed(ActionEvent e)
5745 alignPanel.alignmentChanged();
5750 * make the given alignmentPanel the currently selected tab
5752 * @param alignmentPanel
5754 public void setDisplayedView(AlignmentPanel alignmentPanel)
5756 if (!viewport.getSequenceSetId().equals(
5757 alignmentPanel.av.getSequenceSetId()))
5759 throw new Error(MessageManager.getString("error.implementation_error_cannot_show_view_alignment_frame"));
5761 if (tabbedPane != null
5762 & alignPanels.indexOf(alignmentPanel) != tabbedPane
5763 .getSelectedIndex())
5765 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5770 * Action on selection of menu option to Show or Hide all annotations.
5775 protected void setAllAnnotationsVisibility(boolean visible)
5777 for (AlignmentAnnotation aa : alignPanel.getAlignment()
5778 .getAlignmentAnnotation())
5780 aa.visible = visible;
5782 this.alignPanel.paintAlignment(true);
5786 * Store selected annotation sort order for the view and repaint.
5789 protected void sortAnnotations_actionPerformed(SortOrder sortOrder)
5791 this.alignPanel.av.setSortAnnotationsBy(sortOrder);
5792 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5796 class PrintThread extends Thread
5800 public PrintThread(AlignmentPanel ap)
5805 static PageFormat pf;
5810 PrinterJob printJob = PrinterJob.getPrinterJob();
5814 printJob.setPrintable(ap, pf);
5818 printJob.setPrintable(ap);
5821 if (printJob.printDialog())
5826 } catch (Exception PrintException)
5828 PrintException.printStackTrace();