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.OrderCommand;
38 import jalview.commands.RemoveGapColCommand;
39 import jalview.commands.RemoveGapsCommand;
40 import jalview.commands.SlideSequencesCommand;
41 import jalview.commands.TrimRegionCommand;
42 import jalview.datamodel.AlignedCodonFrame;
43 import jalview.datamodel.Alignment;
44 import jalview.datamodel.AlignmentAnnotation;
45 import jalview.datamodel.AlignmentI;
46 import jalview.datamodel.AlignmentOrder;
47 import jalview.datamodel.AlignmentView;
48 import jalview.datamodel.ColumnSelection;
49 import jalview.datamodel.PDBEntry;
50 import jalview.datamodel.SeqCigar;
51 import jalview.datamodel.Sequence;
52 import jalview.datamodel.SequenceGroup;
53 import jalview.datamodel.SequenceI;
54 import jalview.io.AlignmentProperties;
55 import jalview.io.AnnotationFile;
56 import jalview.io.FeaturesFile;
57 import jalview.io.FileLoader;
58 import jalview.io.FormatAdapter;
59 import jalview.io.HTMLOutput;
60 import jalview.io.IdentifyFile;
61 import jalview.io.JalviewFileChooser;
62 import jalview.io.JalviewFileView;
63 import jalview.io.JnetAnnotationMaker;
64 import jalview.io.NewickFile;
65 import jalview.io.TCoffeeScoreFile;
66 import jalview.jbgui.GAlignFrame;
67 import jalview.schemes.Blosum62ColourScheme;
68 import jalview.schemes.BuriedColourScheme;
69 import jalview.schemes.ClustalxColourScheme;
70 import jalview.schemes.ColourSchemeI;
71 import jalview.schemes.ColourSchemeProperty;
72 import jalview.schemes.HelixColourScheme;
73 import jalview.schemes.HydrophobicColourScheme;
74 import jalview.schemes.NucleotideColourScheme;
75 import jalview.schemes.PIDColourScheme;
76 import jalview.schemes.PurinePyrimidineColourScheme;
77 import jalview.schemes.RNAHelicesColourChooser;
78 import jalview.schemes.ResidueProperties;
79 import jalview.schemes.StrandColourScheme;
80 import jalview.schemes.TCoffeeColourScheme;
81 import jalview.schemes.TaylorColourScheme;
82 import jalview.schemes.TurnColourScheme;
83 import jalview.schemes.UserColourScheme;
84 import jalview.schemes.ZappoColourScheme;
85 import jalview.util.MessageManager;
86 import jalview.ws.jws1.Discoverer;
87 import jalview.ws.jws2.Jws2Discoverer;
88 import jalview.ws.jws2.jabaws2.Jws2Instance;
89 import jalview.ws.seqfetcher.DbSourceProxy;
91 import java.awt.BorderLayout;
92 import java.awt.Component;
93 import java.awt.GridLayout;
94 import java.awt.Rectangle;
95 import java.awt.Toolkit;
96 import java.awt.datatransfer.Clipboard;
97 import java.awt.datatransfer.DataFlavor;
98 import java.awt.datatransfer.StringSelection;
99 import java.awt.datatransfer.Transferable;
100 import java.awt.dnd.DnDConstants;
101 import java.awt.dnd.DropTargetDragEvent;
102 import java.awt.dnd.DropTargetDropEvent;
103 import java.awt.dnd.DropTargetEvent;
104 import java.awt.dnd.DropTargetListener;
105 import java.awt.event.ActionEvent;
106 import java.awt.event.ActionListener;
107 import java.awt.event.KeyAdapter;
108 import java.awt.event.KeyEvent;
109 import java.awt.event.MouseAdapter;
110 import java.awt.event.MouseEvent;
111 import java.awt.print.PageFormat;
112 import java.awt.print.PrinterJob;
113 import java.beans.PropertyChangeEvent;
116 import java.util.ArrayList;
117 import java.util.Enumeration;
118 import java.util.Hashtable;
119 import java.util.List;
120 import java.util.Vector;
122 import javax.swing.JButton;
123 import javax.swing.JCheckBoxMenuItem;
124 import javax.swing.JEditorPane;
125 import javax.swing.JInternalFrame;
126 import javax.swing.JLabel;
127 import javax.swing.JLayeredPane;
128 import javax.swing.JMenu;
129 import javax.swing.JMenuItem;
130 import javax.swing.JOptionPane;
131 import javax.swing.JPanel;
132 import javax.swing.JProgressBar;
133 import javax.swing.JRadioButtonMenuItem;
134 import javax.swing.JScrollPane;
135 import javax.swing.SwingUtilities;
141 * @version $Revision$
143 public class AlignFrame extends GAlignFrame implements DropTargetListener,
144 IProgressIndicator, AlignViewControllerGuiI
148 public static final int DEFAULT_WIDTH = 700;
151 public static final int DEFAULT_HEIGHT = 500;
153 public AlignmentPanel alignPanel;
155 AlignViewport viewport;
157 public AlignViewControllerI avc;
160 Vector alignPanels = new Vector();
163 * Last format used to load or save alignments in this window
165 String currentFileFormat = null;
168 * Current filename for this alignment
170 String fileName = null;
173 * Creates a new AlignFrame object with specific width and height.
179 public AlignFrame(AlignmentI al, int width, int height)
181 this(al, null, width, height);
185 * Creates a new AlignFrame object with specific width, height and
191 * @param sequenceSetId
193 public AlignFrame(AlignmentI al, int width, int height,
194 String sequenceSetId)
196 this(al, null, width, height, sequenceSetId);
200 * Creates a new AlignFrame object with specific width, height and
206 * @param sequenceSetId
209 public AlignFrame(AlignmentI al, int width, int height,
210 String sequenceSetId, String viewId)
212 this(al, null, width, height, sequenceSetId, viewId);
216 * new alignment window with hidden columns
220 * @param hiddenColumns
221 * ColumnSelection or null
223 * Width of alignment frame
227 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
228 int width, int height)
230 this(al, hiddenColumns, width, height, null);
234 * Create alignment frame for al with hiddenColumns, a specific width and
235 * height, and specific sequenceId
238 * @param hiddenColumns
241 * @param sequenceSetId
244 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
245 int width, int height, String sequenceSetId)
247 this(al, hiddenColumns, width, height, sequenceSetId, null);
251 * Create alignment frame for al with hiddenColumns, a specific width and
252 * height, and specific sequenceId
255 * @param hiddenColumns
258 * @param sequenceSetId
263 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
264 int width, int height, String sequenceSetId, String viewId)
266 setSize(width, height);
267 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
269 alignPanel = new AlignmentPanel(this, viewport);
271 if (al.getDataset() == null)
276 addAlignmentPanel(alignPanel, true);
281 * Make a new AlignFrame from exisiting alignmentPanels
288 public AlignFrame(AlignmentPanel ap)
292 addAlignmentPanel(ap, false);
297 * initalise the alignframe from the underlying viewport data and the
302 avc = new jalview.controller.AlignViewController(this, viewport, alignPanel);
303 if (viewport.getAlignmentConservationAnnotation() == null)
305 BLOSUM62Colour.setEnabled(false);
306 conservationMenuItem.setEnabled(false);
307 modifyConservation.setEnabled(false);
308 // PIDColour.setEnabled(false);
309 // abovePIDThreshold.setEnabled(false);
310 // modifyPID.setEnabled(false);
313 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
316 if (sortby.equals("Id"))
318 sortIDMenuItem_actionPerformed(null);
320 else if (sortby.equals("Pairwise Identity"))
322 sortPairwiseMenuItem_actionPerformed(null);
325 if (Desktop.desktop != null)
327 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
328 addServiceListeners();
329 setGUINucleotide(viewport.getAlignment().isNucleotide());
332 setMenusFromViewport(viewport);
333 buildSortByAnnotationScoresMenu();
335 if (viewport.wrapAlignment)
337 wrapMenuItem_actionPerformed(null);
340 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
342 this.overviewMenuItem_actionPerformed(null);
350 * Change the filename and format for the alignment, and enable the 'reload'
351 * button functionality.
358 public void setFileName(String file, String format)
361 currentFileFormat = format;
362 reload.setEnabled(true);
365 void addKeyListener()
367 addKeyListener(new KeyAdapter()
370 public void keyPressed(KeyEvent evt)
372 if (viewport.cursorMode
373 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
374 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
375 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
376 && Character.isDigit(evt.getKeyChar()))
377 alignPanel.seqPanel.numberPressed(evt.getKeyChar());
379 switch (evt.getKeyCode())
382 case 27: // escape key
383 deselectAllSequenceMenuItem_actionPerformed(null);
387 case KeyEvent.VK_DOWN:
388 if (evt.isAltDown() || !viewport.cursorMode)
389 moveSelectedSequences(false);
390 if (viewport.cursorMode)
391 alignPanel.seqPanel.moveCursor(0, 1);
395 if (evt.isAltDown() || !viewport.cursorMode)
396 moveSelectedSequences(true);
397 if (viewport.cursorMode)
398 alignPanel.seqPanel.moveCursor(0, -1);
402 case KeyEvent.VK_LEFT:
403 if (evt.isAltDown() || !viewport.cursorMode)
404 slideSequences(false, alignPanel.seqPanel.getKeyboardNo1());
406 alignPanel.seqPanel.moveCursor(-1, 0);
410 case KeyEvent.VK_RIGHT:
411 if (evt.isAltDown() || !viewport.cursorMode)
412 slideSequences(true, alignPanel.seqPanel.getKeyboardNo1());
414 alignPanel.seqPanel.moveCursor(1, 0);
417 case KeyEvent.VK_SPACE:
418 if (viewport.cursorMode)
420 alignPanel.seqPanel.insertGapAtCursor(evt.isControlDown()
421 || evt.isShiftDown() || evt.isAltDown());
425 // case KeyEvent.VK_A:
426 // if (viewport.cursorMode)
428 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
429 // //System.out.println("A");
433 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
434 * System.out.println("closing bracket"); } break;
436 case KeyEvent.VK_DELETE:
437 case KeyEvent.VK_BACK_SPACE:
438 if (!viewport.cursorMode)
440 cut_actionPerformed(null);
444 alignPanel.seqPanel.deleteGapAtCursor(evt.isControlDown()
445 || evt.isShiftDown() || evt.isAltDown());
451 if (viewport.cursorMode)
453 alignPanel.seqPanel.setCursorRow();
457 if (viewport.cursorMode && !evt.isControlDown())
459 alignPanel.seqPanel.setCursorColumn();
463 if (viewport.cursorMode)
465 alignPanel.seqPanel.setCursorPosition();
469 case KeyEvent.VK_ENTER:
470 case KeyEvent.VK_COMMA:
471 if (viewport.cursorMode)
473 alignPanel.seqPanel.setCursorRowAndColumn();
478 if (viewport.cursorMode)
480 alignPanel.seqPanel.setSelectionAreaAtCursor(true);
484 if (viewport.cursorMode)
486 alignPanel.seqPanel.setSelectionAreaAtCursor(false);
491 viewport.cursorMode = !viewport.cursorMode;
492 statusBar.setText(MessageManager.formatMessage("label.keyboard_editing_mode", new String[]{(viewport.cursorMode ? "on" : "off")}));
493 if (viewport.cursorMode)
495 alignPanel.seqPanel.seqCanvas.cursorX = viewport.startRes;
496 alignPanel.seqPanel.seqCanvas.cursorY = viewport.startSeq;
498 alignPanel.seqPanel.seqCanvas.repaint();
504 ClassLoader cl = jalview.gui.Desktop.class.getClassLoader();
505 java.net.URL url = javax.help.HelpSet.findHelpSet(cl,
507 javax.help.HelpSet hs = new javax.help.HelpSet(cl, url);
509 javax.help.HelpBroker hb = hs.createHelpBroker();
510 hb.setCurrentID("home");
511 hb.setDisplayed(true);
512 } catch (Exception ex)
514 ex.printStackTrace();
519 boolean toggleSeqs = !evt.isControlDown();
520 boolean toggleCols = !evt.isShiftDown();
521 toggleHiddenRegions(toggleSeqs, toggleCols);
524 case KeyEvent.VK_PAGE_UP:
525 if (viewport.wrapAlignment)
527 alignPanel.scrollUp(true);
531 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
532 - viewport.endSeq + viewport.startSeq);
535 case KeyEvent.VK_PAGE_DOWN:
536 if (viewport.wrapAlignment)
538 alignPanel.scrollUp(false);
542 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
543 + viewport.endSeq - viewport.startSeq);
550 public void keyReleased(KeyEvent evt)
552 switch (evt.getKeyCode())
554 case KeyEvent.VK_LEFT:
555 if (evt.isAltDown() || !viewport.cursorMode)
556 viewport.firePropertyChange("alignment", null, viewport
557 .getAlignment().getSequences());
560 case KeyEvent.VK_RIGHT:
561 if (evt.isAltDown() || !viewport.cursorMode)
562 viewport.firePropertyChange("alignment", null, viewport
563 .getAlignment().getSequences());
570 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
572 ap.alignFrame = this;
573 avc = new jalview.controller.AlignViewController(this, viewport, alignPanel);
575 alignPanels.addElement(ap);
577 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
579 int aSize = alignPanels.size();
581 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
583 if (aSize == 1 && ap.av.viewName == null)
585 this.getContentPane().add(ap, BorderLayout.CENTER);
591 setInitialTabVisible();
594 expandViews.setEnabled(true);
595 gatherViews.setEnabled(true);
596 tabbedPane.addTab(ap.av.viewName, ap);
598 ap.setVisible(false);
603 if (ap.av.isPadGaps())
605 ap.av.getAlignment().padGaps();
607 ap.av.updateConservation(ap);
608 ap.av.updateConsensus(ap);
609 ap.av.updateStrucConsensus(ap);
613 public void setInitialTabVisible()
615 expandViews.setEnabled(true);
616 gatherViews.setEnabled(true);
617 tabbedPane.setVisible(true);
618 AlignmentPanel first = (AlignmentPanel) alignPanels.firstElement();
619 tabbedPane.addTab(first.av.viewName, first);
620 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
623 public AlignViewport getViewport()
628 /* Set up intrinsic listeners for dynamically generated GUI bits. */
629 private void addServiceListeners()
631 final java.beans.PropertyChangeListener thisListener;
632 Desktop.instance.addJalviewPropertyChangeListener("services",
633 thisListener = new java.beans.PropertyChangeListener()
636 public void propertyChange(PropertyChangeEvent evt)
638 // // System.out.println("Discoverer property change.");
639 // if (evt.getPropertyName().equals("services"))
641 SwingUtilities.invokeLater(new Runnable()
648 .println("Rebuild WS Menu for service change");
649 BuildWebServiceMenu();
656 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
659 public void internalFrameClosed(
660 javax.swing.event.InternalFrameEvent evt)
662 System.out.println("deregistering discoverer listener");
663 Desktop.instance.removeJalviewPropertyChangeListener("services",
665 closeMenuItem_actionPerformed(true);
668 // Finally, build the menu once to get current service state
669 new Thread(new Runnable()
674 BuildWebServiceMenu();
679 public void setGUINucleotide(boolean nucleotide)
681 showTranslation.setVisible(nucleotide);
682 conservationMenuItem.setEnabled(!nucleotide);
683 modifyConservation.setEnabled(!nucleotide);
684 showGroupConservation.setEnabled(!nucleotide);
685 rnahelicesColour.setEnabled(nucleotide);
686 purinePyrimidineColour.setEnabled(nucleotide);
687 // Remember AlignFrame always starts as protein
691 // calculateMenu.remove(calculateMenu.getItemCount() - 2);
696 * set up menus for the currently viewport. This may be called after any
697 * operation that affects the data in the current view (selection changed,
698 * etc) to update the menus to reflect the new state.
700 public void setMenusForViewport()
702 setMenusFromViewport(viewport);
706 * Need to call this method when tabs are selected for multiple views, or when
707 * loading from Jalview2XML.java
712 void setMenusFromViewport(AlignViewport av)
714 padGapsMenuitem.setSelected(av.isPadGaps());
715 colourTextMenuItem.setSelected(av.showColourText);
716 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
717 conservationMenuItem.setSelected(av.getConservationSelected());
718 seqLimits.setSelected(av.getShowJVSuffix());
719 idRightAlign.setSelected(av.rightAlignIds);
720 centreColumnLabelsMenuItem.setState(av.centreColumnLabels);
721 renderGapsMenuItem.setSelected(av.renderGaps);
722 wrapMenuItem.setSelected(av.wrapAlignment);
723 scaleAbove.setVisible(av.wrapAlignment);
724 scaleLeft.setVisible(av.wrapAlignment);
725 scaleRight.setVisible(av.wrapAlignment);
726 annotationPanelMenuItem.setState(av.showAnnotation);
727 viewBoxesMenuItem.setSelected(av.showBoxes);
728 viewTextMenuItem.setSelected(av.showText);
729 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
730 showGroupConsensus.setSelected(av.isShowGroupConsensus());
731 showGroupConservation.setSelected(av.isShowGroupConservation());
732 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
733 showSequenceLogo.setSelected(av.isShowSequenceLogo());
734 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
736 setColourSelected(ColourSchemeProperty.getColourName(av
737 .getGlobalColourScheme()));
739 showSeqFeatures.setSelected(av.showSequenceFeatures);
740 hiddenMarkers.setState(av.showHiddenMarkers);
741 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
742 showNpFeatsMenuitem.setSelected(av.isShowNpFeats());
743 showDbRefsMenuitem.setSelected(av.isShowDbRefs());
744 autoCalculate.setSelected(av.autoCalculateConsensus);
745 sortByTree.setSelected(av.sortByTree);
746 listenToViewSelections.setSelected(av.followSelection);
747 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
749 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
750 setShowProductsEnabled();
754 // methods for implementing IProgressIndicator
755 // need to refactor to a reusable stub class
756 Hashtable progressBars, progressBarHandlers;
761 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
764 public void setProgressBar(String message, long id)
766 if (progressBars == null)
768 progressBars = new Hashtable();
769 progressBarHandlers = new Hashtable();
772 JPanel progressPanel;
773 Long lId = new Long(id);
774 GridLayout layout = (GridLayout) statusPanel.getLayout();
775 if (progressBars.get(lId) != null)
777 progressPanel = (JPanel) progressBars.get(new Long(id));
778 statusPanel.remove(progressPanel);
779 progressBars.remove(lId);
780 progressPanel = null;
783 statusBar.setText(message);
785 if (progressBarHandlers.contains(lId))
787 progressBarHandlers.remove(lId);
789 layout.setRows(layout.getRows() - 1);
793 progressPanel = new JPanel(new BorderLayout(10, 5));
795 JProgressBar progressBar = new JProgressBar();
796 progressBar.setIndeterminate(true);
798 progressPanel.add(new JLabel(message), BorderLayout.WEST);
799 progressPanel.add(progressBar, BorderLayout.CENTER);
801 layout.setRows(layout.getRows() + 1);
802 statusPanel.add(progressPanel);
804 progressBars.put(lId, progressPanel);
807 // setMenusForViewport();
812 public void registerHandler(final long id,
813 final IProgressIndicatorHandler handler)
815 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
818 "call setProgressBar before registering the progress bar's handler.");
820 progressBarHandlers.put(new Long(id), handler);
821 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
822 if (handler.canCancel())
824 JButton cancel = new JButton(MessageManager.getString("action.cancel"));
825 final IProgressIndicator us = this;
826 cancel.addActionListener(new ActionListener()
830 public void actionPerformed(ActionEvent e)
832 handler.cancelActivity(id);
835 + ((JLabel) progressPanel.getComponent(0))
839 progressPanel.add(cancel, BorderLayout.EAST);
845 * @return true if any progress bars are still active
848 public boolean operationInProgress()
850 if (progressBars != null && progressBars.size() > 0)
858 public void setStatus(String text) {
859 statusBar.setText(text);
862 * Added so Castor Mapping file can obtain Jalview Version
864 public String getVersion()
866 return jalview.bin.Cache.getProperty("VERSION");
869 public FeatureRenderer getFeatureRenderer()
871 return alignPanel.seqPanel.seqCanvas.getFeatureRenderer();
875 public void fetchSequence_actionPerformed(ActionEvent e)
877 new SequenceFetcher(this);
881 public void addFromFile_actionPerformed(ActionEvent e)
883 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
887 public void reload_actionPerformed(ActionEvent e)
889 if (fileName != null)
891 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
892 // originating file's format
893 // TODO: work out how to recover feature settings for correct view(s) when
895 if (currentFileFormat.equals("Jalview"))
897 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
898 for (int i = 0; i < frames.length; i++)
900 if (frames[i] instanceof AlignFrame && frames[i] != this
901 && ((AlignFrame) frames[i]).fileName != null
902 && ((AlignFrame) frames[i]).fileName.equals(fileName))
906 frames[i].setSelected(true);
907 Desktop.instance.closeAssociatedWindows();
908 } catch (java.beans.PropertyVetoException ex)
914 Desktop.instance.closeAssociatedWindows();
916 FileLoader loader = new FileLoader();
917 String protocol = fileName.startsWith("http:") ? "URL" : "File";
918 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
922 Rectangle bounds = this.getBounds();
924 FileLoader loader = new FileLoader();
925 String protocol = fileName.startsWith("http:") ? "URL" : "File";
926 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
927 protocol, currentFileFormat);
929 newframe.setBounds(bounds);
930 if (featureSettings != null && featureSettings.isShowing())
932 final Rectangle fspos = featureSettings.frame.getBounds();
933 // TODO: need a 'show feature settings' function that takes bounds -
934 // need to refactor Desktop.addFrame
935 newframe.featureSettings_actionPerformed(null);
936 final FeatureSettings nfs = newframe.featureSettings;
937 SwingUtilities.invokeLater(new Runnable()
942 nfs.frame.setBounds(fspos);
945 this.featureSettings.close();
946 this.featureSettings = null;
948 this.closeMenuItem_actionPerformed(true);
954 public void addFromText_actionPerformed(ActionEvent e)
956 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
960 public void addFromURL_actionPerformed(ActionEvent e)
962 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
966 public void save_actionPerformed(ActionEvent e)
969 || (currentFileFormat == null || !jalview.io.FormatAdapter
970 .isValidIOFormat(currentFileFormat, true))
971 || fileName.startsWith("http"))
973 saveAs_actionPerformed(null);
977 saveAlignment(fileName, currentFileFormat);
988 public void saveAs_actionPerformed(ActionEvent e)
990 JalviewFileChooser chooser = new JalviewFileChooser(
991 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
992 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
993 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
994 currentFileFormat, false);
996 chooser.setFileView(new JalviewFileView());
997 chooser.setDialogTitle("Save Alignment to file");
998 chooser.setToolTipText(MessageManager.getString("action.save"));
1000 int value = chooser.showSaveDialog(this);
1002 if (value == JalviewFileChooser.APPROVE_OPTION)
1004 currentFileFormat = chooser.getSelectedFormat();
1005 if (currentFileFormat == null)
1007 JOptionPane.showInternalMessageDialog(Desktop.desktop,
1008 MessageManager.getString("label.select_file_format_before_saving"),
1009 MessageManager.getString("label.file_format_not_specified"), JOptionPane.WARNING_MESSAGE);
1010 value = chooser.showSaveDialog(this);
1014 fileName = chooser.getSelectedFile().getPath();
1016 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
1019 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
1020 if (currentFileFormat.indexOf(" ") > -1)
1022 currentFileFormat = currentFileFormat.substring(0,
1023 currentFileFormat.indexOf(" "));
1025 saveAlignment(fileName, currentFileFormat);
1029 public boolean saveAlignment(String file, String format)
1031 boolean success = true;
1033 if (format.equalsIgnoreCase("Jalview"))
1035 String shortName = title;
1037 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1039 shortName = shortName.substring(shortName
1040 .lastIndexOf(java.io.File.separatorChar) + 1);
1043 success = new Jalview2XML().SaveAlignment(this, file, shortName);
1045 statusBar.setText(MessageManager.formatMessage("label.successfully_saved_to_file_in_format",new String[]{fileName, format}));
1051 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1053 warningMessage("Cannot save file " + fileName + " using format "
1054 + format, "Alignment output format not supported");
1055 saveAs_actionPerformed(null);
1056 // JBPNote need to have a raise_gui flag here
1060 String[] omitHidden = null;
1062 if (viewport.hasHiddenColumns())
1064 int reply = JOptionPane
1065 .showInternalConfirmDialog(
1067 MessageManager.getString("label.alignment_contains_hidden_columns"),
1068 MessageManager.getString("action.save_omit_hidden_columns"),
1069 JOptionPane.YES_NO_OPTION,
1070 JOptionPane.QUESTION_MESSAGE);
1072 if (reply == JOptionPane.YES_OPTION)
1074 omitHidden = viewport.getViewAsString(false);
1077 FormatAdapter f = new FormatAdapter();
1078 String output = f.formatSequences(format,
1079 viewport.getAlignment(), // class cast exceptions will
1080 // occur in the distant future
1081 omitHidden, f.getCacheSuffixDefault(format),
1082 viewport.getColumnSelection());
1092 java.io.PrintWriter out = new java.io.PrintWriter(
1093 new java.io.FileWriter(file));
1097 this.setTitle(file);
1098 statusBar.setText(MessageManager.formatMessage("label.successfully_saved_to_file_in_format",new String[]{fileName, format}));
1099 } catch (Exception ex)
1102 ex.printStackTrace();
1109 JOptionPane.showInternalMessageDialog(this, MessageManager.formatMessage("label.couldnt_save_file", new String[]{fileName}),
1110 MessageManager.getString("label.error_saving_file"), JOptionPane.WARNING_MESSAGE);
1116 private void warningMessage(String warning, String title)
1118 if (new jalview.util.Platform().isHeadless())
1120 System.err.println("Warning: " + title + "\nWarning: " + warning);
1125 JOptionPane.showInternalMessageDialog(this, warning, title,
1126 JOptionPane.WARNING_MESSAGE);
1138 protected void outputText_actionPerformed(ActionEvent e)
1140 String[] omitHidden = null;
1142 if (viewport.hasHiddenColumns())
1144 int reply = JOptionPane
1145 .showInternalConfirmDialog(
1147 MessageManager.getString("label.alignment_contains_hidden_columns"),
1148 MessageManager.getString("action.save_omit_hidden_columns"),
1149 JOptionPane.YES_NO_OPTION,
1150 JOptionPane.QUESTION_MESSAGE);
1152 if (reply == JOptionPane.YES_OPTION)
1154 omitHidden = viewport.getViewAsString(false);
1158 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1159 cap.setForInput(null);
1163 cap.setText(new FormatAdapter().formatSequences(e.getActionCommand(),
1164 viewport.getAlignment(), omitHidden,
1165 viewport.getColumnSelection()));
1166 Desktop.addInternalFrame(cap,
1167 MessageManager.formatMessage("label.alignment_output_command", new String[]{e.getActionCommand()}), 600, 500);
1168 } catch (OutOfMemoryError oom)
1170 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1183 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1185 new HTMLOutput(alignPanel,
1186 alignPanel.seqPanel.seqCanvas.getSequenceRenderer(),
1187 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
1190 public void createImageMap(File file, String image)
1192 alignPanel.makePNGImageMap(file, image);
1202 public void createPNG(File f)
1204 alignPanel.makePNG(f);
1214 public void createEPS(File f)
1216 alignPanel.makeEPS(f);
1220 public void pageSetup_actionPerformed(ActionEvent e)
1222 PrinterJob printJob = PrinterJob.getPrinterJob();
1223 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1233 public void printMenuItem_actionPerformed(ActionEvent e)
1235 // Putting in a thread avoids Swing painting problems
1236 PrintThread thread = new PrintThread(alignPanel);
1241 public void exportFeatures_actionPerformed(ActionEvent e)
1243 new AnnotationExporter().exportFeatures(alignPanel);
1247 public void exportAnnotations_actionPerformed(ActionEvent e)
1249 new AnnotationExporter().exportAnnotations(alignPanel,
1250 viewport.showAnnotation ? viewport.getAlignment()
1251 .getAlignmentAnnotation() : null, viewport
1252 .getAlignment().getGroups(), ((Alignment) viewport
1253 .getAlignment()).alignmentProperties);
1257 public void associatedData_actionPerformed(ActionEvent e)
1259 // Pick the tree file
1260 JalviewFileChooser chooser = new JalviewFileChooser(
1261 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1262 chooser.setFileView(new JalviewFileView());
1263 chooser.setDialogTitle(MessageManager.getString("label.load_jalview_annotations"));
1264 chooser.setToolTipText(MessageManager.getString("label.load_jalview_annotations"));
1266 int value = chooser.showOpenDialog(null);
1268 if (value == JalviewFileChooser.APPROVE_OPTION)
1270 String choice = chooser.getSelectedFile().getPath();
1271 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1272 loadJalviewDataFile(choice, null, null, null);
1278 * Close the current view or all views in the alignment frame. If the frame
1279 * only contains one view then the alignment will be removed from memory.
1281 * @param closeAllTabs
1284 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1286 if (alignPanels != null && alignPanels.size() < 2)
1288 closeAllTabs = true;
1293 if (alignPanels != null)
1297 if (this.isClosed())
1299 // really close all the windows - otherwise wait till
1300 // setClosed(true) is called
1301 for (int i = 0; i < alignPanels.size(); i++)
1303 AlignmentPanel ap = (AlignmentPanel) alignPanels.elementAt(i);
1310 closeView(alignPanel);
1316 this.setClosed(true);
1318 } catch (Exception ex)
1320 ex.printStackTrace();
1325 * close alignPanel2 and shuffle tabs appropriately.
1327 * @param alignPanel2
1329 public void closeView(AlignmentPanel alignPanel2)
1331 int index = tabbedPane.getSelectedIndex();
1332 int closedindex = tabbedPane.indexOfComponent(alignPanel2);
1333 alignPanels.removeElement(alignPanel2);
1335 // if (viewport == alignPanel2.av)
1339 alignPanel2.closePanel();
1342 tabbedPane.removeTabAt(closedindex);
1343 tabbedPane.validate();
1345 if (index > closedindex || index == tabbedPane.getTabCount())
1347 // modify currently selected tab index if necessary.
1351 this.tabSelectionChanged(index);
1357 void updateEditMenuBar()
1360 if (viewport.historyList.size() > 0)
1362 undoMenuItem.setEnabled(true);
1363 CommandI command = (CommandI) viewport.historyList.peek();
1364 undoMenuItem.setText(MessageManager.formatMessage("label.undo_command", new String[]{command.getDescription()}));
1368 undoMenuItem.setEnabled(false);
1369 undoMenuItem.setText(MessageManager.getString("action.undo"));
1372 if (viewport.redoList.size() > 0)
1374 redoMenuItem.setEnabled(true);
1376 CommandI command = (CommandI) viewport.redoList.peek();
1377 redoMenuItem.setText(MessageManager.formatMessage("label.redo_command", new String[]{command.getDescription()}));
1381 redoMenuItem.setEnabled(false);
1382 redoMenuItem.setText(MessageManager.getString("action.redo"));
1386 public void addHistoryItem(CommandI command)
1388 if (command.getSize() > 0)
1390 viewport.historyList.push(command);
1391 viewport.redoList.clear();
1392 updateEditMenuBar();
1393 viewport.updateHiddenColumns();
1394 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1395 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1396 // viewport.getColumnSelection()
1397 // .getHiddenColumns().size() > 0);
1403 * @return alignment objects for all views
1405 AlignmentI[] getViewAlignments()
1407 if (alignPanels != null)
1409 Enumeration e = alignPanels.elements();
1410 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1411 for (int i = 0; e.hasMoreElements(); i++)
1413 als[i] = ((AlignmentPanel) e.nextElement()).av.getAlignment();
1417 if (viewport != null)
1419 return new AlignmentI[]
1420 { viewport.getAlignment() };
1432 protected void undoMenuItem_actionPerformed(ActionEvent e)
1434 if (viewport.historyList.empty())
1436 CommandI command = (CommandI) viewport.historyList.pop();
1437 viewport.redoList.push(command);
1438 command.undoCommand(getViewAlignments());
1440 AlignViewport originalSource = getOriginatingSource(command);
1441 updateEditMenuBar();
1443 if (originalSource != null)
1445 if (originalSource != viewport)
1448 .warn("Implementation worry: mismatch of viewport origin for undo");
1450 originalSource.updateHiddenColumns();
1451 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1453 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1454 // viewport.getColumnSelection()
1455 // .getHiddenColumns().size() > 0);
1456 originalSource.firePropertyChange("alignment", null, originalSource
1457 .getAlignment().getSequences());
1468 protected void redoMenuItem_actionPerformed(ActionEvent e)
1470 if (viewport.redoList.size() < 1)
1475 CommandI command = (CommandI) viewport.redoList.pop();
1476 viewport.historyList.push(command);
1477 command.doCommand(getViewAlignments());
1479 AlignViewport originalSource = getOriginatingSource(command);
1480 updateEditMenuBar();
1482 if (originalSource != null)
1485 if (originalSource != viewport)
1488 .warn("Implementation worry: mismatch of viewport origin for redo");
1490 originalSource.updateHiddenColumns();
1491 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1493 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1494 // viewport.getColumnSelection()
1495 // .getHiddenColumns().size() > 0);
1496 originalSource.firePropertyChange("alignment", null, originalSource
1497 .getAlignment().getSequences());
1501 AlignViewport getOriginatingSource(CommandI command)
1503 AlignViewport originalSource = null;
1504 // For sequence removal and addition, we need to fire
1505 // the property change event FROM the viewport where the
1506 // original alignment was altered
1507 AlignmentI al = null;
1508 if (command instanceof EditCommand)
1510 EditCommand editCommand = (EditCommand) command;
1511 al = editCommand.getAlignment();
1512 Vector comps = (Vector) PaintRefresher.components.get(viewport
1513 .getSequenceSetId());
1515 for (int i = 0; i < comps.size(); i++)
1517 if (comps.elementAt(i) instanceof AlignmentPanel)
1519 if (al == ((AlignmentPanel) comps.elementAt(i)).av.getAlignment())
1521 originalSource = ((AlignmentPanel) comps.elementAt(i)).av;
1528 if (originalSource == null)
1530 // The original view is closed, we must validate
1531 // the current view against the closed view first
1534 PaintRefresher.validateSequences(al, viewport.getAlignment());
1537 originalSource = viewport;
1540 return originalSource;
1549 public void moveSelectedSequences(boolean up)
1551 SequenceGroup sg = viewport.getSelectionGroup();
1557 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1558 viewport.getHiddenRepSequences(), up);
1559 alignPanel.paintAlignment(true);
1562 synchronized void slideSequences(boolean right, int size)
1564 List<SequenceI> sg = new Vector();
1565 if (viewport.cursorMode)
1567 sg.add(viewport.getAlignment().getSequenceAt(
1568 alignPanel.seqPanel.seqCanvas.cursorY));
1570 else if (viewport.getSelectionGroup() != null
1571 && viewport.getSelectionGroup().getSize() != viewport
1572 .getAlignment().getHeight())
1574 sg = viewport.getSelectionGroup().getSequences(
1575 viewport.getHiddenRepSequences());
1583 Vector invertGroup = new Vector();
1585 for (int i = 0; i < viewport.getAlignment().getHeight(); i++)
1587 if (!sg.contains(viewport.getAlignment().getSequenceAt(i)))
1588 invertGroup.add(viewport.getAlignment().getSequenceAt(i));
1591 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1593 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1594 for (int i = 0; i < invertGroup.size(); i++)
1595 seqs2[i] = (SequenceI) invertGroup.elementAt(i);
1597 SlideSequencesCommand ssc;
1599 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1600 size, viewport.getGapCharacter());
1602 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1603 size, viewport.getGapCharacter());
1605 int groupAdjustment = 0;
1606 if (ssc.getGapsInsertedBegin() && right)
1608 if (viewport.cursorMode)
1609 alignPanel.seqPanel.moveCursor(size, 0);
1611 groupAdjustment = size;
1613 else if (!ssc.getGapsInsertedBegin() && !right)
1615 if (viewport.cursorMode)
1616 alignPanel.seqPanel.moveCursor(-size, 0);
1618 groupAdjustment = -size;
1621 if (groupAdjustment != 0)
1623 viewport.getSelectionGroup().setStartRes(
1624 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1625 viewport.getSelectionGroup().setEndRes(
1626 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1629 boolean appendHistoryItem = false;
1630 if (viewport.historyList != null && viewport.historyList.size() > 0
1631 && viewport.historyList.peek() instanceof SlideSequencesCommand)
1633 appendHistoryItem = ssc
1634 .appendSlideCommand((SlideSequencesCommand) viewport.historyList
1638 if (!appendHistoryItem)
1639 addHistoryItem(ssc);
1651 protected void copy_actionPerformed(ActionEvent e)
1654 if (viewport.getSelectionGroup() == null)
1658 // TODO: preserve the ordering of displayed alignment annotation in any
1659 // internal paste (particularly sequence associated annotation)
1660 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1661 String[] omitHidden = null;
1663 if (viewport.hasHiddenColumns())
1665 omitHidden = viewport.getViewAsString(true);
1668 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1671 StringSelection ss = new StringSelection(output);
1675 jalview.gui.Desktop.internalCopy = true;
1676 // Its really worth setting the clipboard contents
1677 // to empty before setting the large StringSelection!!
1678 Toolkit.getDefaultToolkit().getSystemClipboard()
1679 .setContents(new StringSelection(""), null);
1681 Toolkit.getDefaultToolkit().getSystemClipboard()
1682 .setContents(ss, Desktop.instance);
1683 } catch (OutOfMemoryError er)
1685 new OOMWarning("copying region", er);
1689 Vector hiddenColumns = null;
1690 if (viewport.hasHiddenColumns())
1692 hiddenColumns = new Vector();
1693 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1694 .getSelectionGroup().getEndRes();
1695 for (int i = 0; i < viewport.getColumnSelection().getHiddenColumns()
1698 int[] region = (int[]) viewport.getColumnSelection()
1699 .getHiddenColumns().elementAt(i);
1700 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1702 hiddenColumns.addElement(new int[]
1703 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1708 Desktop.jalviewClipboard = new Object[]
1709 { seqs, viewport.getAlignment().getDataset(), hiddenColumns };
1710 statusBar.setText(MessageManager.formatMessage("label.copied_sequences_to_clipboard", new String[]{Integer.valueOf(seqs.length).toString()}));
1720 protected void pasteNew_actionPerformed(ActionEvent e)
1732 protected void pasteThis_actionPerformed(ActionEvent e)
1738 * Paste contents of Jalview clipboard
1740 * @param newAlignment
1741 * true to paste to a new alignment, otherwise add to this.
1743 void paste(boolean newAlignment)
1745 boolean externalPaste = true;
1748 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1749 Transferable contents = c.getContents(this);
1751 if (contents == null)
1759 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1760 if (str.length() < 1)
1765 format = new IdentifyFile().Identify(str, "Paste");
1767 } catch (OutOfMemoryError er)
1769 new OOMWarning("Out of memory pasting sequences!!", er);
1773 SequenceI[] sequences;
1774 boolean annotationAdded = false;
1775 AlignmentI alignment = null;
1777 if (Desktop.jalviewClipboard != null)
1779 // The clipboard was filled from within Jalview, we must use the
1781 // And dataset from the copied alignment
1782 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1783 // be doubly sure that we create *new* sequence objects.
1784 sequences = new SequenceI[newseq.length];
1785 for (int i = 0; i < newseq.length; i++)
1787 sequences[i] = new Sequence(newseq[i]);
1789 alignment = new Alignment(sequences);
1790 externalPaste = false;
1794 // parse the clipboard as an alignment.
1795 alignment = new FormatAdapter().readFile(str, "Paste", format);
1796 sequences = alignment.getSequencesArray();
1800 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1806 if (Desktop.jalviewClipboard != null)
1808 // dataset is inherited
1809 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1813 // new dataset is constructed
1814 alignment.setDataset(null);
1816 alwidth = alignment.getWidth() + 1;
1820 AlignmentI pastedal = alignment; // preserve pasted alignment object
1821 // Add pasted sequences and dataset into existing alignment.
1822 alignment = viewport.getAlignment();
1823 alwidth = alignment.getWidth() + 1;
1824 // decide if we need to import sequences from an existing dataset
1825 boolean importDs = Desktop.jalviewClipboard != null
1826 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1827 // importDs==true instructs us to copy over new dataset sequences from
1828 // an existing alignment
1829 Vector newDs = (importDs) ? new Vector() : null; // used to create
1830 // minimum dataset set
1832 for (int i = 0; i < sequences.length; i++)
1836 newDs.addElement(null);
1838 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
1840 if (importDs && ds != null)
1842 if (!newDs.contains(ds))
1844 newDs.setElementAt(ds, i);
1845 ds = new Sequence(ds);
1846 // update with new dataset sequence
1847 sequences[i].setDatasetSequence(ds);
1851 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
1856 // copy and derive new dataset sequence
1857 sequences[i] = sequences[i].deriveSequence();
1858 alignment.getDataset().addSequence(
1859 sequences[i].getDatasetSequence());
1860 // TODO: avoid creation of duplicate dataset sequences with a
1861 // 'contains' method using SequenceI.equals()/SequenceI.contains()
1863 alignment.addSequence(sequences[i]); // merges dataset
1867 newDs.clear(); // tidy up
1869 if (alignment.getAlignmentAnnotation() != null)
1871 for (AlignmentAnnotation alan : alignment
1872 .getAlignmentAnnotation())
1874 if (alan.graphGroup > fgroup)
1876 fgroup = alan.graphGroup;
1880 if (pastedal.getAlignmentAnnotation() != null)
1882 // Add any annotation attached to alignment.
1883 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
1884 for (int i = 0; i < alann.length; i++)
1886 annotationAdded = true;
1887 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
1889 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
1890 if (newann.graphGroup > -1)
1892 if (newGraphGroups.size() <= newann.graphGroup
1893 || newGraphGroups.get(newann.graphGroup) == null)
1895 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
1897 newGraphGroups.add(q, null);
1899 newGraphGroups.set(newann.graphGroup, new Integer(
1902 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
1906 newann.padAnnotation(alwidth);
1907 alignment.addAnnotation(newann);
1917 addHistoryItem(new EditCommand("Add sequences", EditCommand.PASTE,
1918 sequences, 0, alignment.getWidth(), alignment));
1920 // Add any annotations attached to sequences
1921 for (int i = 0; i < sequences.length; i++)
1923 if (sequences[i].getAnnotation() != null)
1925 AlignmentAnnotation newann;
1926 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
1928 annotationAdded = true;
1929 newann = sequences[i].getAnnotation()[a];
1930 newann.adjustForAlignment();
1931 newann.padAnnotation(alwidth);
1932 if (newann.graphGroup > -1)
1934 if (newann.graphGroup > -1)
1936 if (newGraphGroups.size() <= newann.graphGroup
1937 || newGraphGroups.get(newann.graphGroup) == null)
1939 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
1941 newGraphGroups.add(q, null);
1943 newGraphGroups.set(newann.graphGroup, new Integer(
1946 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
1950 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
1955 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
1962 // propagate alignment changed.
1963 viewport.setEndSeq(alignment.getHeight());
1964 if (annotationAdded)
1966 // Duplicate sequence annotation in all views.
1967 AlignmentI[] alview = this.getViewAlignments();
1968 for (int i = 0; i < sequences.length; i++)
1970 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
1973 for (int avnum = 0; avnum < alview.length; avnum++)
1975 if (alview[avnum] != alignment)
1977 // duplicate in a view other than the one with input focus
1978 int avwidth = alview[avnum].getWidth() + 1;
1979 // this relies on sann being preserved after we
1980 // modify the sequence's annotation array for each duplication
1981 for (int a = 0; a < sann.length; a++)
1983 AlignmentAnnotation newann = new AlignmentAnnotation(
1985 sequences[i].addAlignmentAnnotation(newann);
1986 newann.padAnnotation(avwidth);
1987 alview[avnum].addAnnotation(newann); // annotation was
1988 // duplicated earlier
1989 // TODO JAL-1145 graphGroups are not updated for sequence
1990 // annotation added to several views. This may cause
1992 alview[avnum].setAnnotationIndex(newann, a);
1997 buildSortByAnnotationScoresMenu();
1999 viewport.firePropertyChange("alignment", null,
2000 alignment.getSequences());
2001 if (alignPanels != null)
2003 for (AlignmentPanel ap : ((Vector<AlignmentPanel>) alignPanels))
2005 ap.validateAnnotationDimensions(false);
2010 alignPanel.validateAnnotationDimensions(false);
2016 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2018 String newtitle = new String("Copied sequences");
2020 if (Desktop.jalviewClipboard != null
2021 && Desktop.jalviewClipboard[2] != null)
2023 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2024 for (int i = 0; i < hc.size(); i++)
2026 int[] region = (int[]) hc.elementAt(i);
2027 af.viewport.hideColumns(region[0], region[1]);
2031 // >>>This is a fix for the moment, until a better solution is
2033 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
2035 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
2037 // TODO: maintain provenance of an alignment, rather than just make the
2038 // title a concatenation of operations.
2041 if (title.startsWith("Copied sequences"))
2047 newtitle = newtitle.concat("- from " + title);
2052 newtitle = new String("Pasted sequences");
2055 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2060 } catch (Exception ex)
2062 ex.printStackTrace();
2063 System.out.println("Exception whilst pasting: " + ex);
2064 // could be anything being pasted in here
2069 protected void expand_newalign(ActionEvent e)
2072 AlignmentI alignment = AlignmentUtils.expandContext(getViewport().getAlignment(), -1);
2073 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2075 String newtitle = new String("Flanking alignment");
2077 if (Desktop.jalviewClipboard != null
2078 && Desktop.jalviewClipboard[2] != null)
2080 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2081 for (int i = 0; i < hc.size(); i++)
2083 int[] region = (int[]) hc.elementAt(i);
2084 af.viewport.hideColumns(region[0], region[1]);
2088 // >>>This is a fix for the moment, until a better solution is
2090 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
2092 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
2094 // TODO: maintain provenance of an alignment, rather than just make the
2095 // title a concatenation of operations.
2097 if (title.startsWith("Copied sequences"))
2103 newtitle = newtitle.concat("- from " + title);
2107 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2110 } catch (Exception ex)
2112 ex.printStackTrace();
2113 System.out.println("Exception whilst pasting: " + ex);
2114 // could be anything being pasted in here
2116 catch (OutOfMemoryError oom)
2118 new OOMWarning("Viewing flanking region of alignment", oom);
2128 protected void cut_actionPerformed(ActionEvent e)
2130 copy_actionPerformed(null);
2131 delete_actionPerformed(null);
2141 protected void delete_actionPerformed(ActionEvent evt)
2144 SequenceGroup sg = viewport.getSelectionGroup();
2150 Vector seqs = new Vector();
2152 for (int i = 0; i < sg.getSize(); i++)
2154 seq = sg.getSequenceAt(i);
2155 seqs.addElement(seq);
2158 // If the cut affects all sequences, remove highlighted columns
2159 if (sg.getSize() == viewport.getAlignment().getHeight())
2161 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2162 sg.getEndRes() + 1);
2165 SequenceI[] cut = new SequenceI[seqs.size()];
2166 for (int i = 0; i < seqs.size(); i++)
2168 cut[i] = (SequenceI) seqs.elementAt(i);
2172 * //ADD HISTORY ITEM
2174 addHistoryItem(new EditCommand("Cut Sequences", EditCommand.CUT, cut,
2175 sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2176 viewport.getAlignment()));
2178 viewport.setSelectionGroup(null);
2179 viewport.sendSelection();
2180 viewport.getAlignment().deleteGroup(sg);
2182 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2184 if (viewport.getAlignment().getHeight() < 1)
2188 this.setClosed(true);
2189 } catch (Exception ex)
2202 protected void deleteGroups_actionPerformed(ActionEvent e)
2204 if (avc.deleteGroups()) {
2205 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2206 alignPanel.updateAnnotation();
2207 alignPanel.paintAlignment(true);
2218 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2220 SequenceGroup sg = new SequenceGroup();
2222 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2224 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2227 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2228 viewport.setSelectionGroup(sg);
2229 viewport.sendSelection();
2230 alignPanel.paintAlignment(true);
2231 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2241 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2243 if (viewport.cursorMode)
2245 alignPanel.seqPanel.keyboardNo1 = null;
2246 alignPanel.seqPanel.keyboardNo2 = null;
2248 viewport.setSelectionGroup(null);
2249 viewport.getColumnSelection().clear();
2250 viewport.setSelectionGroup(null);
2251 alignPanel.seqPanel.seqCanvas.highlightSearchResults(null);
2252 alignPanel.idPanel.idCanvas.searchResults = null;
2253 alignPanel.paintAlignment(true);
2254 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2255 viewport.sendSelection();
2265 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2267 SequenceGroup sg = viewport.getSelectionGroup();
2271 selectAllSequenceMenuItem_actionPerformed(null);
2276 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2278 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2281 alignPanel.paintAlignment(true);
2282 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2283 viewport.sendSelection();
2287 public void invertColSel_actionPerformed(ActionEvent e)
2289 viewport.invertColumnSelection();
2290 alignPanel.paintAlignment(true);
2291 viewport.sendSelection();
2301 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2303 trimAlignment(true);
2313 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2315 trimAlignment(false);
2318 void trimAlignment(boolean trimLeft)
2320 ColumnSelection colSel = viewport.getColumnSelection();
2323 if (colSel.size() > 0)
2327 column = colSel.getMin();
2331 column = colSel.getMax();
2335 if (viewport.getSelectionGroup() != null)
2337 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2338 viewport.getHiddenRepSequences());
2342 seqs = viewport.getAlignment().getSequencesArray();
2345 TrimRegionCommand trimRegion;
2348 trimRegion = new TrimRegionCommand("Remove Left",
2349 TrimRegionCommand.TRIM_LEFT, seqs, column,
2350 viewport.getAlignment(), viewport.getColumnSelection(),
2351 viewport.getSelectionGroup());
2352 viewport.setStartRes(0);
2356 trimRegion = new TrimRegionCommand("Remove Right",
2357 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2358 viewport.getAlignment(), viewport.getColumnSelection(),
2359 viewport.getSelectionGroup());
2362 statusBar.setText(MessageManager.formatMessage("label.removed_columns", new String[]{Integer.valueOf(trimRegion.getSize()).toString()}));
2364 addHistoryItem(trimRegion);
2366 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2368 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2369 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2371 viewport.getAlignment().deleteGroup(sg);
2375 viewport.firePropertyChange("alignment", null, viewport
2376 .getAlignment().getSequences());
2387 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2389 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2392 if (viewport.getSelectionGroup() != null)
2394 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2395 viewport.getHiddenRepSequences());
2396 start = viewport.getSelectionGroup().getStartRes();
2397 end = viewport.getSelectionGroup().getEndRes();
2401 seqs = viewport.getAlignment().getSequencesArray();
2404 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2405 "Remove Gapped Columns", seqs, start, end,
2406 viewport.getAlignment());
2408 addHistoryItem(removeGapCols);
2410 statusBar.setText(MessageManager.formatMessage("label.removed_empty_columns", new String[]{Integer.valueOf(removeGapCols.getSize()).toString()}));
2412 // This is to maintain viewport position on first residue
2413 // of first sequence
2414 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2415 int startRes = seq.findPosition(viewport.startRes);
2416 // ShiftList shifts;
2417 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2418 // edit.alColumnChanges=shifts.getInverse();
2419 // if (viewport.hasHiddenColumns)
2420 // viewport.getColumnSelection().compensateForEdits(shifts);
2421 viewport.setStartRes(seq.findIndex(startRes) - 1);
2422 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2434 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2436 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2439 if (viewport.getSelectionGroup() != null)
2441 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2442 viewport.getHiddenRepSequences());
2443 start = viewport.getSelectionGroup().getStartRes();
2444 end = viewport.getSelectionGroup().getEndRes();
2448 seqs = viewport.getAlignment().getSequencesArray();
2451 // This is to maintain viewport position on first residue
2452 // of first sequence
2453 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2454 int startRes = seq.findPosition(viewport.startRes);
2456 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2457 viewport.getAlignment()));
2459 viewport.setStartRes(seq.findIndex(startRes) - 1);
2461 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2473 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2475 viewport.setPadGaps(padGapsMenuitem.isSelected());
2476 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2482 // if (justifySeqs>0)
2484 // alignment.justify(justifySeqs!=RIGHT_JUSTIFY);
2497 public void findMenuItem_actionPerformed(ActionEvent e)
2503 public void newView_actionPerformed(ActionEvent e)
2510 * @param copyAnnotation
2511 * if true then duplicate all annnotation, groups and settings
2512 * @return new alignment panel, already displayed.
2514 public AlignmentPanel newView(boolean copyAnnotation)
2516 return newView(null, copyAnnotation);
2522 * title of newly created view
2523 * @return new alignment panel, already displayed.
2525 public AlignmentPanel newView(String viewTitle)
2527 return newView(viewTitle, true);
2533 * title of newly created view
2534 * @param copyAnnotation
2535 * if true then duplicate all annnotation, groups and settings
2536 * @return new alignment panel, already displayed.
2538 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2540 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2542 if (!copyAnnotation)
2544 // just remove all the current annotation except for the automatic stuff
2545 newap.av.getAlignment().deleteAllGroups();
2546 for (AlignmentAnnotation alan : newap.av.getAlignment()
2547 .getAlignmentAnnotation())
2549 if (!alan.autoCalculated)
2551 newap.av.getAlignment().deleteAnnotation(alan);
2557 newap.av.gatherViewsHere = false;
2559 if (viewport.viewName == null)
2561 viewport.viewName = "Original";
2564 newap.av.historyList = viewport.historyList;
2565 newap.av.redoList = viewport.redoList;
2567 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2568 // make sure the new view has a unique name - this is essential for Jalview
2570 boolean addFirstIndex = false;
2571 if (viewTitle == null || viewTitle.trim().length() == 0)
2574 addFirstIndex = true;
2578 index = 1;// we count from 1 if given a specific name
2580 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2581 Vector comps = (Vector) PaintRefresher.components.get(viewport
2582 .getSequenceSetId());
2583 Vector existingNames = new Vector();
2584 for (int i = 0; i < comps.size(); i++)
2586 if (comps.elementAt(i) instanceof AlignmentPanel)
2588 AlignmentPanel ap = (AlignmentPanel) comps.elementAt(i);
2589 if (!existingNames.contains(ap.av.viewName))
2591 existingNames.addElement(ap.av.viewName);
2596 while (existingNames.contains(newViewName))
2598 newViewName = viewTitle + " " + (++index);
2601 newap.av.viewName = newViewName;
2603 addAlignmentPanel(newap, true);
2604 newap.alignmentChanged();
2606 if (alignPanels.size() == 2)
2608 viewport.gatherViewsHere = true;
2610 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2615 public void expandViews_actionPerformed(ActionEvent e)
2617 Desktop.instance.explodeViews(this);
2621 public void gatherViews_actionPerformed(ActionEvent e)
2623 Desktop.instance.gatherViews(this);
2633 public void font_actionPerformed(ActionEvent e)
2635 new FontChooser(alignPanel);
2645 protected void seqLimit_actionPerformed(ActionEvent e)
2647 viewport.setShowJVSuffix(seqLimits.isSelected());
2649 alignPanel.idPanel.idCanvas.setPreferredSize(alignPanel
2650 .calculateIdWidth());
2651 alignPanel.paintAlignment(true);
2655 public void idRightAlign_actionPerformed(ActionEvent e)
2657 viewport.rightAlignIds = idRightAlign.isSelected();
2658 alignPanel.paintAlignment(true);
2662 public void centreColumnLabels_actionPerformed(ActionEvent e)
2664 viewport.centreColumnLabels = centreColumnLabelsMenuItem.getState();
2665 alignPanel.paintAlignment(true);
2671 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2674 protected void followHighlight_actionPerformed()
2676 if (viewport.followHighlight = this.followHighlightMenuItem.getState())
2678 alignPanel.scrollToPosition(
2679 alignPanel.seqPanel.seqCanvas.searchResults, false);
2690 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2692 viewport.setColourText(colourTextMenuItem.isSelected());
2693 alignPanel.paintAlignment(true);
2703 public void wrapMenuItem_actionPerformed(ActionEvent e)
2705 scaleAbove.setVisible(wrapMenuItem.isSelected());
2706 scaleLeft.setVisible(wrapMenuItem.isSelected());
2707 scaleRight.setVisible(wrapMenuItem.isSelected());
2708 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2709 alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2713 public void showAllSeqs_actionPerformed(ActionEvent e)
2715 viewport.showAllHiddenSeqs();
2719 public void showAllColumns_actionPerformed(ActionEvent e)
2721 viewport.showAllHiddenColumns();
2726 public void hideSelSequences_actionPerformed(ActionEvent e)
2728 viewport.hideAllSelectedSeqs();
2729 alignPanel.paintAlignment(true);
2733 * called by key handler and the hide all/show all menu items
2738 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2741 boolean hide = false;
2742 SequenceGroup sg = viewport.getSelectionGroup();
2743 if (!toggleSeqs && !toggleCols)
2745 // Hide everything by the current selection - this is a hack - we do the
2746 // invert and then hide
2747 // first check that there will be visible columns after the invert.
2748 if ((viewport.getColumnSelection() != null
2749 && viewport.getColumnSelection().getSelected() != null && viewport
2750 .getColumnSelection().getSelected().size() > 0)
2751 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2754 // now invert the sequence set, if required - empty selection implies
2755 // that no hiding is required.
2758 invertSequenceMenuItem_actionPerformed(null);
2759 sg = viewport.getSelectionGroup();
2763 viewport.expandColSelection(sg, true);
2764 // finally invert the column selection and get the new sequence
2766 invertColSel_actionPerformed(null);
2773 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
2775 hideSelSequences_actionPerformed(null);
2778 else if (!(toggleCols && viewport.getColumnSelection().getSelected()
2781 showAllSeqs_actionPerformed(null);
2787 if (viewport.getColumnSelection().getSelected().size() > 0)
2789 hideSelColumns_actionPerformed(null);
2792 viewport.setSelectionGroup(sg);
2797 showAllColumns_actionPerformed(null);
2806 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
2807 * event.ActionEvent)
2810 public void hideAllButSelection_actionPerformed(ActionEvent e)
2812 toggleHiddenRegions(false, false);
2819 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
2823 public void hideAllSelection_actionPerformed(ActionEvent e)
2825 SequenceGroup sg = viewport.getSelectionGroup();
2826 viewport.expandColSelection(sg, false);
2827 viewport.hideAllSelectedSeqs();
2828 viewport.hideSelectedColumns();
2829 alignPanel.paintAlignment(true);
2836 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
2840 public void showAllhidden_actionPerformed(ActionEvent e)
2842 viewport.showAllHiddenColumns();
2843 viewport.showAllHiddenSeqs();
2844 alignPanel.paintAlignment(true);
2848 public void hideSelColumns_actionPerformed(ActionEvent e)
2850 viewport.hideSelectedColumns();
2851 alignPanel.paintAlignment(true);
2855 public void hiddenMarkers_actionPerformed(ActionEvent e)
2857 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
2868 protected void scaleAbove_actionPerformed(ActionEvent e)
2870 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
2871 alignPanel.paintAlignment(true);
2881 protected void scaleLeft_actionPerformed(ActionEvent e)
2883 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
2884 alignPanel.paintAlignment(true);
2894 protected void scaleRight_actionPerformed(ActionEvent e)
2896 viewport.setScaleRightWrapped(scaleRight.isSelected());
2897 alignPanel.paintAlignment(true);
2907 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
2909 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
2910 alignPanel.paintAlignment(true);
2920 public void viewTextMenuItem_actionPerformed(ActionEvent e)
2922 viewport.setShowText(viewTextMenuItem.isSelected());
2923 alignPanel.paintAlignment(true);
2933 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
2935 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
2936 alignPanel.paintAlignment(true);
2939 public FeatureSettings featureSettings;
2942 public void featureSettings_actionPerformed(ActionEvent e)
2944 if (featureSettings != null)
2946 featureSettings.close();
2947 featureSettings = null;
2949 if (!showSeqFeatures.isSelected())
2951 // make sure features are actually displayed
2952 showSeqFeatures.setSelected(true);
2953 showSeqFeatures_actionPerformed(null);
2955 featureSettings = new FeatureSettings(this);
2959 * Set or clear 'Show Sequence Features'
2965 public void showSeqFeatures_actionPerformed(ActionEvent evt)
2967 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
2968 alignPanel.paintAlignment(true);
2969 if (alignPanel.getOverviewPanel() != null)
2971 alignPanel.getOverviewPanel().updateOverviewImage();
2976 * Set or clear 'Show Sequence Features'
2982 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
2984 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
2986 if (viewport.getShowSequenceFeaturesHeight())
2988 // ensure we're actually displaying features
2989 viewport.setShowSequenceFeatures(true);
2990 showSeqFeatures.setSelected(true);
2992 alignPanel.paintAlignment(true);
2993 if (alignPanel.getOverviewPanel() != null)
2995 alignPanel.getOverviewPanel().updateOverviewImage();
3006 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3008 viewport.setShowAnnotation(annotationPanelMenuItem.isSelected());
3009 alignPanel.setAnnotationVisible(annotationPanelMenuItem.isSelected());
3013 public void alignmentProperties()
3015 JEditorPane editPane = new JEditorPane("text/html", "");
3016 editPane.setEditable(false);
3017 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3019 editPane.setText(MessageManager.formatMessage("label.html_content", new String[]{contents.toString()}));
3020 JInternalFrame frame = new JInternalFrame();
3021 frame.getContentPane().add(new JScrollPane(editPane));
3023 Desktop.instance.addInternalFrame(frame, MessageManager.formatMessage("label.alignment_properties", new String[]{getTitle()}), 500, 400);
3033 public void overviewMenuItem_actionPerformed(ActionEvent e)
3035 if (alignPanel.overviewPanel != null)
3040 JInternalFrame frame = new JInternalFrame();
3041 OverviewPanel overview = new OverviewPanel(alignPanel);
3042 frame.setContentPane(overview);
3043 Desktop.addInternalFrame(frame, MessageManager.formatMessage("label.overview_params", new String[]{this.getTitle()}),
3044 frame.getWidth(), frame.getHeight());
3046 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3047 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3050 public void internalFrameClosed(
3051 javax.swing.event.InternalFrameEvent evt)
3053 alignPanel.setOverviewPanel(null);
3057 alignPanel.setOverviewPanel(overview);
3061 public void textColour_actionPerformed(ActionEvent e)
3063 new TextColourChooser().chooseColour(alignPanel, null);
3073 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3085 public void clustalColour_actionPerformed(ActionEvent e)
3087 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3088 viewport.getHiddenRepSequences()));
3098 public void zappoColour_actionPerformed(ActionEvent e)
3100 changeColour(new ZappoColourScheme());
3110 public void taylorColour_actionPerformed(ActionEvent e)
3112 changeColour(new TaylorColourScheme());
3122 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3124 changeColour(new HydrophobicColourScheme());
3134 public void helixColour_actionPerformed(ActionEvent e)
3136 changeColour(new HelixColourScheme());
3146 public void strandColour_actionPerformed(ActionEvent e)
3148 changeColour(new StrandColourScheme());
3158 public void turnColour_actionPerformed(ActionEvent e)
3160 changeColour(new TurnColourScheme());
3170 public void buriedColour_actionPerformed(ActionEvent e)
3172 changeColour(new BuriedColourScheme());
3182 public void nucleotideColour_actionPerformed(ActionEvent e)
3184 changeColour(new NucleotideColourScheme());
3188 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3190 changeColour(new PurinePyrimidineColourScheme());
3194 * public void covariationColour_actionPerformed(ActionEvent e) {
3196 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3200 public void annotationColour_actionPerformed(ActionEvent e)
3202 new AnnotationColourChooser(viewport, alignPanel);
3206 public void rnahelicesColour_actionPerformed(ActionEvent e)
3208 new RNAHelicesColourChooser(viewport, alignPanel);
3218 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3220 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3229 public void changeColour(ColourSchemeI cs)
3231 // TODO: compare with applet and pull up to model method
3236 if (viewport.getAbovePIDThreshold())
3238 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3240 cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3244 cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3247 if (viewport.getConservationSelected())
3250 Alignment al = (Alignment) viewport.getAlignment();
3251 Conservation c = new Conservation("All",
3252 ResidueProperties.propHash, 3, al.getSequences(), 0,
3256 c.verdict(false, viewport.getConsPercGaps());
3258 cs.setConservation(c);
3260 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3265 cs.setConservation(null);
3268 cs.setConsensus(viewport.getSequenceConsensusHash());
3271 viewport.setGlobalColourScheme(cs);
3273 if (viewport.getColourAppliesToAllGroups())
3276 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3284 if (cs instanceof ClustalxColourScheme)
3286 sg.cs = new ClustalxColourScheme(sg,
3287 viewport.getHiddenRepSequences());
3289 else if (cs instanceof UserColourScheme)
3291 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
3297 sg.cs = cs.getClass().newInstance();
3298 } catch (Exception ex)
3303 if (viewport.getAbovePIDThreshold()
3304 || cs instanceof PIDColourScheme
3305 || cs instanceof Blosum62ColourScheme)
3307 sg.cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3309 sg.cs.setConsensus(AAFrequency.calculate(
3310 sg.getSequences(viewport.getHiddenRepSequences()),
3311 sg.getStartRes(), sg.getEndRes() + 1));
3315 sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3318 if (viewport.getConservationSelected())
3320 Conservation c = new Conservation("Group",
3321 ResidueProperties.propHash, 3, sg.getSequences(viewport
3322 .getHiddenRepSequences()), sg.getStartRes(),
3323 sg.getEndRes() + 1);
3325 c.verdict(false, viewport.getConsPercGaps());
3326 sg.cs.setConservation(c);
3330 sg.cs.setConservation(null);
3335 if (alignPanel.getOverviewPanel() != null)
3337 alignPanel.getOverviewPanel().updateOverviewImage();
3340 alignPanel.paintAlignment(true);
3350 protected void modifyPID_actionPerformed(ActionEvent e)
3352 if (viewport.getAbovePIDThreshold()
3353 && viewport.getGlobalColourScheme() != null)
3355 SliderPanel.setPIDSliderSource(alignPanel,
3356 viewport.getGlobalColourScheme(), "Background");
3357 SliderPanel.showPIDSlider();
3368 protected void modifyConservation_actionPerformed(ActionEvent e)
3370 if (viewport.getConservationSelected()
3371 && viewport.getGlobalColourScheme() != null)
3373 SliderPanel.setConservationSlider(alignPanel,
3374 viewport.getGlobalColourScheme(), "Background");
3375 SliderPanel.showConservationSlider();
3386 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3388 viewport.setConservationSelected(conservationMenuItem.isSelected());
3390 viewport.setAbovePIDThreshold(false);
3391 abovePIDThreshold.setSelected(false);
3393 changeColour(viewport.getGlobalColourScheme());
3395 modifyConservation_actionPerformed(null);
3405 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3407 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3409 conservationMenuItem.setSelected(false);
3410 viewport.setConservationSelected(false);
3412 changeColour(viewport.getGlobalColourScheme());
3414 modifyPID_actionPerformed(null);
3424 public void userDefinedColour_actionPerformed(ActionEvent e)
3426 if (e.getActionCommand().equals(MessageManager.getString("action.user_defined")))
3428 new UserDefinedColours(alignPanel, null);
3432 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3433 .getUserColourSchemes().get(e.getActionCommand());
3439 public void updateUserColourMenu()
3442 Component[] menuItems = colourMenu.getMenuComponents();
3443 int i, iSize = menuItems.length;
3444 for (i = 0; i < iSize; i++)
3446 if (menuItems[i].getName() != null
3447 && menuItems[i].getName().equals("USER_DEFINED"))
3449 colourMenu.remove(menuItems[i]);
3453 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3455 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3456 .getUserColourSchemes().keys();
3458 while (userColours.hasMoreElements())
3460 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3461 userColours.nextElement().toString());
3462 radioItem.setName("USER_DEFINED");
3463 radioItem.addMouseListener(new MouseAdapter()
3466 public void mousePressed(MouseEvent evt)
3468 if (evt.isControlDown()
3469 || SwingUtilities.isRightMouseButton(evt))
3471 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3473 int option = JOptionPane.showInternalConfirmDialog(
3474 jalview.gui.Desktop.desktop,
3475 MessageManager.getString("label.remove_from_default_list"),
3476 MessageManager.getString("label.remove_user_defined_colour"),
3477 JOptionPane.YES_NO_OPTION);
3478 if (option == JOptionPane.YES_OPTION)
3480 jalview.gui.UserDefinedColours
3481 .removeColourFromDefaults(radioItem.getText());
3482 colourMenu.remove(radioItem);
3486 radioItem.addActionListener(new ActionListener()
3489 public void actionPerformed(ActionEvent evt)
3491 userDefinedColour_actionPerformed(evt);
3498 radioItem.addActionListener(new ActionListener()
3501 public void actionPerformed(ActionEvent evt)
3503 userDefinedColour_actionPerformed(evt);
3507 colourMenu.insert(radioItem, 15);
3508 colours.add(radioItem);
3520 public void PIDColour_actionPerformed(ActionEvent e)
3522 changeColour(new PIDColourScheme());
3532 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3534 changeColour(new Blosum62ColourScheme());
3544 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3546 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3547 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3548 .getAlignment().getSequenceAt(0), null);
3549 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3550 viewport.getAlignment()));
3551 alignPanel.paintAlignment(true);
3561 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3563 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3564 AlignmentSorter.sortByID(viewport.getAlignment());
3565 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3566 viewport.getAlignment()));
3567 alignPanel.paintAlignment(true);
3577 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3579 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3580 AlignmentSorter.sortByLength(viewport.getAlignment());
3581 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3582 viewport.getAlignment()));
3583 alignPanel.paintAlignment(true);
3593 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3595 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3596 AlignmentSorter.sortByGroup(viewport.getAlignment());
3597 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3598 viewport.getAlignment()));
3600 alignPanel.paintAlignment(true);
3610 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3612 new RedundancyPanel(alignPanel, this);
3622 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3624 if ((viewport.getSelectionGroup() == null)
3625 || (viewport.getSelectionGroup().getSize() < 2))
3627 JOptionPane.showInternalMessageDialog(this,
3628 MessageManager.getString("label.you_must_select_least_two_sequences"), MessageManager.getString("label.invalid_selection"),
3629 JOptionPane.WARNING_MESSAGE);
3633 JInternalFrame frame = new JInternalFrame();
3634 frame.setContentPane(new PairwiseAlignPanel(viewport));
3635 Desktop.addInternalFrame(frame, MessageManager.getString("action.pairwise_alignment"), 600, 500);
3646 public void PCAMenuItem_actionPerformed(ActionEvent e)
3648 if (((viewport.getSelectionGroup() != null)
3649 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3650 .getSelectionGroup().getSize() > 0))
3651 || (viewport.getAlignment().getHeight() < 4))
3653 JOptionPane.showInternalMessageDialog(this,
3654 MessageManager.getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3655 MessageManager.getString("label.sequence_selection_insufficient"),
3656 JOptionPane.WARNING_MESSAGE);
3661 new PCAPanel(alignPanel);
3665 public void autoCalculate_actionPerformed(ActionEvent e)
3667 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3668 if (viewport.autoCalculateConsensus)
3670 viewport.firePropertyChange("alignment", null, viewport
3671 .getAlignment().getSequences());
3676 public void sortByTreeOption_actionPerformed(ActionEvent e)
3678 viewport.sortByTree = sortByTree.isSelected();
3682 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3684 viewport.followSelection = listenToViewSelections.isSelected();
3694 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3696 NewTreePanel("AV", "PID", "Average distance tree using PID");
3706 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3708 NewTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3718 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3720 NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3730 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3732 NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3745 void NewTreePanel(String type, String pwType, String title)
3749 if (viewport.getSelectionGroup() != null
3750 && viewport.getSelectionGroup().getSize() > 0)
3752 if (viewport.getSelectionGroup().getSize() < 3)
3757 MessageManager.getString("label.you_need_more_two_sequences_selected_build_tree"),
3758 MessageManager.getString("label.not_enough_sequences"), JOptionPane.WARNING_MESSAGE);
3762 SequenceGroup sg = viewport.getSelectionGroup();
3764 /* Decide if the selection is a column region */
3765 for (SequenceI _s : sg.getSequences())
3767 if (_s.getLength() < sg.getEndRes())
3772 MessageManager.getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3773 MessageManager.getString("label.sequences_selection_not_aligned"),
3774 JOptionPane.WARNING_MESSAGE);
3780 title = title + " on region";
3781 tp = new TreePanel(alignPanel, type, pwType);
3785 // are the visible sequences aligned?
3786 if (!viewport.getAlignment().isAligned(false))
3791 MessageManager.getString("label.sequences_must_be_aligned_before_creating_tree"),
3792 MessageManager.getString("label.sequences_not_aligned"),
3793 JOptionPane.WARNING_MESSAGE);
3798 if (viewport.getAlignment().getHeight() < 2)
3803 tp = new TreePanel(alignPanel, type, pwType);
3808 if (viewport.viewName != null)
3810 title += viewport.viewName + " of ";
3813 title += this.title;
3815 Desktop.addInternalFrame(tp, title, 600, 500);
3826 public void addSortByOrderMenuItem(String title,
3827 final AlignmentOrder order)
3829 final JMenuItem item = new JMenuItem("by " + title);
3831 item.addActionListener(new java.awt.event.ActionListener()
3834 public void actionPerformed(ActionEvent e)
3836 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3838 // TODO: JBPNote - have to map order entries to curent SequenceI
3840 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3842 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
3845 alignPanel.paintAlignment(true);
3851 * Add a new sort by annotation score menu item
3854 * the menu to add the option to
3856 * the label used to retrieve scores for each sequence on the
3859 public void addSortByAnnotScoreMenuItem(JMenu sort,
3860 final String scoreLabel)
3862 final JMenuItem item = new JMenuItem(scoreLabel);
3864 item.addActionListener(new java.awt.event.ActionListener()
3867 public void actionPerformed(ActionEvent e)
3869 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3870 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3871 viewport.getAlignment());// ,viewport.getSelectionGroup());
3872 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3873 viewport.getAlignment()));
3874 alignPanel.paintAlignment(true);
3880 * last hash for alignment's annotation array - used to minimise cost of
3883 protected int _annotationScoreVectorHash;
3886 * search the alignment and rebuild the sort by annotation score submenu the
3887 * last alignment annotation vector hash is stored to minimize cost of
3888 * rebuilding in subsequence calls.
3892 public void buildSortByAnnotationScoresMenu()
3894 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3899 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
3901 sortByAnnotScore.removeAll();
3902 // almost certainly a quicker way to do this - but we keep it simple
3903 Hashtable scoreSorts = new Hashtable();
3904 AlignmentAnnotation aann[];
3905 for (SequenceI sqa : viewport.getAlignment().getSequences())
3907 aann = sqa.getAnnotation();
3908 for (int i = 0; aann != null && i < aann.length; i++)
3910 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3912 scoreSorts.put(aann[i].label, aann[i].label);
3916 Enumeration labels = scoreSorts.keys();
3917 while (labels.hasMoreElements())
3919 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3920 (String) labels.nextElement());
3922 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3925 _annotationScoreVectorHash = viewport.getAlignment()
3926 .getAlignmentAnnotation().hashCode();
3931 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3932 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3933 * call. Listeners are added to remove the menu item when the treePanel is
3934 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3938 * Displayed tree window.
3940 * SortBy menu item title.
3943 public void buildTreeMenu()
3945 calculateTree.removeAll();
3946 // build the calculate menu
3948 for (final String type:new String[] {"NJ", "AV"})
3950 String treecalcnm = MessageManager.getString("label.tree_calc_"+type.toLowerCase());
3951 for (final Object pwtype: ResidueProperties.scoreMatrices.keySet())
3953 JMenuItem tm = new JMenuItem();
3954 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
3955 if (sm.isProtein()==!viewport.getAlignment().isNucleotide())
3957 String smn = MessageManager.getStringOrReturn(
3958 "label.score_model_", sm.getName());
3959 final String title = MessageManager.formatMessage(
3960 "label.treecalc_title", treecalcnm, smn);
3961 tm.setText(title);//
3962 tm.addActionListener(new java.awt.event.ActionListener()
3964 public void actionPerformed(ActionEvent e)
3966 NewTreePanel(type, (String) pwtype, title);
3969 calculateTree.add(tm);
3974 sortByTreeMenu.removeAll();
3976 Vector comps = (Vector) PaintRefresher.components.get(viewport
3977 .getSequenceSetId());
3978 Vector treePanels = new Vector();
3979 int i, iSize = comps.size();
3980 for (i = 0; i < iSize; i++)
3982 if (comps.elementAt(i) instanceof TreePanel)
3984 treePanels.add(comps.elementAt(i));
3988 iSize = treePanels.size();
3992 sortByTreeMenu.setVisible(false);
3996 sortByTreeMenu.setVisible(true);
3998 for (i = 0; i < treePanels.size(); i++)
4000 final TreePanel tp = (TreePanel) treePanels.elementAt(i);
4001 final JMenuItem item = new JMenuItem(tp.getTitle());
4002 final NJTree tree = ((TreePanel) treePanels.elementAt(i)).getTree();
4003 item.addActionListener(new java.awt.event.ActionListener()
4006 public void actionPerformed(ActionEvent e)
4008 tp.sortByTree_actionPerformed(null);
4009 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4014 sortByTreeMenu.add(item);
4018 public boolean sortBy(AlignmentOrder alorder, String undoname)
4020 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4021 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4022 if (undoname != null)
4024 addHistoryItem(new OrderCommand(undoname, oldOrder,
4025 viewport.getAlignment()));
4027 alignPanel.paintAlignment(true);
4032 * Work out whether the whole set of sequences or just the selected set will
4033 * be submitted for multiple alignment.
4036 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4038 // Now, check we have enough sequences
4039 AlignmentView msa = null;
4041 if ((viewport.getSelectionGroup() != null)
4042 && (viewport.getSelectionGroup().getSize() > 1))
4044 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4045 // some common interface!
4047 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4048 * SequenceI[sz = seqs.getSize(false)];
4050 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4051 * seqs.getSequenceAt(i); }
4053 msa = viewport.getAlignmentView(true);
4058 * Vector seqs = viewport.getAlignment().getSequences();
4060 * if (seqs.size() > 1) { msa = new SequenceI[seqs.size()];
4062 * for (int i = 0; i < seqs.size(); i++) { msa[i] = (SequenceI)
4063 * seqs.elementAt(i); } }
4065 msa = viewport.getAlignmentView(false);
4071 * Decides what is submitted to a secondary structure prediction service: the
4072 * first sequence in the alignment, or in the current selection, or, if the
4073 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4074 * region or the whole alignment. (where the first sequence in the set is the
4075 * one that the prediction will be for).
4077 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4079 AlignmentView seqs = null;
4081 if ((viewport.getSelectionGroup() != null)
4082 && (viewport.getSelectionGroup().getSize() > 0))
4084 seqs = viewport.getAlignmentView(true);
4088 seqs = viewport.getAlignmentView(false);
4090 // limit sequences - JBPNote in future - could spawn multiple prediction
4092 // TODO: viewport.getAlignment().isAligned is a global state - the local
4093 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4094 if (!viewport.getAlignment().isAligned(false))
4096 seqs.setSequences(new SeqCigar[]
4097 { seqs.getSequences()[0] });
4098 // TODO: if seqs.getSequences().length>1 then should really have warned
4112 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
4114 // Pick the tree file
4115 JalviewFileChooser chooser = new JalviewFileChooser(
4116 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4117 chooser.setFileView(new JalviewFileView());
4118 chooser.setDialogTitle(MessageManager.getString("label.select_newick_like_tree_file"));
4119 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4121 int value = chooser.showOpenDialog(null);
4123 if (value == JalviewFileChooser.APPROVE_OPTION)
4125 String choice = chooser.getSelectedFile().getPath();
4126 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4127 jalview.io.NewickFile fin = null;
4130 fin = new jalview.io.NewickFile(choice, "File");
4131 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4132 } catch (Exception ex)
4134 JOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4135 MessageManager.getString("label.problem_reading_tree_file"), JOptionPane.WARNING_MESSAGE);
4136 ex.printStackTrace();
4138 if (fin != null && fin.hasWarningMessage())
4140 JOptionPane.showMessageDialog(Desktop.desktop,
4141 fin.getWarningMessage(), MessageManager.getString("label.possible_problem_with_tree_file"),
4142 JOptionPane.WARNING_MESSAGE);
4148 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4150 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4153 public TreePanel ShowNewickTree(NewickFile nf, String title)
4155 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4158 public TreePanel ShowNewickTree(NewickFile nf, String title,
4159 AlignmentView input)
4161 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4164 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4165 int h, int x, int y)
4167 return ShowNewickTree(nf, title, null, w, h, x, y);
4171 * Add a treeviewer for the tree extracted from a newick file object to the
4172 * current alignment view
4179 * Associated alignment input data (or null)
4188 * @return TreePanel handle
4190 public TreePanel ShowNewickTree(NewickFile nf, String title,
4191 AlignmentView input, int w, int h, int x, int y)
4193 TreePanel tp = null;
4199 if (nf.getTree() != null)
4201 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4207 tp.setLocation(x, y);
4210 Desktop.addInternalFrame(tp, title, w, h);
4212 } catch (Exception ex)
4214 ex.printStackTrace();
4220 private boolean buildingMenu = false;
4223 * Generates menu items and listener event actions for web service clients
4226 public void BuildWebServiceMenu()
4228 while (buildingMenu)
4232 System.err.println("Waiting for building menu to finish.");
4234 } catch (Exception e)
4239 final AlignFrame me = this;
4240 buildingMenu = true;
4241 new Thread(new Runnable()
4246 final List<JMenuItem> legacyItems=new ArrayList<JMenuItem>();
4249 System.err.println("Building ws menu again "
4250 + Thread.currentThread());
4251 // TODO: add support for context dependent disabling of services based
4253 // alignment and current selection
4254 // TODO: add additional serviceHandle parameter to specify abstract
4256 // class independently of AbstractName
4257 // TODO: add in rediscovery GUI function to restart discoverer
4258 // TODO: group services by location as well as function and/or
4260 // object broker mechanism.
4261 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4262 final IProgressIndicator af = me;
4263 final JMenu msawsmenu = new JMenu("Alignment");
4264 final JMenu secstrmenu = new JMenu(
4265 "Secondary Structure Prediction");
4266 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4267 final JMenu analymenu = new JMenu("Analysis");
4268 final JMenu dismenu = new JMenu("Protein Disorder");
4269 // JAL-940 - only show secondary structure prediction services from
4270 // the legacy server
4271 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4273 Discoverer.services != null && (Discoverer.services.size() > 0))
4275 // TODO: refactor to allow list of AbstractName/Handler bindings to
4277 // stored or retrieved from elsewhere
4278 // No MSAWS used any more:
4279 // Vector msaws = null; // (Vector) Discoverer.services.get("MsaWS");
4280 Vector secstrpr = (Vector) Discoverer.services
4282 if (secstrpr != null)
4284 // Add any secondary structure prediction services
4285 for (int i = 0, j = secstrpr.size(); i < j; i++)
4287 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4289 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4290 .getServiceClient(sh);
4291 int p=secstrmenu.getItemCount();
4292 impl.attachWSMenuEntry(secstrmenu, me);
4293 int q=secstrmenu.getItemCount();
4294 for (int litm=p;litm<q; litm++)
4296 legacyItems.add(secstrmenu.getItem(litm));
4302 // Add all submenus in the order they should appear on the web
4304 wsmenu.add(msawsmenu);
4305 wsmenu.add(secstrmenu);
4306 wsmenu.add(dismenu);
4307 wsmenu.add(analymenu);
4308 // No search services yet
4309 // wsmenu.add(seqsrchmenu);
4311 javax.swing.SwingUtilities.invokeLater(new Runnable()
4318 webService.removeAll();
4319 // first, add discovered services onto the webservices menu
4320 if (wsmenu.size() > 0)
4322 for (int i = 0, j = wsmenu.size(); i < j; i++)
4324 webService.add(wsmenu.get(i));
4329 webService.add(me.webServiceNoServices);
4331 // TODO: move into separate menu builder class.
4332 boolean new_sspred=false;
4333 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4335 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4336 if (jws2servs != null)
4338 if (jws2servs.hasServices())
4340 jws2servs.attachWSMenuEntry(webService, me);
4341 for (Jws2Instance sv:jws2servs.getServices()) {
4342 if (sv.description.toLowerCase().contains("jpred"))
4344 for (JMenuItem jmi:legacyItems)
4346 jmi.setVisible(false);
4352 if (jws2servs.isRunning())
4354 JMenuItem tm = new JMenuItem(
4355 "Still discovering JABA Services");
4356 tm.setEnabled(false);
4361 build_urlServiceMenu(me.webService);
4362 build_fetchdbmenu(webService);
4363 for (JMenu item : wsmenu)
4365 if (item.getItemCount() == 0)
4367 item.setEnabled(false);
4371 item.setEnabled(true);
4374 } catch (Exception e)
4377 .debug("Exception during web service menu building process.",
4383 } catch (Exception e)
4388 buildingMenu = false;
4395 * construct any groupURL type service menu entries.
4399 private void build_urlServiceMenu(JMenu webService)
4401 // TODO: remove this code when 2.7 is released
4402 // DEBUG - alignmentView
4404 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4405 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4407 * @Override public void actionPerformed(ActionEvent e) {
4408 * jalview.datamodel.AlignmentView
4409 * .testSelectionViews(af.viewport.getAlignment(),
4410 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4412 * }); webService.add(testAlView);
4414 // TODO: refactor to RestClient discoverer and merge menu entries for
4415 // rest-style services with other types of analysis/calculation service
4416 // SHmmr test client - still being implemented.
4417 // DEBUG - alignmentView
4419 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4422 client.attachWSMenuEntry(
4423 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4429 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
4430 * chooser = new JalviewFileChooser(jalview.bin.Cache.
4431 * getProperty("LAST_DIRECTORY"));
4433 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
4434 * to Vamsas file"); chooser.setToolTipText("Export");
4436 * int value = chooser.showSaveDialog(this);
4438 * if (value == JalviewFileChooser.APPROVE_OPTION) {
4439 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
4440 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
4441 * chooser.getSelectedFile().getAbsolutePath(), this); } }
4444 * prototype of an automatically enabled/disabled analysis function
4447 protected void setShowProductsEnabled()
4449 SequenceI[] selection = viewport.getSequenceSelection();
4450 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
4451 viewport.getAlignment().getDataset()))
4453 showProducts.setEnabled(true);
4458 showProducts.setEnabled(false);
4463 * search selection for sequence xRef products and build the show products
4468 * @return true if showProducts menu should be enabled.
4470 public boolean canShowProducts(SequenceI[] selection,
4471 boolean isRegionSelection, Alignment dataset)
4473 boolean showp = false;
4476 showProducts.removeAll();
4477 final boolean dna = viewport.getAlignment().isNucleotide();
4478 final Alignment ds = dataset;
4479 String[] ptypes = (selection == null || selection.length == 0) ? null
4480 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4482 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4483 // selection, dataset, true);
4484 final SequenceI[] sel = selection;
4485 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4488 final boolean isRegSel = isRegionSelection;
4489 final AlignFrame af = this;
4490 final String source = ptypes[t];
4491 JMenuItem xtype = new JMenuItem(ptypes[t]);
4492 xtype.addActionListener(new ActionListener()
4496 public void actionPerformed(ActionEvent e)
4498 // TODO: new thread for this call with vis-delay
4499 af.showProductsFor(af.viewport.getSequenceSelection(), ds,
4500 isRegSel, dna, source);
4504 showProducts.add(xtype);
4506 showProducts.setVisible(showp);
4507 showProducts.setEnabled(showp);
4508 } catch (Exception e)
4510 jalview.bin.Cache.log
4511 .warn("canTranslate threw an exception - please report to help@jalview.org",
4518 protected void showProductsFor(SequenceI[] sel, Alignment ds,
4519 boolean isRegSel, boolean dna, String source)
4521 final boolean fisRegSel = isRegSel;
4522 final boolean fdna = dna;
4523 final String fsrc = source;
4524 final AlignFrame ths = this;
4525 final SequenceI[] fsel = sel;
4526 Runnable foo = new Runnable()
4532 final long sttime = System.currentTimeMillis();
4533 ths.setProgressBar("Searching for sequences from " + fsrc, sttime);
4536 Alignment ds = ths.getViewport().getAlignment().getDataset(); // update
4540 Alignment prods = CrossRef
4541 .findXrefSequences(fsel, fdna, fsrc, ds);
4544 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4545 for (int s = 0; s < sprods.length; s++)
4547 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4548 if (ds.getSequences() == null
4549 || !ds.getSequences().contains(
4550 sprods[s].getDatasetSequence()))
4551 ds.addSequence(sprods[s].getDatasetSequence());
4552 sprods[s].updatePDBIds();
4554 Alignment al = new Alignment(sprods);
4555 AlignedCodonFrame[] cf = prods.getCodonFrames();
4557 for (int s = 0; cf != null && s < cf.length; s++)
4559 al.addCodonFrame(cf[s]);
4562 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4564 String newtitle = "" + ((fdna) ? "Proteins " : "Nucleotides ")
4565 + " for " + ((fisRegSel) ? "selected region of " : "")
4567 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4572 System.err.println("No Sequences generated for xRef type "
4575 } catch (Exception e)
4577 jalview.bin.Cache.log.error(
4578 "Exception when finding crossreferences", e);
4579 } catch (OutOfMemoryError e)
4581 new OOMWarning("whilst fetching crossreferences", e);
4584 jalview.bin.Cache.log.error("Error when finding crossreferences",
4587 ths.setProgressBar("Finished searching for sequences from " + fsrc,
4592 Thread frunner = new Thread(foo);
4596 public boolean canShowTranslationProducts(SequenceI[] selection,
4597 AlignmentI alignment)
4602 return (jalview.analysis.Dna.canTranslate(selection,
4603 viewport.getViewAsVisibleContigs(true)));
4604 } catch (Exception e)
4606 jalview.bin.Cache.log
4607 .warn("canTranslate threw an exception - please report to help@jalview.org",
4614 public void showProducts_actionPerformed(ActionEvent e)
4616 // /////////////////////////////
4617 // Collect Data to be translated/transferred
4619 SequenceI[] selection = viewport.getSequenceSelection();
4620 AlignmentI al = null;
4623 al = jalview.analysis.Dna.CdnaTranslate(selection, viewport
4624 .getViewAsVisibleContigs(true), viewport.getGapCharacter(),
4625 viewport.getAlignment().getDataset());
4626 } catch (Exception ex)
4629 jalview.bin.Cache.log.debug("Exception during translation.", ex);
4636 MessageManager.getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation"),
4637 MessageManager.getString("label.translation_failed"), JOptionPane.WARNING_MESSAGE);
4641 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4642 Desktop.addInternalFrame(af, MessageManager.formatMessage("label.translation_of_params", new String[]{this.getTitle()}),
4643 DEFAULT_WIDTH, DEFAULT_HEIGHT);
4648 public void showTranslation_actionPerformed(ActionEvent e)
4650 // /////////////////////////////
4651 // Collect Data to be translated/transferred
4653 SequenceI[] selection = viewport.getSequenceSelection();
4654 String[] seqstring = viewport.getViewAsString(true);
4655 AlignmentI al = null;
4658 al = jalview.analysis.Dna.CdnaTranslate(selection, seqstring,
4659 viewport.getViewAsVisibleContigs(true), viewport
4660 .getGapCharacter(), viewport.getAlignment()
4661 .getAlignmentAnnotation(), viewport.getAlignment()
4662 .getWidth(), viewport.getAlignment().getDataset());
4663 } catch (Exception ex)
4666 jalview.bin.Cache.log.error("Exception during translation. Please report this !", ex);
4670 MessageManager.getString("label.error_when_translating_sequences_submit_bug_report"),
4671 MessageManager.getString("label.implementation_error") + MessageManager.getString("translation_failed"), JOptionPane.ERROR_MESSAGE);
4679 MessageManager.getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation"),
4680 MessageManager.getString("label.translation_failed"), JOptionPane.WARNING_MESSAGE);
4684 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4685 Desktop.addInternalFrame(af, MessageManager.formatMessage("label.translation_of_params", new String[]{this.getTitle()}),
4686 DEFAULT_WIDTH, DEFAULT_HEIGHT);
4691 * Try to load a features file onto the alignment.
4694 * contents or path to retrieve file
4696 * access mode of file (see jalview.io.AlignFile)
4697 * @return true if features file was parsed corectly.
4699 public boolean parseFeaturesFile(String file, String type)
4701 boolean featuresFile = false;
4704 featuresFile = new FeaturesFile(file, type).parse(viewport
4705 .getAlignment().getDataset(), alignPanel.seqPanel.seqCanvas
4706 .getFeatureRenderer().featureColours, false,
4707 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4708 } catch (Exception ex)
4710 ex.printStackTrace();
4715 viewport.showSequenceFeatures = true;
4716 showSeqFeatures.setSelected(true);
4717 if (alignPanel.seqPanel.seqCanvas.fr != null)
4719 // update the min/max ranges where necessary
4720 alignPanel.seqPanel.seqCanvas.fr.findAllFeatures(true);
4722 if (featureSettings != null)
4724 featureSettings.setTableData();
4726 alignPanel.paintAlignment(true);
4729 return featuresFile;
4733 public void dragEnter(DropTargetDragEvent evt)
4738 public void dragExit(DropTargetEvent evt)
4743 public void dragOver(DropTargetDragEvent evt)
4748 public void dropActionChanged(DropTargetDragEvent evt)
4753 public void drop(DropTargetDropEvent evt)
4755 Transferable t = evt.getTransferable();
4756 java.util.List files = null;
4760 DataFlavor uriListFlavor = new DataFlavor(
4761 "text/uri-list;class=java.lang.String");
4762 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
4764 // Works on Windows and MacOSX
4765 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4766 files = (java.util.List) t
4767 .getTransferData(DataFlavor.javaFileListFlavor);
4769 else if (t.isDataFlavorSupported(uriListFlavor))
4771 // This is used by Unix drag system
4772 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4773 String data = (String) t.getTransferData(uriListFlavor);
4774 files = new java.util.ArrayList(1);
4775 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
4776 data, "\r\n"); st.hasMoreTokens();)
4778 String s = st.nextToken();
4779 if (s.startsWith("#"))
4781 // the line is a comment (as per the RFC 2483)
4785 java.net.URI uri = new java.net.URI(s);
4786 // check to see if we can handle this kind of URI
4787 if (uri.getScheme().toLowerCase().startsWith("http"))
4789 files.add(uri.toString());
4793 // otherwise preserve old behaviour: catch all for file objects
4794 java.io.File file = new java.io.File(uri);
4795 files.add(file.toString());
4799 } catch (Exception e)
4801 e.printStackTrace();
4807 // check to see if any of these files have names matching sequences in
4809 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4810 .getAlignment().getSequencesArray());
4812 * Object[] { String,SequenceI}
4814 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
4815 ArrayList<String> filesnotmatched = new ArrayList<String>();
4816 for (int i = 0; i < files.size(); i++)
4818 String file = files.get(i).toString();
4820 String protocol = FormatAdapter.checkProtocol(file);
4821 if (protocol == jalview.io.FormatAdapter.FILE)
4823 File fl = new File(file);
4824 pdbfn = fl.getName();
4826 else if (protocol == jalview.io.FormatAdapter.URL)
4828 URL url = new URL(file);
4829 pdbfn = url.getFile();
4831 if (pdbfn.length() > 0)
4833 // attempt to find a match in the alignment
4834 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4835 int l = 0, c = pdbfn.indexOf(".");
4836 while (mtch == null && c != -1)
4841 } while ((c = pdbfn.indexOf(".", l)) > l);
4844 pdbfn = pdbfn.substring(0, l);
4846 mtch = idm.findAllIdMatches(pdbfn);
4853 type = new IdentifyFile().Identify(file, protocol);
4854 } catch (Exception ex)
4860 if (type.equalsIgnoreCase("PDB"))
4862 filesmatched.add(new Object[]
4863 { file, protocol, mtch });
4868 // File wasn't named like one of the sequences or wasn't a PDB file.
4869 filesnotmatched.add(file);
4873 if (filesmatched.size() > 0)
4875 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4879 MessageManager.formatMessage("label.automatically_associate_pdb_files_with_sequences_same_name",
4880 new String[]{Integer.valueOf(filesmatched.size()).toString()}),
4881 MessageManager.getString("label.automatically_associate_pdb_files_by_name"),
4882 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
4885 for (Object[] fm : filesmatched)
4887 // try and associate
4888 // TODO: may want to set a standard ID naming formalism for
4889 // associating PDB files which have no IDs.
4890 for (SequenceI toassoc : (SequenceI[]) fm[2])
4892 PDBEntry pe = new AssociatePdbFileWithSeq()
4893 .associatePdbWithSeq((String) fm[0],
4894 (String) fm[1], toassoc, false);
4897 System.err.println("Associated file : "
4898 + ((String) fm[0]) + " with "
4899 + toassoc.getDisplayId(true));
4903 alignPanel.paintAlignment(true);
4907 if (filesnotmatched.size() > 0)
4910 && (Cache.getDefault(
4911 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
4914 MessageManager.formatMessage("label.ignore_unmatched_dropped_files_info", new String[]{Integer.valueOf(filesnotmatched.size()).toString()}),
4915 MessageManager.getString("label.ignore_unmatched_dropped_files"),
4916 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
4920 for (String fn : filesnotmatched)
4922 loadJalviewDataFile(fn, null, null, null);
4926 } catch (Exception ex)
4928 ex.printStackTrace();
4934 * Attempt to load a "dropped" file or URL string: First by testing whether
4935 * it's and Annotation file, then a JNet file, and finally a features file. If
4936 * all are false then the user may have dropped an alignment file onto this
4940 * either a filename or a URL string.
4942 public void loadJalviewDataFile(String file, String protocol,
4943 String format, SequenceI assocSeq)
4947 if (protocol == null)
4949 protocol = jalview.io.FormatAdapter.checkProtocol(file);
4951 // if the file isn't identified, or not positively identified as some
4952 // other filetype (PFAM is default unidentified alignment file type) then
4953 // try to parse as annotation.
4954 boolean isAnnotation = (format == null || format
4955 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
4956 .readAnnotationFile(viewport.getAlignment(), file, protocol)
4961 // first see if its a T-COFFEE score file
4962 TCoffeeScoreFile tcf = null;
4965 tcf = new TCoffeeScoreFile(file, protocol);
4968 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4970 tcoffeeColour.setEnabled(true);
4971 tcoffeeColour.setSelected(true);
4972 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
4973 isAnnotation = true;
4974 statusBar.setText(MessageManager.getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
4978 // some problem - if no warning its probable that the ID matching
4979 // process didn't work
4983 tcf.getWarningMessage() == null ? MessageManager.getString("label.check_file_matches_sequence_ids_alignment")
4984 : tcf.getWarningMessage(),
4985 MessageManager.getString("label.problem_reading_tcoffee_score_file"),
4986 JOptionPane.WARNING_MESSAGE);
4993 } catch (Exception x)
4996 .debug("Exception when processing data source as T-COFFEE score file",
5002 // try to see if its a JNet 'concise' style annotation file *before*
5004 // try to parse it as a features file
5007 format = new IdentifyFile().Identify(file, protocol);
5009 if (format.equalsIgnoreCase("JnetFile"))
5011 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5013 new JnetAnnotationMaker().add_annotation(predictions,
5014 viewport.getAlignment(), 0, false);
5015 isAnnotation = true;
5020 * if (format.equalsIgnoreCase("PDB")) {
5022 * String pdbfn = ""; // try to match up filename with sequence id
5023 * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
5024 * new File(file); pdbfn = fl.getName(); } else if (protocol ==
5025 * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
5026 * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
5027 * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5028 * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
5029 * // attempt to find a match in the alignment SequenceI mtch =
5030 * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
5031 * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
5032 * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
5033 * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
5034 * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
5035 * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
5036 * { System.err.println("Associated file : " + file + " with " +
5037 * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
5038 * TODO: maybe need to load as normal otherwise return; } }
5040 // try to parse it as a features file
5041 boolean isGroupsFile = parseFeaturesFile(file, protocol);
5042 // if it wasn't a features file then we just treat it as a general
5043 // alignment file to load into the current view.
5046 new FileLoader().LoadFile(viewport, file, protocol, format);
5050 alignPanel.paintAlignment(true);
5058 alignPanel.adjustAnnotationHeight();
5059 viewport.updateSequenceIdColours();
5060 buildSortByAnnotationScoresMenu();
5061 alignPanel.paintAlignment(true);
5063 } catch (Exception ex)
5065 ex.printStackTrace();
5066 } catch (OutOfMemoryError oom)
5071 } catch (Exception x)
5077 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5078 : "using " + protocol + " from " + file)
5080 + (format != null ? "(parsing as '" + format
5081 + "' file)" : ""), oom, Desktop.desktop);
5086 public void tabSelectionChanged(int index)
5090 alignPanel = (AlignmentPanel) alignPanels.elementAt(index);
5091 viewport = alignPanel.av;
5092 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5093 setMenusFromViewport(viewport);
5098 public void tabbedPane_mousePressed(MouseEvent e)
5100 if (SwingUtilities.isRightMouseButton(e))
5102 String reply = JOptionPane.showInternalInputDialog(this,
5103 MessageManager.getString("label.enter_view_name"), MessageManager.getString("label.enter_view_name"),
5104 JOptionPane.QUESTION_MESSAGE);
5108 viewport.viewName = reply;
5109 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5114 public AlignViewport getCurrentView()
5120 * Open the dialog for regex description parsing.
5123 protected void extractScores_actionPerformed(ActionEvent e)
5125 ParseProperties pp = new jalview.analysis.ParseProperties(
5126 viewport.getAlignment());
5127 // TODO: verify regex and introduce GUI dialog for version 2.5
5128 // if (pp.getScoresFromDescription("col", "score column ",
5129 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5131 if (pp.getScoresFromDescription("description column",
5132 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5134 buildSortByAnnotationScoresMenu();
5142 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5146 protected void showDbRefs_actionPerformed(ActionEvent e)
5148 viewport.setShowDbRefs(showDbRefsMenuitem.isSelected());
5154 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5158 protected void showNpFeats_actionPerformed(ActionEvent e)
5160 viewport.setShowNpFeats(showNpFeatsMenuitem.isSelected());
5164 * find the viewport amongst the tabs in this alignment frame and close that
5169 public boolean closeView(AlignViewport av)
5173 this.closeMenuItem_actionPerformed(false);
5176 Component[] comp = tabbedPane.getComponents();
5177 for (int i = 0; comp != null && i < comp.length; i++)
5179 if (comp[i] instanceof AlignmentPanel)
5181 if (((AlignmentPanel) comp[i]).av == av)
5184 closeView((AlignmentPanel) comp[i]);
5192 protected void build_fetchdbmenu(JMenu webService)
5194 // Temporary hack - DBRef Fetcher always top level ws entry.
5195 // TODO We probably want to store a sequence database checklist in
5196 // preferences and have checkboxes.. rather than individual sources selected
5198 final JMenu rfetch = new JMenu(MessageManager.getString("action.fetch_db_references"));
5199 rfetch.setToolTipText(MessageManager.getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5200 webService.add(rfetch);
5202 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(MessageManager.getString("option.trim_retrieved_seqs"));
5203 trimrs.setToolTipText(MessageManager.getString("label.trim_retrieved_sequences"));
5204 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5205 trimrs.addActionListener(new ActionListener()
5207 public void actionPerformed(ActionEvent e) {
5208 trimrs.setSelected(trimrs.isSelected());
5209 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS", Boolean.valueOf(trimrs.isSelected()).toString());
5213 JMenuItem fetchr = new JMenuItem(MessageManager.getString("label.standard_databases"));
5214 fetchr.setToolTipText(MessageManager.getString("label.fetch_embl_uniprot"));
5215 fetchr.addActionListener(new ActionListener()
5219 public void actionPerformed(ActionEvent e)
5221 new Thread(new Runnable()
5227 new jalview.ws.DBRefFetcher(alignPanel.av
5228 .getSequenceSelection(), alignPanel.alignFrame)
5229 .fetchDBRefs(false);
5237 final AlignFrame me = this;
5238 new Thread(new Runnable()
5243 final jalview.ws.SequenceFetcher sf = SequenceFetcher
5244 .getSequenceFetcherSingleton(me);
5245 javax.swing.SwingUtilities.invokeLater(new Runnable()
5250 String[] dbclasses = sf.getOrderedSupportedSources();
5251 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5252 // jalview.util.QuickSort.sort(otherdb, otherdb);
5253 List<DbSourceProxy> otherdb;
5254 JMenu dfetch = new JMenu();
5255 JMenu ifetch = new JMenu();
5256 JMenuItem fetchr = null;
5257 int comp = 0, icomp = 0, mcomp = 15;
5258 String mname = null;
5260 for (String dbclass : dbclasses)
5262 otherdb = sf.getSourceProxy(dbclass);
5263 // add a single entry for this class, or submenu allowing 'fetch
5265 if (otherdb == null || otherdb.size() < 1)
5269 // List<DbSourceProxy> dbs=otherdb;
5270 // otherdb=new ArrayList<DbSourceProxy>();
5271 // for (DbSourceProxy db:dbs)
5273 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5277 mname = "From " + dbclass;
5279 if (otherdb.size() == 1)
5281 final DbSourceProxy[] dassource = otherdb
5282 .toArray(new DbSourceProxy[0]);
5283 DbSourceProxy src = otherdb.get(0);
5284 fetchr = new JMenuItem(src.getDbSource());
5285 fetchr.addActionListener(new ActionListener()
5289 public void actionPerformed(ActionEvent e)
5291 new Thread(new Runnable()
5297 new jalview.ws.DBRefFetcher(alignPanel.av
5298 .getSequenceSelection(),
5299 alignPanel.alignFrame, dassource)
5300 .fetchDBRefs(false);
5306 fetchr.setToolTipText("<html>"
5307 + JvSwingUtils.wrapTooltip("Retrieve from "
5308 + src.getDbName()) + "<html>");
5314 final DbSourceProxy[] dassource = otherdb
5315 .toArray(new DbSourceProxy[0]);
5317 DbSourceProxy src = otherdb.get(0);
5318 fetchr = new JMenuItem(MessageManager.formatMessage("label.fetch_all_param", new String[]{src.getDbSource()}));
5319 fetchr.addActionListener(new ActionListener()
5322 public void actionPerformed(ActionEvent e)
5324 new Thread(new Runnable()
5330 new jalview.ws.DBRefFetcher(alignPanel.av
5331 .getSequenceSelection(),
5332 alignPanel.alignFrame, dassource)
5333 .fetchDBRefs(false);
5339 fetchr.setToolTipText("<html>"
5340 + JvSwingUtils.wrapTooltip("Retrieve from all "
5341 + otherdb.size() + " sources in "
5342 + src.getDbSource() + "<br>First is :"
5343 + src.getDbName()) + "<html>");
5346 // and then build the rest of the individual menus
5347 ifetch = new JMenu("Sources from " + src.getDbSource());
5349 String imname = null;
5351 for (DbSourceProxy sproxy : otherdb)
5353 String dbname = sproxy.getDbName();
5354 String sname = dbname.length() > 5 ? dbname.substring(0,
5355 5) + "..." : dbname;
5356 String msname = dbname.length() > 10 ? dbname.substring(
5357 0, 10) + "..." : dbname;
5360 imname = "from '" + sname + "'";
5362 fetchr = new JMenuItem(msname);
5363 final DbSourceProxy[] dassrc =
5365 fetchr.addActionListener(new ActionListener()
5369 public void actionPerformed(ActionEvent e)
5371 new Thread(new Runnable()
5377 new jalview.ws.DBRefFetcher(alignPanel.av
5378 .getSequenceSelection(),
5379 alignPanel.alignFrame, dassrc)
5380 .fetchDBRefs(false);
5386 fetchr.setToolTipText("<html>"
5387 + JvSwingUtils.wrapTooltip("Retrieve from "
5388 + dbname) + "</html>");
5391 if (++icomp >= mcomp || i == (otherdb.size()))
5393 ifetch.setText(MessageManager.formatMessage("label.source_to_target",imname,sname));
5395 ifetch = new JMenu();
5403 if (comp >= mcomp || dbi >= (dbclasses.length))
5405 dfetch.setText(MessageManager.formatMessage("label.source_to_target",mname,dbclass));
5407 dfetch = new JMenu();
5420 * Left justify the whole alignment.
5423 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5425 AlignmentI al = viewport.getAlignment();
5427 viewport.firePropertyChange("alignment", null, al);
5431 * Right justify the whole alignment.
5434 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5436 AlignmentI al = viewport.getAlignment();
5438 viewport.firePropertyChange("alignment", null, al);
5441 public void setShowSeqFeatures(boolean b)
5443 showSeqFeatures.setSelected(true);
5444 viewport.setShowSequenceFeatures(true);
5451 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5452 * awt.event.ActionEvent)
5455 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5457 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5458 alignPanel.paintAlignment(true);
5465 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5469 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5471 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5472 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5480 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5481 * .event.ActionEvent)
5484 protected void showGroupConservation_actionPerformed(ActionEvent e)
5486 viewport.setShowGroupConservation(showGroupConservation.getState());
5487 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5494 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5495 * .event.ActionEvent)
5498 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5500 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5501 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5508 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5509 * .event.ActionEvent)
5512 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5514 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5515 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5519 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5521 showSequenceLogo.setState(true);
5522 viewport.setShowSequenceLogo(true);
5523 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5524 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5528 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5530 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5537 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5538 * .event.ActionEvent)
5541 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5543 if (avc.makeGroupsFromSelection()) {
5544 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5545 alignPanel.updateAnnotation();
5546 alignPanel.paintAlignment(true);
5551 protected void createGroup_actionPerformed(ActionEvent e)
5553 if (avc.createGroup())
5555 alignPanel.alignmentChanged();
5560 protected void unGroup_actionPerformed(ActionEvent e)
5564 alignPanel.alignmentChanged();
5569 * make the given alignmentPanel the currently selected tab
5571 * @param alignmentPanel
5573 public void setDisplayedView(AlignmentPanel alignmentPanel)
5575 if (!viewport.getSequenceSetId().equals(
5576 alignmentPanel.av.getSequenceSetId()))
5579 "Implementation error: cannot show a view from another alignment in an AlignFrame.");
5581 if (tabbedPane != null
5582 & alignPanels.indexOf(alignmentPanel) != tabbedPane
5583 .getSelectedIndex())
5585 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5590 class PrintThread extends Thread
5594 public PrintThread(AlignmentPanel ap)
5599 static PageFormat pf;
5604 PrinterJob printJob = PrinterJob.getPrinterJob();
5608 printJob.setPrintable(ap, pf);
5612 printJob.setPrintable(ap);
5615 if (printJob.printDialog())
5620 } catch (Exception PrintException)
5622 PrintException.printStackTrace();