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.AlignmentUtils;
24 import jalview.analysis.Conservation;
25 import jalview.analysis.CrossRef;
26 import jalview.analysis.NJTree;
27 import jalview.analysis.ParseProperties;
28 import jalview.analysis.SequenceIdMatcher;
29 import jalview.api.AlignViewControllerGuiI;
30 import jalview.api.AlignViewControllerI;
31 import jalview.api.analysis.ScoreModelI;
32 import jalview.bin.Cache;
33 import jalview.commands.CommandI;
34 import jalview.commands.EditCommand;
35 import jalview.commands.OrderCommand;
36 import jalview.commands.RemoveGapColCommand;
37 import jalview.commands.RemoveGapsCommand;
38 import jalview.commands.SlideSequencesCommand;
39 import jalview.commands.TrimRegionCommand;
40 import jalview.datamodel.AlignedCodonFrame;
41 import jalview.datamodel.Alignment;
42 import jalview.datamodel.AlignmentAnnotation;
43 import jalview.datamodel.AlignmentI;
44 import jalview.datamodel.AlignmentOrder;
45 import jalview.datamodel.AlignmentView;
46 import jalview.datamodel.ColumnSelection;
47 import jalview.datamodel.PDBEntry;
48 import jalview.datamodel.SeqCigar;
49 import jalview.datamodel.Sequence;
50 import jalview.datamodel.SequenceGroup;
51 import jalview.datamodel.SequenceI;
52 import jalview.io.AlignmentProperties;
53 import jalview.io.AnnotationFile;
54 import jalview.io.FeaturesFile;
55 import jalview.io.FileLoader;
56 import jalview.io.FormatAdapter;
57 import jalview.io.HTMLOutput;
58 import jalview.io.IdentifyFile;
59 import jalview.io.JalviewFileChooser;
60 import jalview.io.JalviewFileView;
61 import jalview.io.JnetAnnotationMaker;
62 import jalview.io.NewickFile;
63 import jalview.io.TCoffeeScoreFile;
64 import jalview.jbgui.GAlignFrame;
65 import jalview.schemes.Blosum62ColourScheme;
66 import jalview.schemes.BuriedColourScheme;
67 import jalview.schemes.ClustalxColourScheme;
68 import jalview.schemes.ColourSchemeI;
69 import jalview.schemes.ColourSchemeProperty;
70 import jalview.schemes.HelixColourScheme;
71 import jalview.schemes.HydrophobicColourScheme;
72 import jalview.schemes.NucleotideColourScheme;
73 import jalview.schemes.PIDColourScheme;
74 import jalview.schemes.PurinePyrimidineColourScheme;
75 import jalview.schemes.RNAHelicesColourChooser;
76 import jalview.schemes.ResidueProperties;
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.Component;
91 import java.awt.GridLayout;
92 import java.awt.Rectangle;
93 import java.awt.Toolkit;
94 import java.awt.datatransfer.Clipboard;
95 import java.awt.datatransfer.DataFlavor;
96 import java.awt.datatransfer.StringSelection;
97 import java.awt.datatransfer.Transferable;
98 import java.awt.dnd.DnDConstants;
99 import java.awt.dnd.DropTargetDragEvent;
100 import java.awt.dnd.DropTargetDropEvent;
101 import java.awt.dnd.DropTargetEvent;
102 import java.awt.dnd.DropTargetListener;
103 import java.awt.event.ActionEvent;
104 import java.awt.event.ActionListener;
105 import java.awt.event.KeyAdapter;
106 import java.awt.event.KeyEvent;
107 import java.awt.event.MouseAdapter;
108 import java.awt.event.MouseEvent;
109 import java.awt.print.PageFormat;
110 import java.awt.print.PrinterJob;
111 import java.beans.PropertyChangeEvent;
114 import java.util.ArrayList;
115 import java.util.Enumeration;
116 import java.util.Hashtable;
117 import java.util.List;
118 import java.util.Vector;
120 import javax.swing.JButton;
121 import javax.swing.JEditorPane;
122 import javax.swing.JInternalFrame;
123 import javax.swing.JLabel;
124 import javax.swing.JLayeredPane;
125 import javax.swing.JMenu;
126 import javax.swing.JMenuItem;
127 import javax.swing.JOptionPane;
128 import javax.swing.JPanel;
129 import javax.swing.JProgressBar;
130 import javax.swing.JRadioButtonMenuItem;
131 import javax.swing.JScrollPane;
132 import javax.swing.SwingUtilities;
138 * @version $Revision$
140 public class AlignFrame extends GAlignFrame implements DropTargetListener,
141 IProgressIndicator, AlignViewControllerGuiI
145 public static final int DEFAULT_WIDTH = 700;
148 public static final int DEFAULT_HEIGHT = 500;
150 public AlignmentPanel alignPanel;
152 AlignViewport viewport;
154 public AlignViewControllerI avc;
157 Vector alignPanels = new Vector();
160 * Last format used to load or save alignments in this window
162 String currentFileFormat = null;
165 * Current filename for this alignment
167 String fileName = null;
170 * Creates a new AlignFrame object with specific width and height.
176 public AlignFrame(AlignmentI al, int width, int height)
178 this(al, null, width, height);
182 * Creates a new AlignFrame object with specific width, height and
188 * @param sequenceSetId
190 public AlignFrame(AlignmentI al, int width, int height,
191 String sequenceSetId)
193 this(al, null, width, height, sequenceSetId);
197 * Creates a new AlignFrame object with specific width, height and
203 * @param sequenceSetId
206 public AlignFrame(AlignmentI al, int width, int height,
207 String sequenceSetId, String viewId)
209 this(al, null, width, height, sequenceSetId, viewId);
213 * new alignment window with hidden columns
217 * @param hiddenColumns
218 * ColumnSelection or null
220 * Width of alignment frame
224 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
225 int width, int height)
227 this(al, hiddenColumns, width, height, null);
231 * Create alignment frame for al with hiddenColumns, a specific width and
232 * height, and specific sequenceId
235 * @param hiddenColumns
238 * @param sequenceSetId
241 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
242 int width, int height, String sequenceSetId)
244 this(al, hiddenColumns, width, height, sequenceSetId, null);
248 * Create alignment frame for al with hiddenColumns, a specific width and
249 * height, and specific sequenceId
252 * @param hiddenColumns
255 * @param sequenceSetId
260 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
261 int width, int height, String sequenceSetId, String viewId)
263 setSize(width, height);
264 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
266 alignPanel = new AlignmentPanel(this, viewport);
268 if (al.getDataset() == null)
273 addAlignmentPanel(alignPanel, true);
278 * Make a new AlignFrame from exisiting alignmentPanels
285 public AlignFrame(AlignmentPanel ap)
289 addAlignmentPanel(ap, false);
294 * initalise the alignframe from the underlying viewport data and the
299 avc = new jalview.controller.AlignViewController(this, viewport, alignPanel);
300 if (viewport.getAlignmentConservationAnnotation() == null)
302 BLOSUM62Colour.setEnabled(false);
303 conservationMenuItem.setEnabled(false);
304 modifyConservation.setEnabled(false);
305 // PIDColour.setEnabled(false);
306 // abovePIDThreshold.setEnabled(false);
307 // modifyPID.setEnabled(false);
310 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
313 if (sortby.equals("Id"))
315 sortIDMenuItem_actionPerformed(null);
317 else if (sortby.equals("Pairwise Identity"))
319 sortPairwiseMenuItem_actionPerformed(null);
322 if (Desktop.desktop != null)
324 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
325 addServiceListeners();
326 setGUINucleotide(viewport.getAlignment().isNucleotide());
329 setMenusFromViewport(viewport);
330 buildSortByAnnotationScoresMenu();
332 if (viewport.wrapAlignment)
334 wrapMenuItem_actionPerformed(null);
337 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
339 this.overviewMenuItem_actionPerformed(null);
347 * Change the filename and format for the alignment, and enable the 'reload'
348 * button functionality.
355 public void setFileName(String file, String format)
358 currentFileFormat = format;
359 reload.setEnabled(true);
362 void addKeyListener()
364 addKeyListener(new KeyAdapter()
367 public void keyPressed(KeyEvent evt)
369 if (viewport.cursorMode
370 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
371 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
372 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
373 && Character.isDigit(evt.getKeyChar()))
374 alignPanel.seqPanel.numberPressed(evt.getKeyChar());
376 switch (evt.getKeyCode())
379 case 27: // escape key
380 deselectAllSequenceMenuItem_actionPerformed(null);
384 case KeyEvent.VK_DOWN:
385 if (evt.isAltDown() || !viewport.cursorMode)
386 moveSelectedSequences(false);
387 if (viewport.cursorMode)
388 alignPanel.seqPanel.moveCursor(0, 1);
392 if (evt.isAltDown() || !viewport.cursorMode)
393 moveSelectedSequences(true);
394 if (viewport.cursorMode)
395 alignPanel.seqPanel.moveCursor(0, -1);
399 case KeyEvent.VK_LEFT:
400 if (evt.isAltDown() || !viewport.cursorMode)
401 slideSequences(false, alignPanel.seqPanel.getKeyboardNo1());
403 alignPanel.seqPanel.moveCursor(-1, 0);
407 case KeyEvent.VK_RIGHT:
408 if (evt.isAltDown() || !viewport.cursorMode)
409 slideSequences(true, alignPanel.seqPanel.getKeyboardNo1());
411 alignPanel.seqPanel.moveCursor(1, 0);
414 case KeyEvent.VK_SPACE:
415 if (viewport.cursorMode)
417 alignPanel.seqPanel.insertGapAtCursor(evt.isControlDown()
418 || evt.isShiftDown() || evt.isAltDown());
422 // case KeyEvent.VK_A:
423 // if (viewport.cursorMode)
425 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
426 // //System.out.println("A");
430 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
431 * System.out.println("closing bracket"); } break;
433 case KeyEvent.VK_DELETE:
434 case KeyEvent.VK_BACK_SPACE:
435 if (!viewport.cursorMode)
437 cut_actionPerformed(null);
441 alignPanel.seqPanel.deleteGapAtCursor(evt.isControlDown()
442 || evt.isShiftDown() || evt.isAltDown());
448 if (viewport.cursorMode)
450 alignPanel.seqPanel.setCursorRow();
454 if (viewport.cursorMode && !evt.isControlDown())
456 alignPanel.seqPanel.setCursorColumn();
460 if (viewport.cursorMode)
462 alignPanel.seqPanel.setCursorPosition();
466 case KeyEvent.VK_ENTER:
467 case KeyEvent.VK_COMMA:
468 if (viewport.cursorMode)
470 alignPanel.seqPanel.setCursorRowAndColumn();
475 if (viewport.cursorMode)
477 alignPanel.seqPanel.setSelectionAreaAtCursor(true);
481 if (viewport.cursorMode)
483 alignPanel.seqPanel.setSelectionAreaAtCursor(false);
488 viewport.cursorMode = !viewport.cursorMode;
489 statusBar.setText(MessageManager.formatMessage("label.keyboard_editing_mode", new String[]{(viewport.cursorMode ? "on" : "off")}));
490 if (viewport.cursorMode)
492 alignPanel.seqPanel.seqCanvas.cursorX = viewport.startRes;
493 alignPanel.seqPanel.seqCanvas.cursorY = viewport.startSeq;
495 alignPanel.seqPanel.seqCanvas.repaint();
501 ClassLoader cl = jalview.gui.Desktop.class.getClassLoader();
502 java.net.URL url = javax.help.HelpSet.findHelpSet(cl,
504 javax.help.HelpSet hs = new javax.help.HelpSet(cl, url);
506 javax.help.HelpBroker hb = hs.createHelpBroker();
507 hb.setCurrentID("home");
508 hb.setDisplayed(true);
509 } catch (Exception ex)
511 ex.printStackTrace();
516 boolean toggleSeqs = !evt.isControlDown();
517 boolean toggleCols = !evt.isShiftDown();
518 toggleHiddenRegions(toggleSeqs, toggleCols);
521 case KeyEvent.VK_PAGE_UP:
522 if (viewport.wrapAlignment)
524 alignPanel.scrollUp(true);
528 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
529 - viewport.endSeq + viewport.startSeq);
532 case KeyEvent.VK_PAGE_DOWN:
533 if (viewport.wrapAlignment)
535 alignPanel.scrollUp(false);
539 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
540 + viewport.endSeq - viewport.startSeq);
547 public void keyReleased(KeyEvent evt)
549 switch (evt.getKeyCode())
551 case KeyEvent.VK_LEFT:
552 if (evt.isAltDown() || !viewport.cursorMode)
553 viewport.firePropertyChange("alignment", null, viewport
554 .getAlignment().getSequences());
557 case KeyEvent.VK_RIGHT:
558 if (evt.isAltDown() || !viewport.cursorMode)
559 viewport.firePropertyChange("alignment", null, viewport
560 .getAlignment().getSequences());
567 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
569 ap.alignFrame = this;
570 avc = new jalview.controller.AlignViewController(this, viewport, alignPanel);
572 alignPanels.addElement(ap);
574 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
576 int aSize = alignPanels.size();
578 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
580 if (aSize == 1 && ap.av.viewName == null)
582 this.getContentPane().add(ap, BorderLayout.CENTER);
588 setInitialTabVisible();
591 expandViews.setEnabled(true);
592 gatherViews.setEnabled(true);
593 tabbedPane.addTab(ap.av.viewName, ap);
595 ap.setVisible(false);
600 if (ap.av.isPadGaps())
602 ap.av.getAlignment().padGaps();
604 ap.av.updateConservation(ap);
605 ap.av.updateConsensus(ap);
606 ap.av.updateStrucConsensus(ap);
610 public void setInitialTabVisible()
612 expandViews.setEnabled(true);
613 gatherViews.setEnabled(true);
614 tabbedPane.setVisible(true);
615 AlignmentPanel first = (AlignmentPanel) alignPanels.firstElement();
616 tabbedPane.addTab(first.av.viewName, first);
617 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
620 public AlignViewport getViewport()
625 /* Set up intrinsic listeners for dynamically generated GUI bits. */
626 private void addServiceListeners()
628 final java.beans.PropertyChangeListener thisListener;
629 Desktop.instance.addJalviewPropertyChangeListener("services",
630 thisListener = new java.beans.PropertyChangeListener()
633 public void propertyChange(PropertyChangeEvent evt)
635 // // System.out.println("Discoverer property change.");
636 // if (evt.getPropertyName().equals("services"))
638 SwingUtilities.invokeLater(new Runnable()
645 .println("Rebuild WS Menu for service change");
646 BuildWebServiceMenu();
653 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
656 public void internalFrameClosed(
657 javax.swing.event.InternalFrameEvent evt)
659 System.out.println("deregistering discoverer listener");
660 Desktop.instance.removeJalviewPropertyChangeListener("services",
662 closeMenuItem_actionPerformed(true);
665 // Finally, build the menu once to get current service state
666 new Thread(new Runnable()
671 BuildWebServiceMenu();
676 public void setGUINucleotide(boolean nucleotide)
678 showTranslation.setVisible(nucleotide);
679 conservationMenuItem.setEnabled(!nucleotide);
680 modifyConservation.setEnabled(!nucleotide);
681 showGroupConservation.setEnabled(!nucleotide);
682 rnahelicesColour.setEnabled(nucleotide);
683 purinePyrimidineColour.setEnabled(nucleotide);
684 // Remember AlignFrame always starts as protein
688 // calculateMenu.remove(calculateMenu.getItemCount() - 2);
693 * set up menus for the currently viewport. This may be called after any
694 * operation that affects the data in the current view (selection changed,
695 * etc) to update the menus to reflect the new state.
697 public void setMenusForViewport()
699 setMenusFromViewport(viewport);
703 * Need to call this method when tabs are selected for multiple views, or when
704 * loading from Jalview2XML.java
709 void setMenusFromViewport(AlignViewport av)
711 padGapsMenuitem.setSelected(av.isPadGaps());
712 colourTextMenuItem.setSelected(av.showColourText);
713 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
714 conservationMenuItem.setSelected(av.getConservationSelected());
715 seqLimits.setSelected(av.getShowJVSuffix());
716 idRightAlign.setSelected(av.rightAlignIds);
717 centreColumnLabelsMenuItem.setState(av.centreColumnLabels);
718 renderGapsMenuItem.setSelected(av.renderGaps);
719 wrapMenuItem.setSelected(av.wrapAlignment);
720 scaleAbove.setVisible(av.wrapAlignment);
721 scaleLeft.setVisible(av.wrapAlignment);
722 scaleRight.setVisible(av.wrapAlignment);
723 annotationPanelMenuItem.setState(av.showAnnotation);
724 viewBoxesMenuItem.setSelected(av.showBoxes);
725 viewTextMenuItem.setSelected(av.showText);
726 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
727 showGroupConsensus.setSelected(av.isShowGroupConsensus());
728 showGroupConservation.setSelected(av.isShowGroupConservation());
729 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
730 showSequenceLogo.setSelected(av.isShowSequenceLogo());
731 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
733 setColourSelected(ColourSchemeProperty.getColourName(av
734 .getGlobalColourScheme()));
736 showSeqFeatures.setSelected(av.showSequenceFeatures);
737 hiddenMarkers.setState(av.showHiddenMarkers);
738 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
739 showNpFeatsMenuitem.setSelected(av.isShowNpFeats());
740 showDbRefsMenuitem.setSelected(av.isShowDbRefs());
741 autoCalculate.setSelected(av.autoCalculateConsensus);
742 sortByTree.setSelected(av.sortByTree);
743 listenToViewSelections.setSelected(av.followSelection);
744 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
746 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
747 setShowProductsEnabled();
751 // methods for implementing IProgressIndicator
752 // need to refactor to a reusable stub class
753 Hashtable progressBars, progressBarHandlers;
758 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
761 public void setProgressBar(String message, long id)
763 if (progressBars == null)
765 progressBars = new Hashtable();
766 progressBarHandlers = new Hashtable();
769 JPanel progressPanel;
770 Long lId = new Long(id);
771 GridLayout layout = (GridLayout) statusPanel.getLayout();
772 if (progressBars.get(lId) != null)
774 progressPanel = (JPanel) progressBars.get(new Long(id));
775 statusPanel.remove(progressPanel);
776 progressBars.remove(lId);
777 progressPanel = null;
780 statusBar.setText(message);
782 if (progressBarHandlers.contains(lId))
784 progressBarHandlers.remove(lId);
786 layout.setRows(layout.getRows() - 1);
790 progressPanel = new JPanel(new BorderLayout(10, 5));
792 JProgressBar progressBar = new JProgressBar();
793 progressBar.setIndeterminate(true);
795 progressPanel.add(new JLabel(message), BorderLayout.WEST);
796 progressPanel.add(progressBar, BorderLayout.CENTER);
798 layout.setRows(layout.getRows() + 1);
799 statusPanel.add(progressPanel);
801 progressBars.put(lId, progressPanel);
804 // setMenusForViewport();
809 public void registerHandler(final long id,
810 final IProgressIndicatorHandler handler)
812 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
815 "call setProgressBar before registering the progress bar's handler.");
817 progressBarHandlers.put(new Long(id), handler);
818 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
819 if (handler.canCancel())
821 JButton cancel = new JButton(MessageManager.getString("action.cancel"));
822 final IProgressIndicator us = this;
823 cancel.addActionListener(new ActionListener()
827 public void actionPerformed(ActionEvent e)
829 handler.cancelActivity(id);
832 + ((JLabel) progressPanel.getComponent(0))
836 progressPanel.add(cancel, BorderLayout.EAST);
842 * @return true if any progress bars are still active
845 public boolean operationInProgress()
847 if (progressBars != null && progressBars.size() > 0)
855 public void setStatus(String text) {
856 statusBar.setText(text);
859 * Added so Castor Mapping file can obtain Jalview Version
861 public String getVersion()
863 return jalview.bin.Cache.getProperty("VERSION");
866 public FeatureRenderer getFeatureRenderer()
868 return alignPanel.seqPanel.seqCanvas.getFeatureRenderer();
872 public void fetchSequence_actionPerformed(ActionEvent e)
874 new SequenceFetcher(this);
878 public void addFromFile_actionPerformed(ActionEvent e)
880 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
884 public void reload_actionPerformed(ActionEvent e)
886 if (fileName != null)
888 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
889 // originating file's format
890 // TODO: work out how to recover feature settings for correct view(s) when
892 if (currentFileFormat.equals("Jalview"))
894 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
895 for (int i = 0; i < frames.length; i++)
897 if (frames[i] instanceof AlignFrame && frames[i] != this
898 && ((AlignFrame) frames[i]).fileName != null
899 && ((AlignFrame) frames[i]).fileName.equals(fileName))
903 frames[i].setSelected(true);
904 Desktop.instance.closeAssociatedWindows();
905 } catch (java.beans.PropertyVetoException ex)
911 Desktop.instance.closeAssociatedWindows();
913 FileLoader loader = new FileLoader();
914 String protocol = fileName.startsWith("http:") ? "URL" : "File";
915 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
919 Rectangle bounds = this.getBounds();
921 FileLoader loader = new FileLoader();
922 String protocol = fileName.startsWith("http:") ? "URL" : "File";
923 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
924 protocol, currentFileFormat);
926 newframe.setBounds(bounds);
927 if (featureSettings != null && featureSettings.isShowing())
929 final Rectangle fspos = featureSettings.frame.getBounds();
930 // TODO: need a 'show feature settings' function that takes bounds -
931 // need to refactor Desktop.addFrame
932 newframe.featureSettings_actionPerformed(null);
933 final FeatureSettings nfs = newframe.featureSettings;
934 SwingUtilities.invokeLater(new Runnable()
939 nfs.frame.setBounds(fspos);
942 this.featureSettings.close();
943 this.featureSettings = null;
945 this.closeMenuItem_actionPerformed(true);
951 public void addFromText_actionPerformed(ActionEvent e)
953 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
957 public void addFromURL_actionPerformed(ActionEvent e)
959 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
963 public void save_actionPerformed(ActionEvent e)
966 || (currentFileFormat == null || !jalview.io.FormatAdapter
967 .isValidIOFormat(currentFileFormat, true))
968 || fileName.startsWith("http"))
970 saveAs_actionPerformed(null);
974 saveAlignment(fileName, currentFileFormat);
985 public void saveAs_actionPerformed(ActionEvent e)
987 JalviewFileChooser chooser = new JalviewFileChooser(
988 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
989 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
990 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
991 currentFileFormat, false);
993 chooser.setFileView(new JalviewFileView());
994 chooser.setDialogTitle("Save Alignment to file");
995 chooser.setToolTipText(MessageManager.getString("action.save"));
\r
997 int value = chooser.showSaveDialog(this);
999 if (value == JalviewFileChooser.APPROVE_OPTION)
1001 currentFileFormat = chooser.getSelectedFormat();
1002 if (currentFileFormat == null)
1004 JOptionPane.showInternalMessageDialog(Desktop.desktop,
1005 MessageManager.getString("label.select_file_format_before_saving"),
1006 MessageManager.getString("label.file_format_not_specified"), JOptionPane.WARNING_MESSAGE);
1007 value = chooser.showSaveDialog(this);
1011 fileName = chooser.getSelectedFile().getPath();
1013 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
1016 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
1017 if (currentFileFormat.indexOf(" ") > -1)
1019 currentFileFormat = currentFileFormat.substring(0,
1020 currentFileFormat.indexOf(" "));
1022 saveAlignment(fileName, currentFileFormat);
1026 public boolean saveAlignment(String file, String format)
1028 boolean success = true;
1030 if (format.equalsIgnoreCase("Jalview"))
1032 String shortName = title;
1034 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1036 shortName = shortName.substring(shortName
1037 .lastIndexOf(java.io.File.separatorChar) + 1);
1040 success = new Jalview2XML().SaveAlignment(this, file, shortName);
1042 statusBar.setText(MessageManager.formatMessage("label.successfully_saved_to_file_in_format",new String[]{fileName, format}));
1048 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1050 warningMessage("Cannot save file " + fileName + " using format "
1051 + format, "Alignment output format not supported");
1052 saveAs_actionPerformed(null);
1053 // JBPNote need to have a raise_gui flag here
1057 String[] omitHidden = null;
1059 if (viewport.hasHiddenColumns())
1061 int reply = JOptionPane
1062 .showInternalConfirmDialog(
1064 MessageManager.getString("label.alignment_contains_hidden_columns"),
1065 MessageManager.getString("action.save_omit_hidden_columns"),
1066 JOptionPane.YES_NO_OPTION,
1067 JOptionPane.QUESTION_MESSAGE);
1069 if (reply == JOptionPane.YES_OPTION)
1071 omitHidden = viewport.getViewAsString(false);
1074 FormatAdapter f = new FormatAdapter();
1075 String output = f.formatSequences(format,
1076 viewport.getAlignment(), // class cast exceptions will
1077 // occur in the distant future
1078 omitHidden, f.getCacheSuffixDefault(format),
1079 viewport.getColumnSelection());
1089 java.io.PrintWriter out = new java.io.PrintWriter(
1090 new java.io.FileWriter(file));
1094 this.setTitle(file);
1095 statusBar.setText(MessageManager.formatMessage("label.successfully_saved_to_file_in_format",new String[]{fileName, format}));
1096 } catch (Exception ex)
1099 ex.printStackTrace();
1106 JOptionPane.showInternalMessageDialog(this, MessageManager.formatMessage("label.couldnt_save_file", new String[]{fileName}),
1107 MessageManager.getString("label.error_saving_file"), JOptionPane.WARNING_MESSAGE);
1113 private void warningMessage(String warning, String title)
1115 if (new jalview.util.Platform().isHeadless())
1117 System.err.println("Warning: " + title + "\nWarning: " + warning);
1122 JOptionPane.showInternalMessageDialog(this, warning, title,
1123 JOptionPane.WARNING_MESSAGE);
1135 protected void outputText_actionPerformed(ActionEvent e)
1137 String[] omitHidden = null;
1139 if (viewport.hasHiddenColumns())
1141 int reply = JOptionPane
1142 .showInternalConfirmDialog(
1144 MessageManager.getString("label.alignment_contains_hidden_columns"),
1145 MessageManager.getString("action.save_omit_hidden_columns"),
1146 JOptionPane.YES_NO_OPTION,
1147 JOptionPane.QUESTION_MESSAGE);
1149 if (reply == JOptionPane.YES_OPTION)
1151 omitHidden = viewport.getViewAsString(false);
1155 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1156 cap.setForInput(null);
1160 cap.setText(new FormatAdapter().formatSequences(e.getActionCommand(),
1161 viewport.getAlignment(), omitHidden,
1162 viewport.getColumnSelection()));
1163 Desktop.addInternalFrame(cap,
1164 MessageManager.formatMessage("label.alignment_output_command", new String[]{e.getActionCommand()}), 600, 500);
\r
1165 } catch (OutOfMemoryError oom)
1167 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1180 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1182 new HTMLOutput(alignPanel,
1183 alignPanel.seqPanel.seqCanvas.getSequenceRenderer(),
1184 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
1187 public void createImageMap(File file, String image)
1189 alignPanel.makePNGImageMap(file, image);
1199 public void createPNG(File f)
1201 alignPanel.makePNG(f);
1211 public void createEPS(File f)
1213 alignPanel.makeEPS(f);
1217 public void pageSetup_actionPerformed(ActionEvent e)
1219 PrinterJob printJob = PrinterJob.getPrinterJob();
1220 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1230 public void printMenuItem_actionPerformed(ActionEvent e)
1232 // Putting in a thread avoids Swing painting problems
1233 PrintThread thread = new PrintThread(alignPanel);
1238 public void exportFeatures_actionPerformed(ActionEvent e)
1240 new AnnotationExporter().exportFeatures(alignPanel);
1244 public void exportAnnotations_actionPerformed(ActionEvent e)
1246 new AnnotationExporter().exportAnnotations(alignPanel,
1247 viewport.showAnnotation ? viewport.getAlignment()
1248 .getAlignmentAnnotation() : null, viewport
1249 .getAlignment().getGroups(), ((Alignment) viewport
1250 .getAlignment()).alignmentProperties);
1254 public void associatedData_actionPerformed(ActionEvent e)
1256 // Pick the tree file
1257 JalviewFileChooser chooser = new JalviewFileChooser(
1258 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1259 chooser.setFileView(new JalviewFileView());
1260 chooser.setDialogTitle(MessageManager.getString("label.load_jalview_annotations"));
\r
1261 chooser.setToolTipText(MessageManager.getString("label.load_jalview_annotations"));
\r
1263 int value = chooser.showOpenDialog(null);
1265 if (value == JalviewFileChooser.APPROVE_OPTION)
1267 String choice = chooser.getSelectedFile().getPath();
1268 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1269 loadJalviewDataFile(choice, null, null, null);
1275 * Close the current view or all views in the alignment frame. If the frame
1276 * only contains one view then the alignment will be removed from memory.
1278 * @param closeAllTabs
1281 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1283 if (alignPanels != null && alignPanels.size() < 2)
1285 closeAllTabs = true;
1290 if (alignPanels != null)
1294 if (this.isClosed())
1296 // really close all the windows - otherwise wait till
1297 // setClosed(true) is called
1298 for (int i = 0; i < alignPanels.size(); i++)
1300 AlignmentPanel ap = (AlignmentPanel) alignPanels.elementAt(i);
1307 closeView(alignPanel);
1313 this.setClosed(true);
1315 } catch (Exception ex)
1317 ex.printStackTrace();
1322 * close alignPanel2 and shuffle tabs appropriately.
1324 * @param alignPanel2
1326 public void closeView(AlignmentPanel alignPanel2)
1328 int index = tabbedPane.getSelectedIndex();
1329 int closedindex = tabbedPane.indexOfComponent(alignPanel2);
1330 alignPanels.removeElement(alignPanel2);
1332 // if (viewport == alignPanel2.av)
1336 alignPanel2.closePanel();
1339 tabbedPane.removeTabAt(closedindex);
1340 tabbedPane.validate();
1342 if (index > closedindex || index == tabbedPane.getTabCount())
1344 // modify currently selected tab index if necessary.
1348 this.tabSelectionChanged(index);
1354 void updateEditMenuBar()
1357 if (viewport.historyList.size() > 0)
1359 undoMenuItem.setEnabled(true);
1360 CommandI command = (CommandI) viewport.historyList.peek();
1361 undoMenuItem.setText(MessageManager.formatMessage("label.undo_command", new String[]{command.getDescription()}));
1365 undoMenuItem.setEnabled(false);
1366 undoMenuItem.setText(MessageManager.getString("action.undo"));
1369 if (viewport.redoList.size() > 0)
1371 redoMenuItem.setEnabled(true);
1373 CommandI command = (CommandI) viewport.redoList.peek();
1374 redoMenuItem.setText(MessageManager.formatMessage("label.redo_command", new String[]{command.getDescription()}));
1378 redoMenuItem.setEnabled(false);
1379 redoMenuItem.setText(MessageManager.getString("action.redo"));
1383 public void addHistoryItem(CommandI command)
1385 if (command.getSize() > 0)
1387 viewport.historyList.push(command);
1388 viewport.redoList.clear();
1389 updateEditMenuBar();
1390 viewport.updateHiddenColumns();
1391 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1392 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1393 // viewport.getColumnSelection()
1394 // .getHiddenColumns().size() > 0);
1400 * @return alignment objects for all views
1402 AlignmentI[] getViewAlignments()
1404 if (alignPanels != null)
1406 Enumeration e = alignPanels.elements();
1407 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1408 for (int i = 0; e.hasMoreElements(); i++)
1410 als[i] = ((AlignmentPanel) e.nextElement()).av.getAlignment();
1414 if (viewport != null)
1416 return new AlignmentI[]
1417 { viewport.getAlignment() };
1429 protected void undoMenuItem_actionPerformed(ActionEvent e)
1431 if (viewport.historyList.empty())
1433 CommandI command = (CommandI) viewport.historyList.pop();
1434 viewport.redoList.push(command);
1435 command.undoCommand(getViewAlignments());
1437 AlignViewport originalSource = getOriginatingSource(command);
1438 updateEditMenuBar();
1440 if (originalSource != null)
1442 if (originalSource != viewport)
1445 .warn("Implementation worry: mismatch of viewport origin for undo");
1447 originalSource.updateHiddenColumns();
1448 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1450 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1451 // viewport.getColumnSelection()
1452 // .getHiddenColumns().size() > 0);
1453 originalSource.firePropertyChange("alignment", null, originalSource
1454 .getAlignment().getSequences());
1465 protected void redoMenuItem_actionPerformed(ActionEvent e)
1467 if (viewport.redoList.size() < 1)
1472 CommandI command = (CommandI) viewport.redoList.pop();
1473 viewport.historyList.push(command);
1474 command.doCommand(getViewAlignments());
1476 AlignViewport originalSource = getOriginatingSource(command);
1477 updateEditMenuBar();
1479 if (originalSource != null)
1482 if (originalSource != viewport)
1485 .warn("Implementation worry: mismatch of viewport origin for redo");
1487 originalSource.updateHiddenColumns();
1488 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1490 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1491 // viewport.getColumnSelection()
1492 // .getHiddenColumns().size() > 0);
1493 originalSource.firePropertyChange("alignment", null, originalSource
1494 .getAlignment().getSequences());
1498 AlignViewport getOriginatingSource(CommandI command)
1500 AlignViewport originalSource = null;
1501 // For sequence removal and addition, we need to fire
1502 // the property change event FROM the viewport where the
1503 // original alignment was altered
1504 AlignmentI al = null;
1505 if (command instanceof EditCommand)
1507 EditCommand editCommand = (EditCommand) command;
1508 al = editCommand.getAlignment();
1509 Vector comps = (Vector) PaintRefresher.components.get(viewport
1510 .getSequenceSetId());
1512 for (int i = 0; i < comps.size(); i++)
1514 if (comps.elementAt(i) instanceof AlignmentPanel)
1516 if (al == ((AlignmentPanel) comps.elementAt(i)).av.getAlignment())
1518 originalSource = ((AlignmentPanel) comps.elementAt(i)).av;
1525 if (originalSource == null)
1527 // The original view is closed, we must validate
1528 // the current view against the closed view first
1531 PaintRefresher.validateSequences(al, viewport.getAlignment());
1534 originalSource = viewport;
1537 return originalSource;
1546 public void moveSelectedSequences(boolean up)
1548 SequenceGroup sg = viewport.getSelectionGroup();
1554 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1555 viewport.getHiddenRepSequences(), up);
1556 alignPanel.paintAlignment(true);
1559 synchronized void slideSequences(boolean right, int size)
1561 List<SequenceI> sg = new Vector();
1562 if (viewport.cursorMode)
1564 sg.add(viewport.getAlignment().getSequenceAt(
1565 alignPanel.seqPanel.seqCanvas.cursorY));
1567 else if (viewport.getSelectionGroup() != null
1568 && viewport.getSelectionGroup().getSize() != viewport
1569 .getAlignment().getHeight())
1571 sg = viewport.getSelectionGroup().getSequences(
1572 viewport.getHiddenRepSequences());
1580 Vector invertGroup = new Vector();
1582 for (int i = 0; i < viewport.getAlignment().getHeight(); i++)
1584 if (!sg.contains(viewport.getAlignment().getSequenceAt(i)))
1585 invertGroup.add(viewport.getAlignment().getSequenceAt(i));
1588 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1590 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1591 for (int i = 0; i < invertGroup.size(); i++)
1592 seqs2[i] = (SequenceI) invertGroup.elementAt(i);
1594 SlideSequencesCommand ssc;
1596 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1597 size, viewport.getGapCharacter());
1599 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1600 size, viewport.getGapCharacter());
1602 int groupAdjustment = 0;
1603 if (ssc.getGapsInsertedBegin() && right)
1605 if (viewport.cursorMode)
1606 alignPanel.seqPanel.moveCursor(size, 0);
1608 groupAdjustment = size;
1610 else if (!ssc.getGapsInsertedBegin() && !right)
1612 if (viewport.cursorMode)
1613 alignPanel.seqPanel.moveCursor(-size, 0);
1615 groupAdjustment = -size;
1618 if (groupAdjustment != 0)
1620 viewport.getSelectionGroup().setStartRes(
1621 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1622 viewport.getSelectionGroup().setEndRes(
1623 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1626 boolean appendHistoryItem = false;
1627 if (viewport.historyList != null && viewport.historyList.size() > 0
1628 && viewport.historyList.peek() instanceof SlideSequencesCommand)
1630 appendHistoryItem = ssc
1631 .appendSlideCommand((SlideSequencesCommand) viewport.historyList
1635 if (!appendHistoryItem)
1636 addHistoryItem(ssc);
1648 protected void copy_actionPerformed(ActionEvent e)
1651 if (viewport.getSelectionGroup() == null)
1655 // TODO: preserve the ordering of displayed alignment annotation in any
1656 // internal paste (particularly sequence associated annotation)
1657 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1658 String[] omitHidden = null;
1660 if (viewport.hasHiddenColumns())
1662 omitHidden = viewport.getViewAsString(true);
1665 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1668 StringSelection ss = new StringSelection(output);
1672 jalview.gui.Desktop.internalCopy = true;
1673 // Its really worth setting the clipboard contents
1674 // to empty before setting the large StringSelection!!
1675 Toolkit.getDefaultToolkit().getSystemClipboard()
1676 .setContents(new StringSelection(""), null);
1678 Toolkit.getDefaultToolkit().getSystemClipboard()
1679 .setContents(ss, Desktop.instance);
1680 } catch (OutOfMemoryError er)
1682 new OOMWarning("copying region", er);
1686 Vector hiddenColumns = null;
1687 if (viewport.hasHiddenColumns())
1689 hiddenColumns = new Vector();
1690 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1691 .getSelectionGroup().getEndRes();
1692 for (int i = 0; i < viewport.getColumnSelection().getHiddenColumns()
1695 int[] region = (int[]) viewport.getColumnSelection()
1696 .getHiddenColumns().elementAt(i);
1697 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1699 hiddenColumns.addElement(new int[]
1700 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1705 Desktop.jalviewClipboard = new Object[]
1706 { seqs, viewport.getAlignment().getDataset(), hiddenColumns };
1707 statusBar.setText(MessageManager.formatMessage("label.copied_sequences_to_clipboard", new String[]{Integer.valueOf(seqs.length).toString()}));
1717 protected void pasteNew_actionPerformed(ActionEvent e)
1729 protected void pasteThis_actionPerformed(ActionEvent e)
1735 * Paste contents of Jalview clipboard
1737 * @param newAlignment
1738 * true to paste to a new alignment, otherwise add to this.
1740 void paste(boolean newAlignment)
1742 boolean externalPaste = true;
1745 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1746 Transferable contents = c.getContents(this);
1748 if (contents == null)
1756 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1757 if (str.length() < 1)
1762 format = new IdentifyFile().Identify(str, "Paste");
1764 } catch (OutOfMemoryError er)
1766 new OOMWarning("Out of memory pasting sequences!!", er);
1770 SequenceI[] sequences;
1771 boolean annotationAdded = false;
1772 AlignmentI alignment = null;
1774 if (Desktop.jalviewClipboard != null)
1776 // The clipboard was filled from within Jalview, we must use the
1778 // And dataset from the copied alignment
1779 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1780 // be doubly sure that we create *new* sequence objects.
1781 sequences = new SequenceI[newseq.length];
1782 for (int i = 0; i < newseq.length; i++)
1784 sequences[i] = new Sequence(newseq[i]);
1786 alignment = new Alignment(sequences);
1787 externalPaste = false;
1791 // parse the clipboard as an alignment.
1792 alignment = new FormatAdapter().readFile(str, "Paste", format);
1793 sequences = alignment.getSequencesArray();
1797 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1803 if (Desktop.jalviewClipboard != null)
1805 // dataset is inherited
1806 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1810 // new dataset is constructed
1811 alignment.setDataset(null);
1813 alwidth = alignment.getWidth() + 1;
1817 AlignmentI pastedal = alignment; // preserve pasted alignment object
1818 // Add pasted sequences and dataset into existing alignment.
1819 alignment = viewport.getAlignment();
1820 alwidth = alignment.getWidth() + 1;
1821 // decide if we need to import sequences from an existing dataset
1822 boolean importDs = Desktop.jalviewClipboard != null
1823 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1824 // importDs==true instructs us to copy over new dataset sequences from
1825 // an existing alignment
1826 Vector newDs = (importDs) ? new Vector() : null; // used to create
1827 // minimum dataset set
1829 for (int i = 0; i < sequences.length; i++)
1833 newDs.addElement(null);
1835 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
1837 if (importDs && ds != null)
1839 if (!newDs.contains(ds))
1841 newDs.setElementAt(ds, i);
1842 ds = new Sequence(ds);
1843 // update with new dataset sequence
1844 sequences[i].setDatasetSequence(ds);
1848 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
1853 // copy and derive new dataset sequence
1854 sequences[i] = sequences[i].deriveSequence();
1855 alignment.getDataset().addSequence(
1856 sequences[i].getDatasetSequence());
1857 // TODO: avoid creation of duplicate dataset sequences with a
1858 // 'contains' method using SequenceI.equals()/SequenceI.contains()
1860 alignment.addSequence(sequences[i]); // merges dataset
1864 newDs.clear(); // tidy up
1866 if (alignment.getAlignmentAnnotation() != null)
1868 for (AlignmentAnnotation alan : alignment
1869 .getAlignmentAnnotation())
1871 if (alan.graphGroup > fgroup)
1873 fgroup = alan.graphGroup;
1877 if (pastedal.getAlignmentAnnotation() != null)
1879 // Add any annotation attached to alignment.
1880 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
1881 for (int i = 0; i < alann.length; i++)
1883 annotationAdded = true;
1884 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
1886 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
1887 if (newann.graphGroup > -1)
1889 if (newGraphGroups.size() <= newann.graphGroup
1890 || newGraphGroups.get(newann.graphGroup) == null)
1892 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
1894 newGraphGroups.add(q, null);
1896 newGraphGroups.set(newann.graphGroup, new Integer(
1899 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
1903 newann.padAnnotation(alwidth);
1904 alignment.addAnnotation(newann);
1914 addHistoryItem(new EditCommand("Add sequences", EditCommand.PASTE,
1915 sequences, 0, alignment.getWidth(), alignment));
1917 // Add any annotations attached to sequences
1918 for (int i = 0; i < sequences.length; i++)
1920 if (sequences[i].getAnnotation() != null)
1922 AlignmentAnnotation newann;
1923 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
1925 annotationAdded = true;
1926 newann = sequences[i].getAnnotation()[a];
1927 newann.adjustForAlignment();
1928 newann.padAnnotation(alwidth);
1929 if (newann.graphGroup > -1)
1931 if (newann.graphGroup > -1)
1933 if (newGraphGroups.size() <= newann.graphGroup
1934 || newGraphGroups.get(newann.graphGroup) == null)
1936 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
1938 newGraphGroups.add(q, null);
1940 newGraphGroups.set(newann.graphGroup, new Integer(
1943 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
1947 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
1952 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
1959 // propagate alignment changed.
1960 viewport.setEndSeq(alignment.getHeight());
1961 if (annotationAdded)
1963 // Duplicate sequence annotation in all views.
1964 AlignmentI[] alview = this.getViewAlignments();
1965 for (int i = 0; i < sequences.length; i++)
1967 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
1970 for (int avnum = 0; avnum < alview.length; avnum++)
1972 if (alview[avnum] != alignment)
1974 // duplicate in a view other than the one with input focus
1975 int avwidth = alview[avnum].getWidth() + 1;
1976 // this relies on sann being preserved after we
1977 // modify the sequence's annotation array for each duplication
1978 for (int a = 0; a < sann.length; a++)
1980 AlignmentAnnotation newann = new AlignmentAnnotation(
1982 sequences[i].addAlignmentAnnotation(newann);
1983 newann.padAnnotation(avwidth);
1984 alview[avnum].addAnnotation(newann); // annotation was
1985 // duplicated earlier
1986 // TODO JAL-1145 graphGroups are not updated for sequence
1987 // annotation added to several views. This may cause
1989 alview[avnum].setAnnotationIndex(newann, a);
1994 buildSortByAnnotationScoresMenu();
1996 viewport.firePropertyChange("alignment", null,
1997 alignment.getSequences());
1998 if (alignPanels != null)
2000 for (AlignmentPanel ap : ((Vector<AlignmentPanel>) alignPanels))
2002 ap.validateAnnotationDimensions(false);
2007 alignPanel.validateAnnotationDimensions(false);
2013 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2015 String newtitle = new String("Copied sequences");
2017 if (Desktop.jalviewClipboard != null
2018 && Desktop.jalviewClipboard[2] != null)
2020 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2021 for (int i = 0; i < hc.size(); i++)
2023 int[] region = (int[]) hc.elementAt(i);
2024 af.viewport.hideColumns(region[0], region[1]);
2028 // >>>This is a fix for the moment, until a better solution is
2030 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
2032 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
2034 // TODO: maintain provenance of an alignment, rather than just make the
2035 // title a concatenation of operations.
2038 if (title.startsWith("Copied sequences"))
2044 newtitle = newtitle.concat("- from " + title);
2049 newtitle = new String("Pasted sequences");
2052 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2057 } catch (Exception ex)
2059 ex.printStackTrace();
2060 System.out.println("Exception whilst pasting: " + ex);
2061 // could be anything being pasted in here
2066 protected void expand_newalign(ActionEvent e)
2069 AlignmentI alignment = AlignmentUtils.expandContext(getViewport().getAlignment(), -1);
2070 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2072 String newtitle = new String("Flanking alignment");
2074 if (Desktop.jalviewClipboard != null
2075 && Desktop.jalviewClipboard[2] != null)
2077 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2078 for (int i = 0; i < hc.size(); i++)
2080 int[] region = (int[]) hc.elementAt(i);
2081 af.viewport.hideColumns(region[0], region[1]);
2085 // >>>This is a fix for the moment, until a better solution is
2087 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
2089 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
2091 // TODO: maintain provenance of an alignment, rather than just make the
2092 // title a concatenation of operations.
2094 if (title.startsWith("Copied sequences"))
2100 newtitle = newtitle.concat("- from " + title);
2104 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2107 } catch (Exception ex)
2109 ex.printStackTrace();
2110 System.out.println("Exception whilst pasting: " + ex);
2111 // could be anything being pasted in here
2113 catch (OutOfMemoryError oom)
2115 new OOMWarning("Viewing flanking region of alignment", oom);
2125 protected void cut_actionPerformed(ActionEvent e)
2127 copy_actionPerformed(null);
2128 delete_actionPerformed(null);
2138 protected void delete_actionPerformed(ActionEvent evt)
2141 SequenceGroup sg = viewport.getSelectionGroup();
2147 Vector seqs = new Vector();
2149 for (int i = 0; i < sg.getSize(); i++)
2151 seq = sg.getSequenceAt(i);
2152 seqs.addElement(seq);
2155 // If the cut affects all sequences, remove highlighted columns
2156 if (sg.getSize() == viewport.getAlignment().getHeight())
2158 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2159 sg.getEndRes() + 1);
2162 SequenceI[] cut = new SequenceI[seqs.size()];
2163 for (int i = 0; i < seqs.size(); i++)
2165 cut[i] = (SequenceI) seqs.elementAt(i);
2169 * //ADD HISTORY ITEM
2171 addHistoryItem(new EditCommand("Cut Sequences", EditCommand.CUT, cut,
2172 sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2173 viewport.getAlignment()));
2175 viewport.setSelectionGroup(null);
2176 viewport.sendSelection();
2177 viewport.getAlignment().deleteGroup(sg);
2179 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2181 if (viewport.getAlignment().getHeight() < 1)
2185 this.setClosed(true);
2186 } catch (Exception ex)
2199 protected void deleteGroups_actionPerformed(ActionEvent e)
2201 if (avc.deleteGroups()) {
2202 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2203 alignPanel.updateAnnotation();
2204 alignPanel.paintAlignment(true);
2215 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2217 SequenceGroup sg = new SequenceGroup();
2219 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2221 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2224 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2225 viewport.setSelectionGroup(sg);
2226 viewport.sendSelection();
2227 alignPanel.paintAlignment(true);
2228 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2238 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2240 if (viewport.cursorMode)
2242 alignPanel.seqPanel.keyboardNo1 = null;
2243 alignPanel.seqPanel.keyboardNo2 = null;
2245 viewport.setSelectionGroup(null);
2246 viewport.getColumnSelection().clear();
2247 viewport.setSelectionGroup(null);
2248 alignPanel.seqPanel.seqCanvas.highlightSearchResults(null);
2249 alignPanel.idPanel.idCanvas.searchResults = null;
2250 alignPanel.paintAlignment(true);
2251 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2252 viewport.sendSelection();
2262 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2264 SequenceGroup sg = viewport.getSelectionGroup();
2268 selectAllSequenceMenuItem_actionPerformed(null);
2273 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2275 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2278 alignPanel.paintAlignment(true);
2279 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2280 viewport.sendSelection();
2284 public void invertColSel_actionPerformed(ActionEvent e)
2286 viewport.invertColumnSelection();
2287 alignPanel.paintAlignment(true);
2288 viewport.sendSelection();
2298 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2300 trimAlignment(true);
2310 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2312 trimAlignment(false);
2315 void trimAlignment(boolean trimLeft)
2317 ColumnSelection colSel = viewport.getColumnSelection();
2320 if (colSel.size() > 0)
2324 column = colSel.getMin();
2328 column = colSel.getMax();
2332 if (viewport.getSelectionGroup() != null)
2334 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2335 viewport.getHiddenRepSequences());
2339 seqs = viewport.getAlignment().getSequencesArray();
2342 TrimRegionCommand trimRegion;
2345 trimRegion = new TrimRegionCommand("Remove Left",
2346 TrimRegionCommand.TRIM_LEFT, seqs, column,
2347 viewport.getAlignment(), viewport.getColumnSelection(),
2348 viewport.getSelectionGroup());
2349 viewport.setStartRes(0);
2353 trimRegion = new TrimRegionCommand("Remove Right",
2354 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2355 viewport.getAlignment(), viewport.getColumnSelection(),
2356 viewport.getSelectionGroup());
2359 statusBar.setText(MessageManager.formatMessage("label.removed_columns", new String[]{Integer.valueOf(trimRegion.getSize()).toString()}));
2361 addHistoryItem(trimRegion);
2363 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2365 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2366 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2368 viewport.getAlignment().deleteGroup(sg);
2372 viewport.firePropertyChange("alignment", null, viewport
2373 .getAlignment().getSequences());
2384 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2386 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2389 if (viewport.getSelectionGroup() != null)
2391 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2392 viewport.getHiddenRepSequences());
2393 start = viewport.getSelectionGroup().getStartRes();
2394 end = viewport.getSelectionGroup().getEndRes();
2398 seqs = viewport.getAlignment().getSequencesArray();
2401 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2402 "Remove Gapped Columns", seqs, start, end,
2403 viewport.getAlignment());
2405 addHistoryItem(removeGapCols);
2407 statusBar.setText(MessageManager.formatMessage("label.removed_empty_columns", new String[]{Integer.valueOf(removeGapCols.getSize()).toString()}));
2409 // This is to maintain viewport position on first residue
2410 // of first sequence
2411 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2412 int startRes = seq.findPosition(viewport.startRes);
2413 // ShiftList shifts;
2414 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2415 // edit.alColumnChanges=shifts.getInverse();
2416 // if (viewport.hasHiddenColumns)
2417 // viewport.getColumnSelection().compensateForEdits(shifts);
2418 viewport.setStartRes(seq.findIndex(startRes) - 1);
2419 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2431 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2433 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2436 if (viewport.getSelectionGroup() != null)
2438 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2439 viewport.getHiddenRepSequences());
2440 start = viewport.getSelectionGroup().getStartRes();
2441 end = viewport.getSelectionGroup().getEndRes();
2445 seqs = viewport.getAlignment().getSequencesArray();
2448 // This is to maintain viewport position on first residue
2449 // of first sequence
2450 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2451 int startRes = seq.findPosition(viewport.startRes);
2453 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2454 viewport.getAlignment()));
2456 viewport.setStartRes(seq.findIndex(startRes) - 1);
2458 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2470 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2472 viewport.setPadGaps(padGapsMenuitem.isSelected());
2473 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2479 // if (justifySeqs>0)
2481 // alignment.justify(justifySeqs!=RIGHT_JUSTIFY);
2494 public void findMenuItem_actionPerformed(ActionEvent e)
2500 public void newView_actionPerformed(ActionEvent e)
2507 * @param copyAnnotation
2508 * if true then duplicate all annnotation, groups and settings
2509 * @return new alignment panel, already displayed.
2511 public AlignmentPanel newView(boolean copyAnnotation)
2513 return newView(null, copyAnnotation);
2519 * title of newly created view
2520 * @return new alignment panel, already displayed.
2522 public AlignmentPanel newView(String viewTitle)
2524 return newView(viewTitle, true);
2530 * title of newly created view
2531 * @param copyAnnotation
2532 * if true then duplicate all annnotation, groups and settings
2533 * @return new alignment panel, already displayed.
2535 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2537 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2539 if (!copyAnnotation)
2541 // just remove all the current annotation except for the automatic stuff
2542 newap.av.getAlignment().deleteAllGroups();
2543 for (AlignmentAnnotation alan : newap.av.getAlignment()
2544 .getAlignmentAnnotation())
2546 if (!alan.autoCalculated)
2548 newap.av.getAlignment().deleteAnnotation(alan);
2554 newap.av.gatherViewsHere = false;
2556 if (viewport.viewName == null)
2558 viewport.viewName = "Original";
2561 newap.av.historyList = viewport.historyList;
2562 newap.av.redoList = viewport.redoList;
2564 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2565 // make sure the new view has a unique name - this is essential for Jalview
2567 boolean addFirstIndex = false;
2568 if (viewTitle == null || viewTitle.trim().length() == 0)
2571 addFirstIndex = true;
2575 index = 1;// we count from 1 if given a specific name
2577 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2578 Vector comps = (Vector) PaintRefresher.components.get(viewport
2579 .getSequenceSetId());
2580 Vector existingNames = new Vector();
2581 for (int i = 0; i < comps.size(); i++)
2583 if (comps.elementAt(i) instanceof AlignmentPanel)
2585 AlignmentPanel ap = (AlignmentPanel) comps.elementAt(i);
2586 if (!existingNames.contains(ap.av.viewName))
2588 existingNames.addElement(ap.av.viewName);
2593 while (existingNames.contains(newViewName))
2595 newViewName = viewTitle + " " + (++index);
2598 newap.av.viewName = newViewName;
2600 addAlignmentPanel(newap, true);
2601 newap.alignmentChanged();
2603 if (alignPanels.size() == 2)
2605 viewport.gatherViewsHere = true;
2607 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2612 public void expandViews_actionPerformed(ActionEvent e)
2614 Desktop.instance.explodeViews(this);
2618 public void gatherViews_actionPerformed(ActionEvent e)
2620 Desktop.instance.gatherViews(this);
2630 public void font_actionPerformed(ActionEvent e)
2632 new FontChooser(alignPanel);
2642 protected void seqLimit_actionPerformed(ActionEvent e)
2644 viewport.setShowJVSuffix(seqLimits.isSelected());
2646 alignPanel.idPanel.idCanvas.setPreferredSize(alignPanel
2647 .calculateIdWidth());
2648 alignPanel.paintAlignment(true);
2652 public void idRightAlign_actionPerformed(ActionEvent e)
2654 viewport.rightAlignIds = idRightAlign.isSelected();
2655 alignPanel.paintAlignment(true);
2659 public void centreColumnLabels_actionPerformed(ActionEvent e)
2661 viewport.centreColumnLabels = centreColumnLabelsMenuItem.getState();
2662 alignPanel.paintAlignment(true);
2668 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2671 protected void followHighlight_actionPerformed()
2673 if (viewport.followHighlight = this.followHighlightMenuItem.getState())
2675 alignPanel.scrollToPosition(
2676 alignPanel.seqPanel.seqCanvas.searchResults, false);
2687 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2689 viewport.setColourText(colourTextMenuItem.isSelected());
2690 alignPanel.paintAlignment(true);
2700 public void wrapMenuItem_actionPerformed(ActionEvent e)
2702 scaleAbove.setVisible(wrapMenuItem.isSelected());
2703 scaleLeft.setVisible(wrapMenuItem.isSelected());
2704 scaleRight.setVisible(wrapMenuItem.isSelected());
2705 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2706 alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2710 public void showAllSeqs_actionPerformed(ActionEvent e)
2712 viewport.showAllHiddenSeqs();
2716 public void showAllColumns_actionPerformed(ActionEvent e)
2718 viewport.showAllHiddenColumns();
2723 public void hideSelSequences_actionPerformed(ActionEvent e)
2725 viewport.hideAllSelectedSeqs();
2726 alignPanel.paintAlignment(true);
2730 * called by key handler and the hide all/show all menu items
2735 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2738 boolean hide = false;
2739 SequenceGroup sg = viewport.getSelectionGroup();
2740 if (!toggleSeqs && !toggleCols)
2742 // Hide everything by the current selection - this is a hack - we do the
2743 // invert and then hide
2744 // first check that there will be visible columns after the invert.
2745 if ((viewport.getColumnSelection() != null
2746 && viewport.getColumnSelection().getSelected() != null && viewport
2747 .getColumnSelection().getSelected().size() > 0)
2748 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2751 // now invert the sequence set, if required - empty selection implies
2752 // that no hiding is required.
2755 invertSequenceMenuItem_actionPerformed(null);
2756 sg = viewport.getSelectionGroup();
2760 viewport.expandColSelection(sg, true);
2761 // finally invert the column selection and get the new sequence
2763 invertColSel_actionPerformed(null);
2770 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
2772 hideSelSequences_actionPerformed(null);
2775 else if (!(toggleCols && viewport.getColumnSelection().getSelected()
2778 showAllSeqs_actionPerformed(null);
2784 if (viewport.getColumnSelection().getSelected().size() > 0)
2786 hideSelColumns_actionPerformed(null);
2789 viewport.setSelectionGroup(sg);
2794 showAllColumns_actionPerformed(null);
2803 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
2804 * event.ActionEvent)
2807 public void hideAllButSelection_actionPerformed(ActionEvent e)
2809 toggleHiddenRegions(false, false);
2816 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
2820 public void hideAllSelection_actionPerformed(ActionEvent e)
2822 SequenceGroup sg = viewport.getSelectionGroup();
2823 viewport.expandColSelection(sg, false);
2824 viewport.hideAllSelectedSeqs();
2825 viewport.hideSelectedColumns();
2826 alignPanel.paintAlignment(true);
2833 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
2837 public void showAllhidden_actionPerformed(ActionEvent e)
2839 viewport.showAllHiddenColumns();
2840 viewport.showAllHiddenSeqs();
2841 alignPanel.paintAlignment(true);
2845 public void hideSelColumns_actionPerformed(ActionEvent e)
2847 viewport.hideSelectedColumns();
2848 alignPanel.paintAlignment(true);
2852 public void hiddenMarkers_actionPerformed(ActionEvent e)
2854 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
2865 protected void scaleAbove_actionPerformed(ActionEvent e)
2867 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
2868 alignPanel.paintAlignment(true);
2878 protected void scaleLeft_actionPerformed(ActionEvent e)
2880 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
2881 alignPanel.paintAlignment(true);
2891 protected void scaleRight_actionPerformed(ActionEvent e)
2893 viewport.setScaleRightWrapped(scaleRight.isSelected());
2894 alignPanel.paintAlignment(true);
2904 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
2906 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
2907 alignPanel.paintAlignment(true);
2917 public void viewTextMenuItem_actionPerformed(ActionEvent e)
2919 viewport.setShowText(viewTextMenuItem.isSelected());
2920 alignPanel.paintAlignment(true);
2930 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
2932 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
2933 alignPanel.paintAlignment(true);
2936 public FeatureSettings featureSettings;
2939 public void featureSettings_actionPerformed(ActionEvent e)
2941 if (featureSettings != null)
2943 featureSettings.close();
2944 featureSettings = null;
2946 if (!showSeqFeatures.isSelected())
2948 // make sure features are actually displayed
2949 showSeqFeatures.setSelected(true);
2950 showSeqFeatures_actionPerformed(null);
2952 featureSettings = new FeatureSettings(this);
2956 * Set or clear 'Show Sequence Features'
2962 public void showSeqFeatures_actionPerformed(ActionEvent evt)
2964 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
2965 alignPanel.paintAlignment(true);
2966 if (alignPanel.getOverviewPanel() != null)
2968 alignPanel.getOverviewPanel().updateOverviewImage();
2973 * Set or clear 'Show Sequence Features'
2979 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
2981 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
2983 if (viewport.getShowSequenceFeaturesHeight())
2985 // ensure we're actually displaying features
2986 viewport.setShowSequenceFeatures(true);
2987 showSeqFeatures.setSelected(true);
2989 alignPanel.paintAlignment(true);
2990 if (alignPanel.getOverviewPanel() != null)
2992 alignPanel.getOverviewPanel().updateOverviewImage();
3003 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3005 viewport.setShowAnnotation(annotationPanelMenuItem.isSelected());
3006 alignPanel.setAnnotationVisible(annotationPanelMenuItem.isSelected());
3010 public void alignmentProperties()
3012 JEditorPane editPane = new JEditorPane("text/html", "");
3013 editPane.setEditable(false);
3014 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3016 editPane.setText(MessageManager.formatMessage("label.html_content", new String[]{contents.toString()}));
3017 JInternalFrame frame = new JInternalFrame();
3018 frame.getContentPane().add(new JScrollPane(editPane));
3020 Desktop.instance.addInternalFrame(frame, MessageManager.formatMessage("label.alignment_properties", new String[]{getTitle()}), 500, 400);
\r
3030 public void overviewMenuItem_actionPerformed(ActionEvent e)
3032 if (alignPanel.overviewPanel != null)
3037 JInternalFrame frame = new JInternalFrame();
3038 OverviewPanel overview = new OverviewPanel(alignPanel);
3039 frame.setContentPane(overview);
3040 Desktop.addInternalFrame(frame, MessageManager.formatMessage("label.overview_params", new String[]{this.getTitle()}),
\r
3041 frame.getWidth(), frame.getHeight());
3043 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3044 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3047 public void internalFrameClosed(
3048 javax.swing.event.InternalFrameEvent evt)
3050 alignPanel.setOverviewPanel(null);
3054 alignPanel.setOverviewPanel(overview);
3058 public void textColour_actionPerformed(ActionEvent e)
3060 new TextColourChooser().chooseColour(alignPanel, null);
3070 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3082 public void clustalColour_actionPerformed(ActionEvent e)
3084 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3085 viewport.getHiddenRepSequences()));
3095 public void zappoColour_actionPerformed(ActionEvent e)
3097 changeColour(new ZappoColourScheme());
3107 public void taylorColour_actionPerformed(ActionEvent e)
3109 changeColour(new TaylorColourScheme());
3119 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3121 changeColour(new HydrophobicColourScheme());
3131 public void helixColour_actionPerformed(ActionEvent e)
3133 changeColour(new HelixColourScheme());
3143 public void strandColour_actionPerformed(ActionEvent e)
3145 changeColour(new StrandColourScheme());
3155 public void turnColour_actionPerformed(ActionEvent e)
3157 changeColour(new TurnColourScheme());
3167 public void buriedColour_actionPerformed(ActionEvent e)
3169 changeColour(new BuriedColourScheme());
3179 public void nucleotideColour_actionPerformed(ActionEvent e)
3181 changeColour(new NucleotideColourScheme());
3185 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3187 changeColour(new PurinePyrimidineColourScheme());
3191 * public void covariationColour_actionPerformed(ActionEvent e) {
3193 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3197 public void annotationColour_actionPerformed(ActionEvent e)
3199 new AnnotationColourChooser(viewport, alignPanel);
3203 public void rnahelicesColour_actionPerformed(ActionEvent e)
3205 new RNAHelicesColourChooser(viewport, alignPanel);
3215 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3217 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3226 public void changeColour(ColourSchemeI cs)
3228 // TODO: compare with applet and pull up to model method
3233 if (viewport.getAbovePIDThreshold())
3235 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3238 cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3240 viewport.setGlobalColourScheme(cs);
3244 cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3247 if (viewport.getConservationSelected())
3250 Alignment al = (Alignment) viewport.getAlignment();
3251 Conservation c = new Conservation("All",
3252 ResidueProperties.propHash, 3, al.getSequences(), 0,
3256 c.verdict(false, viewport.getConsPercGaps());
3258 cs.setConservation(c);
3260 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3265 cs.setConservation(null);
3268 cs.setConsensus(viewport.getSequenceConsensusHash());
3271 viewport.setGlobalColourScheme(cs);
3273 if (viewport.getColourAppliesToAllGroups())
3276 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3284 if (cs instanceof ClustalxColourScheme)
3286 sg.cs = new ClustalxColourScheme(sg,
3287 viewport.getHiddenRepSequences());
3289 else if (cs instanceof UserColourScheme)
3291 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
3297 sg.cs = cs.getClass().newInstance();
3298 } catch (Exception ex)
3303 if (viewport.getAbovePIDThreshold()
3304 || cs instanceof PIDColourScheme
3305 || cs instanceof Blosum62ColourScheme)
3307 sg.cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3309 sg.cs.setConsensus(AAFrequency.calculate(
3310 sg.getSequences(viewport.getHiddenRepSequences()),
3311 sg.getStartRes(), sg.getEndRes() + 1));
3315 sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3318 if (viewport.getConservationSelected())
3320 Conservation c = new Conservation("Group",
3321 ResidueProperties.propHash, 3, sg.getSequences(viewport
3322 .getHiddenRepSequences()), sg.getStartRes(),
3323 sg.getEndRes() + 1);
3325 c.verdict(false, viewport.getConsPercGaps());
3326 sg.cs.setConservation(c);
3330 sg.cs.setConservation(null);
3335 if (alignPanel.getOverviewPanel() != null)
3337 alignPanel.getOverviewPanel().updateOverviewImage();
3340 alignPanel.paintAlignment(true);
3350 protected void modifyPID_actionPerformed(ActionEvent e)
3352 if (viewport.getAbovePIDThreshold()
3353 && viewport.getGlobalColourScheme() != null)
3355 SliderPanel.setPIDSliderSource(alignPanel,
3356 viewport.getGlobalColourScheme(), "Background");
3357 SliderPanel.showPIDSlider();
3368 protected void modifyConservation_actionPerformed(ActionEvent e)
3370 if (viewport.getConservationSelected()
3371 && viewport.getGlobalColourScheme() != null)
3373 SliderPanel.setConservationSlider(alignPanel,
3374 viewport.getGlobalColourScheme(), "Background");
3375 SliderPanel.showConservationSlider();
3386 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3388 viewport.setConservationSelected(conservationMenuItem.isSelected());
3390 viewport.setAbovePIDThreshold(false);
3391 abovePIDThreshold.setSelected(false);
3393 changeColour(viewport.getGlobalColourScheme());
3395 modifyConservation_actionPerformed(null);
3405 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3407 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3409 conservationMenuItem.setSelected(false);
3410 viewport.setConservationSelected(false);
3412 changeColour(viewport.getGlobalColourScheme());
3414 modifyPID_actionPerformed(null);
3424 public void userDefinedColour_actionPerformed(ActionEvent e)
3426 if (e.getActionCommand().equals(MessageManager.getString("action.user_defined")))
\r
3428 new UserDefinedColours(alignPanel, null);
3432 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3433 .getUserColourSchemes().get(e.getActionCommand());
3439 public void updateUserColourMenu()
3442 Component[] menuItems = colourMenu.getMenuComponents();
3443 int i, iSize = menuItems.length;
3444 for (i = 0; i < iSize; i++)
3446 if (menuItems[i].getName() != null
3447 && menuItems[i].getName().equals("USER_DEFINED"))
3449 colourMenu.remove(menuItems[i]);
3453 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3455 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3456 .getUserColourSchemes().keys();
3458 while (userColours.hasMoreElements())
3460 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3461 userColours.nextElement().toString());
3462 radioItem.setName("USER_DEFINED");
3463 radioItem.addMouseListener(new MouseAdapter()
3466 public void mousePressed(MouseEvent evt)
3468 if (evt.isControlDown()
3469 || SwingUtilities.isRightMouseButton(evt))
3471 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3473 int option = JOptionPane.showInternalConfirmDialog(
3474 jalview.gui.Desktop.desktop,
3475 MessageManager.getString("label.remove_from_default_list"),
3476 MessageManager.getString("label.remove_user_defined_colour"),
3477 JOptionPane.YES_NO_OPTION);
3478 if (option == JOptionPane.YES_OPTION)
3480 jalview.gui.UserDefinedColours
3481 .removeColourFromDefaults(radioItem.getText());
3482 colourMenu.remove(radioItem);
3486 radioItem.addActionListener(new ActionListener()
3489 public void actionPerformed(ActionEvent evt)
3491 userDefinedColour_actionPerformed(evt);
3498 radioItem.addActionListener(new ActionListener()
3501 public void actionPerformed(ActionEvent evt)
3503 userDefinedColour_actionPerformed(evt);
3507 colourMenu.insert(radioItem, 15);
3508 colours.add(radioItem);
3520 public void PIDColour_actionPerformed(ActionEvent e)
3522 changeColour(new PIDColourScheme());
3532 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3534 changeColour(new Blosum62ColourScheme());
3544 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3546 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3547 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3548 .getAlignment().getSequenceAt(0), null);
3549 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3550 viewport.getAlignment()));
3551 alignPanel.paintAlignment(true);
3561 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3563 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3564 AlignmentSorter.sortByID(viewport.getAlignment());
3565 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3566 viewport.getAlignment()));
3567 alignPanel.paintAlignment(true);
3577 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3579 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3580 AlignmentSorter.sortByLength(viewport.getAlignment());
3581 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3582 viewport.getAlignment()));
3583 alignPanel.paintAlignment(true);
3593 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3595 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3596 AlignmentSorter.sortByGroup(viewport.getAlignment());
3597 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3598 viewport.getAlignment()));
3600 alignPanel.paintAlignment(true);
3610 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3612 new RedundancyPanel(alignPanel, this);
3622 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3624 if ((viewport.getSelectionGroup() == null)
3625 || (viewport.getSelectionGroup().getSize() < 2))
3627 JOptionPane.showInternalMessageDialog(this,
3628 MessageManager.getString("label.you_must_select_least_two_sequences"), MessageManager.getString("label.invalid_selection"),
3629 JOptionPane.WARNING_MESSAGE);
3633 JInternalFrame frame = new JInternalFrame();
3634 frame.setContentPane(new PairwiseAlignPanel(viewport));
3635 Desktop.addInternalFrame(frame, MessageManager.getString("action.pairwise_alignment"), 600, 500);
\r
3646 public void PCAMenuItem_actionPerformed(ActionEvent e)
3648 if (((viewport.getSelectionGroup() != null)
3649 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3650 .getSelectionGroup().getSize() > 0))
3651 || (viewport.getAlignment().getHeight() < 4))
3653 JOptionPane.showInternalMessageDialog(this,
3654 MessageManager.getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3655 MessageManager.getString("label.sequence_selection_insufficient"),
3656 JOptionPane.WARNING_MESSAGE);
3661 new PCAPanel(alignPanel);
3665 public void autoCalculate_actionPerformed(ActionEvent e)
3667 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3668 if (viewport.autoCalculateConsensus)
3670 viewport.firePropertyChange("alignment", null, viewport
3671 .getAlignment().getSequences());
3676 public void sortByTreeOption_actionPerformed(ActionEvent e)
3678 viewport.sortByTree = sortByTree.isSelected();
3682 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3684 viewport.followSelection = listenToViewSelections.isSelected();
3694 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3696 NewTreePanel("AV", "PID", "Average distance tree using PID");
3706 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3708 NewTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3718 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3720 NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3730 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3732 NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3745 void NewTreePanel(String type, String pwType, String title)
3749 if (viewport.getSelectionGroup() != null
3750 && viewport.getSelectionGroup().getSize() > 0)
3752 if (viewport.getSelectionGroup().getSize() < 3)
3757 MessageManager.getString("label.you_need_more_two_sequences_selected_build_tree"),
3758 MessageManager.getString("label.not_enough_sequences"), JOptionPane.WARNING_MESSAGE);
3762 SequenceGroup sg = viewport.getSelectionGroup();
3764 /* Decide if the selection is a column region */
3765 for (SequenceI _s : sg.getSequences())
3767 if (_s.getLength() < sg.getEndRes())
3772 MessageManager.getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3773 MessageManager.getString("label.sequences_selection_not_aligned"),
3774 JOptionPane.WARNING_MESSAGE);
3780 title = title + " on region";
3781 tp = new TreePanel(alignPanel, type, pwType);
3785 // are the visible sequences aligned?
3786 if (!viewport.getAlignment().isAligned(false))
3791 MessageManager.getString("label.sequences_must_be_aligned_before_creating_tree"),
3792 MessageManager.getString("label.sequences_not_aligned"),
3793 JOptionPane.WARNING_MESSAGE);
3798 if (viewport.getAlignment().getHeight() < 2)
3803 tp = new TreePanel(alignPanel, type, pwType);
3808 if (viewport.viewName != null)
3810 title += viewport.viewName + " of ";
3813 title += this.title;
3815 Desktop.addInternalFrame(tp, title, 600, 500);
3826 public void addSortByOrderMenuItem(String title,
3827 final AlignmentOrder order)
3829 final JMenuItem item = new JMenuItem("by " + title);
3831 item.addActionListener(new java.awt.event.ActionListener()
3834 public void actionPerformed(ActionEvent e)
3836 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3838 // TODO: JBPNote - have to map order entries to curent SequenceI
3840 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3842 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
3845 alignPanel.paintAlignment(true);
3851 * Add a new sort by annotation score menu item
3854 * the menu to add the option to
3856 * the label used to retrieve scores for each sequence on the
3859 public void addSortByAnnotScoreMenuItem(JMenu sort,
3860 final String scoreLabel)
3862 final JMenuItem item = new JMenuItem(scoreLabel);
3864 item.addActionListener(new java.awt.event.ActionListener()
3867 public void actionPerformed(ActionEvent e)
3869 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3870 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3871 viewport.getAlignment());// ,viewport.getSelectionGroup());
3872 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3873 viewport.getAlignment()));
3874 alignPanel.paintAlignment(true);
3880 * last hash for alignment's annotation array - used to minimise cost of
3883 protected int _annotationScoreVectorHash;
3886 * search the alignment and rebuild the sort by annotation score submenu the
3887 * last alignment annotation vector hash is stored to minimize cost of
3888 * rebuilding in subsequence calls.
3892 public void buildSortByAnnotationScoresMenu()
3894 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3899 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
3901 sortByAnnotScore.removeAll();
3902 // almost certainly a quicker way to do this - but we keep it simple
3903 Hashtable scoreSorts = new Hashtable();
3904 AlignmentAnnotation aann[];
3905 for (SequenceI sqa : viewport.getAlignment().getSequences())
3907 aann = sqa.getAnnotation();
3908 for (int i = 0; aann != null && i < aann.length; i++)
3910 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3912 scoreSorts.put(aann[i].label, aann[i].label);
3916 Enumeration labels = scoreSorts.keys();
3917 while (labels.hasMoreElements())
3919 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3920 (String) labels.nextElement());
3922 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3925 _annotationScoreVectorHash = viewport.getAlignment()
3926 .getAlignmentAnnotation().hashCode();
3931 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3932 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3933 * call. Listeners are added to remove the menu item when the treePanel is
3934 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3938 * Displayed tree window.
3940 * SortBy menu item title.
3943 public void buildTreeMenu()
3945 calculateTree.removeAll();
3946 // build the calculate menu
3947 for (final String type:new String[] {"NJ", "AV"})
3949 for (final Object pwtype: ResidueProperties.scoreMatrices.keySet())
3951 JMenuItem tm = new JMenuItem();
3952 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
3953 final String title="Calculate "+type+" using "+sm.getName();
3954 tm.setText(title);// MessageManager.getString("label.neighbour_blosum62"));
3956 .addActionListener(new java.awt.event.ActionListener()
3958 public void actionPerformed(ActionEvent e)
3960 NewTreePanel(type, (String) pwtype, title);
3963 calculateTree.add(tm);
3967 sortByTreeMenu.removeAll();
3969 Vector comps = (Vector) PaintRefresher.components.get(viewport
3970 .getSequenceSetId());
3971 Vector treePanels = new Vector();
3972 int i, iSize = comps.size();
3973 for (i = 0; i < iSize; i++)
3975 if (comps.elementAt(i) instanceof TreePanel)
3977 treePanels.add(comps.elementAt(i));
3981 iSize = treePanels.size();
3985 sortByTreeMenu.setVisible(false);
3989 sortByTreeMenu.setVisible(true);
3991 for (i = 0; i < treePanels.size(); i++)
3993 final TreePanel tp = (TreePanel) treePanels.elementAt(i);
3994 final JMenuItem item = new JMenuItem(tp.getTitle());
3995 final NJTree tree = ((TreePanel) treePanels.elementAt(i)).getTree();
3996 item.addActionListener(new java.awt.event.ActionListener()
3999 public void actionPerformed(ActionEvent e)
4001 tp.sortByTree_actionPerformed(null);
4002 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4007 sortByTreeMenu.add(item);
4011 public boolean sortBy(AlignmentOrder alorder, String undoname)
4013 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4014 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4015 if (undoname != null)
4017 addHistoryItem(new OrderCommand(undoname, oldOrder,
4018 viewport.getAlignment()));
4020 alignPanel.paintAlignment(true);
4025 * Work out whether the whole set of sequences or just the selected set will
4026 * be submitted for multiple alignment.
4029 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4031 // Now, check we have enough sequences
4032 AlignmentView msa = null;
4034 if ((viewport.getSelectionGroup() != null)
4035 && (viewport.getSelectionGroup().getSize() > 1))
4037 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4038 // some common interface!
4040 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4041 * SequenceI[sz = seqs.getSize(false)];
4043 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4044 * seqs.getSequenceAt(i); }
4046 msa = viewport.getAlignmentView(true);
4051 * Vector seqs = viewport.getAlignment().getSequences();
4053 * if (seqs.size() > 1) { msa = new SequenceI[seqs.size()];
4055 * for (int i = 0; i < seqs.size(); i++) { msa[i] = (SequenceI)
4056 * seqs.elementAt(i); } }
4058 msa = viewport.getAlignmentView(false);
4064 * Decides what is submitted to a secondary structure prediction service: the
4065 * first sequence in the alignment, or in the current selection, or, if the
4066 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4067 * region or the whole alignment. (where the first sequence in the set is the
4068 * one that the prediction will be for).
4070 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4072 AlignmentView seqs = null;
4074 if ((viewport.getSelectionGroup() != null)
4075 && (viewport.getSelectionGroup().getSize() > 0))
4077 seqs = viewport.getAlignmentView(true);
4081 seqs = viewport.getAlignmentView(false);
4083 // limit sequences - JBPNote in future - could spawn multiple prediction
4085 // TODO: viewport.getAlignment().isAligned is a global state - the local
4086 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4087 if (!viewport.getAlignment().isAligned(false))
4089 seqs.setSequences(new SeqCigar[]
4090 { seqs.getSequences()[0] });
4091 // TODO: if seqs.getSequences().length>1 then should really have warned
4105 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
4107 // Pick the tree file
4108 JalviewFileChooser chooser = new JalviewFileChooser(
4109 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4110 chooser.setFileView(new JalviewFileView());
4111 chooser.setDialogTitle(MessageManager.getString("label.select_newick_like_tree_file"));
\r
4112 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
\r
4114 int value = chooser.showOpenDialog(null);
4116 if (value == JalviewFileChooser.APPROVE_OPTION)
4118 String choice = chooser.getSelectedFile().getPath();
4119 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4120 jalview.io.NewickFile fin = null;
4123 fin = new jalview.io.NewickFile(choice, "File");
4124 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4125 } catch (Exception ex)
4127 JOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4128 MessageManager.getString("label.problem_reading_tree_file"), JOptionPane.WARNING_MESSAGE);
4129 ex.printStackTrace();
4131 if (fin != null && fin.hasWarningMessage())
4133 JOptionPane.showMessageDialog(Desktop.desktop,
4134 fin.getWarningMessage(), MessageManager.getString("label.possible_problem_with_tree_file"),
4135 JOptionPane.WARNING_MESSAGE);
4141 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4143 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4146 public TreePanel ShowNewickTree(NewickFile nf, String title)
4148 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4151 public TreePanel ShowNewickTree(NewickFile nf, String title,
4152 AlignmentView input)
4154 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4157 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4158 int h, int x, int y)
4160 return ShowNewickTree(nf, title, null, w, h, x, y);
4164 * Add a treeviewer for the tree extracted from a newick file object to the
4165 * current alignment view
4172 * Associated alignment input data (or null)
4181 * @return TreePanel handle
4183 public TreePanel ShowNewickTree(NewickFile nf, String title,
4184 AlignmentView input, int w, int h, int x, int y)
4186 TreePanel tp = null;
4192 if (nf.getTree() != null)
4194 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4200 tp.setLocation(x, y);
4203 Desktop.addInternalFrame(tp, title, w, h);
4205 } catch (Exception ex)
4207 ex.printStackTrace();
4213 private boolean buildingMenu = false;
4216 * Generates menu items and listener event actions for web service clients
4219 public void BuildWebServiceMenu()
4221 while (buildingMenu)
4225 System.err.println("Waiting for building menu to finish.");
4227 } catch (Exception e)
4232 final AlignFrame me = this;
4233 buildingMenu = true;
4234 new Thread(new Runnable()
4239 final List<JMenuItem> legacyItems=new ArrayList<JMenuItem>();
4242 System.err.println("Building ws menu again "
4243 + Thread.currentThread());
4244 // TODO: add support for context dependent disabling of services based
4246 // alignment and current selection
4247 // TODO: add additional serviceHandle parameter to specify abstract
4249 // class independently of AbstractName
4250 // TODO: add in rediscovery GUI function to restart discoverer
4251 // TODO: group services by location as well as function and/or
4253 // object broker mechanism.
4254 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4255 final IProgressIndicator af = me;
4256 final JMenu msawsmenu = new JMenu("Alignment");
4257 final JMenu secstrmenu = new JMenu(
4258 "Secondary Structure Prediction");
4259 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4260 final JMenu analymenu = new JMenu("Analysis");
4261 final JMenu dismenu = new JMenu("Protein Disorder");
4262 // JAL-940 - only show secondary structure prediction services from
4263 // the legacy server
4264 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4266 Discoverer.services != null && (Discoverer.services.size() > 0))
4268 // TODO: refactor to allow list of AbstractName/Handler bindings to
4270 // stored or retrieved from elsewhere
4271 // No MSAWS used any more:
4272 // Vector msaws = null; // (Vector) Discoverer.services.get("MsaWS");
4273 Vector secstrpr = (Vector) Discoverer.services
4275 if (secstrpr != null)
4277 // Add any secondary structure prediction services
4278 for (int i = 0, j = secstrpr.size(); i < j; i++)
4280 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4282 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4283 .getServiceClient(sh);
4284 int p=secstrmenu.getItemCount();
4285 impl.attachWSMenuEntry(secstrmenu, me);
4286 int q=secstrmenu.getItemCount();
4287 for (int litm=p;litm<q; litm++)
4289 legacyItems.add(secstrmenu.getItem(litm));
4295 // Add all submenus in the order they should appear on the web
4297 wsmenu.add(msawsmenu);
4298 wsmenu.add(secstrmenu);
4299 wsmenu.add(dismenu);
4300 wsmenu.add(analymenu);
4301 // No search services yet
4302 // wsmenu.add(seqsrchmenu);
4304 javax.swing.SwingUtilities.invokeLater(new Runnable()
4311 webService.removeAll();
4312 // first, add discovered services onto the webservices menu
4313 if (wsmenu.size() > 0)
4315 for (int i = 0, j = wsmenu.size(); i < j; i++)
4317 webService.add(wsmenu.get(i));
4322 webService.add(me.webServiceNoServices);
4324 // TODO: move into separate menu builder class.
4325 boolean new_sspred=false;
4326 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4328 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4329 if (jws2servs != null)
4331 if (jws2servs.hasServices())
4333 jws2servs.attachWSMenuEntry(webService, me);
4334 for (Jws2Instance sv:jws2servs.getServices()) {
4335 if (sv.description.toLowerCase().contains("jpred"))
4337 for (JMenuItem jmi:legacyItems)
4339 jmi.setVisible(false);
4345 if (jws2servs.isRunning())
4347 JMenuItem tm = new JMenuItem(
4348 "Still discovering JABA Services");
4349 tm.setEnabled(false);
4354 build_urlServiceMenu(me.webService);
4355 build_fetchdbmenu(webService);
4356 for (JMenu item : wsmenu)
4358 if (item.getItemCount() == 0)
4360 item.setEnabled(false);
4364 item.setEnabled(true);
4367 } catch (Exception e)
4370 .debug("Exception during web service menu building process.",
4376 } catch (Exception e)
4381 buildingMenu = false;
4388 * construct any groupURL type service menu entries.
4392 private void build_urlServiceMenu(JMenu webService)
4394 // TODO: remove this code when 2.7 is released
4395 // DEBUG - alignmentView
4397 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4398 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4400 * @Override public void actionPerformed(ActionEvent e) {
4401 * jalview.datamodel.AlignmentView
4402 * .testSelectionViews(af.viewport.getAlignment(),
4403 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4405 * }); webService.add(testAlView);
4407 // TODO: refactor to RestClient discoverer and merge menu entries for
4408 // rest-style services with other types of analysis/calculation service
4409 // SHmmr test client - still being implemented.
4410 // DEBUG - alignmentView
4412 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4415 client.attachWSMenuEntry(
4416 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4420 if (Cache.getDefault("SHOW_ENFIN_SERVICES", true))
4422 jalview.ws.EnfinEnvision2OneWay.getInstance().attachWSMenuEntry(
4428 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
4429 * chooser = new JalviewFileChooser(jalview.bin.Cache.
4430 * getProperty("LAST_DIRECTORY"));
4432 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
4433 * to Vamsas file"); chooser.setToolTipText("Export");
4435 * int value = chooser.showSaveDialog(this);
4437 * if (value == JalviewFileChooser.APPROVE_OPTION) {
4438 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
4439 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
4440 * chooser.getSelectedFile().getAbsolutePath(), this); } }
4443 * prototype of an automatically enabled/disabled analysis function
4446 protected void setShowProductsEnabled()
4448 SequenceI[] selection = viewport.getSequenceSelection();
4449 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
4450 viewport.getAlignment().getDataset()))
4452 showProducts.setEnabled(true);
4457 showProducts.setEnabled(false);
4462 * search selection for sequence xRef products and build the show products
4467 * @return true if showProducts menu should be enabled.
4469 public boolean canShowProducts(SequenceI[] selection,
4470 boolean isRegionSelection, Alignment dataset)
4472 boolean showp = false;
4475 showProducts.removeAll();
4476 final boolean dna = viewport.getAlignment().isNucleotide();
4477 final Alignment ds = dataset;
4478 String[] ptypes = (selection == null || selection.length == 0) ? null
4479 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4481 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4482 // selection, dataset, true);
4483 final SequenceI[] sel = selection;
4484 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4487 final boolean isRegSel = isRegionSelection;
4488 final AlignFrame af = this;
4489 final String source = ptypes[t];
4490 JMenuItem xtype = new JMenuItem(ptypes[t]);
4491 xtype.addActionListener(new ActionListener()
4495 public void actionPerformed(ActionEvent e)
4497 // TODO: new thread for this call with vis-delay
4498 af.showProductsFor(af.viewport.getSequenceSelection(), ds,
4499 isRegSel, dna, source);
4503 showProducts.add(xtype);
4505 showProducts.setVisible(showp);
4506 showProducts.setEnabled(showp);
4507 } catch (Exception e)
4509 jalview.bin.Cache.log
4510 .warn("canTranslate threw an exception - please report to help@jalview.org",
4517 protected void showProductsFor(SequenceI[] sel, Alignment ds,
4518 boolean isRegSel, boolean dna, String source)
4520 final boolean fisRegSel = isRegSel;
4521 final boolean fdna = dna;
4522 final String fsrc = source;
4523 final AlignFrame ths = this;
4524 final SequenceI[] fsel = sel;
4525 Runnable foo = new Runnable()
4531 final long sttime = System.currentTimeMillis();
4532 ths.setProgressBar("Searching for sequences from " + fsrc, sttime);
4535 Alignment ds = ths.getViewport().getAlignment().getDataset(); // update
4539 Alignment prods = CrossRef
4540 .findXrefSequences(fsel, fdna, fsrc, ds);
4543 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4544 for (int s = 0; s < sprods.length; s++)
4546 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4547 if (ds.getSequences() == null
4548 || !ds.getSequences().contains(
4549 sprods[s].getDatasetSequence()))
4550 ds.addSequence(sprods[s].getDatasetSequence());
4551 sprods[s].updatePDBIds();
4553 Alignment al = new Alignment(sprods);
4554 AlignedCodonFrame[] cf = prods.getCodonFrames();
4556 for (int s = 0; cf != null && s < cf.length; s++)
4558 al.addCodonFrame(cf[s]);
4561 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4563 String newtitle = "" + ((fdna) ? "Proteins " : "Nucleotides ")
4564 + " for " + ((fisRegSel) ? "selected region of " : "")
4566 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4571 System.err.println("No Sequences generated for xRef type "
4574 } catch (Exception e)
4576 jalview.bin.Cache.log.error(
4577 "Exception when finding crossreferences", e);
4578 } catch (OutOfMemoryError e)
4580 new OOMWarning("whilst fetching crossreferences", e);
4583 jalview.bin.Cache.log.error("Error when finding crossreferences",
4586 ths.setProgressBar("Finished searching for sequences from " + fsrc,
4591 Thread frunner = new Thread(foo);
4595 public boolean canShowTranslationProducts(SequenceI[] selection,
4596 AlignmentI alignment)
4601 return (jalview.analysis.Dna.canTranslate(selection,
4602 viewport.getViewAsVisibleContigs(true)));
4603 } catch (Exception e)
4605 jalview.bin.Cache.log
4606 .warn("canTranslate threw an exception - please report to help@jalview.org",
4613 public void showProducts_actionPerformed(ActionEvent e)
4615 // /////////////////////////////
4616 // Collect Data to be translated/transferred
4618 SequenceI[] selection = viewport.getSequenceSelection();
4619 AlignmentI al = null;
4622 al = jalview.analysis.Dna.CdnaTranslate(selection, viewport
4623 .getViewAsVisibleContigs(true), viewport.getGapCharacter(),
4624 viewport.getAlignment().getDataset());
4625 } catch (Exception ex)
4628 jalview.bin.Cache.log.debug("Exception during translation.", ex);
4635 MessageManager.getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation"),
4636 MessageManager.getString("label.translation_failed"), JOptionPane.WARNING_MESSAGE);
4640 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4641 Desktop.addInternalFrame(af, MessageManager.formatMessage("label.translation_of_params", new String[]{this.getTitle()}),
\r
4642 DEFAULT_WIDTH, DEFAULT_HEIGHT);
4647 public void showTranslation_actionPerformed(ActionEvent e)
4649 // /////////////////////////////
4650 // Collect Data to be translated/transferred
4652 SequenceI[] selection = viewport.getSequenceSelection();
4653 String[] seqstring = viewport.getViewAsString(true);
4654 AlignmentI al = null;
4657 al = jalview.analysis.Dna.CdnaTranslate(selection, seqstring,
4658 viewport.getViewAsVisibleContigs(true), viewport
4659 .getGapCharacter(), viewport.getAlignment()
4660 .getAlignmentAnnotation(), viewport.getAlignment()
4661 .getWidth(), viewport.getAlignment().getDataset());
4662 } catch (Exception ex)
4665 jalview.bin.Cache.log.error("Exception during translation. Please report this !", ex);
4669 MessageManager.getString("label.error_when_translating_sequences_submit_bug_report"),
4670 MessageManager.getString("label.implementation_error") + MessageManager.getString("translation_failed"), JOptionPane.ERROR_MESSAGE);
4678 MessageManager.getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation"),
4679 MessageManager.getString("label.translation_failed"), JOptionPane.WARNING_MESSAGE);
4683 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4684 Desktop.addInternalFrame(af, MessageManager.formatMessage("label.translation_of_params", new String[]{this.getTitle()}),
\r
4685 DEFAULT_WIDTH, DEFAULT_HEIGHT);
4690 * Try to load a features file onto the alignment.
4693 * contents or path to retrieve file
4695 * access mode of file (see jalview.io.AlignFile)
4696 * @return true if features file was parsed corectly.
4698 public boolean parseFeaturesFile(String file, String type)
4700 boolean featuresFile = false;
4703 featuresFile = new FeaturesFile(file, type).parse(viewport
4704 .getAlignment().getDataset(), alignPanel.seqPanel.seqCanvas
4705 .getFeatureRenderer().featureColours, false,
4706 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4707 } catch (Exception ex)
4709 ex.printStackTrace();
4714 viewport.showSequenceFeatures = true;
4715 showSeqFeatures.setSelected(true);
4716 if (alignPanel.seqPanel.seqCanvas.fr != null)
4718 // update the min/max ranges where necessary
4719 alignPanel.seqPanel.seqCanvas.fr.findAllFeatures(true);
4721 if (featureSettings != null)
4723 featureSettings.setTableData();
4725 alignPanel.paintAlignment(true);
4728 return featuresFile;
4732 public void dragEnter(DropTargetDragEvent evt)
4737 public void dragExit(DropTargetEvent evt)
4742 public void dragOver(DropTargetDragEvent evt)
4747 public void dropActionChanged(DropTargetDragEvent evt)
4752 public void drop(DropTargetDropEvent evt)
4754 Transferable t = evt.getTransferable();
4755 java.util.List files = null;
4759 DataFlavor uriListFlavor = new DataFlavor(
4760 "text/uri-list;class=java.lang.String");
4761 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
4763 // Works on Windows and MacOSX
4764 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4765 files = (java.util.List) t
4766 .getTransferData(DataFlavor.javaFileListFlavor);
4768 else if (t.isDataFlavorSupported(uriListFlavor))
4770 // This is used by Unix drag system
4771 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4772 String data = (String) t.getTransferData(uriListFlavor);
4773 files = new java.util.ArrayList(1);
4774 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
4775 data, "\r\n"); st.hasMoreTokens();)
4777 String s = st.nextToken();
4778 if (s.startsWith("#"))
4780 // the line is a comment (as per the RFC 2483)
4784 java.net.URI uri = new java.net.URI(s);
4785 // check to see if we can handle this kind of URI
4786 if (uri.getScheme().toLowerCase().startsWith("http"))
4788 files.add(uri.toString());
4792 // otherwise preserve old behaviour: catch all for file objects
4793 java.io.File file = new java.io.File(uri);
4794 files.add(file.toString());
4798 } catch (Exception e)
4800 e.printStackTrace();
4806 // check to see if any of these files have names matching sequences in
4808 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4809 .getAlignment().getSequencesArray());
4811 * Object[] { String,SequenceI}
4813 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
4814 ArrayList<String> filesnotmatched = new ArrayList<String>();
4815 for (int i = 0; i < files.size(); i++)
4817 String file = files.get(i).toString();
4819 String protocol = FormatAdapter.checkProtocol(file);
4820 if (protocol == jalview.io.FormatAdapter.FILE)
4822 File fl = new File(file);
4823 pdbfn = fl.getName();
4825 else if (protocol == jalview.io.FormatAdapter.URL)
4827 URL url = new URL(file);
4828 pdbfn = url.getFile();
4830 if (pdbfn.length() > 0)
4832 // attempt to find a match in the alignment
4833 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4834 int l = 0, c = pdbfn.indexOf(".");
4835 while (mtch == null && c != -1)
4840 } while ((c = pdbfn.indexOf(".", l)) > l);
4843 pdbfn = pdbfn.substring(0, l);
4845 mtch = idm.findAllIdMatches(pdbfn);
4852 type = new IdentifyFile().Identify(file, protocol);
4853 } catch (Exception ex)
4859 if (type.equalsIgnoreCase("PDB"))
4861 filesmatched.add(new Object[]
4862 { file, protocol, mtch });
4867 // File wasn't named like one of the sequences or wasn't a PDB file.
4868 filesnotmatched.add(file);
4872 if (filesmatched.size() > 0)
4874 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4878 MessageManager.formatMessage("label.automatically_associate_pdb_files_with_sequences_same_name",
4879 new String[]{Integer.valueOf(filesmatched.size()).toString()}),
4880 MessageManager.getString("label.automatically_associate_pdb_files_by_name"),
4881 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
4884 for (Object[] fm : filesmatched)
4886 // try and associate
4887 // TODO: may want to set a standard ID naming formalism for
4888 // associating PDB files which have no IDs.
4889 for (SequenceI toassoc : (SequenceI[]) fm[2])
4891 PDBEntry pe = new AssociatePdbFileWithSeq()
4892 .associatePdbWithSeq((String) fm[0],
4893 (String) fm[1], toassoc, false);
4896 System.err.println("Associated file : "
4897 + ((String) fm[0]) + " with "
4898 + toassoc.getDisplayId(true));
4902 alignPanel.paintAlignment(true);
4906 if (filesnotmatched.size() > 0)
4909 && (Cache.getDefault(
4910 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
4913 MessageManager.formatMessage("label.ignore_unmatched_dropped_files_info", new String[]{Integer.valueOf(filesnotmatched.size()).toString()}),
4914 MessageManager.getString("label.ignore_unmatched_dropped_files"),
4915 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
4919 for (String fn : filesnotmatched)
4921 loadJalviewDataFile(fn, null, null, null);
4925 } catch (Exception ex)
4927 ex.printStackTrace();
4933 * Attempt to load a "dropped" file or URL string: First by testing whether
4934 * it's and Annotation file, then a JNet file, and finally a features file. If
4935 * all are false then the user may have dropped an alignment file onto this
4939 * either a filename or a URL string.
4941 public void loadJalviewDataFile(String file, String protocol,
4942 String format, SequenceI assocSeq)
4946 if (protocol == null)
4948 protocol = jalview.io.FormatAdapter.checkProtocol(file);
4950 // if the file isn't identified, or not positively identified as some
4951 // other filetype (PFAM is default unidentified alignment file type) then
4952 // try to parse as annotation.
4953 boolean isAnnotation = (format == null || format
4954 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
4955 .readAnnotationFile(viewport.getAlignment(), file, protocol)
4960 // first see if its a T-COFFEE score file
4961 TCoffeeScoreFile tcf = null;
4964 tcf = new TCoffeeScoreFile(file, protocol);
4967 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4969 tcoffeeColour.setEnabled(true);
4970 tcoffeeColour.setSelected(true);
4971 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
4972 isAnnotation = true;
4973 statusBar.setText(MessageManager.getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
4977 // some problem - if no warning its probable that the ID matching
4978 // process didn't work
4982 tcf.getWarningMessage() == null ? MessageManager.getString("label.check_file_matches_sequence_ids_alignment")
4983 : tcf.getWarningMessage(),
4984 MessageManager.getString("label.problem_reading_tcoffee_score_file"),
4985 JOptionPane.WARNING_MESSAGE);
4992 } catch (Exception x)
4995 .debug("Exception when processing data source as T-COFFEE score file",
5001 // try to see if its a JNet 'concise' style annotation file *before*
5003 // try to parse it as a features file
5006 format = new IdentifyFile().Identify(file, protocol);
5008 if (format.equalsIgnoreCase("JnetFile"))
5010 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5012 new JnetAnnotationMaker().add_annotation(predictions,
5013 viewport.getAlignment(), 0, false);
5014 isAnnotation = true;
5019 * if (format.equalsIgnoreCase("PDB")) {
5021 * String pdbfn = ""; // try to match up filename with sequence id
5022 * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
5023 * new File(file); pdbfn = fl.getName(); } else if (protocol ==
5024 * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
5025 * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
5026 * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5027 * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
5028 * // attempt to find a match in the alignment SequenceI mtch =
5029 * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
5030 * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
5031 * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
5032 * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
5033 * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
5034 * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
5035 * { System.err.println("Associated file : " + file + " with " +
5036 * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
5037 * TODO: maybe need to load as normal otherwise return; } }
5039 // try to parse it as a features file
5040 boolean isGroupsFile = parseFeaturesFile(file, protocol);
5041 // if it wasn't a features file then we just treat it as a general
5042 // alignment file to load into the current view.
5045 new FileLoader().LoadFile(viewport, file, protocol, format);
5049 alignPanel.paintAlignment(true);
5057 alignPanel.adjustAnnotationHeight();
5058 viewport.updateSequenceIdColours();
5059 buildSortByAnnotationScoresMenu();
5060 alignPanel.paintAlignment(true);
5062 } catch (Exception ex)
5064 ex.printStackTrace();
5065 } catch (OutOfMemoryError oom)
5070 } catch (Exception x)
5076 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5077 : "using " + protocol + " from " + file)
5079 + (format != null ? "(parsing as '" + format
5080 + "' file)" : ""), oom, Desktop.desktop);
5085 public void tabSelectionChanged(int index)
5089 alignPanel = (AlignmentPanel) alignPanels.elementAt(index);
5090 viewport = alignPanel.av;
5091 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5092 setMenusFromViewport(viewport);
5097 public void tabbedPane_mousePressed(MouseEvent e)
5099 if (SwingUtilities.isRightMouseButton(e))
5101 String reply = JOptionPane.showInternalInputDialog(this,
5102 MessageManager.getString("label.enter_view_name"), MessageManager.getString("label.enter_view_name"),
5103 JOptionPane.QUESTION_MESSAGE);
5107 viewport.viewName = reply;
5108 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5113 public AlignViewport getCurrentView()
5119 * Open the dialog for regex description parsing.
5122 protected void extractScores_actionPerformed(ActionEvent e)
5124 ParseProperties pp = new jalview.analysis.ParseProperties(
5125 viewport.getAlignment());
5126 // TODO: verify regex and introduce GUI dialog for version 2.5
5127 // if (pp.getScoresFromDescription("col", "score column ",
5128 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5130 if (pp.getScoresFromDescription("description column",
5131 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5133 buildSortByAnnotationScoresMenu();
5141 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5145 protected void showDbRefs_actionPerformed(ActionEvent e)
5147 viewport.setShowDbRefs(showDbRefsMenuitem.isSelected());
5153 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5157 protected void showNpFeats_actionPerformed(ActionEvent e)
5159 viewport.setShowNpFeats(showNpFeatsMenuitem.isSelected());
5163 * find the viewport amongst the tabs in this alignment frame and close that
5168 public boolean closeView(AlignViewport av)
5172 this.closeMenuItem_actionPerformed(false);
5175 Component[] comp = tabbedPane.getComponents();
5176 for (int i = 0; comp != null && i < comp.length; i++)
5178 if (comp[i] instanceof AlignmentPanel)
5180 if (((AlignmentPanel) comp[i]).av == av)
5183 closeView((AlignmentPanel) comp[i]);
5191 protected void build_fetchdbmenu(JMenu webService)
5193 // Temporary hack - DBRef Fetcher always top level ws entry.
5194 // TODO We probably want to store a sequence database checklist in
5195 // preferences and have checkboxes.. rather than individual sources selected
5197 final JMenu rfetch = new JMenu(MessageManager.getString("action.fetch_db_references"));
\r
5198 rfetch.setToolTipText(MessageManager.getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
\r
5199 webService.add(rfetch);
5201 JMenuItem fetchr = new JMenuItem(MessageManager.getString("label.standard_databases"));
\r
5202 fetchr.setToolTipText(MessageManager.getString("label.fetch_embl_uniprot"));
\r
5203 fetchr.addActionListener(new ActionListener()
5207 public void actionPerformed(ActionEvent e)
5209 new Thread(new Runnable()
5215 new jalview.ws.DBRefFetcher(alignPanel.av
5216 .getSequenceSelection(), alignPanel.alignFrame)
5217 .fetchDBRefs(false);
5225 final AlignFrame me = this;
5226 new Thread(new Runnable()
5231 final jalview.ws.SequenceFetcher sf = SequenceFetcher
5232 .getSequenceFetcherSingleton(me);
5233 javax.swing.SwingUtilities.invokeLater(new Runnable()
5238 String[] dbclasses = sf.getOrderedSupportedSources();
5239 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5240 // jalview.util.QuickSort.sort(otherdb, otherdb);
5241 List<DbSourceProxy> otherdb;
5242 JMenu dfetch = new JMenu();
5243 JMenu ifetch = new JMenu();
5244 JMenuItem fetchr = null;
5245 int comp = 0, icomp = 0, mcomp = 15;
5246 String mname = null;
5248 for (String dbclass : dbclasses)
5250 otherdb = sf.getSourceProxy(dbclass);
5251 // add a single entry for this class, or submenu allowing 'fetch
5253 if (otherdb == null || otherdb.size() < 1)
5257 // List<DbSourceProxy> dbs=otherdb;
5258 // otherdb=new ArrayList<DbSourceProxy>();
5259 // for (DbSourceProxy db:dbs)
5261 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5265 mname = "From " + dbclass;
5267 if (otherdb.size() == 1)
5269 final DbSourceProxy[] dassource = otherdb
5270 .toArray(new DbSourceProxy[0]);
5271 DbSourceProxy src = otherdb.get(0);
5272 fetchr = new JMenuItem(src.getDbSource());
5273 fetchr.addActionListener(new ActionListener()
5277 public void actionPerformed(ActionEvent e)
5279 new Thread(new Runnable()
5285 new jalview.ws.DBRefFetcher(alignPanel.av
5286 .getSequenceSelection(),
5287 alignPanel.alignFrame, dassource)
5288 .fetchDBRefs(false);
5294 fetchr.setToolTipText("<html>"
5295 + JvSwingUtils.wrapTooltip("Retrieve from "
5296 + src.getDbName()) + "<html>");
5302 final DbSourceProxy[] dassource = otherdb
5303 .toArray(new DbSourceProxy[0]);
5305 DbSourceProxy src = otherdb.get(0);
5306 fetchr = new JMenuItem(MessageManager.formatMessage("label.fetch_all_param", new String[]{src.getDbSource()}));
\r
5307 fetchr.addActionListener(new ActionListener()
5310 public void actionPerformed(ActionEvent e)
5312 new Thread(new Runnable()
5318 new jalview.ws.DBRefFetcher(alignPanel.av
5319 .getSequenceSelection(),
5320 alignPanel.alignFrame, dassource)
5321 .fetchDBRefs(false);
5327 fetchr.setToolTipText("<html>"
5328 + JvSwingUtils.wrapTooltip("Retrieve from all "
5329 + otherdb.size() + " sources in "
5330 + src.getDbSource() + "<br>First is :"
5331 + src.getDbName()) + "<html>");
5334 // and then build the rest of the individual menus
5335 ifetch = new JMenu("Sources from " + src.getDbSource());
5337 String imname = null;
5339 for (DbSourceProxy sproxy : otherdb)
5341 String dbname = sproxy.getDbName();
5342 String sname = dbname.length() > 5 ? dbname.substring(0,
5343 5) + "..." : dbname;
5344 String msname = dbname.length() > 10 ? dbname.substring(
5345 0, 10) + "..." : dbname;
5348 imname = "from '" + sname + "'";
5350 fetchr = new JMenuItem(msname);
5351 final DbSourceProxy[] dassrc =
5353 fetchr.addActionListener(new ActionListener()
5357 public void actionPerformed(ActionEvent e)
5359 new Thread(new Runnable()
5365 new jalview.ws.DBRefFetcher(alignPanel.av
5366 .getSequenceSelection(),
5367 alignPanel.alignFrame, dassrc)
5368 .fetchDBRefs(false);
5374 fetchr.setToolTipText("<html>"
5375 + JvSwingUtils.wrapTooltip("Retrieve from "
5376 + dbname) + "</html>");
5379 if (++icomp >= mcomp || i == (otherdb.size()))
5381 ifetch.setText(MessageManager.formatMessage("label.source_to_target",imname,sname));
5383 ifetch = new JMenu();
5391 if (comp >= mcomp || dbi >= (dbclasses.length))
5393 dfetch.setText(MessageManager.formatMessage("label.source_to_target",mname,dbclass));
5395 dfetch = new JMenu();
5408 * Left justify the whole alignment.
5411 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5413 AlignmentI al = viewport.getAlignment();
5415 viewport.firePropertyChange("alignment", null, al);
5419 * Right justify the whole alignment.
5422 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5424 AlignmentI al = viewport.getAlignment();
5426 viewport.firePropertyChange("alignment", null, al);
5429 public void setShowSeqFeatures(boolean b)
5431 showSeqFeatures.setSelected(true);
5432 viewport.setShowSequenceFeatures(true);
5439 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5440 * awt.event.ActionEvent)
5443 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5445 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5446 alignPanel.paintAlignment(true);
5453 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5457 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5459 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5460 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5468 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5469 * .event.ActionEvent)
5472 protected void showGroupConservation_actionPerformed(ActionEvent e)
5474 viewport.setShowGroupConservation(showGroupConservation.getState());
5475 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5482 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5483 * .event.ActionEvent)
5486 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5488 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5489 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5496 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5497 * .event.ActionEvent)
5500 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5502 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5503 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5507 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5509 showSequenceLogo.setState(true);
5510 viewport.setShowSequenceLogo(true);
5511 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5512 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5516 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5518 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5525 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5526 * .event.ActionEvent)
5529 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5531 if (avc.makeGroupsFromSelection()) {
5532 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5533 alignPanel.updateAnnotation();
5534 alignPanel.paintAlignment(true);
5539 protected void createGroup_actionPerformed(ActionEvent e)
5541 if (avc.createGroup())
5543 alignPanel.alignmentChanged();
5548 protected void unGroup_actionPerformed(ActionEvent e)
5552 alignPanel.alignmentChanged();
5557 * make the given alignmentPanel the currently selected tab
5559 * @param alignmentPanel
5561 public void setDisplayedView(AlignmentPanel alignmentPanel)
5563 if (!viewport.getSequenceSetId().equals(
5564 alignmentPanel.av.getSequenceSetId()))
5567 "Implementation error: cannot show a view from another alignment in an AlignFrame.");
5569 if (tabbedPane != null
5570 & alignPanels.indexOf(alignmentPanel) != tabbedPane
5571 .getSelectedIndex())
5573 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5578 class PrintThread extends Thread
5582 public PrintThread(AlignmentPanel ap)
5587 static PageFormat pf;
5592 PrinterJob printJob = PrinterJob.getPrinterJob();
5596 printJob.setPrintable(ap, pf);
5600 printJob.setPrintable(ap);
5603 if (printJob.printDialog())
5608 } catch (Exception PrintException)
5610 PrintException.printStackTrace();