2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3 * Copyright (C) 2014 The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AAFrequency;
24 import jalview.analysis.AlignmentSorter;
25 import jalview.analysis.AlignmentUtils;
26 import jalview.analysis.Conservation;
27 import jalview.analysis.CrossRef;
28 import jalview.analysis.NJTree;
29 import jalview.analysis.ParseProperties;
30 import jalview.analysis.SequenceIdMatcher;
31 import jalview.api.AlignViewControllerGuiI;
32 import jalview.api.AlignViewControllerI;
33 import jalview.api.analysis.ScoreModelI;
34 import jalview.bin.Cache;
35 import jalview.commands.CommandI;
36 import jalview.commands.EditCommand;
37 import jalview.commands.EditCommand.Action;
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.BioJsHTMLOutput;
58 import jalview.io.FeaturesFile;
59 import jalview.io.FileLoader;
60 import jalview.io.FormatAdapter;
61 import jalview.io.HTMLOutput;
62 import jalview.io.IdentifyFile;
63 import jalview.io.JalviewFileChooser;
64 import jalview.io.JalviewFileView;
65 import jalview.io.JnetAnnotationMaker;
66 import jalview.io.NewickFile;
67 import jalview.io.TCoffeeScoreFile;
68 import jalview.jbgui.GAlignFrame;
69 import jalview.schemes.Blosum62ColourScheme;
70 import jalview.schemes.BuriedColourScheme;
71 import jalview.schemes.ClustalxColourScheme;
72 import jalview.schemes.ColourSchemeI;
73 import jalview.schemes.ColourSchemeProperty;
74 import jalview.schemes.HelixColourScheme;
75 import jalview.schemes.HydrophobicColourScheme;
76 import jalview.schemes.NucleotideColourScheme;
77 import jalview.schemes.PIDColourScheme;
78 import jalview.schemes.PurinePyrimidineColourScheme;
79 import jalview.schemes.RNAHelicesColourChooser;
80 import jalview.schemes.ResidueProperties;
81 import jalview.schemes.StrandColourScheme;
82 import jalview.schemes.TCoffeeColourScheme;
83 import jalview.schemes.TaylorColourScheme;
84 import jalview.schemes.TurnColourScheme;
85 import jalview.schemes.UserColourScheme;
86 import jalview.schemes.ZappoColourScheme;
87 import jalview.util.MessageManager;
88 import jalview.ws.jws1.Discoverer;
89 import jalview.ws.jws2.Jws2Discoverer;
90 import jalview.ws.jws2.jabaws2.Jws2Instance;
91 import jalview.ws.seqfetcher.DbSourceProxy;
93 import java.awt.BorderLayout;
94 import java.awt.Component;
95 import java.awt.GridLayout;
96 import java.awt.Rectangle;
97 import java.awt.Toolkit;
98 import java.awt.datatransfer.Clipboard;
99 import java.awt.datatransfer.DataFlavor;
100 import java.awt.datatransfer.StringSelection;
101 import java.awt.datatransfer.Transferable;
102 import java.awt.dnd.DnDConstants;
103 import java.awt.dnd.DropTargetDragEvent;
104 import java.awt.dnd.DropTargetDropEvent;
105 import java.awt.dnd.DropTargetEvent;
106 import java.awt.dnd.DropTargetListener;
107 import java.awt.event.ActionEvent;
108 import java.awt.event.ActionListener;
109 import java.awt.event.KeyAdapter;
110 import java.awt.event.KeyEvent;
111 import java.awt.event.MouseAdapter;
112 import java.awt.event.MouseEvent;
113 import java.awt.print.PageFormat;
114 import java.awt.print.PrinterJob;
115 import java.beans.PropertyChangeEvent;
118 import java.util.ArrayList;
119 import java.util.Enumeration;
120 import java.util.Hashtable;
121 import java.util.List;
122 import java.util.Vector;
124 import javax.swing.JButton;
125 import javax.swing.JCheckBoxMenuItem;
126 import javax.swing.JEditorPane;
127 import javax.swing.JInternalFrame;
128 import javax.swing.JLabel;
129 import javax.swing.JLayeredPane;
130 import javax.swing.JMenu;
131 import javax.swing.JMenuItem;
132 import javax.swing.JOptionPane;
133 import javax.swing.JPanel;
134 import javax.swing.JProgressBar;
135 import javax.swing.JRadioButtonMenuItem;
136 import javax.swing.JScrollPane;
137 import javax.swing.SwingUtilities;
143 * @version $Revision$
145 public class AlignFrame extends GAlignFrame implements DropTargetListener,
146 IProgressIndicator, AlignViewControllerGuiI
150 public static final int DEFAULT_WIDTH = 700;
153 public static final int DEFAULT_HEIGHT = 500;
155 public AlignmentPanel alignPanel;
157 AlignViewport viewport;
159 public AlignViewControllerI avc;
161 Vector alignPanels = new Vector();
164 * Last format used to load or save alignments in this window
166 String currentFileFormat = null;
169 * Current filename for this alignment
171 String fileName = null;
174 * Creates a new AlignFrame object with specific width and height.
180 public AlignFrame(AlignmentI al, int width, int height)
182 this(al, null, width, height);
186 * Creates a new AlignFrame object with specific width, height and
192 * @param sequenceSetId
194 public AlignFrame(AlignmentI al, int width, int height,
195 String sequenceSetId)
197 this(al, null, width, height, sequenceSetId);
201 * Creates a new AlignFrame object with specific width, height and
207 * @param sequenceSetId
210 public AlignFrame(AlignmentI al, int width, int height,
211 String sequenceSetId, String viewId)
213 this(al, null, width, height, sequenceSetId, viewId);
217 * new alignment window with hidden columns
221 * @param hiddenColumns
222 * ColumnSelection or null
224 * Width of alignment frame
228 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
229 int width, int height)
231 this(al, hiddenColumns, width, height, null);
235 * Create alignment frame for al with hiddenColumns, a specific width and
236 * height, and specific sequenceId
239 * @param hiddenColumns
242 * @param sequenceSetId
245 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
246 int width, int height, String sequenceSetId)
248 this(al, hiddenColumns, width, height, sequenceSetId, null);
252 * Create alignment frame for al with hiddenColumns, a specific width and
253 * height, and specific sequenceId
256 * @param hiddenColumns
259 * @param sequenceSetId
264 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
265 int width, int height, String sequenceSetId, String viewId)
267 setSize(width, height);
269 if (al.getDataset() == null)
274 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
276 alignPanel = new AlignmentPanel(this, viewport);
279 addAlignmentPanel(alignPanel, true);
284 * Make a new AlignFrame from existing alignmentPanels
291 public AlignFrame(AlignmentPanel ap)
295 addAlignmentPanel(ap, false);
300 * initalise the alignframe from the underlying viewport data and the
305 avc = new jalview.controller.AlignViewController(this, viewport,
307 if (viewport.getAlignmentConservationAnnotation() == null)
309 BLOSUM62Colour.setEnabled(false);
310 conservationMenuItem.setEnabled(false);
311 modifyConservation.setEnabled(false);
312 // PIDColour.setEnabled(false);
313 // abovePIDThreshold.setEnabled(false);
314 // modifyPID.setEnabled(false);
317 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
320 if (sortby.equals("Id"))
322 sortIDMenuItem_actionPerformed(null);
324 else if (sortby.equals("Pairwise Identity"))
326 sortPairwiseMenuItem_actionPerformed(null);
329 if (Desktop.desktop != null)
331 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
332 addServiceListeners();
333 setGUINucleotide(viewport.getAlignment().isNucleotide());
336 setMenusFromViewport(viewport);
337 buildSortByAnnotationScoresMenu();
340 if (viewport.wrapAlignment)
342 wrapMenuItem_actionPerformed(null);
345 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
347 this.overviewMenuItem_actionPerformed(null);
355 * Change the filename and format for the alignment, and enable the 'reload'
356 * button functionality.
363 public void setFileName(String file, String format)
366 currentFileFormat = format;
367 reload.setEnabled(true);
370 void addKeyListener()
372 addKeyListener(new KeyAdapter()
375 public void keyPressed(KeyEvent evt)
377 if (viewport.cursorMode
378 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
379 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
380 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
381 && Character.isDigit(evt.getKeyChar()))
383 alignPanel.seqPanel.numberPressed(evt.getKeyChar());
386 switch (evt.getKeyCode())
389 case 27: // escape key
390 deselectAllSequenceMenuItem_actionPerformed(null);
394 case KeyEvent.VK_DOWN:
395 if (evt.isAltDown() || !viewport.cursorMode)
397 moveSelectedSequences(false);
399 if (viewport.cursorMode)
401 alignPanel.seqPanel.moveCursor(0, 1);
406 if (evt.isAltDown() || !viewport.cursorMode)
408 moveSelectedSequences(true);
410 if (viewport.cursorMode)
412 alignPanel.seqPanel.moveCursor(0, -1);
417 case KeyEvent.VK_LEFT:
418 if (evt.isAltDown() || !viewport.cursorMode)
420 slideSequences(false, alignPanel.seqPanel.getKeyboardNo1());
424 alignPanel.seqPanel.moveCursor(-1, 0);
429 case KeyEvent.VK_RIGHT:
430 if (evt.isAltDown() || !viewport.cursorMode)
432 slideSequences(true, alignPanel.seqPanel.getKeyboardNo1());
436 alignPanel.seqPanel.moveCursor(1, 0);
440 case KeyEvent.VK_SPACE:
441 if (viewport.cursorMode)
443 alignPanel.seqPanel.insertGapAtCursor(evt.isControlDown()
444 || evt.isShiftDown() || evt.isAltDown());
448 // case KeyEvent.VK_A:
449 // if (viewport.cursorMode)
451 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
452 // //System.out.println("A");
456 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
457 * System.out.println("closing bracket"); } break;
459 case KeyEvent.VK_DELETE:
460 case KeyEvent.VK_BACK_SPACE:
461 if (!viewport.cursorMode)
463 cut_actionPerformed(null);
467 alignPanel.seqPanel.deleteGapAtCursor(evt.isControlDown()
468 || evt.isShiftDown() || evt.isAltDown());
474 if (viewport.cursorMode)
476 alignPanel.seqPanel.setCursorRow();
480 if (viewport.cursorMode && !evt.isControlDown())
482 alignPanel.seqPanel.setCursorColumn();
486 if (viewport.cursorMode)
488 alignPanel.seqPanel.setCursorPosition();
492 case KeyEvent.VK_ENTER:
493 case KeyEvent.VK_COMMA:
494 if (viewport.cursorMode)
496 alignPanel.seqPanel.setCursorRowAndColumn();
501 if (viewport.cursorMode)
503 alignPanel.seqPanel.setSelectionAreaAtCursor(true);
507 if (viewport.cursorMode)
509 alignPanel.seqPanel.setSelectionAreaAtCursor(false);
514 viewport.cursorMode = !viewport.cursorMode;
515 statusBar.setText(MessageManager.formatMessage(
516 "label.keyboard_editing_mode", new String[]
517 { (viewport.cursorMode ? "on" : "off") }));
518 if (viewport.cursorMode)
520 alignPanel.seqPanel.seqCanvas.cursorX = viewport.startRes;
521 alignPanel.seqPanel.seqCanvas.cursorY = viewport.startSeq;
523 alignPanel.seqPanel.seqCanvas.repaint();
529 Help.showHelpWindow();
530 } catch (Exception ex)
532 ex.printStackTrace();
537 boolean toggleSeqs = !evt.isControlDown();
538 boolean toggleCols = !evt.isShiftDown();
539 toggleHiddenRegions(toggleSeqs, toggleCols);
542 case KeyEvent.VK_PAGE_UP:
543 if (viewport.wrapAlignment)
545 alignPanel.scrollUp(true);
549 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
550 - viewport.endSeq + viewport.startSeq);
553 case KeyEvent.VK_PAGE_DOWN:
554 if (viewport.wrapAlignment)
556 alignPanel.scrollUp(false);
560 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
561 + viewport.endSeq - viewport.startSeq);
568 public void keyReleased(KeyEvent evt)
570 switch (evt.getKeyCode())
572 case KeyEvent.VK_LEFT:
573 if (evt.isAltDown() || !viewport.cursorMode)
575 viewport.firePropertyChange("alignment", null, viewport
576 .getAlignment().getSequences());
580 case KeyEvent.VK_RIGHT:
581 if (evt.isAltDown() || !viewport.cursorMode)
583 viewport.firePropertyChange("alignment", null, viewport
584 .getAlignment().getSequences());
592 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
594 ap.alignFrame = this;
595 avc = new jalview.controller.AlignViewController(this, viewport,
598 alignPanels.addElement(ap);
600 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
602 int aSize = alignPanels.size();
604 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
606 if (aSize == 1 && ap.av.viewName == null)
608 this.getContentPane().add(ap, BorderLayout.CENTER);
614 setInitialTabVisible();
617 expandViews.setEnabled(true);
618 gatherViews.setEnabled(true);
619 tabbedPane.addTab(ap.av.viewName, ap);
621 ap.setVisible(false);
626 if (ap.av.isPadGaps())
628 ap.av.getAlignment().padGaps();
630 ap.av.updateConservation(ap);
631 ap.av.updateConsensus(ap);
632 ap.av.updateStrucConsensus(ap);
636 public void setInitialTabVisible()
638 expandViews.setEnabled(true);
639 gatherViews.setEnabled(true);
640 tabbedPane.setVisible(true);
641 AlignmentPanel first = (AlignmentPanel) alignPanels.firstElement();
642 tabbedPane.addTab(first.av.viewName, first);
643 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
646 public AlignViewport getViewport()
651 /* Set up intrinsic listeners for dynamically generated GUI bits. */
652 private void addServiceListeners()
654 final java.beans.PropertyChangeListener thisListener;
655 Desktop.instance.addJalviewPropertyChangeListener("services",
656 thisListener = new java.beans.PropertyChangeListener()
659 public void propertyChange(PropertyChangeEvent evt)
661 // // System.out.println("Discoverer property change.");
662 // if (evt.getPropertyName().equals("services"))
664 SwingUtilities.invokeLater(new Runnable()
671 .println("Rebuild WS Menu for service change");
672 BuildWebServiceMenu();
679 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
682 public void internalFrameClosed(
683 javax.swing.event.InternalFrameEvent evt)
685 System.out.println("deregistering discoverer listener");
686 Desktop.instance.removeJalviewPropertyChangeListener("services",
688 closeMenuItem_actionPerformed(true);
691 // Finally, build the menu once to get current service state
692 new Thread(new Runnable()
697 BuildWebServiceMenu();
702 public void setGUINucleotide(boolean nucleotide)
704 showTranslation.setVisible(nucleotide);
705 conservationMenuItem.setEnabled(!nucleotide);
706 modifyConservation.setEnabled(!nucleotide);
707 showGroupConservation.setEnabled(!nucleotide);
708 rnahelicesColour.setEnabled(nucleotide);
709 purinePyrimidineColour.setEnabled(nucleotide);
710 // Remember AlignFrame always starts as protein
714 // calculateMenu.remove(calculateMenu.getItemCount() - 2);
719 * set up menus for the currently viewport. This may be called after any
720 * operation that affects the data in the current view (selection changed,
721 * etc) to update the menus to reflect the new state.
723 public void setMenusForViewport()
725 setMenusFromViewport(viewport);
729 * Need to call this method when tabs are selected for multiple views, or when
730 * loading from Jalview2XML.java
735 void setMenusFromViewport(AlignViewport av)
737 padGapsMenuitem.setSelected(av.isPadGaps());
738 colourTextMenuItem.setSelected(av.showColourText);
739 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
740 conservationMenuItem.setSelected(av.getConservationSelected());
741 seqLimits.setSelected(av.getShowJVSuffix());
742 idRightAlign.setSelected(av.rightAlignIds);
743 centreColumnLabelsMenuItem.setState(av.centreColumnLabels);
744 renderGapsMenuItem.setSelected(av.renderGaps);
745 wrapMenuItem.setSelected(av.wrapAlignment);
746 scaleAbove.setVisible(av.wrapAlignment);
747 scaleLeft.setVisible(av.wrapAlignment);
748 scaleRight.setVisible(av.wrapAlignment);
749 annotationPanelMenuItem.setState(av.showAnnotation);
751 * Show/hide annotations only enabled if annotation panel is shown
753 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
754 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
755 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
756 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
757 viewBoxesMenuItem.setSelected(av.showBoxes);
758 viewTextMenuItem.setSelected(av.showText);
759 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
760 showGroupConsensus.setSelected(av.isShowGroupConsensus());
761 showGroupConservation.setSelected(av.isShowGroupConservation());
762 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
763 showSequenceLogo.setSelected(av.isShowSequenceLogo());
764 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
766 setColourSelected(ColourSchemeProperty.getColourName(av
767 .getGlobalColourScheme()));
769 showSeqFeatures.setSelected(av.showSequenceFeatures);
770 hiddenMarkers.setState(av.showHiddenMarkers);
771 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
772 showNpFeatsMenuitem.setSelected(av.isShowNpFeats());
773 showDbRefsMenuitem.setSelected(av.isShowDbRefs());
774 autoCalculate.setSelected(av.autoCalculateConsensus);
775 sortByTree.setSelected(av.sortByTree);
776 listenToViewSelections.setSelected(av.followSelection);
777 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
779 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
780 setShowProductsEnabled();
784 // methods for implementing IProgressIndicator
785 // need to refactor to a reusable stub class
786 Hashtable progressBars, progressBarHandlers;
791 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
794 public void setProgressBar(String message, long id)
796 if (progressBars == null)
798 progressBars = new Hashtable();
799 progressBarHandlers = new Hashtable();
802 JPanel progressPanel;
803 Long lId = new Long(id);
804 GridLayout layout = (GridLayout) statusPanel.getLayout();
805 if (progressBars.get(lId) != null)
807 progressPanel = (JPanel) progressBars.get(new Long(id));
808 statusPanel.remove(progressPanel);
809 progressBars.remove(lId);
810 progressPanel = null;
813 statusBar.setText(message);
815 if (progressBarHandlers.contains(lId))
817 progressBarHandlers.remove(lId);
819 layout.setRows(layout.getRows() - 1);
823 progressPanel = new JPanel(new BorderLayout(10, 5));
825 JProgressBar progressBar = new JProgressBar();
826 progressBar.setIndeterminate(true);
828 progressPanel.add(new JLabel(message), BorderLayout.WEST);
829 progressPanel.add(progressBar, BorderLayout.CENTER);
831 layout.setRows(layout.getRows() + 1);
832 statusPanel.add(progressPanel);
834 progressBars.put(lId, progressPanel);
837 // setMenusForViewport();
842 public void registerHandler(final long id,
843 final IProgressIndicatorHandler handler)
845 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
847 throw new Error(MessageManager.getString("error.call_setprogressbar_before_registering_handler"));
849 progressBarHandlers.put(new Long(id), handler);
850 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
851 if (handler.canCancel())
853 JButton cancel = new JButton(
854 MessageManager.getString("action.cancel"));
855 final IProgressIndicator us = this;
856 cancel.addActionListener(new ActionListener()
860 public void actionPerformed(ActionEvent e)
862 handler.cancelActivity(id);
863 us.setProgressBar(MessageManager.formatMessage("label.cancelled_params", new String[]{((JLabel) progressPanel.getComponent(0)).getText()}), id);
866 progressPanel.add(cancel, BorderLayout.EAST);
872 * @return true if any progress bars are still active
875 public boolean operationInProgress()
877 if (progressBars != null && progressBars.size() > 0)
885 public void setStatus(String text)
887 statusBar.setText(text);
891 * Added so Castor Mapping file can obtain Jalview Version
893 public String getVersion()
895 return jalview.bin.Cache.getProperty("VERSION");
898 public FeatureRenderer getFeatureRenderer()
900 return alignPanel.seqPanel.seqCanvas.getFeatureRenderer();
904 public void fetchSequence_actionPerformed(ActionEvent e)
906 new SequenceFetcher(this);
910 public void addFromFile_actionPerformed(ActionEvent e)
912 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
916 public void reload_actionPerformed(ActionEvent e)
918 if (fileName != null)
920 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
921 // originating file's format
922 // TODO: work out how to recover feature settings for correct view(s) when
924 if (currentFileFormat.equals("Jalview"))
926 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
927 for (int i = 0; i < frames.length; i++)
929 if (frames[i] instanceof AlignFrame && frames[i] != this
930 && ((AlignFrame) frames[i]).fileName != null
931 && ((AlignFrame) frames[i]).fileName.equals(fileName))
935 frames[i].setSelected(true);
936 Desktop.instance.closeAssociatedWindows();
937 } catch (java.beans.PropertyVetoException ex)
943 Desktop.instance.closeAssociatedWindows();
945 FileLoader loader = new FileLoader();
946 String protocol = fileName.startsWith("http:") ? "URL" : "File";
947 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
951 Rectangle bounds = this.getBounds();
953 FileLoader loader = new FileLoader();
954 String protocol = fileName.startsWith("http:") ? "URL" : "File";
955 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
956 protocol, currentFileFormat);
958 newframe.setBounds(bounds);
959 if (featureSettings != null && featureSettings.isShowing())
961 final Rectangle fspos = featureSettings.frame.getBounds();
962 // TODO: need a 'show feature settings' function that takes bounds -
963 // need to refactor Desktop.addFrame
964 newframe.featureSettings_actionPerformed(null);
965 final FeatureSettings nfs = newframe.featureSettings;
966 SwingUtilities.invokeLater(new Runnable()
971 nfs.frame.setBounds(fspos);
974 this.featureSettings.close();
975 this.featureSettings = null;
977 this.closeMenuItem_actionPerformed(true);
983 public void addFromText_actionPerformed(ActionEvent e)
985 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
989 public void addFromURL_actionPerformed(ActionEvent e)
991 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
995 public void save_actionPerformed(ActionEvent e)
998 || (currentFileFormat == null || !jalview.io.FormatAdapter
999 .isValidIOFormat(currentFileFormat, true))
1000 || fileName.startsWith("http"))
1002 saveAs_actionPerformed(null);
1006 saveAlignment(fileName, currentFileFormat);
1017 public void saveAs_actionPerformed(ActionEvent e)
1019 JalviewFileChooser chooser = new JalviewFileChooser(
1020 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
1021 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
1022 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
1023 currentFileFormat, false);
1025 chooser.setFileView(new JalviewFileView());
1026 chooser.setDialogTitle(MessageManager.getString("label.save_alignment_to_file"));
1027 chooser.setToolTipText(MessageManager.getString("action.save"));
1029 int value = chooser.showSaveDialog(this);
1031 if (value == JalviewFileChooser.APPROVE_OPTION)
1033 currentFileFormat = chooser.getSelectedFormat();
1034 if (currentFileFormat == null)
1037 .showInternalMessageDialog(
1040 .getString("label.select_file_format_before_saving"),
1042 .getString("label.file_format_not_specified"),
1043 JOptionPane.WARNING_MESSAGE);
1044 value = chooser.showSaveDialog(this);
1048 fileName = chooser.getSelectedFile().getPath();
1050 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
1053 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
1054 if (currentFileFormat.indexOf(" ") > -1)
1056 currentFileFormat = currentFileFormat.substring(0,
1057 currentFileFormat.indexOf(" "));
1059 saveAlignment(fileName, currentFileFormat);
1063 public boolean saveAlignment(String file, String format)
1065 boolean success = true;
1067 if (format.equalsIgnoreCase("Jalview"))
1069 String shortName = title;
1071 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1073 shortName = shortName.substring(shortName
1074 .lastIndexOf(java.io.File.separatorChar) + 1);
1077 success = new Jalview2XML().SaveAlignment(this, file, shortName);
1079 statusBar.setText(MessageManager.formatMessage(
1080 "label.successfully_saved_to_file_in_format", new String[]
1081 { fileName, format }));
1086 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1088 warningMessage("Cannot save file " + fileName + " using format "
1089 + format, "Alignment output format not supported");
1090 saveAs_actionPerformed(null);
1091 // JBPNote need to have a raise_gui flag here
1095 String[] omitHidden = null;
1097 if (viewport.hasHiddenColumns())
1099 int reply = JOptionPane
1100 .showInternalConfirmDialog(
1103 .getString("label.alignment_contains_hidden_columns"),
1105 .getString("action.save_omit_hidden_columns"),
1106 JOptionPane.YES_NO_OPTION,
1107 JOptionPane.QUESTION_MESSAGE);
1109 if (reply == JOptionPane.YES_OPTION)
1111 omitHidden = viewport.getViewAsString(false);
1114 FormatAdapter f = new FormatAdapter();
1115 String output = f.formatSequences(format,
1116 viewport.getAlignment(), // class cast exceptions will
1117 // occur in the distant future
1118 omitHidden, f.getCacheSuffixDefault(format),
1119 viewport.getColumnSelection());
1129 java.io.PrintWriter out = new java.io.PrintWriter(
1130 new java.io.FileWriter(file));
1134 this.setTitle(file);
1135 statusBar.setText(MessageManager.formatMessage(
1136 "label.successfully_saved_to_file_in_format",
1138 { fileName, format }));
1139 } catch (Exception ex)
1142 ex.printStackTrace();
1149 JOptionPane.showInternalMessageDialog(this, MessageManager
1150 .formatMessage("label.couldnt_save_file", new String[]
1151 { fileName }), MessageManager
1152 .getString("label.error_saving_file"),
1153 JOptionPane.WARNING_MESSAGE);
1159 private void warningMessage(String warning, String title)
1161 if (new jalview.util.Platform().isHeadless())
1163 System.err.println("Warning: " + title + "\nWarning: " + warning);
1168 JOptionPane.showInternalMessageDialog(this, warning, title,
1169 JOptionPane.WARNING_MESSAGE);
1181 protected void outputText_actionPerformed(ActionEvent e)
1183 String[] omitHidden = null;
1185 if (viewport.hasHiddenColumns())
1187 int reply = JOptionPane
1188 .showInternalConfirmDialog(
1191 .getString("label.alignment_contains_hidden_columns"),
1193 .getString("action.save_omit_hidden_columns"),
1194 JOptionPane.YES_NO_OPTION,
1195 JOptionPane.QUESTION_MESSAGE);
1197 if (reply == JOptionPane.YES_OPTION)
1199 omitHidden = viewport.getViewAsString(false);
1203 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1204 cap.setForInput(null);
1208 cap.setText(new FormatAdapter().formatSequences(e.getActionCommand(),
1209 viewport.getAlignment(), omitHidden,
1210 viewport.getColumnSelection()));
1211 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1212 "label.alignment_output_command", new String[]
1213 { e.getActionCommand() }), 600, 500);
1214 } catch (OutOfMemoryError oom)
1216 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1229 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1231 new HTMLOutput(alignPanel,
1232 alignPanel.seqPanel.seqCanvas.getSequenceRenderer(),
1233 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
1237 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1239 new BioJsHTMLOutput(alignPanel,
1240 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
1242 public void createImageMap(File file, String image)
1244 alignPanel.makePNGImageMap(file, image);
1254 public void createPNG(File f)
1256 alignPanel.makePNG(f);
1266 public void createEPS(File f)
1268 alignPanel.makeEPS(f);
1271 public void createSVG(File f)
1273 alignPanel.makeSVG(f);
1276 public void pageSetup_actionPerformed(ActionEvent e)
1278 PrinterJob printJob = PrinterJob.getPrinterJob();
1279 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1289 public void printMenuItem_actionPerformed(ActionEvent e)
1291 // Putting in a thread avoids Swing painting problems
1292 PrintThread thread = new PrintThread(alignPanel);
1297 public void exportFeatures_actionPerformed(ActionEvent e)
1299 new AnnotationExporter().exportFeatures(alignPanel);
1303 public void exportAnnotations_actionPerformed(ActionEvent e)
1305 new AnnotationExporter().exportAnnotations(alignPanel,
1306 viewport.showAnnotation ? viewport.getAlignment()
1307 .getAlignmentAnnotation() : null, viewport
1308 .getAlignment().getGroups(), ((Alignment) viewport
1309 .getAlignment()).alignmentProperties);
1313 public void associatedData_actionPerformed(ActionEvent e)
1315 // Pick the tree file
1316 JalviewFileChooser chooser = new JalviewFileChooser(
1317 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1318 chooser.setFileView(new JalviewFileView());
1319 chooser.setDialogTitle(MessageManager
1320 .getString("label.load_jalview_annotations"));
1321 chooser.setToolTipText(MessageManager
1322 .getString("label.load_jalview_annotations"));
1324 int value = chooser.showOpenDialog(null);
1326 if (value == JalviewFileChooser.APPROVE_OPTION)
1328 String choice = chooser.getSelectedFile().getPath();
1329 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1330 loadJalviewDataFile(choice, null, null, null);
1336 * Close the current view or all views in the alignment frame. If the frame
1337 * only contains one view then the alignment will be removed from memory.
1339 * @param closeAllTabs
1342 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1344 if (alignPanels != null && alignPanels.size() < 2)
1346 closeAllTabs = true;
1351 if (alignPanels != null)
1355 if (this.isClosed())
1357 // really close all the windows - otherwise wait till
1358 // setClosed(true) is called
1359 for (int i = 0; i < alignPanels.size(); i++)
1361 AlignmentPanel ap = (AlignmentPanel) alignPanels.elementAt(i);
1368 closeView(alignPanel);
1374 this.setClosed(true);
1376 } catch (Exception ex)
1378 ex.printStackTrace();
1383 * close alignPanel2 and shuffle tabs appropriately.
1385 * @param alignPanel2
1387 public void closeView(AlignmentPanel alignPanel2)
1389 int index = tabbedPane.getSelectedIndex();
1390 int closedindex = tabbedPane.indexOfComponent(alignPanel2);
1391 alignPanels.removeElement(alignPanel2);
1393 // if (viewport == alignPanel2.av)
1397 alignPanel2.closePanel();
1400 tabbedPane.removeTabAt(closedindex);
1401 tabbedPane.validate();
1403 if (index > closedindex || index == tabbedPane.getTabCount())
1405 // modify currently selected tab index if necessary.
1409 this.tabSelectionChanged(index);
1415 void updateEditMenuBar()
1418 if (viewport.historyList.size() > 0)
1420 undoMenuItem.setEnabled(true);
1421 CommandI command = viewport.historyList.peek();
1422 undoMenuItem.setText(MessageManager.formatMessage(
1423 "label.undo_command", new String[]
1424 { command.getDescription() }));
1428 undoMenuItem.setEnabled(false);
1429 undoMenuItem.setText(MessageManager.getString("action.undo"));
1432 if (viewport.redoList.size() > 0)
1434 redoMenuItem.setEnabled(true);
1436 CommandI command = viewport.redoList.peek();
1437 redoMenuItem.setText(MessageManager.formatMessage(
1438 "label.redo_command", new String[]
1439 { command.getDescription() }));
1443 redoMenuItem.setEnabled(false);
1444 redoMenuItem.setText(MessageManager.getString("action.redo"));
1448 public void addHistoryItem(CommandI command)
1450 if (command.getSize() > 0)
1452 viewport.historyList.push(command);
1453 viewport.redoList.clear();
1454 updateEditMenuBar();
1455 viewport.updateHiddenColumns();
1456 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1457 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1458 // viewport.getColumnSelection()
1459 // .getHiddenColumns().size() > 0);
1465 * @return alignment objects for all views
1467 AlignmentI[] getViewAlignments()
1469 if (alignPanels != null)
1471 Enumeration e = alignPanels.elements();
1472 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1473 for (int i = 0; e.hasMoreElements(); i++)
1475 als[i] = ((AlignmentPanel) e.nextElement()).av.getAlignment();
1479 if (viewport != null)
1481 return new AlignmentI[]
1482 { viewport.getAlignment() };
1494 protected void undoMenuItem_actionPerformed(ActionEvent e)
1496 if (viewport.historyList.empty())
1500 CommandI command = viewport.historyList.pop();
1501 viewport.redoList.push(command);
1502 command.undoCommand(getViewAlignments());
1504 AlignViewport originalSource = getOriginatingSource(command);
1505 updateEditMenuBar();
1507 if (originalSource != null)
1509 if (originalSource != viewport)
1512 .warn("Implementation worry: mismatch of viewport origin for undo");
1514 originalSource.updateHiddenColumns();
1515 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1517 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1518 // viewport.getColumnSelection()
1519 // .getHiddenColumns().size() > 0);
1520 originalSource.firePropertyChange("alignment", null, originalSource
1521 .getAlignment().getSequences());
1532 protected void redoMenuItem_actionPerformed(ActionEvent e)
1534 if (viewport.redoList.size() < 1)
1539 CommandI command = viewport.redoList.pop();
1540 viewport.historyList.push(command);
1541 command.doCommand(getViewAlignments());
1543 AlignViewport originalSource = getOriginatingSource(command);
1544 updateEditMenuBar();
1546 if (originalSource != null)
1549 if (originalSource != viewport)
1552 .warn("Implementation worry: mismatch of viewport origin for redo");
1554 originalSource.updateHiddenColumns();
1555 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1557 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1558 // viewport.getColumnSelection()
1559 // .getHiddenColumns().size() > 0);
1560 originalSource.firePropertyChange("alignment", null, originalSource
1561 .getAlignment().getSequences());
1565 AlignViewport getOriginatingSource(CommandI command)
1567 AlignViewport originalSource = null;
1568 // For sequence removal and addition, we need to fire
1569 // the property change event FROM the viewport where the
1570 // original alignment was altered
1571 AlignmentI al = null;
1572 if (command instanceof EditCommand)
1574 EditCommand editCommand = (EditCommand) command;
1575 al = editCommand.getAlignment();
1576 Vector comps = (Vector) PaintRefresher.components.get(viewport
1577 .getSequenceSetId());
1579 for (int i = 0; i < comps.size(); i++)
1581 if (comps.elementAt(i) instanceof AlignmentPanel)
1583 if (al == ((AlignmentPanel) comps.elementAt(i)).av.getAlignment())
1585 originalSource = ((AlignmentPanel) comps.elementAt(i)).av;
1592 if (originalSource == null)
1594 // The original view is closed, we must validate
1595 // the current view against the closed view first
1598 PaintRefresher.validateSequences(al, viewport.getAlignment());
1601 originalSource = viewport;
1604 return originalSource;
1613 public void moveSelectedSequences(boolean up)
1615 SequenceGroup sg = viewport.getSelectionGroup();
1621 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1622 viewport.getHiddenRepSequences(), up);
1623 alignPanel.paintAlignment(true);
1626 synchronized void slideSequences(boolean right, int size)
1628 List<SequenceI> sg = new Vector();
1629 if (viewport.cursorMode)
1631 sg.add(viewport.getAlignment().getSequenceAt(
1632 alignPanel.seqPanel.seqCanvas.cursorY));
1634 else if (viewport.getSelectionGroup() != null
1635 && viewport.getSelectionGroup().getSize() != viewport
1636 .getAlignment().getHeight())
1638 sg = viewport.getSelectionGroup().getSequences(
1639 viewport.getHiddenRepSequences());
1647 Vector invertGroup = new Vector();
1649 for (int i = 0; i < viewport.getAlignment().getHeight(); i++)
1651 if (!sg.contains(viewport.getAlignment().getSequenceAt(i)))
1653 invertGroup.add(viewport.getAlignment().getSequenceAt(i));
1657 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1659 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1660 for (int i = 0; i < invertGroup.size(); i++)
1662 seqs2[i] = (SequenceI) invertGroup.elementAt(i);
1665 SlideSequencesCommand ssc;
1668 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1669 size, viewport.getGapCharacter());
1673 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1674 size, viewport.getGapCharacter());
1677 int groupAdjustment = 0;
1678 if (ssc.getGapsInsertedBegin() && right)
1680 if (viewport.cursorMode)
1682 alignPanel.seqPanel.moveCursor(size, 0);
1686 groupAdjustment = size;
1689 else if (!ssc.getGapsInsertedBegin() && !right)
1691 if (viewport.cursorMode)
1693 alignPanel.seqPanel.moveCursor(-size, 0);
1697 groupAdjustment = -size;
1701 if (groupAdjustment != 0)
1703 viewport.getSelectionGroup().setStartRes(
1704 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1705 viewport.getSelectionGroup().setEndRes(
1706 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1709 boolean appendHistoryItem = false;
1710 if (viewport.historyList != null && viewport.historyList.size() > 0
1711 && viewport.historyList.peek() instanceof SlideSequencesCommand)
1713 appendHistoryItem = ssc
1714 .appendSlideCommand((SlideSequencesCommand) viewport.historyList
1718 if (!appendHistoryItem)
1720 addHistoryItem(ssc);
1733 protected void copy_actionPerformed(ActionEvent e)
1736 if (viewport.getSelectionGroup() == null)
1740 // TODO: preserve the ordering of displayed alignment annotation in any
1741 // internal paste (particularly sequence associated annotation)
1742 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1743 String[] omitHidden = null;
1745 if (viewport.hasHiddenColumns())
1747 omitHidden = viewport.getViewAsString(true);
1750 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1753 StringSelection ss = new StringSelection(output);
1757 jalview.gui.Desktop.internalCopy = true;
1758 // Its really worth setting the clipboard contents
1759 // to empty before setting the large StringSelection!!
1760 Toolkit.getDefaultToolkit().getSystemClipboard()
1761 .setContents(new StringSelection(""), null);
1763 Toolkit.getDefaultToolkit().getSystemClipboard()
1764 .setContents(ss, Desktop.instance);
1765 } catch (OutOfMemoryError er)
1767 new OOMWarning("copying region", er);
1771 Vector hiddenColumns = null;
1772 if (viewport.hasHiddenColumns())
1774 hiddenColumns = new Vector();
1775 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1776 .getSelectionGroup().getEndRes();
1777 for (int i = 0; i < viewport.getColumnSelection().getHiddenColumns()
1780 int[] region = (int[]) viewport.getColumnSelection()
1781 .getHiddenColumns().elementAt(i);
1782 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1784 hiddenColumns.addElement(new int[]
1785 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1790 Desktop.jalviewClipboard = new Object[]
1791 { seqs, viewport.getAlignment().getDataset(), hiddenColumns };
1792 statusBar.setText(MessageManager.formatMessage(
1793 "label.copied_sequences_to_clipboard", new String[]
1794 { Integer.valueOf(seqs.length).toString() }));
1804 protected void pasteNew_actionPerformed(ActionEvent e)
1816 protected void pasteThis_actionPerformed(ActionEvent e)
1822 * Paste contents of Jalview clipboard
1824 * @param newAlignment
1825 * true to paste to a new alignment, otherwise add to this.
1827 void paste(boolean newAlignment)
1829 boolean externalPaste = true;
1832 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1833 Transferable contents = c.getContents(this);
1835 if (contents == null)
1843 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1844 if (str.length() < 1)
1849 format = new IdentifyFile().Identify(str, "Paste");
1851 } catch (OutOfMemoryError er)
1853 new OOMWarning("Out of memory pasting sequences!!", er);
1857 SequenceI[] sequences;
1858 boolean annotationAdded = false;
1859 AlignmentI alignment = null;
1861 if (Desktop.jalviewClipboard != null)
1863 // The clipboard was filled from within Jalview, we must use the
1865 // And dataset from the copied alignment
1866 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1867 // be doubly sure that we create *new* sequence objects.
1868 sequences = new SequenceI[newseq.length];
1869 for (int i = 0; i < newseq.length; i++)
1871 sequences[i] = new Sequence(newseq[i]);
1873 alignment = new Alignment(sequences);
1874 externalPaste = false;
1878 // parse the clipboard as an alignment.
1879 alignment = new FormatAdapter().readFile(str, "Paste", format);
1880 sequences = alignment.getSequencesArray();
1884 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1890 if (Desktop.jalviewClipboard != null)
1892 // dataset is inherited
1893 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1897 // new dataset is constructed
1898 alignment.setDataset(null);
1900 alwidth = alignment.getWidth() + 1;
1904 AlignmentI pastedal = alignment; // preserve pasted alignment object
1905 // Add pasted sequences and dataset into existing alignment.
1906 alignment = viewport.getAlignment();
1907 alwidth = alignment.getWidth() + 1;
1908 // decide if we need to import sequences from an existing dataset
1909 boolean importDs = Desktop.jalviewClipboard != null
1910 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1911 // importDs==true instructs us to copy over new dataset sequences from
1912 // an existing alignment
1913 Vector newDs = (importDs) ? new Vector() : null; // used to create
1914 // minimum dataset set
1916 for (int i = 0; i < sequences.length; i++)
1920 newDs.addElement(null);
1922 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
1924 if (importDs && ds != null)
1926 if (!newDs.contains(ds))
1928 newDs.setElementAt(ds, i);
1929 ds = new Sequence(ds);
1930 // update with new dataset sequence
1931 sequences[i].setDatasetSequence(ds);
1935 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
1940 // copy and derive new dataset sequence
1941 sequences[i] = sequences[i].deriveSequence();
1942 alignment.getDataset().addSequence(
1943 sequences[i].getDatasetSequence());
1944 // TODO: avoid creation of duplicate dataset sequences with a
1945 // 'contains' method using SequenceI.equals()/SequenceI.contains()
1947 alignment.addSequence(sequences[i]); // merges dataset
1951 newDs.clear(); // tidy up
1953 if (alignment.getAlignmentAnnotation() != null)
1955 for (AlignmentAnnotation alan : alignment
1956 .getAlignmentAnnotation())
1958 if (alan.graphGroup > fgroup)
1960 fgroup = alan.graphGroup;
1964 if (pastedal.getAlignmentAnnotation() != null)
1966 // Add any annotation attached to alignment.
1967 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
1968 for (int i = 0; i < alann.length; i++)
1970 annotationAdded = true;
1971 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
1973 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
1974 if (newann.graphGroup > -1)
1976 if (newGraphGroups.size() <= newann.graphGroup
1977 || newGraphGroups.get(newann.graphGroup) == null)
1979 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
1981 newGraphGroups.add(q, null);
1983 newGraphGroups.set(newann.graphGroup, new Integer(
1986 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
1990 newann.padAnnotation(alwidth);
1991 alignment.addAnnotation(newann);
2001 addHistoryItem(new EditCommand(
2002 MessageManager.getString("label.add_sequences"),
2004 sequences, 0, alignment.getWidth(), alignment));
2006 // Add any annotations attached to sequences
2007 for (int i = 0; i < sequences.length; i++)
2009 if (sequences[i].getAnnotation() != null)
2011 AlignmentAnnotation newann;
2012 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2014 annotationAdded = true;
2015 newann = sequences[i].getAnnotation()[a];
2016 newann.adjustForAlignment();
2017 newann.padAnnotation(alwidth);
2018 if (newann.graphGroup > -1)
2020 if (newann.graphGroup > -1)
2022 if (newGraphGroups.size() <= newann.graphGroup
2023 || newGraphGroups.get(newann.graphGroup) == null)
2025 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2027 newGraphGroups.add(q, null);
2029 newGraphGroups.set(newann.graphGroup, new Integer(
2032 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2036 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2041 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2048 // propagate alignment changed.
2049 viewport.setEndSeq(alignment.getHeight());
2050 if (annotationAdded)
2052 // Duplicate sequence annotation in all views.
2053 AlignmentI[] alview = this.getViewAlignments();
2054 for (int i = 0; i < sequences.length; i++)
2056 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2061 for (int avnum = 0; avnum < alview.length; avnum++)
2063 if (alview[avnum] != alignment)
2065 // duplicate in a view other than the one with input focus
2066 int avwidth = alview[avnum].getWidth() + 1;
2067 // this relies on sann being preserved after we
2068 // modify the sequence's annotation array for each duplication
2069 for (int a = 0; a < sann.length; a++)
2071 AlignmentAnnotation newann = new AlignmentAnnotation(
2073 sequences[i].addAlignmentAnnotation(newann);
2074 newann.padAnnotation(avwidth);
2075 alview[avnum].addAnnotation(newann); // annotation was
2076 // duplicated earlier
2077 // TODO JAL-1145 graphGroups are not updated for sequence
2078 // annotation added to several views. This may cause
2080 alview[avnum].setAnnotationIndex(newann, a);
2085 buildSortByAnnotationScoresMenu();
2087 viewport.firePropertyChange("alignment", null,
2088 alignment.getSequences());
2089 if (alignPanels != null)
2091 for (AlignmentPanel ap : ((Vector<AlignmentPanel>) alignPanels))
2093 ap.validateAnnotationDimensions(false);
2098 alignPanel.validateAnnotationDimensions(false);
2104 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2106 String newtitle = new String("Copied sequences");
2108 if (Desktop.jalviewClipboard != null
2109 && Desktop.jalviewClipboard[2] != null)
2111 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2112 for (int i = 0; i < hc.size(); i++)
2114 int[] region = (int[]) hc.elementAt(i);
2115 af.viewport.hideColumns(region[0], region[1]);
2119 // >>>This is a fix for the moment, until a better solution is
2121 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
2123 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
2125 // TODO: maintain provenance of an alignment, rather than just make the
2126 // title a concatenation of operations.
2129 if (title.startsWith("Copied sequences"))
2135 newtitle = newtitle.concat("- from " + title);
2140 newtitle = new String("Pasted sequences");
2143 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2148 } catch (Exception ex)
2150 ex.printStackTrace();
2151 System.out.println("Exception whilst pasting: " + ex);
2152 // could be anything being pasted in here
2158 protected void expand_newalign(ActionEvent e)
2162 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2163 .getAlignment(), -1);
2164 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2166 String newtitle = new String("Flanking alignment");
2168 if (Desktop.jalviewClipboard != null
2169 && Desktop.jalviewClipboard[2] != null)
2171 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2172 for (int i = 0; i < hc.size(); i++)
2174 int[] region = (int[]) hc.elementAt(i);
2175 af.viewport.hideColumns(region[0], region[1]);
2179 // >>>This is a fix for the moment, until a better solution is
2181 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
2183 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
2185 // TODO: maintain provenance of an alignment, rather than just make the
2186 // title a concatenation of operations.
2188 if (title.startsWith("Copied sequences"))
2194 newtitle = newtitle.concat("- from " + title);
2198 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2200 } catch (Exception ex)
2202 ex.printStackTrace();
2203 System.out.println("Exception whilst pasting: " + ex);
2204 // could be anything being pasted in here
2205 } catch (OutOfMemoryError oom)
2207 new OOMWarning("Viewing flanking region of alignment", oom);
2218 protected void cut_actionPerformed(ActionEvent e)
2220 copy_actionPerformed(null);
2221 delete_actionPerformed(null);
2231 protected void delete_actionPerformed(ActionEvent evt)
2234 SequenceGroup sg = viewport.getSelectionGroup();
2240 List<SequenceI> seqs = new ArrayList<SequenceI>(sg.getSize());
2242 for (int i = 0; i < sg.getSize(); i++)
2244 seq = sg.getSequenceAt(i);
2248 // If the cut affects all sequences, warn, remove highlighted columns
2249 if (sg.getSize() == viewport.getAlignment().getHeight())
2251 int confirm = JOptionPane.showConfirmDialog(this,
2252 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2253 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2254 JOptionPane.OK_CANCEL_OPTION);
2256 if (confirm == JOptionPane.CANCEL_OPTION
2257 || confirm == JOptionPane.CLOSED_OPTION)
2261 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2262 sg.getEndRes() + 1);
2265 SequenceI[] cut = new SequenceI[seqs.size()];
2266 for (int i = 0; i < seqs.size(); i++)
2268 cut[i] = seqs.get(i);
2272 * //ADD HISTORY ITEM
2274 addHistoryItem(new EditCommand(
2275 MessageManager.getString("label.cut_sequences"), Action.CUT,
2276 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2277 viewport.getAlignment()));
2279 viewport.setSelectionGroup(null);
2280 viewport.sendSelection();
2281 viewport.getAlignment().deleteGroup(sg);
2283 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2285 if (viewport.getAlignment().getHeight() < 1)
2289 this.setClosed(true);
2290 } catch (Exception ex)
2303 protected void deleteGroups_actionPerformed(ActionEvent e)
2305 if (avc.deleteGroups())
2307 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2308 alignPanel.updateAnnotation();
2309 alignPanel.paintAlignment(true);
2320 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2322 SequenceGroup sg = new SequenceGroup();
2324 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2326 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2329 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2330 viewport.setSelectionGroup(sg);
2331 viewport.sendSelection();
2332 alignPanel.paintAlignment(true);
2333 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2343 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2345 if (viewport.cursorMode)
2347 alignPanel.seqPanel.keyboardNo1 = null;
2348 alignPanel.seqPanel.keyboardNo2 = null;
2350 viewport.setSelectionGroup(null);
2351 viewport.getColumnSelection().clear();
2352 viewport.setSelectionGroup(null);
2353 alignPanel.seqPanel.seqCanvas.highlightSearchResults(null);
2354 alignPanel.idPanel.idCanvas.searchResults = null;
2355 alignPanel.paintAlignment(true);
2356 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2357 viewport.sendSelection();
2367 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2369 SequenceGroup sg = viewport.getSelectionGroup();
2373 selectAllSequenceMenuItem_actionPerformed(null);
2378 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2380 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2383 alignPanel.paintAlignment(true);
2384 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2385 viewport.sendSelection();
2389 public void invertColSel_actionPerformed(ActionEvent e)
2391 viewport.invertColumnSelection();
2392 alignPanel.paintAlignment(true);
2393 viewport.sendSelection();
2403 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2405 trimAlignment(true);
2415 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2417 trimAlignment(false);
2420 void trimAlignment(boolean trimLeft)
2422 ColumnSelection colSel = viewport.getColumnSelection();
2425 if (colSel.size() > 0)
2429 column = colSel.getMin();
2433 column = colSel.getMax();
2437 if (viewport.getSelectionGroup() != null)
2439 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2440 viewport.getHiddenRepSequences());
2444 seqs = viewport.getAlignment().getSequencesArray();
2447 TrimRegionCommand trimRegion;
2450 trimRegion = new TrimRegionCommand("Remove Left",
2451 TrimRegionCommand.TRIM_LEFT, seqs, column,
2452 viewport.getAlignment(), viewport.getColumnSelection(),
2453 viewport.getSelectionGroup());
2454 viewport.setStartRes(0);
2458 trimRegion = new TrimRegionCommand("Remove Right",
2459 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2460 viewport.getAlignment(), viewport.getColumnSelection(),
2461 viewport.getSelectionGroup());
2464 statusBar.setText(MessageManager.formatMessage(
2465 "label.removed_columns", new String[]
2466 { Integer.valueOf(trimRegion.getSize()).toString() }));
2468 addHistoryItem(trimRegion);
2470 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2472 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2473 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2475 viewport.getAlignment().deleteGroup(sg);
2479 viewport.firePropertyChange("alignment", null, viewport
2480 .getAlignment().getSequences());
2491 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2493 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2496 if (viewport.getSelectionGroup() != null)
2498 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2499 viewport.getHiddenRepSequences());
2500 start = viewport.getSelectionGroup().getStartRes();
2501 end = viewport.getSelectionGroup().getEndRes();
2505 seqs = viewport.getAlignment().getSequencesArray();
2508 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2509 "Remove Gapped Columns", seqs, start, end,
2510 viewport.getAlignment());
2512 addHistoryItem(removeGapCols);
2514 statusBar.setText(MessageManager.formatMessage(
2515 "label.removed_empty_columns", new String[]
2516 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2518 // This is to maintain viewport position on first residue
2519 // of first sequence
2520 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2521 int startRes = seq.findPosition(viewport.startRes);
2522 // ShiftList shifts;
2523 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2524 // edit.alColumnChanges=shifts.getInverse();
2525 // if (viewport.hasHiddenColumns)
2526 // viewport.getColumnSelection().compensateForEdits(shifts);
2527 viewport.setStartRes(seq.findIndex(startRes) - 1);
2528 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2540 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2542 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2545 if (viewport.getSelectionGroup() != null)
2547 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2548 viewport.getHiddenRepSequences());
2549 start = viewport.getSelectionGroup().getStartRes();
2550 end = viewport.getSelectionGroup().getEndRes();
2554 seqs = viewport.getAlignment().getSequencesArray();
2557 // This is to maintain viewport position on first residue
2558 // of first sequence
2559 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2560 int startRes = seq.findPosition(viewport.startRes);
2562 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2563 viewport.getAlignment()));
2565 viewport.setStartRes(seq.findIndex(startRes) - 1);
2567 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2579 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2581 viewport.setPadGaps(padGapsMenuitem.isSelected());
2582 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2588 // if (justifySeqs>0)
2590 // alignment.justify(justifySeqs!=RIGHT_JUSTIFY);
2603 public void findMenuItem_actionPerformed(ActionEvent e)
2609 public void newView_actionPerformed(ActionEvent e)
2616 * @param copyAnnotation
2617 * if true then duplicate all annnotation, groups and settings
2618 * @return new alignment panel, already displayed.
2620 public AlignmentPanel newView(boolean copyAnnotation)
2622 return newView(null, copyAnnotation);
2628 * title of newly created view
2629 * @return new alignment panel, already displayed.
2631 public AlignmentPanel newView(String viewTitle)
2633 return newView(viewTitle, true);
2639 * title of newly created view
2640 * @param copyAnnotation
2641 * if true then duplicate all annnotation, groups and settings
2642 * @return new alignment panel, already displayed.
2644 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2646 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2648 if (!copyAnnotation)
2650 // just remove all the current annotation except for the automatic stuff
2651 newap.av.getAlignment().deleteAllGroups();
2652 for (AlignmentAnnotation alan : newap.av.getAlignment()
2653 .getAlignmentAnnotation())
2655 if (!alan.autoCalculated)
2657 newap.av.getAlignment().deleteAnnotation(alan);
2663 newap.av.gatherViewsHere = false;
2665 if (viewport.viewName == null)
2667 viewport.viewName = "Original";
2670 newap.av.historyList = viewport.historyList;
2671 newap.av.redoList = viewport.redoList;
2673 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2674 // make sure the new view has a unique name - this is essential for Jalview
2676 boolean addFirstIndex = false;
2677 if (viewTitle == null || viewTitle.trim().length() == 0)
2679 viewTitle = MessageManager.getString("action.view");
2680 addFirstIndex = true;
2684 index = 1;// we count from 1 if given a specific name
2686 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2687 Vector comps = (Vector) PaintRefresher.components.get(viewport
2688 .getSequenceSetId());
2689 Vector existingNames = new Vector();
2690 for (int i = 0; i < comps.size(); i++)
2692 if (comps.elementAt(i) instanceof AlignmentPanel)
2694 AlignmentPanel ap = (AlignmentPanel) comps.elementAt(i);
2695 if (!existingNames.contains(ap.av.viewName))
2697 existingNames.addElement(ap.av.viewName);
2702 while (existingNames.contains(newViewName))
2704 newViewName = viewTitle + " " + (++index);
2707 newap.av.viewName = newViewName;
2709 addAlignmentPanel(newap, true);
2710 newap.alignmentChanged();
2712 if (alignPanels.size() == 2)
2714 viewport.gatherViewsHere = true;
2716 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2721 public void expandViews_actionPerformed(ActionEvent e)
2723 Desktop.instance.explodeViews(this);
2727 public void gatherViews_actionPerformed(ActionEvent e)
2729 Desktop.instance.gatherViews(this);
2739 public void font_actionPerformed(ActionEvent e)
2741 new FontChooser(alignPanel);
2751 protected void seqLimit_actionPerformed(ActionEvent e)
2753 viewport.setShowJVSuffix(seqLimits.isSelected());
2755 alignPanel.idPanel.idCanvas.setPreferredSize(alignPanel
2756 .calculateIdWidth());
2757 alignPanel.paintAlignment(true);
2761 public void idRightAlign_actionPerformed(ActionEvent e)
2763 viewport.rightAlignIds = idRightAlign.isSelected();
2764 alignPanel.paintAlignment(true);
2768 public void centreColumnLabels_actionPerformed(ActionEvent e)
2770 viewport.centreColumnLabels = centreColumnLabelsMenuItem.getState();
2771 alignPanel.paintAlignment(true);
2777 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2780 protected void followHighlight_actionPerformed()
2782 if (viewport.followHighlight = this.followHighlightMenuItem.getState())
2784 alignPanel.scrollToPosition(
2785 alignPanel.seqPanel.seqCanvas.searchResults, false);
2796 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2798 viewport.setColourText(colourTextMenuItem.isSelected());
2799 alignPanel.paintAlignment(true);
2809 public void wrapMenuItem_actionPerformed(ActionEvent e)
2811 scaleAbove.setVisible(wrapMenuItem.isSelected());
2812 scaleLeft.setVisible(wrapMenuItem.isSelected());
2813 scaleRight.setVisible(wrapMenuItem.isSelected());
2814 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2815 alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2819 public void showAllSeqs_actionPerformed(ActionEvent e)
2821 viewport.showAllHiddenSeqs();
2825 public void showAllColumns_actionPerformed(ActionEvent e)
2827 viewport.showAllHiddenColumns();
2832 public void hideSelSequences_actionPerformed(ActionEvent e)
2834 viewport.hideAllSelectedSeqs();
2835 alignPanel.paintAlignment(true);
2839 * called by key handler and the hide all/show all menu items
2844 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2847 boolean hide = false;
2848 SequenceGroup sg = viewport.getSelectionGroup();
2849 if (!toggleSeqs && !toggleCols)
2851 // Hide everything by the current selection - this is a hack - we do the
2852 // invert and then hide
2853 // first check that there will be visible columns after the invert.
2854 if ((viewport.getColumnSelection() != null
2855 && viewport.getColumnSelection().getSelected() != null && viewport
2856 .getColumnSelection().getSelected().size() > 0)
2857 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2860 // now invert the sequence set, if required - empty selection implies
2861 // that no hiding is required.
2864 invertSequenceMenuItem_actionPerformed(null);
2865 sg = viewport.getSelectionGroup();
2869 viewport.expandColSelection(sg, true);
2870 // finally invert the column selection and get the new sequence
2872 invertColSel_actionPerformed(null);
2879 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
2881 hideSelSequences_actionPerformed(null);
2884 else if (!(toggleCols && viewport.getColumnSelection().getSelected()
2887 showAllSeqs_actionPerformed(null);
2893 if (viewport.getColumnSelection().getSelected().size() > 0)
2895 hideSelColumns_actionPerformed(null);
2898 viewport.setSelectionGroup(sg);
2903 showAllColumns_actionPerformed(null);
2912 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
2913 * event.ActionEvent)
2916 public void hideAllButSelection_actionPerformed(ActionEvent e)
2918 toggleHiddenRegions(false, false);
2925 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
2929 public void hideAllSelection_actionPerformed(ActionEvent e)
2931 SequenceGroup sg = viewport.getSelectionGroup();
2932 viewport.expandColSelection(sg, false);
2933 viewport.hideAllSelectedSeqs();
2934 viewport.hideSelectedColumns();
2935 alignPanel.paintAlignment(true);
2942 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
2946 public void showAllhidden_actionPerformed(ActionEvent e)
2948 viewport.showAllHiddenColumns();
2949 viewport.showAllHiddenSeqs();
2950 alignPanel.paintAlignment(true);
2954 public void hideSelColumns_actionPerformed(ActionEvent e)
2956 viewport.hideSelectedColumns();
2957 alignPanel.paintAlignment(true);
2961 public void hiddenMarkers_actionPerformed(ActionEvent e)
2963 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
2974 protected void scaleAbove_actionPerformed(ActionEvent e)
2976 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
2977 alignPanel.paintAlignment(true);
2987 protected void scaleLeft_actionPerformed(ActionEvent e)
2989 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
2990 alignPanel.paintAlignment(true);
3000 protected void scaleRight_actionPerformed(ActionEvent e)
3002 viewport.setScaleRightWrapped(scaleRight.isSelected());
3003 alignPanel.paintAlignment(true);
3013 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3015 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3016 alignPanel.paintAlignment(true);
3026 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3028 viewport.setShowText(viewTextMenuItem.isSelected());
3029 alignPanel.paintAlignment(true);
3039 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3041 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3042 alignPanel.paintAlignment(true);
3045 public FeatureSettings featureSettings;
3048 public void featureSettings_actionPerformed(ActionEvent e)
3050 if (featureSettings != null)
3052 featureSettings.close();
3053 featureSettings = null;
3055 if (!showSeqFeatures.isSelected())
3057 // make sure features are actually displayed
3058 showSeqFeatures.setSelected(true);
3059 showSeqFeatures_actionPerformed(null);
3061 featureSettings = new FeatureSettings(this);
3065 * Set or clear 'Show Sequence Features'
3071 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3073 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3074 alignPanel.paintAlignment(true);
3075 if (alignPanel.getOverviewPanel() != null)
3077 alignPanel.getOverviewPanel().updateOverviewImage();
3082 * Set or clear 'Show Sequence Features'
3088 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
3090 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
3092 if (viewport.getShowSequenceFeaturesHeight())
3094 // ensure we're actually displaying features
3095 viewport.setShowSequenceFeatures(true);
3096 showSeqFeatures.setSelected(true);
3098 alignPanel.paintAlignment(true);
3099 if (alignPanel.getOverviewPanel() != null)
3101 alignPanel.getOverviewPanel().updateOverviewImage();
3106 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3107 * the annotations panel as a whole.
3109 * The options to show/hide all annotations should be enabled when the panel
3110 * is shown, and disabled when the panel is hidden.
3115 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3117 final boolean setVisible = annotationPanelMenuItem.isSelected();
3118 viewport.setShowAnnotation(setVisible);
3119 alignPanel.setAnnotationVisible(setVisible);
3120 this.showAllSeqAnnotations.setEnabled(setVisible);
3121 this.hideAllSeqAnnotations.setEnabled(setVisible);
3122 this.showAllAlAnnotations.setEnabled(setVisible);
3123 this.hideAllAlAnnotations.setEnabled(setVisible);
3127 public void alignmentProperties()
3129 JEditorPane editPane = new JEditorPane("text/html", "");
3130 editPane.setEditable(false);
3131 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3133 editPane.setText(MessageManager.formatMessage("label.html_content",
3135 { contents.toString() }));
3136 JInternalFrame frame = new JInternalFrame();
3137 frame.getContentPane().add(new JScrollPane(editPane));
3139 Desktop.instance.addInternalFrame(frame, MessageManager.formatMessage(
3140 "label.alignment_properties", new String[]
3141 { getTitle() }), 500, 400);
3151 public void overviewMenuItem_actionPerformed(ActionEvent e)
3153 if (alignPanel.overviewPanel != null)
3158 JInternalFrame frame = new JInternalFrame();
3159 OverviewPanel overview = new OverviewPanel(alignPanel);
3160 frame.setContentPane(overview);
3161 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3162 "label.overview_params", new String[]
3163 { this.getTitle() }), frame.getWidth(), frame.getHeight());
3165 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3166 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3169 public void internalFrameClosed(
3170 javax.swing.event.InternalFrameEvent evt)
3172 alignPanel.setOverviewPanel(null);
3176 alignPanel.setOverviewPanel(overview);
3180 public void textColour_actionPerformed(ActionEvent e)
3182 new TextColourChooser().chooseColour(alignPanel, null);
3192 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3204 public void clustalColour_actionPerformed(ActionEvent e)
3206 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3207 viewport.getHiddenRepSequences()));
3217 public void zappoColour_actionPerformed(ActionEvent e)
3219 changeColour(new ZappoColourScheme());
3229 public void taylorColour_actionPerformed(ActionEvent e)
3231 changeColour(new TaylorColourScheme());
3241 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3243 changeColour(new HydrophobicColourScheme());
3253 public void helixColour_actionPerformed(ActionEvent e)
3255 changeColour(new HelixColourScheme());
3265 public void strandColour_actionPerformed(ActionEvent e)
3267 changeColour(new StrandColourScheme());
3277 public void turnColour_actionPerformed(ActionEvent e)
3279 changeColour(new TurnColourScheme());
3289 public void buriedColour_actionPerformed(ActionEvent e)
3291 changeColour(new BuriedColourScheme());
3301 public void nucleotideColour_actionPerformed(ActionEvent e)
3303 changeColour(new NucleotideColourScheme());
3307 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3309 changeColour(new PurinePyrimidineColourScheme());
3313 * public void covariationColour_actionPerformed(ActionEvent e) {
3315 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3319 public void annotationColour_actionPerformed(ActionEvent e)
3321 new AnnotationColourChooser(viewport, alignPanel);
3325 public void rnahelicesColour_actionPerformed(ActionEvent e)
3327 new RNAHelicesColourChooser(viewport, alignPanel);
3337 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3339 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3348 public void changeColour(ColourSchemeI cs)
3350 // TODO: compare with applet and pull up to model method
3355 if (viewport.getAbovePIDThreshold())
3357 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3359 cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3363 cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3366 if (viewport.getConservationSelected())
3369 Alignment al = (Alignment) viewport.getAlignment();
3370 Conservation c = new Conservation("All",
3371 ResidueProperties.propHash, 3, al.getSequences(), 0,
3375 c.verdict(false, viewport.getConsPercGaps());
3377 cs.setConservation(c);
3379 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3384 cs.setConservation(null);
3387 cs.setConsensus(viewport.getSequenceConsensusHash());
3390 viewport.setGlobalColourScheme(cs);
3392 if (viewport.getColourAppliesToAllGroups())
3395 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3403 if (cs instanceof ClustalxColourScheme)
3405 sg.cs = new ClustalxColourScheme(sg,
3406 viewport.getHiddenRepSequences());
3408 else if (cs instanceof UserColourScheme)
3410 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
3416 sg.cs = cs.getClass().newInstance();
3417 } catch (Exception ex)
3422 if (viewport.getAbovePIDThreshold()
3423 || cs instanceof PIDColourScheme
3424 || cs instanceof Blosum62ColourScheme)
3426 sg.cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3428 sg.cs.setConsensus(AAFrequency.calculate(
3429 sg.getSequences(viewport.getHiddenRepSequences()),
3430 sg.getStartRes(), sg.getEndRes() + 1));
3434 sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3437 if (viewport.getConservationSelected())
3439 Conservation c = new Conservation("Group",
3440 ResidueProperties.propHash, 3, sg.getSequences(viewport
3441 .getHiddenRepSequences()), sg.getStartRes(),
3442 sg.getEndRes() + 1);
3444 c.verdict(false, viewport.getConsPercGaps());
3445 sg.cs.setConservation(c);
3449 sg.cs.setConservation(null);
3454 if (alignPanel.getOverviewPanel() != null)
3456 alignPanel.getOverviewPanel().updateOverviewImage();
3459 alignPanel.paintAlignment(true);
3469 protected void modifyPID_actionPerformed(ActionEvent e)
3471 if (viewport.getAbovePIDThreshold()
3472 && viewport.getGlobalColourScheme() != null)
3474 SliderPanel.setPIDSliderSource(alignPanel,
3475 viewport.getGlobalColourScheme(), "Background");
3476 SliderPanel.showPIDSlider();
3487 protected void modifyConservation_actionPerformed(ActionEvent e)
3489 if (viewport.getConservationSelected()
3490 && viewport.getGlobalColourScheme() != null)
3492 SliderPanel.setConservationSlider(alignPanel,
3493 viewport.getGlobalColourScheme(), "Background");
3494 SliderPanel.showConservationSlider();
3505 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3507 viewport.setConservationSelected(conservationMenuItem.isSelected());
3509 viewport.setAbovePIDThreshold(false);
3510 abovePIDThreshold.setSelected(false);
3512 changeColour(viewport.getGlobalColourScheme());
3514 modifyConservation_actionPerformed(null);
3524 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3526 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3528 conservationMenuItem.setSelected(false);
3529 viewport.setConservationSelected(false);
3531 changeColour(viewport.getGlobalColourScheme());
3533 modifyPID_actionPerformed(null);
3543 public void userDefinedColour_actionPerformed(ActionEvent e)
3545 if (e.getActionCommand().equals(
3546 MessageManager.getString("action.user_defined")))
3548 new UserDefinedColours(alignPanel, null);
3552 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3553 .getUserColourSchemes().get(e.getActionCommand());
3559 public void updateUserColourMenu()
3562 Component[] menuItems = colourMenu.getMenuComponents();
3563 int i, iSize = menuItems.length;
3564 for (i = 0; i < iSize; i++)
3566 if (menuItems[i].getName() != null
3567 && menuItems[i].getName().equals("USER_DEFINED"))
3569 colourMenu.remove(menuItems[i]);
3573 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3575 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3576 .getUserColourSchemes().keys();
3578 while (userColours.hasMoreElements())
3580 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3581 userColours.nextElement().toString());
3582 radioItem.setName("USER_DEFINED");
3583 radioItem.addMouseListener(new MouseAdapter()
3586 public void mousePressed(MouseEvent evt)
3588 if (evt.isControlDown()
3589 || SwingUtilities.isRightMouseButton(evt))
3591 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3593 int option = JOptionPane.showInternalConfirmDialog(
3594 jalview.gui.Desktop.desktop,
3596 .getString("label.remove_from_default_list"),
3598 .getString("label.remove_user_defined_colour"),
3599 JOptionPane.YES_NO_OPTION);
3600 if (option == JOptionPane.YES_OPTION)
3602 jalview.gui.UserDefinedColours
3603 .removeColourFromDefaults(radioItem.getText());
3604 colourMenu.remove(radioItem);
3608 radioItem.addActionListener(new ActionListener()
3611 public void actionPerformed(ActionEvent evt)
3613 userDefinedColour_actionPerformed(evt);
3620 radioItem.addActionListener(new ActionListener()
3623 public void actionPerformed(ActionEvent evt)
3625 userDefinedColour_actionPerformed(evt);
3629 colourMenu.insert(radioItem, 15);
3630 colours.add(radioItem);
3642 public void PIDColour_actionPerformed(ActionEvent e)
3644 changeColour(new PIDColourScheme());
3654 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3656 changeColour(new Blosum62ColourScheme());
3666 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3668 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3669 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3670 .getAlignment().getSequenceAt(0), null);
3671 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3672 viewport.getAlignment()));
3673 alignPanel.paintAlignment(true);
3683 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3685 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3686 AlignmentSorter.sortByID(viewport.getAlignment());
3687 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3688 viewport.getAlignment()));
3689 alignPanel.paintAlignment(true);
3699 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3701 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3702 AlignmentSorter.sortByLength(viewport.getAlignment());
3703 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3704 viewport.getAlignment()));
3705 alignPanel.paintAlignment(true);
3715 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3717 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3718 AlignmentSorter.sortByGroup(viewport.getAlignment());
3719 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3720 viewport.getAlignment()));
3722 alignPanel.paintAlignment(true);
3732 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3734 new RedundancyPanel(alignPanel, this);
3744 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3746 if ((viewport.getSelectionGroup() == null)
3747 || (viewport.getSelectionGroup().getSize() < 2))
3749 JOptionPane.showInternalMessageDialog(this, MessageManager
3750 .getString("label.you_must_select_least_two_sequences"),
3751 MessageManager.getString("label.invalid_selection"),
3752 JOptionPane.WARNING_MESSAGE);
3756 JInternalFrame frame = new JInternalFrame();
3757 frame.setContentPane(new PairwiseAlignPanel(viewport));
3758 Desktop.addInternalFrame(frame,
3759 MessageManager.getString("action.pairwise_alignment"), 600,
3771 public void PCAMenuItem_actionPerformed(ActionEvent e)
3773 if (((viewport.getSelectionGroup() != null)
3774 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3775 .getSelectionGroup().getSize() > 0))
3776 || (viewport.getAlignment().getHeight() < 4))
3779 .showInternalMessageDialog(
3782 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3784 .getString("label.sequence_selection_insufficient"),
3785 JOptionPane.WARNING_MESSAGE);
3790 new PCAPanel(alignPanel);
3794 public void autoCalculate_actionPerformed(ActionEvent e)
3796 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3797 if (viewport.autoCalculateConsensus)
3799 viewport.firePropertyChange("alignment", null, viewport
3800 .getAlignment().getSequences());
3805 public void sortByTreeOption_actionPerformed(ActionEvent e)
3807 viewport.sortByTree = sortByTree.isSelected();
3811 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3813 viewport.followSelection = listenToViewSelections.isSelected();
3823 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3825 NewTreePanel("AV", "PID", "Average distance tree using PID");
3835 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3837 NewTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3847 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3849 NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3859 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3861 NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3874 void NewTreePanel(String type, String pwType, String title)
3878 if (viewport.getSelectionGroup() != null
3879 && viewport.getSelectionGroup().getSize() > 0)
3881 if (viewport.getSelectionGroup().getSize() < 3)
3887 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3889 .getString("label.not_enough_sequences"),
3890 JOptionPane.WARNING_MESSAGE);
3894 SequenceGroup sg = viewport.getSelectionGroup();
3896 /* Decide if the selection is a column region */
3897 for (SequenceI _s : sg.getSequences())
3899 if (_s.getLength() < sg.getEndRes())
3905 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3907 .getString("label.sequences_selection_not_aligned"),
3908 JOptionPane.WARNING_MESSAGE);
3914 title = title + " on region";
3915 tp = new TreePanel(alignPanel, type, pwType);
3919 // are the visible sequences aligned?
3920 if (!viewport.getAlignment().isAligned(false))
3926 .getString("label.sequences_must_be_aligned_before_creating_tree"),
3928 .getString("label.sequences_not_aligned"),
3929 JOptionPane.WARNING_MESSAGE);
3934 if (viewport.getAlignment().getHeight() < 2)
3939 tp = new TreePanel(alignPanel, type, pwType);
3944 if (viewport.viewName != null)
3946 title += viewport.viewName + " of ";
3949 title += this.title;
3951 Desktop.addInternalFrame(tp, title, 600, 500);
3962 public void addSortByOrderMenuItem(String title,
3963 final AlignmentOrder order)
3965 final JMenuItem item = new JMenuItem(MessageManager.formatMessage("action.by_title_param", new String[]{title}));
3967 item.addActionListener(new java.awt.event.ActionListener()
3970 public void actionPerformed(ActionEvent e)
3972 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3974 // TODO: JBPNote - have to map order entries to curent SequenceI
3976 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3978 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
3981 alignPanel.paintAlignment(true);
3987 * Add a new sort by annotation score menu item
3990 * the menu to add the option to
3992 * the label used to retrieve scores for each sequence on the
3995 public void addSortByAnnotScoreMenuItem(JMenu sort,
3996 final String scoreLabel)
3998 final JMenuItem item = new JMenuItem(scoreLabel);
4000 item.addActionListener(new java.awt.event.ActionListener()
4003 public void actionPerformed(ActionEvent e)
4005 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4006 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4007 viewport.getAlignment());// ,viewport.getSelectionGroup());
4008 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4009 viewport.getAlignment()));
4010 alignPanel.paintAlignment(true);
4016 * last hash for alignment's annotation array - used to minimise cost of
4019 protected int _annotationScoreVectorHash;
4022 * search the alignment and rebuild the sort by annotation score submenu the
4023 * last alignment annotation vector hash is stored to minimize cost of
4024 * rebuilding in subsequence calls.
4028 public void buildSortByAnnotationScoresMenu()
4030 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4035 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4037 sortByAnnotScore.removeAll();
4038 // almost certainly a quicker way to do this - but we keep it simple
4039 Hashtable scoreSorts = new Hashtable();
4040 AlignmentAnnotation aann[];
4041 for (SequenceI sqa : viewport.getAlignment().getSequences())
4043 aann = sqa.getAnnotation();
4044 for (int i = 0; aann != null && i < aann.length; i++)
4046 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4048 scoreSorts.put(aann[i].label, aann[i].label);
4052 Enumeration labels = scoreSorts.keys();
4053 while (labels.hasMoreElements())
4055 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4056 (String) labels.nextElement());
4058 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4061 _annotationScoreVectorHash = viewport.getAlignment()
4062 .getAlignmentAnnotation().hashCode();
4067 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4068 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4069 * call. Listeners are added to remove the menu item when the treePanel is
4070 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4074 * Displayed tree window.
4076 * SortBy menu item title.
4079 public void buildTreeMenu()
4081 calculateTree.removeAll();
4082 // build the calculate menu
4084 for (final String type : new String[]
4087 String treecalcnm = MessageManager.getString("label.tree_calc_"
4088 + type.toLowerCase());
4089 for (final Object pwtype : ResidueProperties.scoreMatrices.keySet())
4091 JMenuItem tm = new JMenuItem();
4092 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4093 if (sm.isProtein() == !viewport.getAlignment().isNucleotide())
4095 String smn = MessageManager.getStringOrReturn(
4096 "label.score_model_", sm.getName());
4097 final String title = MessageManager.formatMessage(
4098 "label.treecalc_title", treecalcnm, smn);
4099 tm.setText(title);//
4100 tm.addActionListener(new java.awt.event.ActionListener()
4103 public void actionPerformed(ActionEvent e)
4105 NewTreePanel(type, (String) pwtype, title);
4108 calculateTree.add(tm);
4113 sortByTreeMenu.removeAll();
4115 Vector comps = (Vector) PaintRefresher.components.get(viewport
4116 .getSequenceSetId());
4117 Vector treePanels = new Vector();
4118 int i, iSize = comps.size();
4119 for (i = 0; i < iSize; i++)
4121 if (comps.elementAt(i) instanceof TreePanel)
4123 treePanels.add(comps.elementAt(i));
4127 iSize = treePanels.size();
4131 sortByTreeMenu.setVisible(false);
4135 sortByTreeMenu.setVisible(true);
4137 for (i = 0; i < treePanels.size(); i++)
4139 final TreePanel tp = (TreePanel) treePanels.elementAt(i);
4140 final JMenuItem item = new JMenuItem(tp.getTitle());
4141 final NJTree tree = ((TreePanel) treePanels.elementAt(i)).getTree();
4142 item.addActionListener(new java.awt.event.ActionListener()
4145 public void actionPerformed(ActionEvent e)
4147 tp.sortByTree_actionPerformed(null);
4148 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4153 sortByTreeMenu.add(item);
4157 public boolean sortBy(AlignmentOrder alorder, String undoname)
4159 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4160 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4161 if (undoname != null)
4163 addHistoryItem(new OrderCommand(undoname, oldOrder,
4164 viewport.getAlignment()));
4166 alignPanel.paintAlignment(true);
4171 * Work out whether the whole set of sequences or just the selected set will
4172 * be submitted for multiple alignment.
4175 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4177 // Now, check we have enough sequences
4178 AlignmentView msa = null;
4180 if ((viewport.getSelectionGroup() != null)
4181 && (viewport.getSelectionGroup().getSize() > 1))
4183 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4184 // some common interface!
4186 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4187 * SequenceI[sz = seqs.getSize(false)];
4189 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4190 * seqs.getSequenceAt(i); }
4192 msa = viewport.getAlignmentView(true);
4194 else if (viewport.getSelectionGroup() != null
4195 && viewport.getSelectionGroup().getSize() == 1)
4197 int option = JOptionPane
4200 "More than one sequece group selection is required for this Job, click \n'Cancel' to edit your selection or 'Ok' to submit the entire sequence.",
4201 "Invalid selection",
4202 JOptionPane.OK_CANCEL_OPTION);
4203 if (option == JOptionPane.OK_OPTION)
4205 msa = viewport.getAlignmentView(false);
4212 * Vector seqs = viewport.getAlignment().getSequences();
4214 * if (seqs.size() > 1) { msa = new SequenceI[seqs.size()];
4216 * for (int i = 0; i < seqs.size(); i++) { msa[i] = (SequenceI)
4217 * seqs.elementAt(i); } }
4219 msa = viewport.getAlignmentView(false);
4225 * Decides what is submitted to a secondary structure prediction service: the
4226 * first sequence in the alignment, or in the current selection, or, if the
4227 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4228 * region or the whole alignment. (where the first sequence in the set is the
4229 * one that the prediction will be for).
4231 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4233 AlignmentView seqs = null;
4235 if ((viewport.getSelectionGroup() != null)
4236 && (viewport.getSelectionGroup().getSize() > 0))
4238 seqs = viewport.getAlignmentView(true);
4242 seqs = viewport.getAlignmentView(false);
4244 // limit sequences - JBPNote in future - could spawn multiple prediction
4246 // TODO: viewport.getAlignment().isAligned is a global state - the local
4247 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4248 if (!viewport.getAlignment().isAligned(false))
4250 seqs.setSequences(new SeqCigar[]
4251 { seqs.getSequences()[0] });
4252 // TODO: if seqs.getSequences().length>1 then should really have warned
4266 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
4268 // Pick the tree file
4269 JalviewFileChooser chooser = new JalviewFileChooser(
4270 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4271 chooser.setFileView(new JalviewFileView());
4272 chooser.setDialogTitle(MessageManager
4273 .getString("label.select_newick_like_tree_file"));
4274 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4276 int value = chooser.showOpenDialog(null);
4278 if (value == JalviewFileChooser.APPROVE_OPTION)
4280 String choice = chooser.getSelectedFile().getPath();
4281 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4282 jalview.io.NewickFile fin = null;
4285 fin = new jalview.io.NewickFile(choice, "File");
4286 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4287 } catch (Exception ex)
4294 .getString("label.problem_reading_tree_file"),
4295 JOptionPane.WARNING_MESSAGE);
4296 ex.printStackTrace();
4298 if (fin != null && fin.hasWarningMessage())
4300 JOptionPane.showMessageDialog(Desktop.desktop, fin
4301 .getWarningMessage(), MessageManager
4302 .getString("label.possible_problem_with_tree_file"),
4303 JOptionPane.WARNING_MESSAGE);
4309 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4311 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4314 public TreePanel ShowNewickTree(NewickFile nf, String title)
4316 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4319 public TreePanel ShowNewickTree(NewickFile nf, String title,
4320 AlignmentView input)
4322 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4325 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4326 int h, int x, int y)
4328 return ShowNewickTree(nf, title, null, w, h, x, y);
4332 * Add a treeviewer for the tree extracted from a newick file object to the
4333 * current alignment view
4340 * Associated alignment input data (or null)
4349 * @return TreePanel handle
4351 public TreePanel ShowNewickTree(NewickFile nf, String title,
4352 AlignmentView input, int w, int h, int x, int y)
4354 TreePanel tp = null;
4360 if (nf.getTree() != null)
4362 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4368 tp.setLocation(x, y);
4371 Desktop.addInternalFrame(tp, title, w, h);
4373 } catch (Exception ex)
4375 ex.printStackTrace();
4381 private boolean buildingMenu = false;
4384 * Generates menu items and listener event actions for web service clients
4387 public void BuildWebServiceMenu()
4389 while (buildingMenu)
4393 System.err.println("Waiting for building menu to finish.");
4395 } catch (Exception e)
4400 final AlignFrame me = this;
4401 buildingMenu = true;
4402 new Thread(new Runnable()
4407 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4410 System.err.println("Building ws menu again "
4411 + Thread.currentThread());
4412 // TODO: add support for context dependent disabling of services based
4414 // alignment and current selection
4415 // TODO: add additional serviceHandle parameter to specify abstract
4417 // class independently of AbstractName
4418 // TODO: add in rediscovery GUI function to restart discoverer
4419 // TODO: group services by location as well as function and/or
4421 // object broker mechanism.
4422 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4423 final IProgressIndicator af = me;
4424 final JMenu msawsmenu = new JMenu("Alignment");
4425 final JMenu secstrmenu = new JMenu(
4426 "Secondary Structure Prediction");
4427 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4428 final JMenu analymenu = new JMenu("Analysis");
4429 final JMenu dismenu = new JMenu("Protein Disorder");
4430 // final JMenu msawsmenu = new
4431 // JMenu(MessageManager.getString("label.alignment"));
4432 // final JMenu secstrmenu = new
4433 // JMenu(MessageManager.getString("label.secondary_structure_prediction"));
4434 // final JMenu seqsrchmenu = new
4435 // JMenu(MessageManager.getString("label.sequence_database_search"));
4436 // final JMenu analymenu = new
4437 // JMenu(MessageManager.getString("label.analysis"));
4438 // final JMenu dismenu = new
4439 // JMenu(MessageManager.getString("label.protein_disorder"));
4440 // JAL-940 - only show secondary structure prediction services from
4441 // the legacy server
4442 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4444 Discoverer.services != null && (Discoverer.services.size() > 0))
4446 // TODO: refactor to allow list of AbstractName/Handler bindings to
4448 // stored or retrieved from elsewhere
4449 // No MSAWS used any more:
4450 // Vector msaws = null; // (Vector)
4451 // Discoverer.services.get("MsaWS");
4452 Vector secstrpr = (Vector) Discoverer.services
4454 if (secstrpr != null)
4456 // Add any secondary structure prediction services
4457 for (int i = 0, j = secstrpr.size(); i < j; i++)
4459 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4461 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4462 .getServiceClient(sh);
4463 int p = secstrmenu.getItemCount();
4464 impl.attachWSMenuEntry(secstrmenu, me);
4465 int q = secstrmenu.getItemCount();
4466 for (int litm = p; litm < q; litm++)
4468 legacyItems.add(secstrmenu.getItem(litm));
4474 // Add all submenus in the order they should appear on the web
4476 wsmenu.add(msawsmenu);
4477 wsmenu.add(secstrmenu);
4478 wsmenu.add(dismenu);
4479 wsmenu.add(analymenu);
4480 // No search services yet
4481 // wsmenu.add(seqsrchmenu);
4483 javax.swing.SwingUtilities.invokeLater(new Runnable()
4490 webService.removeAll();
4491 // first, add discovered services onto the webservices menu
4492 if (wsmenu.size() > 0)
4494 for (int i = 0, j = wsmenu.size(); i < j; i++)
4496 webService.add(wsmenu.get(i));
4501 webService.add(me.webServiceNoServices);
4503 // TODO: move into separate menu builder class.
4504 boolean new_sspred = false;
4505 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4507 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4508 if (jws2servs != null)
4510 if (jws2servs.hasServices())
4512 jws2servs.attachWSMenuEntry(webService, me);
4513 for (Jws2Instance sv : jws2servs.getServices())
4515 if (sv.description.toLowerCase().contains("jpred"))
4517 for (JMenuItem jmi : legacyItems)
4519 jmi.setVisible(false);
4525 if (jws2servs.isRunning())
4527 JMenuItem tm = new JMenuItem(
4528 "Still discovering JABA Services");
4529 tm.setEnabled(false);
4534 build_urlServiceMenu(me.webService);
4535 build_fetchdbmenu(webService);
4536 for (JMenu item : wsmenu)
4538 if (item.getItemCount() == 0)
4540 item.setEnabled(false);
4544 item.setEnabled(true);
4547 } catch (Exception e)
4550 .debug("Exception during web service menu building process.",
4556 } catch (Exception e)
4561 buildingMenu = false;
4568 * construct any groupURL type service menu entries.
4572 private void build_urlServiceMenu(JMenu webService)
4574 // TODO: remove this code when 2.7 is released
4575 // DEBUG - alignmentView
4577 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4578 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4580 * @Override public void actionPerformed(ActionEvent e) {
4581 * jalview.datamodel.AlignmentView
4582 * .testSelectionViews(af.viewport.getAlignment(),
4583 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4585 * }); webService.add(testAlView);
4587 // TODO: refactor to RestClient discoverer and merge menu entries for
4588 // rest-style services with other types of analysis/calculation service
4589 // SHmmr test client - still being implemented.
4590 // DEBUG - alignmentView
4592 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4595 client.attachWSMenuEntry(
4596 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4602 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
4603 * chooser = new JalviewFileChooser(jalview.bin.Cache.
4604 * getProperty("LAST_DIRECTORY"));
4606 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
4607 * to Vamsas file"); chooser.setToolTipText("Export");
4609 * int value = chooser.showSaveDialog(this);
4611 * if (value == JalviewFileChooser.APPROVE_OPTION) {
4612 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
4613 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
4614 * chooser.getSelectedFile().getAbsolutePath(), this); } }
4617 * prototype of an automatically enabled/disabled analysis function
4620 protected void setShowProductsEnabled()
4622 SequenceI[] selection = viewport.getSequenceSelection();
4623 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
4624 viewport.getAlignment().getDataset()))
4626 showProducts.setEnabled(true);
4631 showProducts.setEnabled(false);
4636 * search selection for sequence xRef products and build the show products
4641 * @return true if showProducts menu should be enabled.
4643 public boolean canShowProducts(SequenceI[] selection,
4644 boolean isRegionSelection, Alignment dataset)
4646 boolean showp = false;
4649 showProducts.removeAll();
4650 final boolean dna = viewport.getAlignment().isNucleotide();
4651 final Alignment ds = dataset;
4652 String[] ptypes = (selection == null || selection.length == 0) ? null
4653 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4655 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4656 // selection, dataset, true);
4657 final SequenceI[] sel = selection;
4658 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4661 final boolean isRegSel = isRegionSelection;
4662 final AlignFrame af = this;
4663 final String source = ptypes[t];
4664 JMenuItem xtype = new JMenuItem(ptypes[t]);
4665 xtype.addActionListener(new ActionListener()
4669 public void actionPerformed(ActionEvent e)
4671 // TODO: new thread for this call with vis-delay
4672 af.showProductsFor(af.viewport.getSequenceSelection(), ds,
4673 isRegSel, dna, source);
4677 showProducts.add(xtype);
4679 showProducts.setVisible(showp);
4680 showProducts.setEnabled(showp);
4681 } catch (Exception e)
4683 jalview.bin.Cache.log
4684 .warn("canTranslate threw an exception - please report to help@jalview.org",
4691 protected void showProductsFor(SequenceI[] sel, Alignment ds,
4692 boolean isRegSel, boolean dna, String source)
4694 final boolean fisRegSel = isRegSel;
4695 final boolean fdna = dna;
4696 final String fsrc = source;
4697 final AlignFrame ths = this;
4698 final SequenceI[] fsel = sel;
4699 Runnable foo = new Runnable()
4705 final long sttime = System.currentTimeMillis();
4706 ths.setProgressBar(MessageManager.formatMessage("status.searching_for_sequences_from", new String[]{fsrc}), sttime);
4709 Alignment ds = ths.getViewport().getAlignment().getDataset(); // update
4713 Alignment prods = CrossRef
4714 .findXrefSequences(fsel, fdna, fsrc, ds);
4717 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4718 for (int s = 0; s < sprods.length; s++)
4720 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4721 if (ds.getSequences() == null
4722 || !ds.getSequences().contains(
4723 sprods[s].getDatasetSequence()))
4725 ds.addSequence(sprods[s].getDatasetSequence());
4727 sprods[s].updatePDBIds();
4729 Alignment al = new Alignment(sprods);
4730 AlignedCodonFrame[] cf = prods.getCodonFrames();
4732 for (int s = 0; cf != null && s < cf.length; s++)
4734 al.addCodonFrame(cf[s]);
4737 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4739 String newtitle = "" + ((fdna) ? "Proteins " : "Nucleotides ")
4740 + " for " + ((fisRegSel) ? "selected region of " : "")
4742 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4747 System.err.println("No Sequences generated for xRef type "
4750 } catch (Exception e)
4752 jalview.bin.Cache.log.error(
4753 "Exception when finding crossreferences", e);
4754 } catch (OutOfMemoryError e)
4756 new OOMWarning("whilst fetching crossreferences", e);
4759 jalview.bin.Cache.log.error("Error when finding crossreferences",
4762 ths.setProgressBar(MessageManager.formatMessage("status.finished_searching_for_sequences_from", new String[]{fsrc}),
4767 Thread frunner = new Thread(foo);
4771 public boolean canShowTranslationProducts(SequenceI[] selection,
4772 AlignmentI alignment)
4777 return (jalview.analysis.Dna.canTranslate(selection,
4778 viewport.getViewAsVisibleContigs(true)));
4779 } catch (Exception e)
4781 jalview.bin.Cache.log
4782 .warn("canTranslate threw an exception - please report to help@jalview.org",
4789 public void showProducts_actionPerformed(ActionEvent e)
4791 // /////////////////////////////
4792 // Collect Data to be translated/transferred
4794 SequenceI[] selection = viewport.getSequenceSelection();
4795 AlignmentI al = null;
4798 al = jalview.analysis.Dna.CdnaTranslate(selection, viewport
4799 .getViewAsVisibleContigs(true), viewport.getGapCharacter(),
4800 viewport.getAlignment().getDataset());
4801 } catch (Exception ex)
4804 jalview.bin.Cache.log.debug("Exception during translation.", ex);
4812 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation"),
4813 MessageManager.getString("label.translation_failed"),
4814 JOptionPane.WARNING_MESSAGE);
4818 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4819 Desktop.addInternalFrame(af, MessageManager.formatMessage(
4820 "label.translation_of_params", new String[]
4821 { this.getTitle() }), DEFAULT_WIDTH, DEFAULT_HEIGHT);
4826 public void showTranslation_actionPerformed(ActionEvent e)
4828 // /////////////////////////////
4829 // Collect Data to be translated/transferred
4831 SequenceI[] selection = viewport.getSequenceSelection();
4832 String[] seqstring = viewport.getViewAsString(true);
4833 AlignmentI al = null;
4836 al = jalview.analysis.Dna.CdnaTranslate(selection, seqstring,
4837 viewport.getViewAsVisibleContigs(true), viewport
4838 .getGapCharacter(), viewport.getAlignment()
4839 .getAlignmentAnnotation(), viewport.getAlignment()
4840 .getWidth(), viewport.getAlignment().getDataset());
4841 } catch (Exception ex)
4844 jalview.bin.Cache.log.error(
4845 "Exception during translation. Please report this !", ex);
4850 .getString("label.error_when_translating_sequences_submit_bug_report"),
4852 .getString("label.implementation_error")
4854 .getString("translation_failed"),
4855 JOptionPane.ERROR_MESSAGE);
4864 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation"),
4865 MessageManager.getString("label.translation_failed"),
4866 JOptionPane.WARNING_MESSAGE);
4870 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4871 Desktop.addInternalFrame(af, MessageManager.formatMessage(
4872 "label.translation_of_params", new String[]
4873 { this.getTitle() }), DEFAULT_WIDTH, DEFAULT_HEIGHT);
4878 * Try to load a features file onto the alignment.
4881 * contents or path to retrieve file
4883 * access mode of file (see jalview.io.AlignFile)
4884 * @return true if features file was parsed corectly.
4886 public boolean parseFeaturesFile(String file, String type)
4888 boolean featuresFile = false;
4891 featuresFile = new FeaturesFile(file, type).parse(viewport
4892 .getAlignment().getDataset(), alignPanel.seqPanel.seqCanvas
4893 .getFeatureRenderer().featureColours, false,
4894 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4895 } catch (Exception ex)
4897 ex.printStackTrace();
4902 viewport.showSequenceFeatures = true;
4903 showSeqFeatures.setSelected(true);
4904 if (alignPanel.seqPanel.seqCanvas.fr != null)
4906 // update the min/max ranges where necessary
4907 alignPanel.seqPanel.seqCanvas.fr.findAllFeatures(true);
4909 if (featureSettings != null)
4911 featureSettings.setTableData();
4913 alignPanel.paintAlignment(true);
4916 return featuresFile;
4920 public void dragEnter(DropTargetDragEvent evt)
4925 public void dragExit(DropTargetEvent evt)
4930 public void dragOver(DropTargetDragEvent evt)
4935 public void dropActionChanged(DropTargetDragEvent evt)
4940 public void drop(DropTargetDropEvent evt)
4942 Transferable t = evt.getTransferable();
4943 java.util.List files = null;
4947 DataFlavor uriListFlavor = new DataFlavor(
4948 "text/uri-list;class=java.lang.String");
4949 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
4951 // Works on Windows and MacOSX
4952 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4953 files = (java.util.List) t
4954 .getTransferData(DataFlavor.javaFileListFlavor);
4956 else if (t.isDataFlavorSupported(uriListFlavor))
4958 // This is used by Unix drag system
4959 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4960 String data = (String) t.getTransferData(uriListFlavor);
4961 files = new java.util.ArrayList(1);
4962 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
4963 data, "\r\n"); st.hasMoreTokens();)
4965 String s = st.nextToken();
4966 if (s.startsWith("#"))
4968 // the line is a comment (as per the RFC 2483)
4972 java.net.URI uri = new java.net.URI(s);
4973 // check to see if we can handle this kind of URI
4974 if (uri.getScheme().toLowerCase().startsWith("http"))
4976 files.add(uri.toString());
4980 // otherwise preserve old behaviour: catch all for file objects
4981 java.io.File file = new java.io.File(uri);
4982 files.add(file.toString());
4986 } catch (Exception e)
4988 e.printStackTrace();
4994 // check to see if any of these files have names matching sequences in
4996 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4997 .getAlignment().getSequencesArray());
4999 * Object[] { String,SequenceI}
5001 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
5002 ArrayList<String> filesnotmatched = new ArrayList<String>();
5003 for (int i = 0; i < files.size(); i++)
5005 String file = files.get(i).toString();
5007 String protocol = FormatAdapter.checkProtocol(file);
5008 if (protocol == jalview.io.FormatAdapter.FILE)
5010 File fl = new File(file);
5011 pdbfn = fl.getName();
5013 else if (protocol == jalview.io.FormatAdapter.URL)
5015 URL url = new URL(file);
5016 pdbfn = url.getFile();
5018 if (pdbfn.length() > 0)
5020 // attempt to find a match in the alignment
5021 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5022 int l = 0, c = pdbfn.indexOf(".");
5023 while (mtch == null && c != -1)
5028 } while ((c = pdbfn.indexOf(".", l)) > l);
5031 pdbfn = pdbfn.substring(0, l);
5033 mtch = idm.findAllIdMatches(pdbfn);
5040 type = new IdentifyFile().Identify(file, protocol);
5041 } catch (Exception ex)
5047 if (type.equalsIgnoreCase("PDB"))
5049 filesmatched.add(new Object[]
5050 { file, protocol, mtch });
5055 // File wasn't named like one of the sequences or wasn't a PDB file.
5056 filesnotmatched.add(file);
5060 if (filesmatched.size() > 0)
5062 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
5068 "label.automatically_associate_pdb_files_with_sequences_same_name",
5075 .getString("label.automatically_associate_pdb_files_by_name"),
5076 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
5079 for (Object[] fm : filesmatched)
5081 // try and associate
5082 // TODO: may want to set a standard ID naming formalism for
5083 // associating PDB files which have no IDs.
5084 for (SequenceI toassoc : (SequenceI[]) fm[2])
5086 PDBEntry pe = new AssociatePdbFileWithSeq()
5087 .associatePdbWithSeq((String) fm[0],
5088 (String) fm[1], toassoc, false,
5092 System.err.println("Associated file : "
5093 + ((String) fm[0]) + " with "
5094 + toassoc.getDisplayId(true));
5098 alignPanel.paintAlignment(true);
5102 if (filesnotmatched.size() > 0)
5105 && (Cache.getDefault(
5106 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
5109 "<html>"+MessageManager
5111 "label.ignore_unmatched_dropped_files_info",
5116 .toString() })+"</html>",
5118 .getString("label.ignore_unmatched_dropped_files"),
5119 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
5123 for (String fn : filesnotmatched)
5125 loadJalviewDataFile(fn, null, null, null);
5129 } catch (Exception ex)
5131 ex.printStackTrace();
5137 * Attempt to load a "dropped" file or URL string: First by testing whether
5138 * it's and Annotation file, then a JNet file, and finally a features file. If
5139 * all are false then the user may have dropped an alignment file onto this
5143 * either a filename or a URL string.
5145 public void loadJalviewDataFile(String file, String protocol,
5146 String format, SequenceI assocSeq)
5150 if (protocol == null)
5152 protocol = jalview.io.FormatAdapter.checkProtocol(file);
5154 // if the file isn't identified, or not positively identified as some
5155 // other filetype (PFAM is default unidentified alignment file type) then
5156 // try to parse as annotation.
5157 boolean isAnnotation = (format == null || format
5158 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
5159 .readAnnotationFile(viewport.getAlignment(), file, protocol)
5164 // first see if its a T-COFFEE score file
5165 TCoffeeScoreFile tcf = null;
5168 tcf = new TCoffeeScoreFile(file, protocol);
5171 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5173 tcoffeeColour.setEnabled(true);
5174 tcoffeeColour.setSelected(true);
5175 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5176 isAnnotation = true;
5178 .setText(MessageManager
5179 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5183 // some problem - if no warning its probable that the ID matching
5184 // process didn't work
5188 tcf.getWarningMessage() == null ? MessageManager
5189 .getString("label.check_file_matches_sequence_ids_alignment")
5190 : tcf.getWarningMessage(),
5192 .getString("label.problem_reading_tcoffee_score_file"),
5193 JOptionPane.WARNING_MESSAGE);
5200 } catch (Exception x)
5203 .debug("Exception when processing data source as T-COFFEE score file",
5209 // try to see if its a JNet 'concise' style annotation file *before*
5211 // try to parse it as a features file
5214 format = new IdentifyFile().Identify(file, protocol);
5216 if (format.equalsIgnoreCase("JnetFile"))
5218 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5220 new JnetAnnotationMaker().add_annotation(predictions,
5221 viewport.getAlignment(), 0, false);
5222 isAnnotation = true;
5227 * if (format.equalsIgnoreCase("PDB")) {
5229 * String pdbfn = ""; // try to match up filename with sequence id
5230 * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
5231 * new File(file); pdbfn = fl.getName(); } else if (protocol ==
5232 * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
5233 * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
5234 * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5235 * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
5236 * // attempt to find a match in the alignment SequenceI mtch =
5237 * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
5238 * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
5239 * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
5240 * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
5241 * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
5242 * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
5243 * { System.err.println("Associated file : " + file + " with " +
5244 * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
5245 * TODO: maybe need to load as normal otherwise return; } }
5247 // try to parse it as a features file
5248 boolean isGroupsFile = parseFeaturesFile(file, protocol);
5249 // if it wasn't a features file then we just treat it as a general
5250 // alignment file to load into the current view.
5253 new FileLoader().LoadFile(viewport, file, protocol, format);
5257 alignPanel.paintAlignment(true);
5265 alignPanel.adjustAnnotationHeight();
5266 viewport.updateSequenceIdColours();
5267 buildSortByAnnotationScoresMenu();
5268 alignPanel.paintAlignment(true);
5270 } catch (Exception ex)
5272 ex.printStackTrace();
5273 } catch (OutOfMemoryError oom)
5278 } catch (Exception x)
5284 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5285 : "using " + protocol + " from " + file)
5287 + (format != null ? "(parsing as '" + format
5288 + "' file)" : ""), oom, Desktop.desktop);
5293 public void tabSelectionChanged(int index)
5297 alignPanel = (AlignmentPanel) alignPanels.elementAt(index);
5298 viewport = alignPanel.av;
5299 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5300 setMenusFromViewport(viewport);
5305 public void tabbedPane_mousePressed(MouseEvent e)
5307 if (SwingUtilities.isRightMouseButton(e))
5309 String reply = JOptionPane.showInternalInputDialog(this,
5310 MessageManager.getString("label.enter_view_name"),
5311 MessageManager.getString("label.enter_view_name"),
5312 JOptionPane.QUESTION_MESSAGE);
5316 viewport.viewName = reply;
5317 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5322 public AlignViewport getCurrentView()
5328 * Open the dialog for regex description parsing.
5331 protected void extractScores_actionPerformed(ActionEvent e)
5333 ParseProperties pp = new jalview.analysis.ParseProperties(
5334 viewport.getAlignment());
5335 // TODO: verify regex and introduce GUI dialog for version 2.5
5336 // if (pp.getScoresFromDescription("col", "score column ",
5337 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5339 if (pp.getScoresFromDescription("description column",
5340 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5342 buildSortByAnnotationScoresMenu();
5350 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5354 protected void showDbRefs_actionPerformed(ActionEvent e)
5356 viewport.setShowDbRefs(showDbRefsMenuitem.isSelected());
5362 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5366 protected void showNpFeats_actionPerformed(ActionEvent e)
5368 viewport.setShowNpFeats(showNpFeatsMenuitem.isSelected());
5372 * find the viewport amongst the tabs in this alignment frame and close that
5377 public boolean closeView(AlignViewport av)
5381 this.closeMenuItem_actionPerformed(false);
5384 Component[] comp = tabbedPane.getComponents();
5385 for (int i = 0; comp != null && i < comp.length; i++)
5387 if (comp[i] instanceof AlignmentPanel)
5389 if (((AlignmentPanel) comp[i]).av == av)
5392 closeView((AlignmentPanel) comp[i]);
5400 protected void build_fetchdbmenu(JMenu webService)
5402 // Temporary hack - DBRef Fetcher always top level ws entry.
5403 // TODO We probably want to store a sequence database checklist in
5404 // preferences and have checkboxes.. rather than individual sources selected
5406 final JMenu rfetch = new JMenu(
5407 MessageManager.getString("action.fetch_db_references"));
5408 rfetch.setToolTipText(MessageManager
5409 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5410 webService.add(rfetch);
5412 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5413 MessageManager.getString("option.trim_retrieved_seqs"));
5414 trimrs.setToolTipText(MessageManager
5415 .getString("label.trim_retrieved_sequences"));
5416 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5417 trimrs.addActionListener(new ActionListener()
5420 public void actionPerformed(ActionEvent e)
5422 trimrs.setSelected(trimrs.isSelected());
5423 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5424 Boolean.valueOf(trimrs.isSelected()).toString());
5428 JMenuItem fetchr = new JMenuItem(
5429 MessageManager.getString("label.standard_databases"));
5430 fetchr.setToolTipText(MessageManager
5431 .getString("label.fetch_embl_uniprot"));
5432 fetchr.addActionListener(new ActionListener()
5436 public void actionPerformed(ActionEvent e)
5438 new Thread(new Runnable()
5444 new jalview.ws.DBRefFetcher(alignPanel.av
5445 .getSequenceSelection(), alignPanel.alignFrame)
5446 .fetchDBRefs(false);
5454 final AlignFrame me = this;
5455 new Thread(new Runnable()
5460 final jalview.ws.SequenceFetcher sf = SequenceFetcher
5461 .getSequenceFetcherSingleton(me);
5462 javax.swing.SwingUtilities.invokeLater(new Runnable()
5467 String[] dbclasses = sf.getOrderedSupportedSources();
5468 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5469 // jalview.util.QuickSort.sort(otherdb, otherdb);
5470 List<DbSourceProxy> otherdb;
5471 JMenu dfetch = new JMenu();
5472 JMenu ifetch = new JMenu();
5473 JMenuItem fetchr = null;
5474 int comp = 0, icomp = 0, mcomp = 15;
5475 String mname = null;
5477 for (String dbclass : dbclasses)
5479 otherdb = sf.getSourceProxy(dbclass);
5480 // add a single entry for this class, or submenu allowing 'fetch
5482 if (otherdb == null || otherdb.size() < 1)
5486 // List<DbSourceProxy> dbs=otherdb;
5487 // otherdb=new ArrayList<DbSourceProxy>();
5488 // for (DbSourceProxy db:dbs)
5490 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5494 mname = "From " + dbclass;
5496 if (otherdb.size() == 1)
5498 final DbSourceProxy[] dassource = otherdb
5499 .toArray(new DbSourceProxy[0]);
5500 DbSourceProxy src = otherdb.get(0);
5501 fetchr = new JMenuItem(src.getDbSource());
5502 fetchr.addActionListener(new ActionListener()
5506 public void actionPerformed(ActionEvent e)
5508 new Thread(new Runnable()
5514 new jalview.ws.DBRefFetcher(alignPanel.av
5515 .getSequenceSelection(),
5516 alignPanel.alignFrame, dassource)
5517 .fetchDBRefs(false);
5523 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from", new String[]{src.getDbName()})));
5529 final DbSourceProxy[] dassource = otherdb
5530 .toArray(new DbSourceProxy[0]);
5532 DbSourceProxy src = otherdb.get(0);
5533 fetchr = new JMenuItem(MessageManager.formatMessage(
5534 "label.fetch_all_param", new String[]
5535 { src.getDbSource() }));
5536 fetchr.addActionListener(new ActionListener()
5539 public void actionPerformed(ActionEvent e)
5541 new Thread(new Runnable()
5547 new jalview.ws.DBRefFetcher(alignPanel.av
5548 .getSequenceSelection(),
5549 alignPanel.alignFrame, dassource)
5550 .fetchDBRefs(false);
5556 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from_all_sources", new String[]{Integer.valueOf(otherdb.size()).toString(), src.getDbSource(), src.getDbName()})));
5559 // and then build the rest of the individual menus
5560 ifetch = new JMenu(MessageManager.formatMessage("label.source_from_db_source", new String[]{src.getDbSource()}));
5562 String imname = null;
5564 for (DbSourceProxy sproxy : otherdb)
5566 String dbname = sproxy.getDbName();
5567 String sname = dbname.length() > 5 ? dbname.substring(0,
5568 5) + "..." : dbname;
5569 String msname = dbname.length() > 10 ? dbname.substring(
5570 0, 10) + "..." : dbname;
5573 imname = MessageManager.formatMessage("label.from_msname", new String[]{sname});
5575 fetchr = new JMenuItem(msname);
5576 final DbSourceProxy[] dassrc =
5578 fetchr.addActionListener(new ActionListener()
5582 public void actionPerformed(ActionEvent e)
5584 new Thread(new Runnable()
5590 new jalview.ws.DBRefFetcher(alignPanel.av
5591 .getSequenceSelection(),
5592 alignPanel.alignFrame, dassrc)
5593 .fetchDBRefs(false);
5599 fetchr.setToolTipText("<html>"
5600 + MessageManager.formatMessage("label.fetch_retrieve_from", new String[]{dbname}));
5603 if (++icomp >= mcomp || i == (otherdb.size()))
5605 ifetch.setText(MessageManager.formatMessage(
5606 "label.source_to_target", imname, sname));
5608 ifetch = new JMenu();
5616 if (comp >= mcomp || dbi >= (dbclasses.length))
5618 dfetch.setText(MessageManager.formatMessage(
5619 "label.source_to_target", mname, dbclass));
5621 dfetch = new JMenu();
5634 * Left justify the whole alignment.
5637 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5639 AlignmentI al = viewport.getAlignment();
5641 viewport.firePropertyChange("alignment", null, al);
5645 * Right justify the whole alignment.
5648 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5650 AlignmentI al = viewport.getAlignment();
5652 viewport.firePropertyChange("alignment", null, al);
5655 public void setShowSeqFeatures(boolean b)
5657 showSeqFeatures.setSelected(true);
5658 viewport.setShowSequenceFeatures(true);
5665 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5666 * awt.event.ActionEvent)
5669 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5671 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5672 alignPanel.paintAlignment(true);
5679 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5683 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5685 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5686 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5694 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5695 * .event.ActionEvent)
5698 protected void showGroupConservation_actionPerformed(ActionEvent e)
5700 viewport.setShowGroupConservation(showGroupConservation.getState());
5701 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5708 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5709 * .event.ActionEvent)
5712 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5714 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5715 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5722 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5723 * .event.ActionEvent)
5726 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5728 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5729 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5733 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5735 showSequenceLogo.setState(true);
5736 viewport.setShowSequenceLogo(true);
5737 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5738 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5742 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5744 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5751 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5752 * .event.ActionEvent)
5755 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5757 if (avc.makeGroupsFromSelection())
5759 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5760 alignPanel.updateAnnotation();
5761 alignPanel.paintAlignment(true);
5766 protected void createGroup_actionPerformed(ActionEvent e)
5768 if (avc.createGroup())
5770 alignPanel.alignmentChanged();
5775 protected void unGroup_actionPerformed(ActionEvent e)
5779 alignPanel.alignmentChanged();
5784 * make the given alignmentPanel the currently selected tab
5786 * @param alignmentPanel
5788 public void setDisplayedView(AlignmentPanel alignmentPanel)
5790 if (!viewport.getSequenceSetId().equals(
5791 alignmentPanel.av.getSequenceSetId()))
5793 throw new Error(MessageManager.getString("error.implementation_error_cannot_show_view_alignment_frame"));
5795 if (tabbedPane != null
5796 & alignPanels.indexOf(alignmentPanel) != tabbedPane
5797 .getSelectedIndex())
5799 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5804 * Action on selection of menu options to Show or Hide annotations.
5807 * @param forSequences
5808 * update sequence-related annotations
5809 * @param forAlignment
5810 * update non-sequence-related annotations
5813 protected void setAnnotationsVisibility(boolean visible,
5814 boolean forSequences, boolean forAlignment)
5816 for (AlignmentAnnotation aa : alignPanel.getAlignment()
5817 .getAlignmentAnnotation())
5819 boolean apply = (aa.sequenceRef == null && forAlignment)
5820 || (aa.sequenceRef != null && forSequences);
5823 aa.visible = visible;
5826 alignPanel.validateAnnotationDimensions(false);
5827 alignPanel.alignmentChanged();
5831 * Store selected annotation sort order for the view and repaint.
5834 protected void sortAnnotations_actionPerformed()
5836 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5838 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5839 alignPanel.paintAlignment(true);
5843 class PrintThread extends Thread
5847 public PrintThread(AlignmentPanel ap)
5852 static PageFormat pf;
5857 PrinterJob printJob = PrinterJob.getPrinterJob();
5861 printJob.setPrintable(ap, pf);
5865 printJob.setPrintable(ap);
5868 if (printJob.printDialog())
5873 } catch (Exception PrintException)
5875 PrintException.printStackTrace();