2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.0b1)
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 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
17 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 import jalview.analysis.AAFrequency;
22 import jalview.analysis.AlignmentSorter;
23 import jalview.analysis.Conservation;
24 import jalview.analysis.CrossRef;
25 import jalview.analysis.NJTree;
26 import jalview.analysis.ParseProperties;
27 import jalview.analysis.SequenceIdMatcher;
28 import jalview.api.AlignViewControllerGuiI;
29 import jalview.api.AlignViewControllerI;
30 import jalview.api.analysis.ScoreModelI;
31 import jalview.bin.Cache;
32 import jalview.commands.CommandI;
33 import jalview.commands.EditCommand;
34 import jalview.commands.OrderCommand;
35 import jalview.commands.RemoveGapColCommand;
36 import jalview.commands.RemoveGapsCommand;
37 import jalview.commands.SlideSequencesCommand;
38 import jalview.commands.TrimRegionCommand;
39 import jalview.datamodel.AlignedCodonFrame;
40 import jalview.datamodel.Alignment;
41 import jalview.datamodel.AlignmentAnnotation;
42 import jalview.datamodel.AlignmentI;
43 import jalview.datamodel.AlignmentOrder;
44 import jalview.datamodel.AlignmentView;
45 import jalview.datamodel.ColumnSelection;
46 import jalview.datamodel.PDBEntry;
47 import jalview.datamodel.SeqCigar;
48 import jalview.datamodel.Sequence;
49 import jalview.datamodel.SequenceGroup;
50 import jalview.datamodel.SequenceI;
51 import jalview.io.AlignmentProperties;
52 import jalview.io.AnnotationFile;
53 import jalview.io.FeaturesFile;
54 import jalview.io.FileLoader;
55 import jalview.io.FormatAdapter;
56 import jalview.io.HTMLOutput;
57 import jalview.io.IdentifyFile;
58 import jalview.io.JalviewFileChooser;
59 import jalview.io.JalviewFileView;
60 import jalview.io.JnetAnnotationMaker;
61 import jalview.io.NewickFile;
62 import jalview.io.TCoffeeScoreFile;
63 import jalview.jbgui.GAlignFrame;
64 import jalview.schemes.Blosum62ColourScheme;
65 import jalview.schemes.BuriedColourScheme;
66 import jalview.schemes.ClustalxColourScheme;
67 import jalview.schemes.ColourSchemeI;
68 import jalview.schemes.ColourSchemeProperty;
69 import jalview.schemes.HelixColourScheme;
70 import jalview.schemes.HydrophobicColourScheme;
71 import jalview.schemes.NucleotideColourScheme;
72 import jalview.schemes.PIDColourScheme;
73 import jalview.schemes.PurinePyrimidineColourScheme;
74 import jalview.schemes.RNAHelicesColourChooser;
75 import jalview.schemes.ResidueProperties;
76 import jalview.schemes.ScoreMatrix;
77 import jalview.schemes.StrandColourScheme;
78 import jalview.schemes.TCoffeeColourScheme;
79 import jalview.schemes.TaylorColourScheme;
80 import jalview.schemes.TurnColourScheme;
81 import jalview.schemes.UserColourScheme;
82 import jalview.schemes.ZappoColourScheme;
83 import jalview.util.MessageManager;
84 import jalview.ws.jws1.Discoverer;
85 import jalview.ws.jws2.Jws2Discoverer;
86 import jalview.ws.jws2.jabaws2.Jws2Instance;
87 import jalview.ws.seqfetcher.DbSourceProxy;
89 import java.awt.BorderLayout;
90 import java.awt.Color;
91 import java.awt.Component;
92 import java.awt.GridLayout;
93 import java.awt.Rectangle;
94 import java.awt.Toolkit;
95 import java.awt.datatransfer.Clipboard;
96 import java.awt.datatransfer.DataFlavor;
97 import java.awt.datatransfer.StringSelection;
98 import java.awt.datatransfer.Transferable;
99 import java.awt.dnd.DnDConstants;
100 import java.awt.dnd.DropTargetDragEvent;
101 import java.awt.dnd.DropTargetDropEvent;
102 import java.awt.dnd.DropTargetEvent;
103 import java.awt.dnd.DropTargetListener;
104 import java.awt.event.ActionEvent;
105 import java.awt.event.ActionListener;
106 import java.awt.event.KeyAdapter;
107 import java.awt.event.KeyEvent;
108 import java.awt.event.MouseAdapter;
109 import java.awt.event.MouseEvent;
110 import java.awt.print.PageFormat;
111 import java.awt.print.PrinterJob;
112 import java.beans.PropertyChangeEvent;
115 import java.util.ArrayList;
116 import java.util.Enumeration;
117 import java.util.Hashtable;
118 import java.util.List;
119 import java.util.Vector;
121 import javax.swing.JButton;
122 import javax.swing.JEditorPane;
123 import javax.swing.JInternalFrame;
124 import javax.swing.JLabel;
125 import javax.swing.JLayeredPane;
126 import javax.swing.JMenu;
127 import javax.swing.JMenuItem;
128 import javax.swing.JOptionPane;
129 import javax.swing.JPanel;
130 import javax.swing.JProgressBar;
131 import javax.swing.JRadioButtonMenuItem;
132 import javax.swing.JScrollPane;
133 import javax.swing.SwingUtilities;
139 * @version $Revision$
141 public class AlignFrame extends GAlignFrame implements DropTargetListener,
142 IProgressIndicator, AlignViewControllerGuiI
146 public static final int DEFAULT_WIDTH = 700;
149 public static final int DEFAULT_HEIGHT = 500;
151 public AlignmentPanel alignPanel;
153 AlignViewport viewport;
155 public AlignViewControllerI avc;
158 Vector alignPanels = new Vector();
161 * Last format used to load or save alignments in this window
163 String currentFileFormat = null;
166 * Current filename for this alignment
168 String fileName = null;
171 * Creates a new AlignFrame object with specific width and height.
177 public AlignFrame(AlignmentI al, int width, int height)
179 this(al, null, width, height);
183 * Creates a new AlignFrame object with specific width, height and
189 * @param sequenceSetId
191 public AlignFrame(AlignmentI al, int width, int height,
192 String sequenceSetId)
194 this(al, null, width, height, sequenceSetId);
198 * Creates a new AlignFrame object with specific width, height and
204 * @param sequenceSetId
207 public AlignFrame(AlignmentI al, int width, int height,
208 String sequenceSetId, String viewId)
210 this(al, null, width, height, sequenceSetId, viewId);
214 * new alignment window with hidden columns
218 * @param hiddenColumns
219 * ColumnSelection or null
221 * Width of alignment frame
225 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
226 int width, int height)
228 this(al, hiddenColumns, width, height, null);
232 * Create alignment frame for al with hiddenColumns, a specific width and
233 * height, and specific sequenceId
236 * @param hiddenColumns
239 * @param sequenceSetId
242 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
243 int width, int height, String sequenceSetId)
245 this(al, hiddenColumns, width, height, sequenceSetId, null);
249 * Create alignment frame for al with hiddenColumns, a specific width and
250 * height, and specific sequenceId
253 * @param hiddenColumns
256 * @param sequenceSetId
261 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
262 int width, int height, String sequenceSetId, String viewId)
264 setSize(width, height);
265 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
267 alignPanel = new AlignmentPanel(this, viewport);
269 if (al.getDataset() == null)
274 addAlignmentPanel(alignPanel, true);
279 * Make a new AlignFrame from exisiting alignmentPanels
286 public AlignFrame(AlignmentPanel ap)
290 addAlignmentPanel(ap, false);
295 * initalise the alignframe from the underlying viewport data and the
300 avc = new jalview.controller.AlignViewController(this, viewport, alignPanel);
301 if (viewport.getAlignmentConservationAnnotation() == null)
303 BLOSUM62Colour.setEnabled(false);
304 conservationMenuItem.setEnabled(false);
305 modifyConservation.setEnabled(false);
306 // PIDColour.setEnabled(false);
307 // abovePIDThreshold.setEnabled(false);
308 // modifyPID.setEnabled(false);
311 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
314 if (sortby.equals("Id"))
316 sortIDMenuItem_actionPerformed(null);
318 else if (sortby.equals("Pairwise Identity"))
320 sortPairwiseMenuItem_actionPerformed(null);
323 if (Desktop.desktop != null)
325 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
326 addServiceListeners();
327 setGUINucleotide(viewport.getAlignment().isNucleotide());
330 setMenusFromViewport(viewport);
331 buildSortByAnnotationScoresMenu();
333 if (viewport.wrapAlignment)
335 wrapMenuItem_actionPerformed(null);
338 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
340 this.overviewMenuItem_actionPerformed(null);
348 * Change the filename and format for the alignment, and enable the 'reload'
349 * button functionality.
356 public void setFileName(String file, String format)
359 currentFileFormat = format;
360 reload.setEnabled(true);
363 void addKeyListener()
365 addKeyListener(new KeyAdapter()
368 public void keyPressed(KeyEvent evt)
370 if (viewport.cursorMode
371 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
372 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
373 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
374 && Character.isDigit(evt.getKeyChar()))
375 alignPanel.seqPanel.numberPressed(evt.getKeyChar());
377 switch (evt.getKeyCode())
380 case 27: // escape key
381 deselectAllSequenceMenuItem_actionPerformed(null);
385 case KeyEvent.VK_DOWN:
386 if (evt.isAltDown() || !viewport.cursorMode)
387 moveSelectedSequences(false);
388 if (viewport.cursorMode)
389 alignPanel.seqPanel.moveCursor(0, 1);
393 if (evt.isAltDown() || !viewport.cursorMode)
394 moveSelectedSequences(true);
395 if (viewport.cursorMode)
396 alignPanel.seqPanel.moveCursor(0, -1);
400 case KeyEvent.VK_LEFT:
401 if (evt.isAltDown() || !viewport.cursorMode)
402 slideSequences(false, alignPanel.seqPanel.getKeyboardNo1());
404 alignPanel.seqPanel.moveCursor(-1, 0);
408 case KeyEvent.VK_RIGHT:
409 if (evt.isAltDown() || !viewport.cursorMode)
410 slideSequences(true, alignPanel.seqPanel.getKeyboardNo1());
412 alignPanel.seqPanel.moveCursor(1, 0);
415 case KeyEvent.VK_SPACE:
416 if (viewport.cursorMode)
418 alignPanel.seqPanel.insertGapAtCursor(evt.isControlDown()
419 || evt.isShiftDown() || evt.isAltDown());
423 // case KeyEvent.VK_A:
424 // if (viewport.cursorMode)
426 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
427 // //System.out.println("A");
431 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
432 * System.out.println("closing bracket"); } break;
434 case KeyEvent.VK_DELETE:
435 case KeyEvent.VK_BACK_SPACE:
436 if (!viewport.cursorMode)
438 cut_actionPerformed(null);
442 alignPanel.seqPanel.deleteGapAtCursor(evt.isControlDown()
443 || evt.isShiftDown() || evt.isAltDown());
449 if (viewport.cursorMode)
451 alignPanel.seqPanel.setCursorRow();
455 if (viewport.cursorMode && !evt.isControlDown())
457 alignPanel.seqPanel.setCursorColumn();
461 if (viewport.cursorMode)
463 alignPanel.seqPanel.setCursorPosition();
467 case KeyEvent.VK_ENTER:
468 case KeyEvent.VK_COMMA:
469 if (viewport.cursorMode)
471 alignPanel.seqPanel.setCursorRowAndColumn();
476 if (viewport.cursorMode)
478 alignPanel.seqPanel.setSelectionAreaAtCursor(true);
482 if (viewport.cursorMode)
484 alignPanel.seqPanel.setSelectionAreaAtCursor(false);
489 viewport.cursorMode = !viewport.cursorMode;
490 statusBar.setText(MessageManager.formatMessage("label.keyboard_editing_mode", new String[]{(viewport.cursorMode ? "on" : "off")}));
491 if (viewport.cursorMode)
493 alignPanel.seqPanel.seqCanvas.cursorX = viewport.startRes;
494 alignPanel.seqPanel.seqCanvas.cursorY = viewport.startSeq;
496 alignPanel.seqPanel.seqCanvas.repaint();
502 ClassLoader cl = jalview.gui.Desktop.class.getClassLoader();
503 java.net.URL url = javax.help.HelpSet.findHelpSet(cl,
505 javax.help.HelpSet hs = new javax.help.HelpSet(cl, url);
507 javax.help.HelpBroker hb = hs.createHelpBroker();
508 hb.setCurrentID("home");
509 hb.setDisplayed(true);
510 } catch (Exception ex)
512 ex.printStackTrace();
517 boolean toggleSeqs = !evt.isControlDown();
518 boolean toggleCols = !evt.isShiftDown();
519 toggleHiddenRegions(toggleSeqs, toggleCols);
522 case KeyEvent.VK_PAGE_UP:
523 if (viewport.wrapAlignment)
525 alignPanel.scrollUp(true);
529 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
530 - viewport.endSeq + viewport.startSeq);
533 case KeyEvent.VK_PAGE_DOWN:
534 if (viewport.wrapAlignment)
536 alignPanel.scrollUp(false);
540 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
541 + viewport.endSeq - viewport.startSeq);
548 public void keyReleased(KeyEvent evt)
550 switch (evt.getKeyCode())
552 case KeyEvent.VK_LEFT:
553 if (evt.isAltDown() || !viewport.cursorMode)
554 viewport.firePropertyChange("alignment", null, viewport
555 .getAlignment().getSequences());
558 case KeyEvent.VK_RIGHT:
559 if (evt.isAltDown() || !viewport.cursorMode)
560 viewport.firePropertyChange("alignment", null, viewport
561 .getAlignment().getSequences());
568 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
570 ap.alignFrame = this;
571 avc = new jalview.controller.AlignViewController(this, viewport, alignPanel);
573 alignPanels.addElement(ap);
575 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
577 int aSize = alignPanels.size();
579 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
581 if (aSize == 1 && ap.av.viewName == null)
583 this.getContentPane().add(ap, BorderLayout.CENTER);
589 setInitialTabVisible();
592 expandViews.setEnabled(true);
593 gatherViews.setEnabled(true);
594 tabbedPane.addTab(ap.av.viewName, ap);
596 ap.setVisible(false);
601 if (ap.av.isPadGaps())
603 ap.av.getAlignment().padGaps();
605 ap.av.updateConservation(ap);
606 ap.av.updateConsensus(ap);
607 ap.av.updateStrucConsensus(ap);
611 public void setInitialTabVisible()
613 expandViews.setEnabled(true);
614 gatherViews.setEnabled(true);
615 tabbedPane.setVisible(true);
616 AlignmentPanel first = (AlignmentPanel) alignPanels.firstElement();
617 tabbedPane.addTab(first.av.viewName, first);
618 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
621 public AlignViewport getViewport()
626 /* Set up intrinsic listeners for dynamically generated GUI bits. */
627 private void addServiceListeners()
629 final java.beans.PropertyChangeListener thisListener;
630 Desktop.instance.addJalviewPropertyChangeListener("services",
631 thisListener = new java.beans.PropertyChangeListener()
634 public void propertyChange(PropertyChangeEvent evt)
636 // // System.out.println("Discoverer property change.");
637 // if (evt.getPropertyName().equals("services"))
639 SwingUtilities.invokeLater(new Runnable()
646 .println("Rebuild WS Menu for service change");
647 BuildWebServiceMenu();
654 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
657 public void internalFrameClosed(
658 javax.swing.event.InternalFrameEvent evt)
660 System.out.println("deregistering discoverer listener");
661 Desktop.instance.removeJalviewPropertyChangeListener("services",
663 closeMenuItem_actionPerformed(true);
666 // Finally, build the menu once to get current service state
667 new Thread(new Runnable()
672 BuildWebServiceMenu();
677 public void setGUINucleotide(boolean nucleotide)
679 showTranslation.setVisible(nucleotide);
680 conservationMenuItem.setEnabled(!nucleotide);
681 modifyConservation.setEnabled(!nucleotide);
682 showGroupConservation.setEnabled(!nucleotide);
683 rnahelicesColour.setEnabled(nucleotide);
684 purinePyrimidineColour.setEnabled(nucleotide);
685 // Remember AlignFrame always starts as protein
689 // calculateMenu.remove(calculateMenu.getItemCount() - 2);
694 * set up menus for the currently viewport. This may be called after any
695 * operation that affects the data in the current view (selection changed,
696 * etc) to update the menus to reflect the new state.
698 public void setMenusForViewport()
700 setMenusFromViewport(viewport);
704 * Need to call this method when tabs are selected for multiple views, or when
705 * loading from Jalview2XML.java
710 void setMenusFromViewport(AlignViewport av)
712 padGapsMenuitem.setSelected(av.isPadGaps());
713 colourTextMenuItem.setSelected(av.showColourText);
714 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
715 conservationMenuItem.setSelected(av.getConservationSelected());
716 seqLimits.setSelected(av.getShowJVSuffix());
717 idRightAlign.setSelected(av.rightAlignIds);
718 centreColumnLabelsMenuItem.setState(av.centreColumnLabels);
719 renderGapsMenuItem.setSelected(av.renderGaps);
720 wrapMenuItem.setSelected(av.wrapAlignment);
721 scaleAbove.setVisible(av.wrapAlignment);
722 scaleLeft.setVisible(av.wrapAlignment);
723 scaleRight.setVisible(av.wrapAlignment);
724 annotationPanelMenuItem.setState(av.showAnnotation);
725 viewBoxesMenuItem.setSelected(av.showBoxes);
726 viewTextMenuItem.setSelected(av.showText);
727 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
728 showGroupConsensus.setSelected(av.isShowGroupConsensus());
729 showGroupConservation.setSelected(av.isShowGroupConservation());
730 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
731 showSequenceLogo.setSelected(av.isShowSequenceLogo());
732 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
734 setColourSelected(ColourSchemeProperty.getColourName(av
735 .getGlobalColourScheme()));
737 showSeqFeatures.setSelected(av.showSequenceFeatures);
738 hiddenMarkers.setState(av.showHiddenMarkers);
739 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
740 showNpFeatsMenuitem.setSelected(av.isShowNpFeats());
741 showDbRefsMenuitem.setSelected(av.isShowDbRefs());
742 autoCalculate.setSelected(av.autoCalculateConsensus);
743 sortByTree.setSelected(av.sortByTree);
744 listenToViewSelections.setSelected(av.followSelection);
745 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
747 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
748 setShowProductsEnabled();
752 // methods for implementing IProgressIndicator
753 // need to refactor to a reusable stub class
754 Hashtable progressBars, progressBarHandlers;
759 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
762 public void setProgressBar(String message, long id)
764 if (progressBars == null)
766 progressBars = new Hashtable();
767 progressBarHandlers = new Hashtable();
770 JPanel progressPanel;
771 Long lId = new Long(id);
772 GridLayout layout = (GridLayout) statusPanel.getLayout();
773 if (progressBars.get(lId) != null)
775 progressPanel = (JPanel) progressBars.get(new Long(id));
776 statusPanel.remove(progressPanel);
777 progressBars.remove(lId);
778 progressPanel = null;
781 statusBar.setText(message);
783 if (progressBarHandlers.contains(lId))
785 progressBarHandlers.remove(lId);
787 layout.setRows(layout.getRows() - 1);
791 progressPanel = new JPanel(new BorderLayout(10, 5));
793 JProgressBar progressBar = new JProgressBar();
794 progressBar.setIndeterminate(true);
796 progressPanel.add(new JLabel(message), BorderLayout.WEST);
797 progressPanel.add(progressBar, BorderLayout.CENTER);
799 layout.setRows(layout.getRows() + 1);
800 statusPanel.add(progressPanel);
802 progressBars.put(lId, progressPanel);
805 // setMenusForViewport();
810 public void registerHandler(final long id,
811 final IProgressIndicatorHandler handler)
813 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
816 "call setProgressBar before registering the progress bar's handler.");
818 progressBarHandlers.put(new Long(id), handler);
819 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
820 if (handler.canCancel())
822 JButton cancel = new JButton(MessageManager.getString("action.cancel"));
823 final IProgressIndicator us = this;
824 cancel.addActionListener(new ActionListener()
828 public void actionPerformed(ActionEvent e)
830 handler.cancelActivity(id);
833 + ((JLabel) progressPanel.getComponent(0))
837 progressPanel.add(cancel, BorderLayout.EAST);
843 * @return true if any progress bars are still active
846 public boolean operationInProgress()
848 if (progressBars != null && progressBars.size() > 0)
856 public void setStatus(String text) {
857 statusBar.setText(text);
860 * Added so Castor Mapping file can obtain Jalview Version
862 public String getVersion()
864 return jalview.bin.Cache.getProperty("VERSION");
867 public FeatureRenderer getFeatureRenderer()
869 return alignPanel.seqPanel.seqCanvas.getFeatureRenderer();
873 public void fetchSequence_actionPerformed(ActionEvent e)
875 new SequenceFetcher(this);
879 public void addFromFile_actionPerformed(ActionEvent e)
881 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
885 public void reload_actionPerformed(ActionEvent e)
887 if (fileName != null)
889 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
890 // originating file's format
891 // TODO: work out how to recover feature settings for correct view(s) when
893 if (currentFileFormat.equals("Jalview"))
895 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
896 for (int i = 0; i < frames.length; i++)
898 if (frames[i] instanceof AlignFrame && frames[i] != this
899 && ((AlignFrame) frames[i]).fileName != null
900 && ((AlignFrame) frames[i]).fileName.equals(fileName))
904 frames[i].setSelected(true);
905 Desktop.instance.closeAssociatedWindows();
906 } catch (java.beans.PropertyVetoException ex)
912 Desktop.instance.closeAssociatedWindows();
914 FileLoader loader = new FileLoader();
915 String protocol = fileName.startsWith("http:") ? "URL" : "File";
916 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
920 Rectangle bounds = this.getBounds();
922 FileLoader loader = new FileLoader();
923 String protocol = fileName.startsWith("http:") ? "URL" : "File";
924 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
925 protocol, currentFileFormat);
927 newframe.setBounds(bounds);
928 if (featureSettings != null && featureSettings.isShowing())
930 final Rectangle fspos = featureSettings.frame.getBounds();
931 // TODO: need a 'show feature settings' function that takes bounds -
932 // need to refactor Desktop.addFrame
933 newframe.featureSettings_actionPerformed(null);
934 final FeatureSettings nfs = newframe.featureSettings;
935 SwingUtilities.invokeLater(new Runnable()
940 nfs.frame.setBounds(fspos);
943 this.featureSettings.close();
944 this.featureSettings = null;
946 this.closeMenuItem_actionPerformed(true);
952 public void addFromText_actionPerformed(ActionEvent e)
954 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
958 public void addFromURL_actionPerformed(ActionEvent e)
960 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
964 public void save_actionPerformed(ActionEvent e)
967 || (currentFileFormat == null || !jalview.io.FormatAdapter
968 .isValidIOFormat(currentFileFormat, true))
969 || fileName.startsWith("http"))
971 saveAs_actionPerformed(null);
975 saveAlignment(fileName, currentFileFormat);
986 public void saveAs_actionPerformed(ActionEvent e)
988 JalviewFileChooser chooser = new JalviewFileChooser(
989 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
990 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
991 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
992 currentFileFormat, false);
994 chooser.setFileView(new JalviewFileView());
995 chooser.setDialogTitle("Save Alignment to file");
996 chooser.setToolTipText(MessageManager.getString("action.save"));
\r
998 int value = chooser.showSaveDialog(this);
1000 if (value == JalviewFileChooser.APPROVE_OPTION)
1002 currentFileFormat = chooser.getSelectedFormat();
1003 if (currentFileFormat == null)
1005 JOptionPane.showInternalMessageDialog(Desktop.desktop,
1006 MessageManager.getString("label.select_file_format_before_saving"),
1007 MessageManager.getString("label.file_format_not_specified"), JOptionPane.WARNING_MESSAGE);
1008 value = chooser.showSaveDialog(this);
1012 fileName = chooser.getSelectedFile().getPath();
1014 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
1017 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
1018 if (currentFileFormat.indexOf(" ") > -1)
1020 currentFileFormat = currentFileFormat.substring(0,
1021 currentFileFormat.indexOf(" "));
1023 saveAlignment(fileName, currentFileFormat);
1027 public boolean saveAlignment(String file, String format)
1029 boolean success = true;
1031 if (format.equalsIgnoreCase("Jalview"))
1033 String shortName = title;
1035 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1037 shortName = shortName.substring(shortName
1038 .lastIndexOf(java.io.File.separatorChar) + 1);
1041 success = new Jalview2XML().SaveAlignment(this, file, shortName);
1043 statusBar.setText(MessageManager.formatMessage("label.successfully_saved_to_file_in_format",new String[]{fileName, format}));
1049 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1051 warningMessage("Cannot save file " + fileName + " using format "
1052 + format, "Alignment output format not supported");
1053 saveAs_actionPerformed(null);
1054 // JBPNote need to have a raise_gui flag here
1058 String[] omitHidden = null;
1060 if (viewport.hasHiddenColumns())
1062 int reply = JOptionPane
1063 .showInternalConfirmDialog(
1065 MessageManager.getString("label.alignment_contains_hidden_columns"),
1066 MessageManager.getString("action.save_omit_hidden_columns"),
1067 JOptionPane.YES_NO_OPTION,
1068 JOptionPane.QUESTION_MESSAGE);
1070 if (reply == JOptionPane.YES_OPTION)
1072 omitHidden = viewport.getViewAsString(false);
1075 FormatAdapter f = new FormatAdapter();
1076 String output = f.formatSequences(format,
1077 viewport.getAlignment(), // class cast exceptions will
1078 // occur in the distant future
1079 omitHidden, f.getCacheSuffixDefault(format),
1080 viewport.getColumnSelection());
1090 java.io.PrintWriter out = new java.io.PrintWriter(
1091 new java.io.FileWriter(file));
1095 this.setTitle(file);
1096 statusBar.setText(MessageManager.formatMessage("label.successfully_saved_to_file_in_format",new String[]{fileName, format}));
1097 } catch (Exception ex)
1100 ex.printStackTrace();
1107 JOptionPane.showInternalMessageDialog(this, MessageManager.formatMessage("label.couldnt_save_file", new String[]{fileName}),
1108 MessageManager.getString("label.error_saving_file"), JOptionPane.WARNING_MESSAGE);
1114 private void warningMessage(String warning, String title)
1116 if (new jalview.util.Platform().isHeadless())
1118 System.err.println("Warning: " + title + "\nWarning: " + warning);
1123 JOptionPane.showInternalMessageDialog(this, warning, title,
1124 JOptionPane.WARNING_MESSAGE);
1136 protected void outputText_actionPerformed(ActionEvent e)
1138 String[] omitHidden = null;
1140 if (viewport.hasHiddenColumns())
1142 int reply = JOptionPane
1143 .showInternalConfirmDialog(
1145 MessageManager.getString("label.alignment_contains_hidden_columns"),
1146 MessageManager.getString("action.save_omit_hidden_columns"),
1147 JOptionPane.YES_NO_OPTION,
1148 JOptionPane.QUESTION_MESSAGE);
1150 if (reply == JOptionPane.YES_OPTION)
1152 omitHidden = viewport.getViewAsString(false);
1156 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1157 cap.setForInput(null);
1161 cap.setText(new FormatAdapter().formatSequences(e.getActionCommand(),
1162 viewport.getAlignment(), omitHidden,
1163 viewport.getColumnSelection()));
1164 Desktop.addInternalFrame(cap,
1165 MessageManager.formatMessage("label.alignment_output_command", new String[]{e.getActionCommand()}), 600, 500);
\r
1166 } catch (OutOfMemoryError oom)
1168 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1181 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1183 new HTMLOutput(alignPanel,
1184 alignPanel.seqPanel.seqCanvas.getSequenceRenderer(),
1185 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
1188 public void createImageMap(File file, String image)
1190 alignPanel.makePNGImageMap(file, image);
1200 public void createPNG(File f)
1202 alignPanel.makePNG(f);
1212 public void createEPS(File f)
1214 alignPanel.makeEPS(f);
1218 public void pageSetup_actionPerformed(ActionEvent e)
1220 PrinterJob printJob = PrinterJob.getPrinterJob();
1221 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1231 public void printMenuItem_actionPerformed(ActionEvent e)
1233 // Putting in a thread avoids Swing painting problems
1234 PrintThread thread = new PrintThread(alignPanel);
1239 public void exportFeatures_actionPerformed(ActionEvent e)
1241 new AnnotationExporter().exportFeatures(alignPanel);
1245 public void exportAnnotations_actionPerformed(ActionEvent e)
1247 new AnnotationExporter().exportAnnotations(alignPanel,
1248 viewport.showAnnotation ? viewport.getAlignment()
1249 .getAlignmentAnnotation() : null, viewport
1250 .getAlignment().getGroups(), ((Alignment) viewport
1251 .getAlignment()).alignmentProperties);
1255 public void associatedData_actionPerformed(ActionEvent e)
1257 // Pick the tree file
1258 JalviewFileChooser chooser = new JalviewFileChooser(
1259 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1260 chooser.setFileView(new JalviewFileView());
1261 chooser.setDialogTitle(MessageManager.getString("label.load_jalview_annotations"));
\r
1262 chooser.setToolTipText(MessageManager.getString("label.load_jalview_annotations"));
\r
1264 int value = chooser.showOpenDialog(null);
1266 if (value == JalviewFileChooser.APPROVE_OPTION)
1268 String choice = chooser.getSelectedFile().getPath();
1269 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1270 loadJalviewDataFile(choice, null, null, null);
1276 * Close the current view or all views in the alignment frame. If the frame
1277 * only contains one view then the alignment will be removed from memory.
1279 * @param closeAllTabs
1282 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1284 if (alignPanels != null && alignPanels.size() < 2)
1286 closeAllTabs = true;
1291 if (alignPanels != null)
1295 if (this.isClosed())
1297 // really close all the windows - otherwise wait till
1298 // setClosed(true) is called
1299 for (int i = 0; i < alignPanels.size(); i++)
1301 AlignmentPanel ap = (AlignmentPanel) alignPanels.elementAt(i);
1308 closeView(alignPanel);
1314 this.setClosed(true);
1316 } catch (Exception ex)
1318 ex.printStackTrace();
1323 * close alignPanel2 and shuffle tabs appropriately.
1325 * @param alignPanel2
1327 public void closeView(AlignmentPanel alignPanel2)
1329 int index = tabbedPane.getSelectedIndex();
1330 int closedindex = tabbedPane.indexOfComponent(alignPanel2);
1331 alignPanels.removeElement(alignPanel2);
1333 // if (viewport == alignPanel2.av)
1337 alignPanel2.closePanel();
1340 tabbedPane.removeTabAt(closedindex);
1341 tabbedPane.validate();
1343 if (index > closedindex || index == tabbedPane.getTabCount())
1345 // modify currently selected tab index if necessary.
1349 this.tabSelectionChanged(index);
1355 void updateEditMenuBar()
1358 if (viewport.historyList.size() > 0)
1360 undoMenuItem.setEnabled(true);
1361 CommandI command = (CommandI) viewport.historyList.peek();
1362 undoMenuItem.setText(MessageManager.formatMessage("label.undo_command", new String[]{command.getDescription()}));
1366 undoMenuItem.setEnabled(false);
1367 undoMenuItem.setText(MessageManager.getString("action.undo"));
1370 if (viewport.redoList.size() > 0)
1372 redoMenuItem.setEnabled(true);
1374 CommandI command = (CommandI) viewport.redoList.peek();
1375 redoMenuItem.setText(MessageManager.formatMessage("label.redo_command", new String[]{command.getDescription()}));
1379 redoMenuItem.setEnabled(false);
1380 redoMenuItem.setText(MessageManager.getString("action.redo"));
1384 public void addHistoryItem(CommandI command)
1386 if (command.getSize() > 0)
1388 viewport.historyList.push(command);
1389 viewport.redoList.clear();
1390 updateEditMenuBar();
1391 viewport.updateHiddenColumns();
1392 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1393 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1394 // viewport.getColumnSelection()
1395 // .getHiddenColumns().size() > 0);
1401 * @return alignment objects for all views
1403 AlignmentI[] getViewAlignments()
1405 if (alignPanels != null)
1407 Enumeration e = alignPanels.elements();
1408 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1409 for (int i = 0; e.hasMoreElements(); i++)
1411 als[i] = ((AlignmentPanel) e.nextElement()).av.getAlignment();
1415 if (viewport != null)
1417 return new AlignmentI[]
1418 { viewport.getAlignment() };
1430 protected void undoMenuItem_actionPerformed(ActionEvent e)
1432 if (viewport.historyList.empty())
1434 CommandI command = (CommandI) viewport.historyList.pop();
1435 viewport.redoList.push(command);
1436 command.undoCommand(getViewAlignments());
1438 AlignViewport originalSource = getOriginatingSource(command);
1439 updateEditMenuBar();
1441 if (originalSource != null)
1443 if (originalSource != viewport)
1446 .warn("Implementation worry: mismatch of viewport origin for undo");
1448 originalSource.updateHiddenColumns();
1449 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1451 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1452 // viewport.getColumnSelection()
1453 // .getHiddenColumns().size() > 0);
1454 originalSource.firePropertyChange("alignment", null, originalSource
1455 .getAlignment().getSequences());
1466 protected void redoMenuItem_actionPerformed(ActionEvent e)
1468 if (viewport.redoList.size() < 1)
1473 CommandI command = (CommandI) viewport.redoList.pop();
1474 viewport.historyList.push(command);
1475 command.doCommand(getViewAlignments());
1477 AlignViewport originalSource = getOriginatingSource(command);
1478 updateEditMenuBar();
1480 if (originalSource != null)
1483 if (originalSource != viewport)
1486 .warn("Implementation worry: mismatch of viewport origin for redo");
1488 originalSource.updateHiddenColumns();
1489 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1491 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1492 // viewport.getColumnSelection()
1493 // .getHiddenColumns().size() > 0);
1494 originalSource.firePropertyChange("alignment", null, originalSource
1495 .getAlignment().getSequences());
1499 AlignViewport getOriginatingSource(CommandI command)
1501 AlignViewport originalSource = null;
1502 // For sequence removal and addition, we need to fire
1503 // the property change event FROM the viewport where the
1504 // original alignment was altered
1505 AlignmentI al = null;
1506 if (command instanceof EditCommand)
1508 EditCommand editCommand = (EditCommand) command;
1509 al = editCommand.getAlignment();
1510 Vector comps = (Vector) PaintRefresher.components.get(viewport
1511 .getSequenceSetId());
1513 for (int i = 0; i < comps.size(); i++)
1515 if (comps.elementAt(i) instanceof AlignmentPanel)
1517 if (al == ((AlignmentPanel) comps.elementAt(i)).av.getAlignment())
1519 originalSource = ((AlignmentPanel) comps.elementAt(i)).av;
1526 if (originalSource == null)
1528 // The original view is closed, we must validate
1529 // the current view against the closed view first
1532 PaintRefresher.validateSequences(al, viewport.getAlignment());
1535 originalSource = viewport;
1538 return originalSource;
1547 public void moveSelectedSequences(boolean up)
1549 SequenceGroup sg = viewport.getSelectionGroup();
1555 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1556 viewport.getHiddenRepSequences(), up);
1557 alignPanel.paintAlignment(true);
1560 synchronized void slideSequences(boolean right, int size)
1562 List<SequenceI> sg = new Vector();
1563 if (viewport.cursorMode)
1565 sg.add(viewport.getAlignment().getSequenceAt(
1566 alignPanel.seqPanel.seqCanvas.cursorY));
1568 else if (viewport.getSelectionGroup() != null
1569 && viewport.getSelectionGroup().getSize() != viewport
1570 .getAlignment().getHeight())
1572 sg = viewport.getSelectionGroup().getSequences(
1573 viewport.getHiddenRepSequences());
1581 Vector invertGroup = new Vector();
1583 for (int i = 0; i < viewport.getAlignment().getHeight(); i++)
1585 if (!sg.contains(viewport.getAlignment().getSequenceAt(i)))
1586 invertGroup.add(viewport.getAlignment().getSequenceAt(i));
1589 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1591 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1592 for (int i = 0; i < invertGroup.size(); i++)
1593 seqs2[i] = (SequenceI) invertGroup.elementAt(i);
1595 SlideSequencesCommand ssc;
1597 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1598 size, viewport.getGapCharacter());
1600 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1601 size, viewport.getGapCharacter());
1603 int groupAdjustment = 0;
1604 if (ssc.getGapsInsertedBegin() && right)
1606 if (viewport.cursorMode)
1607 alignPanel.seqPanel.moveCursor(size, 0);
1609 groupAdjustment = size;
1611 else if (!ssc.getGapsInsertedBegin() && !right)
1613 if (viewport.cursorMode)
1614 alignPanel.seqPanel.moveCursor(-size, 0);
1616 groupAdjustment = -size;
1619 if (groupAdjustment != 0)
1621 viewport.getSelectionGroup().setStartRes(
1622 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1623 viewport.getSelectionGroup().setEndRes(
1624 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1627 boolean appendHistoryItem = false;
1628 if (viewport.historyList != null && viewport.historyList.size() > 0
1629 && viewport.historyList.peek() instanceof SlideSequencesCommand)
1631 appendHistoryItem = ssc
1632 .appendSlideCommand((SlideSequencesCommand) viewport.historyList
1636 if (!appendHistoryItem)
1637 addHistoryItem(ssc);
1649 protected void copy_actionPerformed(ActionEvent e)
1652 if (viewport.getSelectionGroup() == null)
1656 // TODO: preserve the ordering of displayed alignment annotation in any
1657 // internal paste (particularly sequence associated annotation)
1658 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1659 String[] omitHidden = null;
1661 if (viewport.hasHiddenColumns())
1663 omitHidden = viewport.getViewAsString(true);
1666 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1669 StringSelection ss = new StringSelection(output);
1673 jalview.gui.Desktop.internalCopy = true;
1674 // Its really worth setting the clipboard contents
1675 // to empty before setting the large StringSelection!!
1676 Toolkit.getDefaultToolkit().getSystemClipboard()
1677 .setContents(new StringSelection(""), null);
1679 Toolkit.getDefaultToolkit().getSystemClipboard()
1680 .setContents(ss, Desktop.instance);
1681 } catch (OutOfMemoryError er)
1683 new OOMWarning("copying region", er);
1687 Vector hiddenColumns = null;
1688 if (viewport.hasHiddenColumns())
1690 hiddenColumns = new Vector();
1691 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1692 .getSelectionGroup().getEndRes();
1693 for (int i = 0; i < viewport.getColumnSelection().getHiddenColumns()
1696 int[] region = (int[]) viewport.getColumnSelection()
1697 .getHiddenColumns().elementAt(i);
1698 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1700 hiddenColumns.addElement(new int[]
1701 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1706 Desktop.jalviewClipboard = new Object[]
1707 { seqs, viewport.getAlignment().getDataset(), hiddenColumns };
1708 statusBar.setText(MessageManager.formatMessage("label.copied_sequences_to_clipboard", new String[]{Integer.valueOf(seqs.length).toString()}));
1718 protected void pasteNew_actionPerformed(ActionEvent e)
1730 protected void pasteThis_actionPerformed(ActionEvent e)
1736 * Paste contents of Jalview clipboard
1738 * @param newAlignment
1739 * true to paste to a new alignment, otherwise add to this.
1741 void paste(boolean newAlignment)
1743 boolean externalPaste = true;
1746 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1747 Transferable contents = c.getContents(this);
1749 if (contents == null)
1757 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1758 if (str.length() < 1)
1763 format = new IdentifyFile().Identify(str, "Paste");
1765 } catch (OutOfMemoryError er)
1767 new OOMWarning("Out of memory pasting sequences!!", er);
1771 SequenceI[] sequences;
1772 boolean annotationAdded = false;
1773 AlignmentI alignment = null;
1775 if (Desktop.jalviewClipboard != null)
1777 // The clipboard was filled from within Jalview, we must use the
1779 // And dataset from the copied alignment
1780 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1781 // be doubly sure that we create *new* sequence objects.
1782 sequences = new SequenceI[newseq.length];
1783 for (int i = 0; i < newseq.length; i++)
1785 sequences[i] = new Sequence(newseq[i]);
1787 alignment = new Alignment(sequences);
1788 externalPaste = false;
1792 // parse the clipboard as an alignment.
1793 alignment = new FormatAdapter().readFile(str, "Paste", format);
1794 sequences = alignment.getSequencesArray();
1798 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1804 if (Desktop.jalviewClipboard != null)
1806 // dataset is inherited
1807 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1811 // new dataset is constructed
1812 alignment.setDataset(null);
1814 alwidth = alignment.getWidth() + 1;
1818 AlignmentI pastedal = alignment; // preserve pasted alignment object
1819 // Add pasted sequences and dataset into existing alignment.
1820 alignment = viewport.getAlignment();
1821 alwidth = alignment.getWidth() + 1;
1822 // decide if we need to import sequences from an existing dataset
1823 boolean importDs = Desktop.jalviewClipboard != null
1824 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1825 // importDs==true instructs us to copy over new dataset sequences from
1826 // an existing alignment
1827 Vector newDs = (importDs) ? new Vector() : null; // used to create
1828 // minimum dataset set
1830 for (int i = 0; i < sequences.length; i++)
1834 newDs.addElement(null);
1836 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
1838 if (importDs && ds != null)
1840 if (!newDs.contains(ds))
1842 newDs.setElementAt(ds, i);
1843 ds = new Sequence(ds);
1844 // update with new dataset sequence
1845 sequences[i].setDatasetSequence(ds);
1849 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
1854 // copy and derive new dataset sequence
1855 sequences[i] = sequences[i].deriveSequence();
1856 alignment.getDataset().addSequence(
1857 sequences[i].getDatasetSequence());
1858 // TODO: avoid creation of duplicate dataset sequences with a
1859 // 'contains' method using SequenceI.equals()/SequenceI.contains()
1861 alignment.addSequence(sequences[i]); // merges dataset
1865 newDs.clear(); // tidy up
1867 if (alignment.getAlignmentAnnotation() != null)
1869 for (AlignmentAnnotation alan : alignment
1870 .getAlignmentAnnotation())
1872 if (alan.graphGroup > fgroup)
1874 fgroup = alan.graphGroup;
1878 if (pastedal.getAlignmentAnnotation() != null)
1880 // Add any annotation attached to alignment.
1881 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
1882 for (int i = 0; i < alann.length; i++)
1884 annotationAdded = true;
1885 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
1887 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
1888 if (newann.graphGroup > -1)
1890 if (newGraphGroups.size() <= newann.graphGroup
1891 || newGraphGroups.get(newann.graphGroup) == null)
1893 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
1895 newGraphGroups.add(q, null);
1897 newGraphGroups.set(newann.graphGroup, new Integer(
1900 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
1904 newann.padAnnotation(alwidth);
1905 alignment.addAnnotation(newann);
1915 addHistoryItem(new EditCommand("Add sequences", EditCommand.PASTE,
1916 sequences, 0, alignment.getWidth(), alignment));
1918 // Add any annotations attached to sequences
1919 for (int i = 0; i < sequences.length; i++)
1921 if (sequences[i].getAnnotation() != null)
1923 AlignmentAnnotation newann;
1924 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
1926 annotationAdded = true;
1927 newann = sequences[i].getAnnotation()[a];
1928 newann.adjustForAlignment();
1929 newann.padAnnotation(alwidth);
1930 if (newann.graphGroup > -1)
1932 if (newann.graphGroup > -1)
1934 if (newGraphGroups.size() <= newann.graphGroup
1935 || newGraphGroups.get(newann.graphGroup) == null)
1937 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
1939 newGraphGroups.add(q, null);
1941 newGraphGroups.set(newann.graphGroup, new Integer(
1944 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
1948 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
1953 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
1960 // propagate alignment changed.
1961 viewport.setEndSeq(alignment.getHeight());
1962 if (annotationAdded)
1964 // Duplicate sequence annotation in all views.
1965 AlignmentI[] alview = this.getViewAlignments();
1966 for (int i = 0; i < sequences.length; i++)
1968 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
1971 for (int avnum = 0; avnum < alview.length; avnum++)
1973 if (alview[avnum] != alignment)
1975 // duplicate in a view other than the one with input focus
1976 int avwidth = alview[avnum].getWidth() + 1;
1977 // this relies on sann being preserved after we
1978 // modify the sequence's annotation array for each duplication
1979 for (int a = 0; a < sann.length; a++)
1981 AlignmentAnnotation newann = new AlignmentAnnotation(
1983 sequences[i].addAlignmentAnnotation(newann);
1984 newann.padAnnotation(avwidth);
1985 alview[avnum].addAnnotation(newann); // annotation was
1986 // duplicated earlier
1987 // TODO JAL-1145 graphGroups are not updated for sequence
1988 // annotation added to several views. This may cause
1990 alview[avnum].setAnnotationIndex(newann, a);
1995 buildSortByAnnotationScoresMenu();
1997 viewport.firePropertyChange("alignment", null,
1998 alignment.getSequences());
1999 if (alignPanels != null)
2001 for (AlignmentPanel ap : ((Vector<AlignmentPanel>) alignPanels))
2003 ap.validateAnnotationDimensions(false);
2008 alignPanel.validateAnnotationDimensions(false);
2014 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2016 String newtitle = new String("Copied sequences");
2018 if (Desktop.jalviewClipboard != null
2019 && Desktop.jalviewClipboard[2] != null)
2021 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2022 for (int i = 0; i < hc.size(); i++)
2024 int[] region = (int[]) hc.elementAt(i);
2025 af.viewport.hideColumns(region[0], region[1]);
2029 // >>>This is a fix for the moment, until a better solution is
2031 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
2033 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
2035 // TODO: maintain provenance of an alignment, rather than just make the
2036 // title a concatenation of operations.
2039 if (title.startsWith("Copied sequences"))
2045 newtitle = newtitle.concat("- from " + title);
2050 newtitle = new String("Pasted sequences");
2053 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2058 } catch (Exception ex)
2060 ex.printStackTrace();
2061 System.out.println("Exception whilst pasting: " + ex);
2062 // could be anything being pasted in here
2074 protected void cut_actionPerformed(ActionEvent e)
2076 copy_actionPerformed(null);
2077 delete_actionPerformed(null);
2087 protected void delete_actionPerformed(ActionEvent evt)
2090 SequenceGroup sg = viewport.getSelectionGroup();
2096 Vector seqs = new Vector();
2098 for (int i = 0; i < sg.getSize(); i++)
2100 seq = sg.getSequenceAt(i);
2101 seqs.addElement(seq);
2104 // If the cut affects all sequences, remove highlighted columns
2105 if (sg.getSize() == viewport.getAlignment().getHeight())
2107 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2108 sg.getEndRes() + 1);
2111 SequenceI[] cut = new SequenceI[seqs.size()];
2112 for (int i = 0; i < seqs.size(); i++)
2114 cut[i] = (SequenceI) seqs.elementAt(i);
2118 * //ADD HISTORY ITEM
2120 addHistoryItem(new EditCommand("Cut Sequences", EditCommand.CUT, cut,
2121 sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2122 viewport.getAlignment()));
2124 viewport.setSelectionGroup(null);
2125 viewport.sendSelection();
2126 viewport.getAlignment().deleteGroup(sg);
2128 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2130 if (viewport.getAlignment().getHeight() < 1)
2134 this.setClosed(true);
2135 } catch (Exception ex)
2148 protected void deleteGroups_actionPerformed(ActionEvent e)
2150 if (avc.deleteGroups()) {
2151 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2152 alignPanel.updateAnnotation();
2153 alignPanel.paintAlignment(true);
2164 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2166 SequenceGroup sg = new SequenceGroup();
2168 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2170 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2173 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2174 viewport.setSelectionGroup(sg);
2175 viewport.sendSelection();
2176 alignPanel.paintAlignment(true);
2177 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2187 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2189 if (viewport.cursorMode)
2191 alignPanel.seqPanel.keyboardNo1 = null;
2192 alignPanel.seqPanel.keyboardNo2 = null;
2194 viewport.setSelectionGroup(null);
2195 viewport.getColumnSelection().clear();
2196 viewport.setSelectionGroup(null);
2197 alignPanel.seqPanel.seqCanvas.highlightSearchResults(null);
2198 alignPanel.idPanel.idCanvas.searchResults = null;
2199 alignPanel.paintAlignment(true);
2200 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2201 viewport.sendSelection();
2211 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2213 SequenceGroup sg = viewport.getSelectionGroup();
2217 selectAllSequenceMenuItem_actionPerformed(null);
2222 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2224 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2227 alignPanel.paintAlignment(true);
2228 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2229 viewport.sendSelection();
2233 public void invertColSel_actionPerformed(ActionEvent e)
2235 viewport.invertColumnSelection();
2236 alignPanel.paintAlignment(true);
2237 viewport.sendSelection();
2247 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2249 trimAlignment(true);
2259 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2261 trimAlignment(false);
2264 void trimAlignment(boolean trimLeft)
2266 ColumnSelection colSel = viewport.getColumnSelection();
2269 if (colSel.size() > 0)
2273 column = colSel.getMin();
2277 column = colSel.getMax();
2281 if (viewport.getSelectionGroup() != null)
2283 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2284 viewport.getHiddenRepSequences());
2288 seqs = viewport.getAlignment().getSequencesArray();
2291 TrimRegionCommand trimRegion;
2294 trimRegion = new TrimRegionCommand("Remove Left",
2295 TrimRegionCommand.TRIM_LEFT, seqs, column,
2296 viewport.getAlignment(), viewport.getColumnSelection(),
2297 viewport.getSelectionGroup());
2298 viewport.setStartRes(0);
2302 trimRegion = new TrimRegionCommand("Remove Right",
2303 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2304 viewport.getAlignment(), viewport.getColumnSelection(),
2305 viewport.getSelectionGroup());
2308 statusBar.setText(MessageManager.formatMessage("label.removed_columns", new String[]{Integer.valueOf(trimRegion.getSize()).toString()}));
2310 addHistoryItem(trimRegion);
2312 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2314 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2315 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2317 viewport.getAlignment().deleteGroup(sg);
2321 viewport.firePropertyChange("alignment", null, viewport
2322 .getAlignment().getSequences());
2333 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2335 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2338 if (viewport.getSelectionGroup() != null)
2340 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2341 viewport.getHiddenRepSequences());
2342 start = viewport.getSelectionGroup().getStartRes();
2343 end = viewport.getSelectionGroup().getEndRes();
2347 seqs = viewport.getAlignment().getSequencesArray();
2350 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2351 "Remove Gapped Columns", seqs, start, end,
2352 viewport.getAlignment());
2354 addHistoryItem(removeGapCols);
2356 statusBar.setText(MessageManager.formatMessage("label.removed_empty_columns", new String[]{Integer.valueOf(removeGapCols.getSize()).toString()}));
2358 // This is to maintain viewport position on first residue
2359 // of first sequence
2360 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2361 int startRes = seq.findPosition(viewport.startRes);
2362 // ShiftList shifts;
2363 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2364 // edit.alColumnChanges=shifts.getInverse();
2365 // if (viewport.hasHiddenColumns)
2366 // viewport.getColumnSelection().compensateForEdits(shifts);
2367 viewport.setStartRes(seq.findIndex(startRes) - 1);
2368 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2380 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2382 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2385 if (viewport.getSelectionGroup() != null)
2387 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2388 viewport.getHiddenRepSequences());
2389 start = viewport.getSelectionGroup().getStartRes();
2390 end = viewport.getSelectionGroup().getEndRes();
2394 seqs = viewport.getAlignment().getSequencesArray();
2397 // This is to maintain viewport position on first residue
2398 // of first sequence
2399 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2400 int startRes = seq.findPosition(viewport.startRes);
2402 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2403 viewport.getAlignment()));
2405 viewport.setStartRes(seq.findIndex(startRes) - 1);
2407 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2419 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2421 viewport.setPadGaps(padGapsMenuitem.isSelected());
2422 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2428 // if (justifySeqs>0)
2430 // alignment.justify(justifySeqs!=RIGHT_JUSTIFY);
2443 public void findMenuItem_actionPerformed(ActionEvent e)
2449 public void newView_actionPerformed(ActionEvent e)
2456 * @param copyAnnotation
2457 * if true then duplicate all annnotation, groups and settings
2458 * @return new alignment panel, already displayed.
2460 public AlignmentPanel newView(boolean copyAnnotation)
2462 return newView(null, copyAnnotation);
2468 * title of newly created view
2469 * @return new alignment panel, already displayed.
2471 public AlignmentPanel newView(String viewTitle)
2473 return newView(viewTitle, true);
2479 * title of newly created view
2480 * @param copyAnnotation
2481 * if true then duplicate all annnotation, groups and settings
2482 * @return new alignment panel, already displayed.
2484 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2486 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2488 if (!copyAnnotation)
2490 // just remove all the current annotation except for the automatic stuff
2491 newap.av.getAlignment().deleteAllGroups();
2492 for (AlignmentAnnotation alan : newap.av.getAlignment()
2493 .getAlignmentAnnotation())
2495 if (!alan.autoCalculated)
2497 newap.av.getAlignment().deleteAnnotation(alan);
2503 newap.av.gatherViewsHere = false;
2505 if (viewport.viewName == null)
2507 viewport.viewName = "Original";
2510 newap.av.historyList = viewport.historyList;
2511 newap.av.redoList = viewport.redoList;
2513 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2514 // make sure the new view has a unique name - this is essential for Jalview
2516 boolean addFirstIndex = false;
2517 if (viewTitle == null || viewTitle.trim().length() == 0)
2520 addFirstIndex = true;
2524 index = 1;// we count from 1 if given a specific name
2526 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2527 Vector comps = (Vector) PaintRefresher.components.get(viewport
2528 .getSequenceSetId());
2529 Vector existingNames = new Vector();
2530 for (int i = 0; i < comps.size(); i++)
2532 if (comps.elementAt(i) instanceof AlignmentPanel)
2534 AlignmentPanel ap = (AlignmentPanel) comps.elementAt(i);
2535 if (!existingNames.contains(ap.av.viewName))
2537 existingNames.addElement(ap.av.viewName);
2542 while (existingNames.contains(newViewName))
2544 newViewName = viewTitle + " " + (++index);
2547 newap.av.viewName = newViewName;
2549 addAlignmentPanel(newap, true);
2550 newap.alignmentChanged();
2552 if (alignPanels.size() == 2)
2554 viewport.gatherViewsHere = true;
2556 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2561 public void expandViews_actionPerformed(ActionEvent e)
2563 Desktop.instance.explodeViews(this);
2567 public void gatherViews_actionPerformed(ActionEvent e)
2569 Desktop.instance.gatherViews(this);
2579 public void font_actionPerformed(ActionEvent e)
2581 new FontChooser(alignPanel);
2591 protected void seqLimit_actionPerformed(ActionEvent e)
2593 viewport.setShowJVSuffix(seqLimits.isSelected());
2595 alignPanel.idPanel.idCanvas.setPreferredSize(alignPanel
2596 .calculateIdWidth());
2597 alignPanel.paintAlignment(true);
2601 public void idRightAlign_actionPerformed(ActionEvent e)
2603 viewport.rightAlignIds = idRightAlign.isSelected();
2604 alignPanel.paintAlignment(true);
2608 public void centreColumnLabels_actionPerformed(ActionEvent e)
2610 viewport.centreColumnLabels = centreColumnLabelsMenuItem.getState();
2611 alignPanel.paintAlignment(true);
2617 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2620 protected void followHighlight_actionPerformed()
2622 if (viewport.followHighlight = this.followHighlightMenuItem.getState())
2624 alignPanel.scrollToPosition(
2625 alignPanel.seqPanel.seqCanvas.searchResults, false);
2636 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2638 viewport.setColourText(colourTextMenuItem.isSelected());
2639 alignPanel.paintAlignment(true);
2649 public void wrapMenuItem_actionPerformed(ActionEvent e)
2651 scaleAbove.setVisible(wrapMenuItem.isSelected());
2652 scaleLeft.setVisible(wrapMenuItem.isSelected());
2653 scaleRight.setVisible(wrapMenuItem.isSelected());
2654 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2655 alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2659 public void showAllSeqs_actionPerformed(ActionEvent e)
2661 viewport.showAllHiddenSeqs();
2665 public void showAllColumns_actionPerformed(ActionEvent e)
2667 viewport.showAllHiddenColumns();
2672 public void hideSelSequences_actionPerformed(ActionEvent e)
2674 viewport.hideAllSelectedSeqs();
2675 alignPanel.paintAlignment(true);
2679 * called by key handler and the hide all/show all menu items
2684 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2687 boolean hide = false;
2688 SequenceGroup sg = viewport.getSelectionGroup();
2689 if (!toggleSeqs && !toggleCols)
2691 // Hide everything by the current selection - this is a hack - we do the
2692 // invert and then hide
2693 // first check that there will be visible columns after the invert.
2694 if ((viewport.getColumnSelection() != null
2695 && viewport.getColumnSelection().getSelected() != null && viewport
2696 .getColumnSelection().getSelected().size() > 0)
2697 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2700 // now invert the sequence set, if required - empty selection implies
2701 // that no hiding is required.
2704 invertSequenceMenuItem_actionPerformed(null);
2705 sg = viewport.getSelectionGroup();
2709 viewport.expandColSelection(sg, true);
2710 // finally invert the column selection and get the new sequence
2712 invertColSel_actionPerformed(null);
2719 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
2721 hideSelSequences_actionPerformed(null);
2724 else if (!(toggleCols && viewport.getColumnSelection().getSelected()
2727 showAllSeqs_actionPerformed(null);
2733 if (viewport.getColumnSelection().getSelected().size() > 0)
2735 hideSelColumns_actionPerformed(null);
2738 viewport.setSelectionGroup(sg);
2743 showAllColumns_actionPerformed(null);
2752 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
2753 * event.ActionEvent)
2756 public void hideAllButSelection_actionPerformed(ActionEvent e)
2758 toggleHiddenRegions(false, false);
2765 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
2769 public void hideAllSelection_actionPerformed(ActionEvent e)
2771 SequenceGroup sg = viewport.getSelectionGroup();
2772 viewport.expandColSelection(sg, false);
2773 viewport.hideAllSelectedSeqs();
2774 viewport.hideSelectedColumns();
2775 alignPanel.paintAlignment(true);
2782 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
2786 public void showAllhidden_actionPerformed(ActionEvent e)
2788 viewport.showAllHiddenColumns();
2789 viewport.showAllHiddenSeqs();
2790 alignPanel.paintAlignment(true);
2794 public void hideSelColumns_actionPerformed(ActionEvent e)
2796 viewport.hideSelectedColumns();
2797 alignPanel.paintAlignment(true);
2801 public void hiddenMarkers_actionPerformed(ActionEvent e)
2803 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
2814 protected void scaleAbove_actionPerformed(ActionEvent e)
2816 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
2817 alignPanel.paintAlignment(true);
2827 protected void scaleLeft_actionPerformed(ActionEvent e)
2829 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
2830 alignPanel.paintAlignment(true);
2840 protected void scaleRight_actionPerformed(ActionEvent e)
2842 viewport.setScaleRightWrapped(scaleRight.isSelected());
2843 alignPanel.paintAlignment(true);
2853 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
2855 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
2856 alignPanel.paintAlignment(true);
2866 public void viewTextMenuItem_actionPerformed(ActionEvent e)
2868 viewport.setShowText(viewTextMenuItem.isSelected());
2869 alignPanel.paintAlignment(true);
2879 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
2881 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
2882 alignPanel.paintAlignment(true);
2885 public FeatureSettings featureSettings;
2888 public void featureSettings_actionPerformed(ActionEvent e)
2890 if (featureSettings != null)
2892 featureSettings.close();
2893 featureSettings = null;
2895 if (!showSeqFeatures.isSelected())
2897 // make sure features are actually displayed
2898 showSeqFeatures.setSelected(true);
2899 showSeqFeatures_actionPerformed(null);
2901 featureSettings = new FeatureSettings(this);
2905 * Set or clear 'Show Sequence Features'
2911 public void showSeqFeatures_actionPerformed(ActionEvent evt)
2913 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
2914 alignPanel.paintAlignment(true);
2915 if (alignPanel.getOverviewPanel() != null)
2917 alignPanel.getOverviewPanel().updateOverviewImage();
2922 * Set or clear 'Show Sequence Features'
2928 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
2930 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
2932 if (viewport.getShowSequenceFeaturesHeight())
2934 // ensure we're actually displaying features
2935 viewport.setShowSequenceFeatures(true);
2936 showSeqFeatures.setSelected(true);
2938 alignPanel.paintAlignment(true);
2939 if (alignPanel.getOverviewPanel() != null)
2941 alignPanel.getOverviewPanel().updateOverviewImage();
2952 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
2954 viewport.setShowAnnotation(annotationPanelMenuItem.isSelected());
2955 alignPanel.setAnnotationVisible(annotationPanelMenuItem.isSelected());
2959 public void alignmentProperties()
2961 JEditorPane editPane = new JEditorPane("text/html", "");
2962 editPane.setEditable(false);
2963 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
2965 editPane.setText(MessageManager.formatMessage("label.html_content", new String[]{contents.toString()}));
2966 JInternalFrame frame = new JInternalFrame();
2967 frame.getContentPane().add(new JScrollPane(editPane));
2969 Desktop.instance.addInternalFrame(frame, MessageManager.formatMessage("label.alignment_properties", new String[]{getTitle()}), 500, 400);
\r
2979 public void overviewMenuItem_actionPerformed(ActionEvent e)
2981 if (alignPanel.overviewPanel != null)
2986 JInternalFrame frame = new JInternalFrame();
2987 OverviewPanel overview = new OverviewPanel(alignPanel);
2988 frame.setContentPane(overview);
2989 Desktop.addInternalFrame(frame, MessageManager.formatMessage("label.overview_params", new String[]{this.getTitle()}),
\r
2990 frame.getWidth(), frame.getHeight());
2992 frame.setLayer(JLayeredPane.PALETTE_LAYER);
2993 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
2996 public void internalFrameClosed(
2997 javax.swing.event.InternalFrameEvent evt)
2999 alignPanel.setOverviewPanel(null);
3003 alignPanel.setOverviewPanel(overview);
3007 public void textColour_actionPerformed(ActionEvent e)
3009 new TextColourChooser().chooseColour(alignPanel, null);
3019 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3031 public void clustalColour_actionPerformed(ActionEvent e)
3033 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3034 viewport.getHiddenRepSequences()));
3044 public void zappoColour_actionPerformed(ActionEvent e)
3046 changeColour(new ZappoColourScheme());
3056 public void taylorColour_actionPerformed(ActionEvent e)
3058 changeColour(new TaylorColourScheme());
3068 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3070 changeColour(new HydrophobicColourScheme());
3080 public void helixColour_actionPerformed(ActionEvent e)
3082 changeColour(new HelixColourScheme());
3092 public void strandColour_actionPerformed(ActionEvent e)
3094 changeColour(new StrandColourScheme());
3104 public void turnColour_actionPerformed(ActionEvent e)
3106 changeColour(new TurnColourScheme());
3116 public void buriedColour_actionPerformed(ActionEvent e)
3118 changeColour(new BuriedColourScheme());
3128 public void nucleotideColour_actionPerformed(ActionEvent e)
3130 changeColour(new NucleotideColourScheme());
3134 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3136 changeColour(new PurinePyrimidineColourScheme());
3140 * public void covariationColour_actionPerformed(ActionEvent e) {
3142 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3146 public void annotationColour_actionPerformed(ActionEvent e)
3148 new AnnotationColourChooser(viewport, alignPanel);
3152 public void rnahelicesColour_actionPerformed(ActionEvent e)
3154 new RNAHelicesColourChooser(viewport, alignPanel);
3164 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3166 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3175 public void changeColour(ColourSchemeI cs)
3177 // TODO: compare with applet and pull up to model method
3182 if (viewport.getAbovePIDThreshold())
3184 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3187 cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3189 viewport.setGlobalColourScheme(cs);
3193 cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3196 if (viewport.getConservationSelected())
3199 Alignment al = (Alignment) viewport.getAlignment();
3200 Conservation c = new Conservation("All",
3201 ResidueProperties.propHash, 3, al.getSequences(), 0,
3205 c.verdict(false, viewport.getConsPercGaps());
3207 cs.setConservation(c);
3209 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3214 cs.setConservation(null);
3217 cs.setConsensus(viewport.getSequenceConsensusHash());
3220 viewport.setGlobalColourScheme(cs);
3222 if (viewport.getColourAppliesToAllGroups())
3225 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3233 if (cs instanceof ClustalxColourScheme)
3235 sg.cs = new ClustalxColourScheme(sg,
3236 viewport.getHiddenRepSequences());
3238 else if (cs instanceof UserColourScheme)
3240 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
3246 sg.cs = cs.getClass().newInstance();
3247 } catch (Exception ex)
3252 if (viewport.getAbovePIDThreshold()
3253 || cs instanceof PIDColourScheme
3254 || cs instanceof Blosum62ColourScheme)
3256 sg.cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3258 sg.cs.setConsensus(AAFrequency.calculate(
3259 sg.getSequences(viewport.getHiddenRepSequences()),
3260 sg.getStartRes(), sg.getEndRes() + 1));
3264 sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3267 if (viewport.getConservationSelected())
3269 Conservation c = new Conservation("Group",
3270 ResidueProperties.propHash, 3, sg.getSequences(viewport
3271 .getHiddenRepSequences()), sg.getStartRes(),
3272 sg.getEndRes() + 1);
3274 c.verdict(false, viewport.getConsPercGaps());
3275 sg.cs.setConservation(c);
3279 sg.cs.setConservation(null);
3284 if (alignPanel.getOverviewPanel() != null)
3286 alignPanel.getOverviewPanel().updateOverviewImage();
3289 alignPanel.paintAlignment(true);
3299 protected void modifyPID_actionPerformed(ActionEvent e)
3301 if (viewport.getAbovePIDThreshold()
3302 && viewport.getGlobalColourScheme() != null)
3304 SliderPanel.setPIDSliderSource(alignPanel,
3305 viewport.getGlobalColourScheme(), "Background");
3306 SliderPanel.showPIDSlider();
3317 protected void modifyConservation_actionPerformed(ActionEvent e)
3319 if (viewport.getConservationSelected()
3320 && viewport.getGlobalColourScheme() != null)
3322 SliderPanel.setConservationSlider(alignPanel,
3323 viewport.getGlobalColourScheme(), "Background");
3324 SliderPanel.showConservationSlider();
3335 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3337 viewport.setConservationSelected(conservationMenuItem.isSelected());
3339 viewport.setAbovePIDThreshold(false);
3340 abovePIDThreshold.setSelected(false);
3342 changeColour(viewport.getGlobalColourScheme());
3344 modifyConservation_actionPerformed(null);
3354 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3356 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3358 conservationMenuItem.setSelected(false);
3359 viewport.setConservationSelected(false);
3361 changeColour(viewport.getGlobalColourScheme());
3363 modifyPID_actionPerformed(null);
3373 public void userDefinedColour_actionPerformed(ActionEvent e)
3375 if (e.getActionCommand().equals(MessageManager.getString("action.user_defined")))
\r
3377 new UserDefinedColours(alignPanel, null);
3381 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3382 .getUserColourSchemes().get(e.getActionCommand());
3388 public void updateUserColourMenu()
3391 Component[] menuItems = colourMenu.getMenuComponents();
3392 int i, iSize = menuItems.length;
3393 for (i = 0; i < iSize; i++)
3395 if (menuItems[i].getName() != null
3396 && menuItems[i].getName().equals("USER_DEFINED"))
3398 colourMenu.remove(menuItems[i]);
3402 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3404 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3405 .getUserColourSchemes().keys();
3407 while (userColours.hasMoreElements())
3409 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3410 userColours.nextElement().toString());
3411 radioItem.setName("USER_DEFINED");
3412 radioItem.addMouseListener(new MouseAdapter()
3415 public void mousePressed(MouseEvent evt)
3417 if (evt.isControlDown()
3418 || SwingUtilities.isRightMouseButton(evt))
3420 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3422 int option = JOptionPane.showInternalConfirmDialog(
3423 jalview.gui.Desktop.desktop,
3424 MessageManager.getString("label.remove_from_default_list"),
3425 MessageManager.getString("label.remove_user_defined_colour"),
3426 JOptionPane.YES_NO_OPTION);
3427 if (option == JOptionPane.YES_OPTION)
3429 jalview.gui.UserDefinedColours
3430 .removeColourFromDefaults(radioItem.getText());
3431 colourMenu.remove(radioItem);
3435 radioItem.addActionListener(new ActionListener()
3438 public void actionPerformed(ActionEvent evt)
3440 userDefinedColour_actionPerformed(evt);
3447 radioItem.addActionListener(new ActionListener()
3450 public void actionPerformed(ActionEvent evt)
3452 userDefinedColour_actionPerformed(evt);
3456 colourMenu.insert(radioItem, 15);
3457 colours.add(radioItem);
3469 public void PIDColour_actionPerformed(ActionEvent e)
3471 changeColour(new PIDColourScheme());
3481 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3483 changeColour(new Blosum62ColourScheme());
3493 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3495 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3496 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3497 .getAlignment().getSequenceAt(0), null);
3498 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3499 viewport.getAlignment()));
3500 alignPanel.paintAlignment(true);
3510 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3512 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3513 AlignmentSorter.sortByID(viewport.getAlignment());
3514 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3515 viewport.getAlignment()));
3516 alignPanel.paintAlignment(true);
3526 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3528 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3529 AlignmentSorter.sortByLength(viewport.getAlignment());
3530 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3531 viewport.getAlignment()));
3532 alignPanel.paintAlignment(true);
3542 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3544 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3545 AlignmentSorter.sortByGroup(viewport.getAlignment());
3546 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3547 viewport.getAlignment()));
3549 alignPanel.paintAlignment(true);
3559 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3561 new RedundancyPanel(alignPanel, this);
3571 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3573 if ((viewport.getSelectionGroup() == null)
3574 || (viewport.getSelectionGroup().getSize() < 2))
3576 JOptionPane.showInternalMessageDialog(this,
3577 MessageManager.getString("label.you_must_select_least_two_sequences"), MessageManager.getString("label.invalid_selection"),
3578 JOptionPane.WARNING_MESSAGE);
3582 JInternalFrame frame = new JInternalFrame();
3583 frame.setContentPane(new PairwiseAlignPanel(viewport));
3584 Desktop.addInternalFrame(frame, MessageManager.getString("action.pairwise_alignment"), 600, 500);
\r
3595 public void PCAMenuItem_actionPerformed(ActionEvent e)
3597 if (((viewport.getSelectionGroup() != null)
3598 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3599 .getSelectionGroup().getSize() > 0))
3600 || (viewport.getAlignment().getHeight() < 4))
3602 JOptionPane.showInternalMessageDialog(this,
3603 MessageManager.getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3604 MessageManager.getString("label.sequence_selection_insufficient"),
3605 JOptionPane.WARNING_MESSAGE);
3610 new PCAPanel(alignPanel);
3614 public void autoCalculate_actionPerformed(ActionEvent e)
3616 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3617 if (viewport.autoCalculateConsensus)
3619 viewport.firePropertyChange("alignment", null, viewport
3620 .getAlignment().getSequences());
3625 public void sortByTreeOption_actionPerformed(ActionEvent e)
3627 viewport.sortByTree = sortByTree.isSelected();
3631 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3633 viewport.followSelection = listenToViewSelections.isSelected();
3643 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3645 NewTreePanel("AV", "PID", "Average distance tree using PID");
3655 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3657 NewTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3667 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3669 NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3679 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3681 NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3694 void NewTreePanel(String type, String pwType, String title)
3698 if (viewport.getSelectionGroup() != null
3699 && viewport.getSelectionGroup().getSize() > 0)
3701 if (viewport.getSelectionGroup().getSize() < 3)
3706 MessageManager.getString("label.you_need_more_two_sequences_selected_build_tree"),
3707 MessageManager.getString("label.not_enough_sequences"), JOptionPane.WARNING_MESSAGE);
3711 SequenceGroup sg = viewport.getSelectionGroup();
3713 /* Decide if the selection is a column region */
3714 for (SequenceI _s : sg.getSequences())
3716 if (_s.getLength() < sg.getEndRes())
3721 MessageManager.getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3722 MessageManager.getString("label.sequences_selection_not_aligned"),
3723 JOptionPane.WARNING_MESSAGE);
3729 title = title + " on region";
3730 tp = new TreePanel(alignPanel, type, pwType);
3734 // are the visible sequences aligned?
3735 if (!viewport.getAlignment().isAligned(false))
3740 MessageManager.getString("label.sequences_must_be_aligned_before_creating_tree"),
3741 MessageManager.getString("label.sequences_not_aligned"),
3742 JOptionPane.WARNING_MESSAGE);
3747 if (viewport.getAlignment().getHeight() < 2)
3752 tp = new TreePanel(alignPanel, type, pwType);
3757 if (viewport.viewName != null)
3759 title += viewport.viewName + " of ";
3762 title += this.title;
3764 Desktop.addInternalFrame(tp, title, 600, 500);
3775 public void addSortByOrderMenuItem(String title,
3776 final AlignmentOrder order)
3778 final JMenuItem item = new JMenuItem("by " + title);
3780 item.addActionListener(new java.awt.event.ActionListener()
3783 public void actionPerformed(ActionEvent e)
3785 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3787 // TODO: JBPNote - have to map order entries to curent SequenceI
3789 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3791 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
3794 alignPanel.paintAlignment(true);
3800 * Add a new sort by annotation score menu item
3803 * the menu to add the option to
3805 * the label used to retrieve scores for each sequence on the
3808 public void addSortByAnnotScoreMenuItem(JMenu sort,
3809 final String scoreLabel)
3811 final JMenuItem item = new JMenuItem(scoreLabel);
3813 item.addActionListener(new java.awt.event.ActionListener()
3816 public void actionPerformed(ActionEvent e)
3818 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3819 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3820 viewport.getAlignment());// ,viewport.getSelectionGroup());
3821 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3822 viewport.getAlignment()));
3823 alignPanel.paintAlignment(true);
3829 * last hash for alignment's annotation array - used to minimise cost of
3832 protected int _annotationScoreVectorHash;
3835 * search the alignment and rebuild the sort by annotation score submenu the
3836 * last alignment annotation vector hash is stored to minimize cost of
3837 * rebuilding in subsequence calls.
3841 public void buildSortByAnnotationScoresMenu()
3843 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3848 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
3850 sortByAnnotScore.removeAll();
3851 // almost certainly a quicker way to do this - but we keep it simple
3852 Hashtable scoreSorts = new Hashtable();
3853 AlignmentAnnotation aann[];
3854 for (SequenceI sqa : viewport.getAlignment().getSequences())
3856 aann = sqa.getAnnotation();
3857 for (int i = 0; aann != null && i < aann.length; i++)
3859 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3861 scoreSorts.put(aann[i].label, aann[i].label);
3865 Enumeration labels = scoreSorts.keys();
3866 while (labels.hasMoreElements())
3868 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3869 (String) labels.nextElement());
3871 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3874 _annotationScoreVectorHash = viewport.getAlignment()
3875 .getAlignmentAnnotation().hashCode();
3880 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3881 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3882 * call. Listeners are added to remove the menu item when the treePanel is
3883 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3887 * Displayed tree window.
3889 * SortBy menu item title.
3892 public void buildTreeMenu()
3894 calculateTree.removeAll();
3895 // build the calculate menu
3896 for (final String type:new String[] {"NJ", "AV"})
3898 for (final Object pwtype: ResidueProperties.scoreMatrices.keySet())
3900 JMenuItem tm = new JMenuItem();
3901 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
3902 final String title="Calculate "+type+" using "+sm.getName();
3903 tm.setText(title);// MessageManager.getString("label.neighbour_blosum62"));
3905 .addActionListener(new java.awt.event.ActionListener()
3907 public void actionPerformed(ActionEvent e)
3909 NewTreePanel(type, (String) pwtype, title);
3912 calculateTree.add(tm);
3916 sortByTreeMenu.removeAll();
3918 Vector comps = (Vector) PaintRefresher.components.get(viewport
3919 .getSequenceSetId());
3920 Vector treePanels = new Vector();
3921 int i, iSize = comps.size();
3922 for (i = 0; i < iSize; i++)
3924 if (comps.elementAt(i) instanceof TreePanel)
3926 treePanels.add(comps.elementAt(i));
3930 iSize = treePanels.size();
3934 sortByTreeMenu.setVisible(false);
3938 sortByTreeMenu.setVisible(true);
3940 for (i = 0; i < treePanels.size(); i++)
3942 final TreePanel tp = (TreePanel) treePanels.elementAt(i);
3943 final JMenuItem item = new JMenuItem(tp.getTitle());
3944 final NJTree tree = ((TreePanel) treePanels.elementAt(i)).getTree();
3945 item.addActionListener(new java.awt.event.ActionListener()
3948 public void actionPerformed(ActionEvent e)
3950 tp.sortByTree_actionPerformed(null);
3951 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3956 sortByTreeMenu.add(item);
3960 public boolean sortBy(AlignmentOrder alorder, String undoname)
3962 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3963 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3964 if (undoname != null)
3966 addHistoryItem(new OrderCommand(undoname, oldOrder,
3967 viewport.getAlignment()));
3969 alignPanel.paintAlignment(true);
3974 * Work out whether the whole set of sequences or just the selected set will
3975 * be submitted for multiple alignment.
3978 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3980 // Now, check we have enough sequences
3981 AlignmentView msa = null;
3983 if ((viewport.getSelectionGroup() != null)
3984 && (viewport.getSelectionGroup().getSize() > 1))
3986 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3987 // some common interface!
3989 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3990 * SequenceI[sz = seqs.getSize(false)];
3992 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3993 * seqs.getSequenceAt(i); }
3995 msa = viewport.getAlignmentView(true);
4000 * Vector seqs = viewport.getAlignment().getSequences();
4002 * if (seqs.size() > 1) { msa = new SequenceI[seqs.size()];
4004 * for (int i = 0; i < seqs.size(); i++) { msa[i] = (SequenceI)
4005 * seqs.elementAt(i); } }
4007 msa = viewport.getAlignmentView(false);
4013 * Decides what is submitted to a secondary structure prediction service: the
4014 * first sequence in the alignment, or in the current selection, or, if the
4015 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4016 * region or the whole alignment. (where the first sequence in the set is the
4017 * one that the prediction will be for).
4019 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4021 AlignmentView seqs = null;
4023 if ((viewport.getSelectionGroup() != null)
4024 && (viewport.getSelectionGroup().getSize() > 0))
4026 seqs = viewport.getAlignmentView(true);
4030 seqs = viewport.getAlignmentView(false);
4032 // limit sequences - JBPNote in future - could spawn multiple prediction
4034 // TODO: viewport.getAlignment().isAligned is a global state - the local
4035 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4036 if (!viewport.getAlignment().isAligned(false))
4038 seqs.setSequences(new SeqCigar[]
4039 { seqs.getSequences()[0] });
4040 // TODO: if seqs.getSequences().length>1 then should really have warned
4054 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
4056 // Pick the tree file
4057 JalviewFileChooser chooser = new JalviewFileChooser(
4058 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4059 chooser.setFileView(new JalviewFileView());
4060 chooser.setDialogTitle(MessageManager.getString("label.select_newick_like_tree_file"));
\r
4061 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
\r
4063 int value = chooser.showOpenDialog(null);
4065 if (value == JalviewFileChooser.APPROVE_OPTION)
4067 String choice = chooser.getSelectedFile().getPath();
4068 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4069 jalview.io.NewickFile fin = null;
4072 fin = new jalview.io.NewickFile(choice, "File");
4073 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4074 } catch (Exception ex)
4076 JOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4077 MessageManager.getString("label.problem_reading_tree_file"), JOptionPane.WARNING_MESSAGE);
4078 ex.printStackTrace();
4080 if (fin != null && fin.hasWarningMessage())
4082 JOptionPane.showMessageDialog(Desktop.desktop,
4083 fin.getWarningMessage(), MessageManager.getString("label.possible_problem_with_tree_file"),
4084 JOptionPane.WARNING_MESSAGE);
4090 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4092 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4095 public TreePanel ShowNewickTree(NewickFile nf, String title)
4097 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4100 public TreePanel ShowNewickTree(NewickFile nf, String title,
4101 AlignmentView input)
4103 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4106 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4107 int h, int x, int y)
4109 return ShowNewickTree(nf, title, null, w, h, x, y);
4113 * Add a treeviewer for the tree extracted from a newick file object to the
4114 * current alignment view
4121 * Associated alignment input data (or null)
4130 * @return TreePanel handle
4132 public TreePanel ShowNewickTree(NewickFile nf, String title,
4133 AlignmentView input, int w, int h, int x, int y)
4135 TreePanel tp = null;
4141 if (nf.getTree() != null)
4143 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4149 tp.setLocation(x, y);
4152 Desktop.addInternalFrame(tp, title, w, h);
4154 } catch (Exception ex)
4156 ex.printStackTrace();
4162 private boolean buildingMenu = false;
4165 * Generates menu items and listener event actions for web service clients
4168 public void BuildWebServiceMenu()
4170 while (buildingMenu)
4174 System.err.println("Waiting for building menu to finish.");
4176 } catch (Exception e)
4181 final AlignFrame me = this;
4182 buildingMenu = true;
4183 new Thread(new Runnable()
4188 final List<JMenuItem> legacyItems=new ArrayList<JMenuItem>();
4191 System.err.println("Building ws menu again "
4192 + Thread.currentThread());
4193 // TODO: add support for context dependent disabling of services based
4195 // alignment and current selection
4196 // TODO: add additional serviceHandle parameter to specify abstract
4198 // class independently of AbstractName
4199 // TODO: add in rediscovery GUI function to restart discoverer
4200 // TODO: group services by location as well as function and/or
4202 // object broker mechanism.
4203 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4204 final IProgressIndicator af = me;
4205 final JMenu msawsmenu = new JMenu("Alignment");
4206 final JMenu secstrmenu = new JMenu(
4207 "Secondary Structure Prediction");
4208 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4209 final JMenu analymenu = new JMenu("Analysis");
4210 final JMenu dismenu = new JMenu("Protein Disorder");
4211 // JAL-940 - only show secondary structure prediction services from
4212 // the legacy server
4213 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4215 Discoverer.services != null && (Discoverer.services.size() > 0))
4217 // TODO: refactor to allow list of AbstractName/Handler bindings to
4219 // stored or retrieved from elsewhere
4220 // No MSAWS used any more:
4221 // Vector msaws = null; // (Vector) Discoverer.services.get("MsaWS");
4222 Vector secstrpr = (Vector) Discoverer.services
4224 if (secstrpr != null)
4226 // Add any secondary structure prediction services
4227 for (int i = 0, j = secstrpr.size(); i < j; i++)
4229 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4231 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4232 .getServiceClient(sh);
4233 int p=secstrmenu.getItemCount();
4234 impl.attachWSMenuEntry(secstrmenu, me);
4235 int q=secstrmenu.getItemCount();
4236 for (int litm=p;litm<q; litm++)
4238 legacyItems.add(secstrmenu.getItem(litm));
4244 // Add all submenus in the order they should appear on the web
4246 wsmenu.add(msawsmenu);
4247 wsmenu.add(secstrmenu);
4248 wsmenu.add(dismenu);
4249 wsmenu.add(analymenu);
4250 // No search services yet
4251 // wsmenu.add(seqsrchmenu);
4253 javax.swing.SwingUtilities.invokeLater(new Runnable()
4260 webService.removeAll();
4261 // first, add discovered services onto the webservices menu
4262 if (wsmenu.size() > 0)
4264 for (int i = 0, j = wsmenu.size(); i < j; i++)
4266 webService.add(wsmenu.get(i));
4271 webService.add(me.webServiceNoServices);
4273 // TODO: move into separate menu builder class.
4274 boolean new_sspred=false;
4275 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4277 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4278 if (jws2servs != null)
4280 if (jws2servs.hasServices())
4282 jws2servs.attachWSMenuEntry(webService, me);
4283 for (Jws2Instance sv:jws2servs.getServices()) {
4284 if (sv.description.toLowerCase().contains("jpred"))
4286 for (JMenuItem jmi:legacyItems)
4288 jmi.setVisible(false);
4294 if (jws2servs.isRunning())
4296 JMenuItem tm = new JMenuItem(
4297 "Still discovering JABA Services");
4298 tm.setEnabled(false);
4303 build_urlServiceMenu(me.webService);
4304 build_fetchdbmenu(webService);
4305 for (JMenu item : wsmenu)
4307 if (item.getItemCount() == 0)
4309 item.setEnabled(false);
4313 item.setEnabled(true);
4316 } catch (Exception e)
4319 .debug("Exception during web service menu building process.",
4325 } catch (Exception e)
4330 buildingMenu = false;
4337 * construct any groupURL type service menu entries.
4341 private void build_urlServiceMenu(JMenu webService)
4343 // TODO: remove this code when 2.7 is released
4344 // DEBUG - alignmentView
4346 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4347 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4349 * @Override public void actionPerformed(ActionEvent e) {
4350 * jalview.datamodel.AlignmentView
4351 * .testSelectionViews(af.viewport.getAlignment(),
4352 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4354 * }); webService.add(testAlView);
4356 // TODO: refactor to RestClient discoverer and merge menu entries for
4357 // rest-style services with other types of analysis/calculation service
4358 // SHmmr test client - still being implemented.
4359 // DEBUG - alignmentView
4361 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4364 client.attachWSMenuEntry(
4365 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4369 if (Cache.getDefault("SHOW_ENFIN_SERVICES", true))
4371 jalview.ws.EnfinEnvision2OneWay.getInstance().attachWSMenuEntry(
4377 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
4378 * chooser = new JalviewFileChooser(jalview.bin.Cache.
4379 * getProperty("LAST_DIRECTORY"));
4381 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
4382 * to Vamsas file"); chooser.setToolTipText("Export");
4384 * int value = chooser.showSaveDialog(this);
4386 * if (value == JalviewFileChooser.APPROVE_OPTION) {
4387 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
4388 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
4389 * chooser.getSelectedFile().getAbsolutePath(), this); } }
4392 * prototype of an automatically enabled/disabled analysis function
4395 protected void setShowProductsEnabled()
4397 SequenceI[] selection = viewport.getSequenceSelection();
4398 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
4399 viewport.getAlignment().getDataset()))
4401 showProducts.setEnabled(true);
4406 showProducts.setEnabled(false);
4411 * search selection for sequence xRef products and build the show products
4416 * @return true if showProducts menu should be enabled.
4418 public boolean canShowProducts(SequenceI[] selection,
4419 boolean isRegionSelection, Alignment dataset)
4421 boolean showp = false;
4424 showProducts.removeAll();
4425 final boolean dna = viewport.getAlignment().isNucleotide();
4426 final Alignment ds = dataset;
4427 String[] ptypes = (selection == null || selection.length == 0) ? null
4428 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4430 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4431 // selection, dataset, true);
4432 final SequenceI[] sel = selection;
4433 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4436 final boolean isRegSel = isRegionSelection;
4437 final AlignFrame af = this;
4438 final String source = ptypes[t];
4439 JMenuItem xtype = new JMenuItem(ptypes[t]);
4440 xtype.addActionListener(new ActionListener()
4444 public void actionPerformed(ActionEvent e)
4446 // TODO: new thread for this call with vis-delay
4447 af.showProductsFor(af.viewport.getSequenceSelection(), ds,
4448 isRegSel, dna, source);
4452 showProducts.add(xtype);
4454 showProducts.setVisible(showp);
4455 showProducts.setEnabled(showp);
4456 } catch (Exception e)
4458 jalview.bin.Cache.log
4459 .warn("canTranslate threw an exception - please report to help@jalview.org",
4466 protected void showProductsFor(SequenceI[] sel, Alignment ds,
4467 boolean isRegSel, boolean dna, String source)
4469 final boolean fisRegSel = isRegSel;
4470 final boolean fdna = dna;
4471 final String fsrc = source;
4472 final AlignFrame ths = this;
4473 final SequenceI[] fsel = sel;
4474 Runnable foo = new Runnable()
4480 final long sttime = System.currentTimeMillis();
4481 ths.setProgressBar("Searching for sequences from " + fsrc, sttime);
4484 Alignment ds = ths.getViewport().getAlignment().getDataset(); // update
4488 Alignment prods = CrossRef
4489 .findXrefSequences(fsel, fdna, fsrc, ds);
4492 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4493 for (int s = 0; s < sprods.length; s++)
4495 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4496 if (ds.getSequences() == null
4497 || !ds.getSequences().contains(
4498 sprods[s].getDatasetSequence()))
4499 ds.addSequence(sprods[s].getDatasetSequence());
4500 sprods[s].updatePDBIds();
4502 Alignment al = new Alignment(sprods);
4503 AlignedCodonFrame[] cf = prods.getCodonFrames();
4505 for (int s = 0; cf != null && s < cf.length; s++)
4507 al.addCodonFrame(cf[s]);
4510 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4512 String newtitle = "" + ((fdna) ? "Proteins " : "Nucleotides ")
4513 + " for " + ((fisRegSel) ? "selected region of " : "")
4515 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4520 System.err.println("No Sequences generated for xRef type "
4523 } catch (Exception e)
4525 jalview.bin.Cache.log.error(
4526 "Exception when finding crossreferences", e);
4527 } catch (OutOfMemoryError e)
4529 new OOMWarning("whilst fetching crossreferences", e);
4532 jalview.bin.Cache.log.error("Error when finding crossreferences",
4535 ths.setProgressBar("Finished searching for sequences from " + fsrc,
4540 Thread frunner = new Thread(foo);
4544 public boolean canShowTranslationProducts(SequenceI[] selection,
4545 AlignmentI alignment)
4550 return (jalview.analysis.Dna.canTranslate(selection,
4551 viewport.getViewAsVisibleContigs(true)));
4552 } catch (Exception e)
4554 jalview.bin.Cache.log
4555 .warn("canTranslate threw an exception - please report to help@jalview.org",
4562 public void showProducts_actionPerformed(ActionEvent e)
4564 // /////////////////////////////
4565 // Collect Data to be translated/transferred
4567 SequenceI[] selection = viewport.getSequenceSelection();
4568 AlignmentI al = null;
4571 al = jalview.analysis.Dna.CdnaTranslate(selection, viewport
4572 .getViewAsVisibleContigs(true), viewport.getGapCharacter(),
4573 viewport.getAlignment().getDataset());
4574 } catch (Exception ex)
4577 jalview.bin.Cache.log.debug("Exception during translation.", ex);
4584 MessageManager.getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation"),
4585 MessageManager.getString("label.translation_failed"), JOptionPane.WARNING_MESSAGE);
4589 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4590 Desktop.addInternalFrame(af, MessageManager.formatMessage("label.translation_of_params", new String[]{this.getTitle()}),
\r
4591 DEFAULT_WIDTH, DEFAULT_HEIGHT);
4596 public void showTranslation_actionPerformed(ActionEvent e)
4598 // /////////////////////////////
4599 // Collect Data to be translated/transferred
4601 SequenceI[] selection = viewport.getSequenceSelection();
4602 String[] seqstring = viewport.getViewAsString(true);
4603 AlignmentI al = null;
4606 al = jalview.analysis.Dna.CdnaTranslate(selection, seqstring,
4607 viewport.getViewAsVisibleContigs(true), viewport
4608 .getGapCharacter(), viewport.getAlignment()
4609 .getAlignmentAnnotation(), viewport.getAlignment()
4610 .getWidth(), viewport.getAlignment().getDataset());
4611 } catch (Exception ex)
4614 jalview.bin.Cache.log.error("Exception during translation. Please report this !", ex);
4618 MessageManager.getString("label.error_when_translating_sequences_submit_bug_report"),
4619 MessageManager.getString("label.implementation_error") + MessageManager.getString("translation_failed"), JOptionPane.ERROR_MESSAGE);
4627 MessageManager.getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation"),
4628 MessageManager.getString("label.translation_failed"), JOptionPane.WARNING_MESSAGE);
4632 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4633 Desktop.addInternalFrame(af, MessageManager.formatMessage("label.translation_of_params", new String[]{this.getTitle()}),
\r
4634 DEFAULT_WIDTH, DEFAULT_HEIGHT);
4639 * Try to load a features file onto the alignment.
4642 * contents or path to retrieve file
4644 * access mode of file (see jalview.io.AlignFile)
4645 * @return true if features file was parsed corectly.
4647 public boolean parseFeaturesFile(String file, String type)
4649 boolean featuresFile = false;
4652 featuresFile = new FeaturesFile(file, type).parse(viewport
4653 .getAlignment().getDataset(), alignPanel.seqPanel.seqCanvas
4654 .getFeatureRenderer().featureColours, false,
4655 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4656 } catch (Exception ex)
4658 ex.printStackTrace();
4663 viewport.showSequenceFeatures = true;
4664 showSeqFeatures.setSelected(true);
4665 if (alignPanel.seqPanel.seqCanvas.fr != null)
4667 // update the min/max ranges where necessary
4668 alignPanel.seqPanel.seqCanvas.fr.findAllFeatures(true);
4670 if (featureSettings != null)
4672 featureSettings.setTableData();
4674 alignPanel.paintAlignment(true);
4677 return featuresFile;
4681 public void dragEnter(DropTargetDragEvent evt)
4686 public void dragExit(DropTargetEvent evt)
4691 public void dragOver(DropTargetDragEvent evt)
4696 public void dropActionChanged(DropTargetDragEvent evt)
4701 public void drop(DropTargetDropEvent evt)
4703 Transferable t = evt.getTransferable();
4704 java.util.List files = null;
4708 DataFlavor uriListFlavor = new DataFlavor(
4709 "text/uri-list;class=java.lang.String");
4710 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
4712 // Works on Windows and MacOSX
4713 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4714 files = (java.util.List) t
4715 .getTransferData(DataFlavor.javaFileListFlavor);
4717 else if (t.isDataFlavorSupported(uriListFlavor))
4719 // This is used by Unix drag system
4720 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4721 String data = (String) t.getTransferData(uriListFlavor);
4722 files = new java.util.ArrayList(1);
4723 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
4724 data, "\r\n"); st.hasMoreTokens();)
4726 String s = st.nextToken();
4727 if (s.startsWith("#"))
4729 // the line is a comment (as per the RFC 2483)
4733 java.net.URI uri = new java.net.URI(s);
4734 // check to see if we can handle this kind of URI
4735 if (uri.getScheme().toLowerCase().startsWith("http"))
4737 files.add(uri.toString());
4741 // otherwise preserve old behaviour: catch all for file objects
4742 java.io.File file = new java.io.File(uri);
4743 files.add(file.toString());
4747 } catch (Exception e)
4749 e.printStackTrace();
4755 // check to see if any of these files have names matching sequences in
4757 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4758 .getAlignment().getSequencesArray());
4760 * Object[] { String,SequenceI}
4762 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
4763 ArrayList<String> filesnotmatched = new ArrayList<String>();
4764 for (int i = 0; i < files.size(); i++)
4766 String file = files.get(i).toString();
4768 String protocol = FormatAdapter.checkProtocol(file);
4769 if (protocol == jalview.io.FormatAdapter.FILE)
4771 File fl = new File(file);
4772 pdbfn = fl.getName();
4774 else if (protocol == jalview.io.FormatAdapter.URL)
4776 URL url = new URL(file);
4777 pdbfn = url.getFile();
4779 if (pdbfn.length() > 0)
4781 // attempt to find a match in the alignment
4782 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4783 int l = 0, c = pdbfn.indexOf(".");
4784 while (mtch == null && c != -1)
4789 } while ((c = pdbfn.indexOf(".", l)) > l);
4792 pdbfn = pdbfn.substring(0, l);
4794 mtch = idm.findAllIdMatches(pdbfn);
4801 type = new IdentifyFile().Identify(file, protocol);
4802 } catch (Exception ex)
4808 if (type.equalsIgnoreCase("PDB"))
4810 filesmatched.add(new Object[]
4811 { file, protocol, mtch });
4816 // File wasn't named like one of the sequences or wasn't a PDB file.
4817 filesnotmatched.add(file);
4821 if (filesmatched.size() > 0)
4823 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4827 MessageManager.formatMessage("label.automatically_associate_pdb_files_with_sequences_same_name",
4828 new String[]{Integer.valueOf(filesmatched.size()).toString()}),
4829 MessageManager.getString("label.automatically_associate_pdb_files_by_name"),
4830 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
4833 for (Object[] fm : filesmatched)
4835 // try and associate
4836 // TODO: may want to set a standard ID naming formalism for
4837 // associating PDB files which have no IDs.
4838 for (SequenceI toassoc : (SequenceI[]) fm[2])
4840 PDBEntry pe = new AssociatePdbFileWithSeq()
4841 .associatePdbWithSeq((String) fm[0],
4842 (String) fm[1], toassoc, false);
4845 System.err.println("Associated file : "
4846 + ((String) fm[0]) + " with "
4847 + toassoc.getDisplayId(true));
4851 alignPanel.paintAlignment(true);
4855 if (filesnotmatched.size() > 0)
4858 && (Cache.getDefault(
4859 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
4862 MessageManager.formatMessage("label.ignore_unmatched_dropped_files_info", new String[]{Integer.valueOf(filesnotmatched.size()).toString()}),
4863 MessageManager.getString("label.ignore_unmatched_dropped_files"),
4864 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
4868 for (String fn : filesnotmatched)
4870 loadJalviewDataFile(fn, null, null, null);
4874 } catch (Exception ex)
4876 ex.printStackTrace();
4882 * Attempt to load a "dropped" file or URL string: First by testing whether
4883 * it's and Annotation file, then a JNet file, and finally a features file. If
4884 * all are false then the user may have dropped an alignment file onto this
4888 * either a filename or a URL string.
4890 public void loadJalviewDataFile(String file, String protocol,
4891 String format, SequenceI assocSeq)
4895 if (protocol == null)
4897 protocol = jalview.io.FormatAdapter.checkProtocol(file);
4899 // if the file isn't identified, or not positively identified as some
4900 // other filetype (PFAM is default unidentified alignment file type) then
4901 // try to parse as annotation.
4902 boolean isAnnotation = (format == null || format
4903 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
4904 .readAnnotationFile(viewport.getAlignment(), file, protocol)
4909 // first see if its a T-COFFEE score file
4910 TCoffeeScoreFile tcf = null;
4913 tcf = new TCoffeeScoreFile(file, protocol);
4916 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4918 tcoffeeColour.setEnabled(true);
4919 tcoffeeColour.setSelected(true);
4920 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
4921 isAnnotation = true;
4922 statusBar.setText(MessageManager.getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
4926 // some problem - if no warning its probable that the ID matching
4927 // process didn't work
4931 tcf.getWarningMessage() == null ? MessageManager.getString("label.check_file_matches_sequence_ids_alignment")
4932 : tcf.getWarningMessage(),
4933 MessageManager.getString("label.problem_reading_tcoffee_score_file"),
4934 JOptionPane.WARNING_MESSAGE);
4941 } catch (Exception x)
4944 .debug("Exception when processing data source as T-COFFEE score file",
4950 // try to see if its a JNet 'concise' style annotation file *before*
4952 // try to parse it as a features file
4955 format = new IdentifyFile().Identify(file, protocol);
4957 if (format.equalsIgnoreCase("JnetFile"))
4959 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
4961 new JnetAnnotationMaker().add_annotation(predictions,
4962 viewport.getAlignment(), 0, false);
4963 isAnnotation = true;
4968 * if (format.equalsIgnoreCase("PDB")) {
4970 * String pdbfn = ""; // try to match up filename with sequence id
4971 * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
4972 * new File(file); pdbfn = fl.getName(); } else if (protocol ==
4973 * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
4974 * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
4975 * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4976 * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
4977 * // attempt to find a match in the alignment SequenceI mtch =
4978 * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
4979 * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
4980 * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
4981 * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
4982 * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
4983 * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
4984 * { System.err.println("Associated file : " + file + " with " +
4985 * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
4986 * TODO: maybe need to load as normal otherwise return; } }
4988 // try to parse it as a features file
4989 boolean isGroupsFile = parseFeaturesFile(file, protocol);
4990 // if it wasn't a features file then we just treat it as a general
4991 // alignment file to load into the current view.
4994 new FileLoader().LoadFile(viewport, file, protocol, format);
4998 alignPanel.paintAlignment(true);
5006 alignPanel.adjustAnnotationHeight();
5007 viewport.updateSequenceIdColours();
5008 buildSortByAnnotationScoresMenu();
5009 alignPanel.paintAlignment(true);
5011 } catch (Exception ex)
5013 ex.printStackTrace();
5014 } catch (OutOfMemoryError oom)
5019 } catch (Exception x)
5025 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5026 : "using " + protocol + " from " + file)
5028 + (format != null ? "(parsing as '" + format
5029 + "' file)" : ""), oom, Desktop.desktop);
5034 public void tabSelectionChanged(int index)
5038 alignPanel = (AlignmentPanel) alignPanels.elementAt(index);
5039 viewport = alignPanel.av;
5040 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5041 setMenusFromViewport(viewport);
5046 public void tabbedPane_mousePressed(MouseEvent e)
5048 if (SwingUtilities.isRightMouseButton(e))
5050 String reply = JOptionPane.showInternalInputDialog(this,
5051 MessageManager.getString("label.enter_view_name"), MessageManager.getString("label.enter_view_name"),
5052 JOptionPane.QUESTION_MESSAGE);
5056 viewport.viewName = reply;
5057 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5062 public AlignViewport getCurrentView()
5068 * Open the dialog for regex description parsing.
5071 protected void extractScores_actionPerformed(ActionEvent e)
5073 ParseProperties pp = new jalview.analysis.ParseProperties(
5074 viewport.getAlignment());
5075 // TODO: verify regex and introduce GUI dialog for version 2.5
5076 // if (pp.getScoresFromDescription("col", "score column ",
5077 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5079 if (pp.getScoresFromDescription("description column",
5080 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5082 buildSortByAnnotationScoresMenu();
5090 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5094 protected void showDbRefs_actionPerformed(ActionEvent e)
5096 viewport.setShowDbRefs(showDbRefsMenuitem.isSelected());
5102 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5106 protected void showNpFeats_actionPerformed(ActionEvent e)
5108 viewport.setShowNpFeats(showNpFeatsMenuitem.isSelected());
5112 * find the viewport amongst the tabs in this alignment frame and close that
5117 public boolean closeView(AlignViewport av)
5121 this.closeMenuItem_actionPerformed(false);
5124 Component[] comp = tabbedPane.getComponents();
5125 for (int i = 0; comp != null && i < comp.length; i++)
5127 if (comp[i] instanceof AlignmentPanel)
5129 if (((AlignmentPanel) comp[i]).av == av)
5132 closeView((AlignmentPanel) comp[i]);
5140 protected void build_fetchdbmenu(JMenu webService)
5142 // Temporary hack - DBRef Fetcher always top level ws entry.
5143 // TODO We probably want to store a sequence database checklist in
5144 // preferences and have checkboxes.. rather than individual sources selected
5146 final JMenu rfetch = new JMenu(MessageManager.getString("action.fetch_db_references"));
\r
5147 rfetch.setToolTipText(MessageManager.getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
\r
5148 webService.add(rfetch);
5150 JMenuItem fetchr = new JMenuItem(MessageManager.getString("label.standard_databases"));
\r
5151 fetchr.setToolTipText(MessageManager.getString("label.fetch_embl_uniprot"));
\r
5152 fetchr.addActionListener(new ActionListener()
5156 public void actionPerformed(ActionEvent e)
5158 new Thread(new Runnable()
5164 new jalview.ws.DBRefFetcher(alignPanel.av
5165 .getSequenceSelection(), alignPanel.alignFrame)
5166 .fetchDBRefs(false);
5174 final AlignFrame me = this;
5175 new Thread(new Runnable()
5180 final jalview.ws.SequenceFetcher sf = SequenceFetcher
5181 .getSequenceFetcherSingleton(me);
5182 javax.swing.SwingUtilities.invokeLater(new Runnable()
5187 String[] dbclasses = sf.getOrderedSupportedSources();
5188 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5189 // jalview.util.QuickSort.sort(otherdb, otherdb);
5190 List<DbSourceProxy> otherdb;
5191 JMenu dfetch = new JMenu();
5192 JMenu ifetch = new JMenu();
5193 JMenuItem fetchr = null;
5194 int comp = 0, icomp = 0, mcomp = 15;
5195 String mname = null;
5197 for (String dbclass : dbclasses)
5199 otherdb = sf.getSourceProxy(dbclass);
5200 // add a single entry for this class, or submenu allowing 'fetch
5202 if (otherdb == null || otherdb.size() < 1)
5206 // List<DbSourceProxy> dbs=otherdb;
5207 // otherdb=new ArrayList<DbSourceProxy>();
5208 // for (DbSourceProxy db:dbs)
5210 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5214 mname = "From " + dbclass;
5216 if (otherdb.size() == 1)
5218 final DbSourceProxy[] dassource = otherdb
5219 .toArray(new DbSourceProxy[0]);
5220 DbSourceProxy src = otherdb.get(0);
5221 fetchr = new JMenuItem(src.getDbSource());
5222 fetchr.addActionListener(new ActionListener()
5226 public void actionPerformed(ActionEvent e)
5228 new Thread(new Runnable()
5234 new jalview.ws.DBRefFetcher(alignPanel.av
5235 .getSequenceSelection(),
5236 alignPanel.alignFrame, dassource)
5237 .fetchDBRefs(false);
5243 fetchr.setToolTipText("<html>"
5244 + JvSwingUtils.wrapTooltip("Retrieve from "
5245 + src.getDbName()) + "<html>");
5251 final DbSourceProxy[] dassource = otherdb
5252 .toArray(new DbSourceProxy[0]);
5254 DbSourceProxy src = otherdb.get(0);
5255 fetchr = new JMenuItem(MessageManager.formatMessage("label.fetch_all_param", new String[]{src.getDbSource()}));
\r
5256 fetchr.addActionListener(new ActionListener()
5259 public void actionPerformed(ActionEvent e)
5261 new Thread(new Runnable()
5267 new jalview.ws.DBRefFetcher(alignPanel.av
5268 .getSequenceSelection(),
5269 alignPanel.alignFrame, dassource)
5270 .fetchDBRefs(false);
5276 fetchr.setToolTipText("<html>"
5277 + JvSwingUtils.wrapTooltip("Retrieve from all "
5278 + otherdb.size() + " sources in "
5279 + src.getDbSource() + "<br>First is :"
5280 + src.getDbName()) + "<html>");
5283 // and then build the rest of the individual menus
5284 ifetch = new JMenu("Sources from " + src.getDbSource());
5286 String imname = null;
5288 for (DbSourceProxy sproxy : otherdb)
5290 String dbname = sproxy.getDbName();
5291 String sname = dbname.length() > 5 ? dbname.substring(0,
5292 5) + "..." : dbname;
5293 String msname = dbname.length() > 10 ? dbname.substring(
5294 0, 10) + "..." : dbname;
5297 imname = "from '" + sname + "'";
5299 fetchr = new JMenuItem(msname);
5300 final DbSourceProxy[] dassrc =
5302 fetchr.addActionListener(new ActionListener()
5306 public void actionPerformed(ActionEvent e)
5308 new Thread(new Runnable()
5314 new jalview.ws.DBRefFetcher(alignPanel.av
5315 .getSequenceSelection(),
5316 alignPanel.alignFrame, dassrc)
5317 .fetchDBRefs(false);
5323 fetchr.setToolTipText("<html>"
5324 + JvSwingUtils.wrapTooltip("Retrieve from "
5325 + dbname) + "</html>");
5328 if (++icomp >= mcomp || i == (otherdb.size()))
5330 ifetch.setText(MessageManager.formatMessage("label.source_to_target",imname,sname));
5332 ifetch = new JMenu();
5340 if (comp >= mcomp || dbi >= (dbclasses.length))
5342 dfetch.setText(MessageManager.formatMessage("label.source_to_target",mname,dbclass));
5344 dfetch = new JMenu();
5357 * Left justify the whole alignment.
5360 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5362 AlignmentI al = viewport.getAlignment();
5364 viewport.firePropertyChange("alignment", null, al);
5368 * Right justify the whole alignment.
5371 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5373 AlignmentI al = viewport.getAlignment();
5375 viewport.firePropertyChange("alignment", null, al);
5378 public void setShowSeqFeatures(boolean b)
5380 showSeqFeatures.setSelected(true);
5381 viewport.setShowSequenceFeatures(true);
5388 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5389 * awt.event.ActionEvent)
5392 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5394 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5395 alignPanel.paintAlignment(true);
5402 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5406 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5408 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5409 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5417 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5418 * .event.ActionEvent)
5421 protected void showGroupConservation_actionPerformed(ActionEvent e)
5423 viewport.setShowGroupConservation(showGroupConservation.getState());
5424 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5431 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5432 * .event.ActionEvent)
5435 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5437 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5438 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5445 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5446 * .event.ActionEvent)
5449 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5451 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5452 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5456 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5458 showSequenceLogo.setState(true);
5459 viewport.setShowSequenceLogo(true);
5460 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5461 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5465 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5467 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5474 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5475 * .event.ActionEvent)
5478 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5480 if (avc.makeGroupsFromSelection()) {
5481 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5482 alignPanel.updateAnnotation();
5483 alignPanel.paintAlignment(true);
5488 protected void createGroup_actionPerformed(ActionEvent e)
5490 if (avc.createGroup())
5492 alignPanel.alignmentChanged();
5497 protected void unGroup_actionPerformed(ActionEvent e)
5501 alignPanel.alignmentChanged();
5506 * make the given alignmentPanel the currently selected tab
5508 * @param alignmentPanel
5510 public void setDisplayedView(AlignmentPanel alignmentPanel)
5512 if (!viewport.getSequenceSetId().equals(
5513 alignmentPanel.av.getSequenceSetId()))
5516 "Implementation error: cannot show a view from another alignment in an AlignFrame.");
5518 if (tabbedPane != null
5519 & alignPanels.indexOf(alignmentPanel) != tabbedPane
5520 .getSelectedIndex())
5522 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5527 class PrintThread extends Thread
5531 public PrintThread(AlignmentPanel ap)
5536 static PageFormat pf;
5541 PrinterJob printJob = PrinterJob.getPrinterJob();
5545 printJob.setPrintable(ap, pf);
5549 printJob.setPrintable(ap);
5552 if (printJob.printDialog())
5557 } catch (Exception PrintException)
5559 PrintException.printStackTrace();