2 * Jalview - A Sequence Alignment Editor and Viewer
3 * Copyright (C) 2007 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Softwarechang
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
26 import java.awt.datatransfer.*;
27 import java.awt.dnd.*;
28 import java.awt.event.*;
29 import java.awt.print.*;
31 import javax.swing.event.MenuEvent;
33 import jalview.analysis.*;
34 import jalview.commands.*;
35 import jalview.datamodel.*;
37 import jalview.jbgui.*;
38 import jalview.schemes.*;
47 public class AlignFrame
48 extends GAlignFrame implements DropTargetListener
51 public static final int DEFAULT_WIDTH = 700;
54 public static final int DEFAULT_HEIGHT = 500;
55 public AlignmentPanel alignPanel;
57 AlignViewport viewport;
59 Vector alignPanels = new Vector();
63 * Last format used to load or save alignments in this window
65 String currentFileFormat = null;
67 * Current filename for this alignment
69 String fileName = null;
73 * Creates a new AlignFrame object.
75 * @param al DOCUMENT ME!
77 public AlignFrame(AlignmentI al, int width, int height)
79 this(al, null, width, height);
84 * new alignment window with hidden columns
85 * @param al AlignmentI
86 * @param hiddenColumns ColumnSelection or null
88 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
89 int width, int height)
91 this.setSize(width, height);
92 viewport = new AlignViewport(al, hiddenColumns);
94 alignPanel = new AlignmentPanel(this, viewport);
96 if(al.getDataset()==null)
101 addAlignmentPanel(alignPanel, true);
106 * Make a new AlignFrame from exisiting alignmentPanels
107 * @param ap AlignmentPanel
108 * @param av AlignViewport
110 public AlignFrame(AlignmentPanel ap)
114 addAlignmentPanel(ap, false);
120 if (viewport.conservation == null)
122 BLOSUM62Colour.setEnabled(false);
123 conservationMenuItem.setEnabled(false);
124 modifyConservation.setEnabled(false);
125 // PIDColour.setEnabled(false);
126 // abovePIDThreshold.setEnabled(false);
127 // modifyPID.setEnabled(false);
130 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT", "No sort");
132 if (sortby.equals("Id"))
134 sortIDMenuItem_actionPerformed(null);
136 else if (sortby.equals("Pairwise Identity"))
138 sortPairwiseMenuItem_actionPerformed(null);
141 if (Desktop.desktop != null)
143 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
144 addServiceListeners();
145 setGUINucleotide(viewport.alignment.isNucleotide());
148 setMenusFromViewport(viewport);
149 buildSortByAnnotationScoresMenu();
150 if (viewport.wrapAlignment)
152 wrapMenuItem_actionPerformed(null);
155 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW",false))
157 this.overviewMenuItem_actionPerformed(null);
164 public void setFileName(String file, String format)
167 currentFileFormat = format;
168 reload.setEnabled(true);
171 void addKeyListener()
173 addKeyListener(new KeyAdapter()
175 public void keyPressed(KeyEvent evt)
177 if (viewport.cursorMode &&
178 ( (evt.getKeyCode() >= KeyEvent.VK_0 &&
179 evt.getKeyCode() <= KeyEvent.VK_9)
181 (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0 &&
182 evt.getKeyCode() <= KeyEvent.VK_NUMPAD9)
184 && Character.isDigit(evt.getKeyChar()))
185 alignPanel.seqPanel.numberPressed(evt.getKeyChar());
187 switch (evt.getKeyCode())
190 case 27: // escape key
191 deselectAllSequenceMenuItem_actionPerformed(null);
195 case KeyEvent.VK_DOWN:
196 if (evt.isAltDown() || !viewport.cursorMode)
197 moveSelectedSequences(false);
198 if (viewport.cursorMode)
199 alignPanel.seqPanel.moveCursor(0, 1);
203 if (evt.isAltDown() || !viewport.cursorMode)
204 moveSelectedSequences(true);
205 if (viewport.cursorMode)
206 alignPanel.seqPanel.moveCursor(0, -1);
210 case KeyEvent.VK_LEFT:
211 if (evt.isAltDown() || !viewport.cursorMode)
212 slideSequences(false,
213 alignPanel.seqPanel.getKeyboardNo1());
215 alignPanel.seqPanel.moveCursor( -1, 0);
220 case KeyEvent.VK_RIGHT:
221 if (evt.isAltDown() || !viewport.cursorMode)
223 alignPanel.seqPanel.getKeyboardNo1());
225 alignPanel.seqPanel.moveCursor(1, 0);
228 case KeyEvent.VK_SPACE:
229 if (viewport.cursorMode)
231 alignPanel.seqPanel.insertGapAtCursor(evt.isControlDown()
237 case KeyEvent.VK_DELETE:
238 case KeyEvent.VK_BACK_SPACE:
239 if (!viewport.cursorMode)
241 cut_actionPerformed(null);
245 alignPanel.seqPanel.deleteGapAtCursor(evt.isControlDown()
253 if (viewport.cursorMode)
255 alignPanel.seqPanel.setCursorRow();
259 if (viewport.cursorMode && !evt.isControlDown())
261 alignPanel.seqPanel.setCursorColumn();
265 if (viewport.cursorMode)
267 alignPanel.seqPanel.setCursorPosition();
271 case KeyEvent.VK_ENTER:
272 case KeyEvent.VK_COMMA:
273 if (viewport.cursorMode)
275 alignPanel.seqPanel.setCursorRowAndColumn();
280 if (viewport.cursorMode)
282 alignPanel.seqPanel.setSelectionAreaAtCursor(true);
286 if (viewport.cursorMode)
288 alignPanel.seqPanel.setSelectionAreaAtCursor(false);
293 viewport.cursorMode = !viewport.cursorMode;
294 statusBar.setText("Keyboard editing mode is " +
295 (viewport.cursorMode ? "on" : "off"));
296 if (viewport.cursorMode)
298 alignPanel.seqPanel.seqCanvas.cursorX = viewport.startRes;
299 alignPanel.seqPanel.seqCanvas.cursorY = viewport.startSeq;
301 alignPanel.seqPanel.seqCanvas.repaint();
307 ClassLoader cl = jalview.gui.Desktop.class.getClassLoader();
308 java.net.URL url = javax.help.HelpSet.findHelpSet(cl, "help/help");
309 javax.help.HelpSet hs = new javax.help.HelpSet(cl, url);
311 javax.help.HelpBroker hb = hs.createHelpBroker();
312 hb.setCurrentID("home");
313 hb.setDisplayed(true);
317 ex.printStackTrace();
323 boolean toggleSeqs = !evt.isControlDown();
324 boolean toggleCols = !evt.isShiftDown();
326 boolean hide = false;
328 SequenceGroup sg = viewport.getSelectionGroup();
331 if (sg != null && sg.getSize() != viewport.alignment.getHeight())
333 hideSelSequences_actionPerformed(null);
336 else if (! (toggleCols &&
337 viewport.colSel.getSelected().size() > 0))
339 showAllSeqs_actionPerformed(null);
345 if (viewport.colSel.getSelected().size() > 0)
347 hideSelColumns_actionPerformed(null);
350 viewport.selectionGroup = sg;
355 showAllColumns_actionPerformed(null);
360 case KeyEvent.VK_PAGE_UP:
361 if (viewport.wrapAlignment)
363 alignPanel.scrollUp(true);
367 alignPanel.setScrollValues(viewport.startRes,
369 - viewport.endSeq + viewport.startSeq);
372 case KeyEvent.VK_PAGE_DOWN:
373 if (viewport.wrapAlignment)
375 alignPanel.scrollUp(false);
379 alignPanel.setScrollValues(viewport.startRes,
381 + viewport.endSeq - viewport.startSeq);
387 public void keyReleased(KeyEvent evt)
389 switch(evt.getKeyCode())
391 case KeyEvent.VK_LEFT:
392 if (evt.isAltDown() || !viewport.cursorMode)
393 viewport.firePropertyChange("alignment", null,
394 viewport.getAlignment().getSequences());
397 case KeyEvent.VK_RIGHT:
398 if (evt.isAltDown() || !viewport.cursorMode)
399 viewport.firePropertyChange("alignment", null,
400 viewport.getAlignment().getSequences());
408 public void addAlignmentPanel(final AlignmentPanel ap,
411 ap.alignFrame = this;
413 alignPanels.addElement(ap);
415 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
417 int aSize = alignPanels.size();
419 tabbedPane.setVisible(aSize>1 || ap.av.viewName!=null);
421 if (aSize == 1 && ap.av.viewName==null)
423 this.getContentPane().add(ap, BorderLayout.CENTER);
429 setInitialTabVisible();
432 expandViews.setEnabled(true);
433 gatherViews.setEnabled(true);
434 tabbedPane.addTab(ap.av.viewName, ap);
436 ap.setVisible(false);
443 ap.av.alignment.padGaps();
445 ap.av.updateConservation(ap);
446 ap.av.updateConsensus(ap);
450 public void setInitialTabVisible()
452 expandViews.setEnabled(true);
453 gatherViews.setEnabled(true);
454 tabbedPane.setVisible(true);
455 AlignmentPanel first = (AlignmentPanel) alignPanels.firstElement();
456 tabbedPane.addTab(first.av.viewName,first);
457 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
461 public AlignViewport getViewport()
466 /* Set up intrinsic listeners for dynamically generated GUI bits. */
467 private void addServiceListeners()
469 final java.beans.PropertyChangeListener thisListener;
470 // Do this once to get current state
471 BuildWebServiceMenu();
472 Desktop.discoverer.addPropertyChangeListener(
473 thisListener = new java.beans.PropertyChangeListener()
475 public void propertyChange(PropertyChangeEvent evt)
477 // System.out.println("Discoverer property change.");
478 if (evt.getPropertyName().equals("services"))
480 // System.out.println("Rebuilding web service menu");
481 BuildWebServiceMenu();
486 addInternalFrameListener(new javax.swing.event.
487 InternalFrameAdapter()
489 public void internalFrameClosed(
490 javax.swing.event.InternalFrameEvent evt)
492 // System.out.println("deregistering discoverer listener");
493 Desktop.discoverer.removePropertyChangeListener(thisListener);
494 closeMenuItem_actionPerformed(true);
500 public void setGUINucleotide(boolean nucleotide)
502 showTranslation.setVisible( nucleotide );
503 conservationMenuItem.setEnabled( !nucleotide );
504 modifyConservation.setEnabled( !nucleotide );
506 //Remember AlignFrame always starts as protein
509 calculateMenu.remove(calculateMenu.getItemCount()-2);
511 setShowProductsEnabled();
517 * Need to call this method when tabs are selected for multiple views,
518 * or when loading from Jalview2XML.java
519 * @param av AlignViewport
521 void setMenusFromViewport(AlignViewport av)
523 padGapsMenuitem.setSelected(av.padGaps);
524 colourTextMenuItem.setSelected(av.showColourText);
525 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
526 conservationMenuItem.setSelected(av.getConservationSelected());
527 seqLimits.setSelected(av.getShowJVSuffix());
528 idRightAlign.setSelected(av.rightAlignIds);
529 renderGapsMenuItem.setSelected(av.renderGaps);
530 wrapMenuItem.setSelected(av.wrapAlignment);
531 scaleAbove.setVisible(av.wrapAlignment);
532 scaleLeft.setVisible(av.wrapAlignment);
533 scaleRight.setVisible(av.wrapAlignment);
534 annotationPanelMenuItem.setState(av.showAnnotation);
535 viewBoxesMenuItem.setSelected(av.showBoxes);
536 viewTextMenuItem.setSelected(av.showText);
538 setColourSelected(ColourSchemeProperty.
539 getColourName(av.getGlobalColourScheme()));
541 showSeqFeatures.setSelected(av.showSequenceFeatures);
542 hiddenMarkers.setState(av.showHiddenMarkers);
543 applyToAllGroups.setState(av.colourAppliesToAllGroups);
549 Hashtable progressBars;
550 public void setProgressBar(String message, long id)
552 if(progressBars == null)
554 progressBars = new Hashtable();
557 JPanel progressPanel;
558 GridLayout layout = (GridLayout) statusPanel.getLayout();
559 if(progressBars.get( new Long(id) )!=null)
561 progressPanel = (JPanel)progressBars.get( new Long(id) );
562 statusPanel.remove(progressPanel);
563 progressBars.remove( progressPanel );
564 progressPanel = null;
567 statusBar.setText(message);
570 layout.setRows(layout.getRows() - 1);
574 progressPanel = new JPanel(new BorderLayout(10, 5));
576 JProgressBar progressBar = new JProgressBar();
577 progressBar.setIndeterminate(true);
579 progressPanel.add(new JLabel(message), BorderLayout.WEST);
580 progressPanel.add(progressBar, BorderLayout.CENTER);
582 layout.setRows(layout.getRows() + 1);
583 statusPanel.add(progressPanel);
585 progressBars.put(new Long(id), progressPanel);
595 Added so Castor Mapping file can obtain Jalview Version
597 public String getVersion()
599 return jalview.bin.Cache.getProperty("VERSION");
602 public FeatureRenderer getFeatureRenderer()
604 return alignPanel.seqPanel.seqCanvas.getFeatureRenderer();
608 public void fetchSequence_actionPerformed(ActionEvent e)
610 new SequenceFetcher(this);
613 public void addFromFile_actionPerformed(ActionEvent e)
615 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
618 public void reload_actionPerformed(ActionEvent e)
622 if(currentFileFormat.equals("Jalview"))
624 JInternalFrame [] frames = Desktop.desktop.getAllFrames();
625 for(int i=0; i<frames.length; i++)
627 if (frames[i] instanceof AlignFrame
629 && ( (AlignFrame) frames[i]).fileName.equals(fileName))
633 frames[i].setSelected(true);
634 Desktop.instance.closeAssociatedWindows();
636 catch (java.beans.PropertyVetoException ex)
641 Desktop.instance.closeAssociatedWindows();
643 FileLoader loader = new FileLoader();
644 String protocol = fileName.startsWith("http:")? "URL":"File";
645 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
649 Rectangle bounds = this.getBounds();
651 FileLoader loader = new FileLoader();
652 String protocol = fileName.startsWith("http:") ? "URL" : "File";
653 AlignFrame newframe =
654 loader.LoadFileWaitTillLoaded(fileName, protocol, currentFileFormat);
656 newframe.setBounds(bounds);
658 this.closeMenuItem_actionPerformed(true);
664 public void addFromText_actionPerformed(ActionEvent e)
666 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
669 public void addFromURL_actionPerformed(ActionEvent e)
671 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
675 public void save_actionPerformed(ActionEvent e)
678 || currentFileFormat==null
679 || fileName.startsWith("http")
682 saveAs_actionPerformed(null);
686 saveAlignment(fileName, currentFileFormat);
693 * @param e DOCUMENT ME!
695 public void saveAs_actionPerformed(ActionEvent e)
697 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
698 getProperty( "LAST_DIRECTORY"),
699 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
700 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
705 chooser.setFileView(new JalviewFileView());
706 chooser.setDialogTitle("Save Alignment to file");
707 chooser.setToolTipText("Save");
709 int value = chooser.showSaveDialog(this);
711 if (value == JalviewFileChooser.APPROVE_OPTION)
713 currentFileFormat = chooser.getSelectedFormat();
714 if (currentFileFormat == null)
716 JOptionPane.showInternalMessageDialog(Desktop.desktop,
717 "You must select a file format before saving!",
718 "File format not specified",
719 JOptionPane.WARNING_MESSAGE);
720 value = chooser.showSaveDialog(this);
724 fileName = chooser.getSelectedFile().getPath();
726 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
729 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
730 if (currentFileFormat.indexOf(" ")>-1)
732 currentFileFormat = currentFileFormat.substring(0, currentFileFormat.indexOf(" "));
734 saveAlignment(fileName, currentFileFormat);
738 public boolean saveAlignment(String file, String format)
740 boolean success = true;
742 if (format.equalsIgnoreCase("Jalview"))
744 String shortName = title;
746 if (shortName.indexOf(java.io.File.separatorChar) > -1)
748 shortName = shortName.substring(shortName.lastIndexOf(
749 java.io.File.separatorChar) + 1);
752 success = new Jalview2XML().SaveAlignment(this, file, shortName);
754 statusBar.setText("Successfully saved to file: "
756 +format +" format.");
762 String[] omitHidden = null;
764 if (viewport.hasHiddenColumns)
766 int reply = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
767 "The Alignment contains hidden columns."
768 + "\nDo you want to save only the visible alignment?",
769 "Save / Omit Hidden Columns",
770 JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
772 if (reply == JOptionPane.YES_OPTION)
774 omitHidden = viewport.getViewAsString(false);
777 FormatAdapter f = new FormatAdapter();
779 String output = f.formatSequences(
781 (Alignment) viewport.alignment, // class cast exceptions will occur in the distant future
782 omitHidden, f.getCacheSuffixDefault(format), viewport.colSel);
792 java.io.PrintWriter out = new java.io.PrintWriter(
793 new java.io.FileWriter(file));
798 statusBar.setText("Successfully saved to file: "
800 + format + " format.");
805 ex.printStackTrace();
812 JOptionPane.showInternalMessageDialog(
813 this, "Couldn't save file: " + fileName,
815 JOptionPane.WARNING_MESSAGE);
824 * @param e DOCUMENT ME!
826 protected void outputText_actionPerformed(ActionEvent e)
828 String [] omitHidden = null;
830 if(viewport.hasHiddenColumns)
832 int reply = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
833 "The Alignment contains hidden columns."
834 +"\nDo you want to output only the visible alignment?",
835 "Save / Omit Hidden Columns",
836 JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
838 if(reply==JOptionPane.YES_OPTION)
840 omitHidden = viewport.getViewAsString(false);
844 CutAndPasteTransfer cap = new CutAndPasteTransfer();
845 cap.setForInput(null);
846 Desktop.addInternalFrame(cap,
847 "Alignment output - " + e.getActionCommand(), 600,
851 cap.setText(new FormatAdapter().formatSequences(
852 e.getActionCommand(),
854 omitHidden, viewport.colSel));
860 * @param e DOCUMENT ME!
862 protected void htmlMenuItem_actionPerformed(ActionEvent e)
864 new HTMLOutput(alignPanel,
865 alignPanel.seqPanel.seqCanvas.getSequenceRenderer(),
866 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
869 public void createImageMap(File file, String image)
871 alignPanel.makePNGImageMap(file, image);
877 * @param e DOCUMENT ME!
879 public void createPNG(File f)
881 alignPanel.makePNG(f);
887 * @param e DOCUMENT ME!
889 public void createEPS(File f)
891 alignPanel.makeEPS(f);
895 public void pageSetup_actionPerformed(ActionEvent e)
897 PrinterJob printJob = PrinterJob.getPrinterJob();
898 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
904 * @param e DOCUMENT ME!
906 public void printMenuItem_actionPerformed(ActionEvent e)
908 //Putting in a thread avoids Swing painting problems
909 PrintThread thread = new PrintThread(alignPanel);
913 public void exportFeatures_actionPerformed(ActionEvent e)
915 new AnnotationExporter().exportFeatures(alignPanel);
919 public void exportAnnotations_actionPerformed(ActionEvent e)
921 new AnnotationExporter().exportAnnotations(
923 viewport.showAnnotation ? viewport.alignment.getAlignmentAnnotation() : null,
924 viewport.alignment.getGroups(),
925 ((Alignment)viewport.alignment).alignmentProperties
930 public void associatedData_actionPerformed(ActionEvent e)
932 // Pick the tree file
933 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
936 chooser.setFileView(new JalviewFileView());
937 chooser.setDialogTitle("Load Jalview Annotations or Features File");
938 chooser.setToolTipText("Load Jalview Annotations / Features file");
940 int value = chooser.showOpenDialog(null);
942 if (value == JalviewFileChooser.APPROVE_OPTION)
944 String choice = chooser.getSelectedFile().getPath();
945 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
946 loadJalviewDataFile(choice);
955 * @param e DOCUMENT ME!
957 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
959 if(alignPanels!=null && alignPanels.size()<2)
966 if(alignPanels!=null)
970 for (int i = 0; i < alignPanels.size(); i++)
972 AlignmentPanel ap = (AlignmentPanel) alignPanels.elementAt(i);
973 jalview.structure.StructureSelectionManager.getStructureSelectionManager()
974 .removeStructureViewerListener(ap.seqPanel, null);
975 PaintRefresher.RemoveComponent(ap.seqPanel.seqCanvas);
976 PaintRefresher.RemoveComponent(ap.idPanel.idCanvas);
977 PaintRefresher.RemoveComponent(ap);
978 ap.av.alignment = null;
983 int index = tabbedPane.getSelectedIndex();
985 alignPanels.removeElement(alignPanel);
986 PaintRefresher.RemoveComponent(alignPanel.seqPanel.seqCanvas);
987 PaintRefresher.RemoveComponent(alignPanel.idPanel.idCanvas);
988 PaintRefresher.RemoveComponent(alignPanel);
989 viewport.alignment = null;
993 tabbedPane.removeTabAt(index);
994 tabbedPane.validate();
996 if(index==tabbedPane.getTabCount())
1001 this.tabSelectionChanged(index);
1007 this.setClosed(true);
1010 catch (Exception ex)
1012 ex.printStackTrace();
1020 void updateEditMenuBar()
1023 if (viewport.historyList.size() > 0)
1025 undoMenuItem.setEnabled(true);
1026 CommandI command = (CommandI) viewport.historyList.peek();
1027 undoMenuItem.setText("Undo " + command.getDescription());
1031 undoMenuItem.setEnabled(false);
1032 undoMenuItem.setText("Undo");
1035 if (viewport.redoList.size() > 0)
1037 redoMenuItem.setEnabled(true);
1039 CommandI command = (CommandI) viewport.redoList.peek();
1040 redoMenuItem.setText("Redo " + command.getDescription());
1044 redoMenuItem.setEnabled(false);
1045 redoMenuItem.setText("Redo");
1050 public void addHistoryItem(CommandI command)
1052 if(command.getSize()>0)
1054 viewport.historyList.push(command);
1055 viewport.redoList.clear();
1056 updateEditMenuBar();
1057 viewport.hasHiddenColumns = viewport.colSel.getHiddenColumns() != null;
1063 * @return alignment objects for all views
1065 AlignmentI[] getViewAlignments()
1067 if (alignPanels!=null)
1069 Enumeration e = alignPanels.elements();
1070 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1071 for (int i=0; e.hasMoreElements(); i++)
1073 als[i] = ((AlignmentPanel) e.nextElement()).av.getAlignment();
1079 return new AlignmentI[] { viewport.alignment };
1086 * @param e DOCUMENT ME!
1088 protected void undoMenuItem_actionPerformed(ActionEvent e)
1090 if (viewport.historyList.empty())
1092 CommandI command = (CommandI)viewport.historyList.pop();
1093 viewport.redoList.push(command);
1094 command.undoCommand(getViewAlignments());
1096 AlignViewport originalSource = getOriginatingSource(command);
1097 updateEditMenuBar();
1099 if(originalSource!=null)
1101 originalSource.hasHiddenColumns = viewport.colSel.getHiddenColumns() != null;
1102 originalSource.firePropertyChange("alignment",
1104 originalSource.alignment.getSequences());
1111 * @param e DOCUMENT ME!
1113 protected void redoMenuItem_actionPerformed(ActionEvent e)
1115 if(viewport.redoList.size()<1)
1120 CommandI command = (CommandI) viewport.redoList.pop();
1121 viewport.historyList.push(command);
1122 command.doCommand(getViewAlignments());
1124 AlignViewport originalSource = getOriginatingSource(command);
1125 updateEditMenuBar();
1127 if(originalSource!=null)
1129 originalSource.hasHiddenColumns = viewport.colSel.getHiddenColumns() != null;
1130 originalSource.firePropertyChange("alignment",
1132 originalSource.alignment.getSequences());
1136 AlignViewport getOriginatingSource(CommandI command)
1138 AlignViewport originalSource = null;
1139 //For sequence removal and addition, we need to fire
1140 //the property change event FROM the viewport where the
1141 //original alignment was altered
1143 if (command instanceof EditCommand)
1145 EditCommand editCommand = (EditCommand) command;
1146 al = editCommand.getAlignment();
1147 Vector comps = (Vector) PaintRefresher.components
1148 .get(viewport.getSequenceSetId());
1150 for (int i = 0; i < comps.size(); i++)
1152 if (comps.elementAt(i) instanceof AlignmentPanel)
1154 if (al == ( (AlignmentPanel) comps.elementAt(i)).av.alignment)
1156 originalSource = ( (AlignmentPanel) comps.elementAt(i)).av;
1163 if (originalSource == null)
1165 //The original view is closed, we must validate
1166 //the current view against the closed view first
1169 PaintRefresher.validateSequences(al, viewport.alignment);
1172 originalSource = viewport;
1175 return originalSource;
1181 * @param up DOCUMENT ME!
1183 public void moveSelectedSequences(boolean up)
1185 SequenceGroup sg = viewport.getSelectionGroup();
1194 for (int i = 1; i < viewport.alignment.getHeight(); i++)
1196 SequenceI seq = viewport.alignment.getSequenceAt(i);
1198 if (!sg.getSequences(null).contains(seq))
1203 SequenceI temp = viewport.alignment.getSequenceAt(i - 1);
1205 if (sg.getSequences(null).contains(temp))
1210 viewport.alignment.getSequences().setElementAt(temp, i);
1211 viewport.alignment.getSequences().setElementAt(seq, i - 1);
1216 for (int i = viewport.alignment.getHeight() - 2; i > -1; i--)
1218 SequenceI seq = viewport.alignment.getSequenceAt(i);
1220 if (!sg.getSequences(null).contains(seq))
1225 SequenceI temp = viewport.alignment.getSequenceAt(i + 1);
1227 if (sg.getSequences(null).contains(temp))
1232 viewport.alignment.getSequences().setElementAt(temp, i);
1233 viewport.alignment.getSequences().setElementAt(seq, i + 1);
1237 alignPanel.paintAlignment(true);
1243 synchronized void slideSequences(boolean right, int size)
1245 Vector sg = new Vector();
1246 if(viewport.cursorMode)
1248 sg.addElement(viewport.alignment.getSequenceAt(
1249 alignPanel.seqPanel.seqCanvas.cursorY));
1251 else if(viewport.getSelectionGroup()!=null
1252 && viewport.getSelectionGroup().getSize()!=viewport.alignment.getHeight())
1254 sg = viewport.getSelectionGroup().getSequences(
1255 viewport.hiddenRepSequences);
1263 Vector invertGroup = new Vector();
1265 for (int i = 0; i < viewport.alignment.getHeight(); i++)
1267 if(!sg.contains(viewport.alignment.getSequenceAt(i)))
1268 invertGroup.add(viewport.alignment.getSequenceAt(i));
1271 SequenceI[] seqs1 = new SequenceI[sg.size()];
1272 for (int i = 0; i < sg.size(); i++)
1273 seqs1[i] = (SequenceI) sg.elementAt(i);
1275 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1276 for (int i = 0; i < invertGroup.size(); i++)
1277 seqs2[i] = (SequenceI) invertGroup.elementAt(i);
1279 SlideSequencesCommand ssc;
1281 ssc = new SlideSequencesCommand("Slide Sequences",
1283 viewport.getGapCharacter()
1286 ssc = new SlideSequencesCommand("Slide Sequences",
1288 viewport.getGapCharacter()
1291 int groupAdjustment = 0;
1292 if (ssc.getGapsInsertedBegin() && right)
1294 if (viewport.cursorMode)
1295 alignPanel.seqPanel.moveCursor(size, 0);
1297 groupAdjustment = size;
1299 else if (!ssc.getGapsInsertedBegin() && !right)
1301 if (viewport.cursorMode)
1302 alignPanel.seqPanel.moveCursor( -size, 0);
1304 groupAdjustment = -size;
1307 if (groupAdjustment != 0)
1309 viewport.getSelectionGroup().setStartRes(
1310 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1311 viewport.getSelectionGroup().setEndRes(
1312 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1316 boolean appendHistoryItem = false;
1317 if(viewport.historyList!=null
1318 && viewport.historyList.size()>0
1319 && viewport.historyList.peek() instanceof SlideSequencesCommand)
1321 appendHistoryItem = ssc.appendSlideCommand(
1322 (SlideSequencesCommand)viewport.historyList.peek())
1326 if(!appendHistoryItem)
1327 addHistoryItem(ssc);
1336 * @param e DOCUMENT ME!
1338 protected void copy_actionPerformed(ActionEvent e)
1341 if (viewport.getSelectionGroup() == null)
1345 // TODO: preserve the ordering of displayed alignment annotation in any internal paste (particularly sequence associated annotation)
1346 SequenceI [] seqs = viewport.getSelectionAsNewSequence();
1347 String[] omitHidden = null;
1349 if (viewport.hasHiddenColumns)
1351 omitHidden = viewport.getViewAsString(true);
1354 String output = new FormatAdapter().formatSequences(
1359 StringSelection ss = new StringSelection(output);
1363 jalview.gui.Desktop.internalCopy = true;
1364 //Its really worth setting the clipboard contents
1365 //to empty before setting the large StringSelection!!
1366 Toolkit.getDefaultToolkit().getSystemClipboard()
1367 .setContents(new StringSelection(""), null);
1369 Toolkit.getDefaultToolkit().getSystemClipboard()
1370 .setContents(ss, Desktop.instance);
1372 catch (OutOfMemoryError er)
1374 er.printStackTrace();
1375 javax.swing.SwingUtilities.invokeLater(new Runnable()
1379 javax.swing.JOptionPane.showInternalMessageDialog(Desktop.desktop,
1380 "Out of memory copying region!!"
1382 "\nSee help files for increasing Java Virtual Machine memory."
1384 javax.swing.JOptionPane.WARNING_MESSAGE);
1391 Vector hiddenColumns = null;
1392 if(viewport.hasHiddenColumns)
1394 hiddenColumns =new Vector();
1395 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1396 for (int i = 0; i < viewport.getColumnSelection().getHiddenColumns().size();
1399 int[] region = (int[])
1400 viewport.getColumnSelection().getHiddenColumns().elementAt(i);
1402 hiddenColumns.addElement(new int[]
1403 {region[0] - hiddenOffset,
1404 region[1]-hiddenOffset});
1408 Desktop.jalviewClipboard = new Object[]
1411 viewport.alignment.getDataset(),
1413 statusBar.setText("Copied "+seqs.length+" sequences to clipboard.");
1419 * @param e DOCUMENT ME!
1421 protected void pasteNew_actionPerformed(ActionEvent e)
1429 * @param e DOCUMENT ME!
1431 protected void pasteThis_actionPerformed(ActionEvent e)
1439 * @param newAlignment DOCUMENT ME!
1441 void paste(boolean newAlignment)
1443 boolean externalPaste=true;
1446 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1447 Transferable contents = c.getContents(this);
1449 if (contents == null)
1457 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1458 if (str.length() < 1)
1463 format = new IdentifyFile().Identify(str, "Paste");
1466 catch (OutOfMemoryError er)
1468 er.printStackTrace();
1469 javax.swing.SwingUtilities.invokeLater(new Runnable()
1473 javax.swing.JOptionPane.showInternalMessageDialog(Desktop.desktop,
1474 "Out of memory pasting sequences!!"
1476 "\nSee help files for increasing Java Virtual Machine memory."
1478 javax.swing.JOptionPane.WARNING_MESSAGE);
1485 SequenceI[] sequences;
1486 boolean annotationAdded = false;
1487 AlignmentI alignment = null;
1489 if(Desktop.jalviewClipboard!=null)
1491 // The clipboard was filled from within Jalview, we must use the sequences
1492 // And dataset from the copied alignment
1493 SequenceI[] newseq = (SequenceI[])Desktop.jalviewClipboard[0];
1494 // be doubly sure that we create *new* sequence objects.
1495 sequences = new SequenceI[newseq.length];
1496 for (int i=0;i<newseq.length;i++) {
1497 sequences[i] = new Sequence(newseq[i]);
1499 alignment = new Alignment(sequences);
1500 externalPaste = false;
1504 // parse the clipboard as an alignment.
1505 alignment = new FormatAdapter().readFile(str, "Paste", format);
1506 sequences = alignment.getSequencesArray();
1514 if (Desktop.jalviewClipboard != null)
1516 // dataset is inherited
1517 alignment.setDataset( (Alignment) Desktop.jalviewClipboard[1]);
1521 // new dataset is constructed
1522 alignment.setDataset(null);
1524 alwidth = alignment.getWidth()+1;
1528 AlignmentI pastedal = alignment; // preserve pasted alignment object
1529 // Add pasted sequences and dataset into existing alignment.
1530 alignment = viewport.getAlignment();
1531 alwidth = alignment.getWidth()+1;
1532 // decide if we need to import sequences from an existing dataset
1533 boolean importDs = Desktop.jalviewClipboard != null
1534 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1535 // importDs==true instructs us to copy over new dataset sequences from
1536 // an existing alignment
1537 Vector newDs = (importDs) ? new Vector() : null; // used to create
1538 // minimum dataset set
1540 for (int i = 0; i < sequences.length; i++)
1544 newDs.addElement(null);
1546 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
1548 if (importDs && ds != null)
1550 if (!newDs.contains(ds))
1552 newDs.setElementAt(ds, i);
1553 ds = new Sequence(ds);
1554 // update with new dataset sequence
1555 sequences[i].setDatasetSequence(ds);
1559 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
1564 // copy and derive new dataset sequence
1565 sequences[i] = sequences[i].deriveSequence();
1566 alignment.getDataset().addSequence(sequences[i].getDatasetSequence());
1567 // TODO: avoid creation of duplicate dataset sequences with a
1568 // 'contains' method using SequenceI.equals()/SequenceI.contains()
1570 alignment.addSequence(sequences[i]); // merges dataset
1574 newDs.clear(); // tidy up
1576 if (pastedal.getAlignmentAnnotation()!=null) {
1577 // Add any annotation attached to alignment.
1578 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
1579 for (int i=0; i<alann.length; i++)
1581 annotationAdded=true;
1582 if (alann[i].sequenceRef==null && !alann[i].autoCalculated) {
1583 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
1584 newann.padAnnotation(alwidth);
1585 alignment.addAnnotation(newann);
1590 if (!newAlignment) {
1594 addHistoryItem(new EditCommand(
1599 alignment.getWidth(),
1603 // Add any annotations attached to sequences
1604 for (int i = 0; i < sequences.length; i++)
1606 if (sequences[i].getAnnotation() != null)
1608 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
1610 annotationAdded=true;
1611 sequences[i].getAnnotation()[a].adjustForAlignment();
1612 sequences[i].getAnnotation()[a].padAnnotation(alwidth);
1613 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation was duplicated earlier
1614 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a], a);
1618 if (!newAlignment) {
1620 // propagate alignment changed.
1621 viewport.setEndSeq(alignment.getHeight());
1622 if (annotationAdded)
1624 // Duplicate sequence annotation in all views.
1625 AlignmentI[] alview = this.getViewAlignments();
1626 for (int i = 0; i < sequences.length; i++)
1628 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
1631 for (int avnum=0;avnum<alview.length; avnum++)
1633 if (alview[avnum]!=alignment)
1635 // duplicate in a view other than the one with input focus
1636 int avwidth = alview[avnum].getWidth()+1;
1637 // this relies on sann being preserved after we
1638 // modify the sequence's annotation array for each duplication
1639 for (int a=0; a<sann.length; a++)
1641 AlignmentAnnotation newann = new AlignmentAnnotation(sann[a]);
1642 sequences[i].addAlignmentAnnotation(newann);
1643 newann.padAnnotation(avwidth);
1644 alview[avnum].addAnnotation(newann); // annotation was duplicated earlier
1645 alview[avnum].setAnnotationIndex(newann, a);
1650 buildSortByAnnotationScoresMenu();
1652 viewport.firePropertyChange("alignment", null, alignment.getSequences());
1655 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH, DEFAULT_HEIGHT);
1656 String newtitle = new String("Copied sequences");
1658 if(Desktop.jalviewClipboard!=null && Desktop.jalviewClipboard[2]!=null)
1660 Vector hc = (Vector)Desktop.jalviewClipboard[2];
1661 for(int i=0; i<hc.size(); i++)
1663 int [] region = (int[]) hc.elementAt(i);
1664 af.viewport.hideColumns(region[0], region[1]);
1669 //>>>This is a fix for the moment, until a better solution is found!!<<<
1670 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer().transferSettings(
1671 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
1673 // TODO: maintain provenance of an alignment, rather than just make the title a concatenation of operations.
1674 if (!externalPaste) {
1675 if (title.startsWith("Copied sequences"))
1681 newtitle = newtitle.concat("- from " + title);
1684 newtitle = new String("Pasted sequences");
1687 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
1694 catch (Exception ex)
1696 ex.printStackTrace();
1697 System.out.println("Exception whilst pasting: "+ex);
1698 // could be anything being pasted in here
1707 * @param e DOCUMENT ME!
1709 protected void cut_actionPerformed(ActionEvent e)
1711 copy_actionPerformed(null);
1712 delete_actionPerformed(null);
1718 * @param e DOCUMENT ME!
1720 protected void delete_actionPerformed(ActionEvent evt)
1723 SequenceGroup sg = viewport.getSelectionGroup();
1729 Vector seqs = new Vector();
1731 for (int i = 0; i < sg.getSize(); i++)
1733 seq = sg.getSequenceAt(i);
1734 seqs.addElement(seq);
1738 // If the cut affects all sequences, remove highlighted columns
1739 if (sg.getSize() == viewport.alignment.getHeight())
1741 viewport.getColumnSelection().removeElements(sg.getStartRes(),
1742 sg.getEndRes() + 1);
1746 SequenceI [] cut = new SequenceI[seqs.size()];
1747 for(int i=0; i<seqs.size(); i++)
1749 cut[i] = (SequenceI)seqs.elementAt(i);
1756 addHistoryItem(new EditCommand("Cut Sequences",
1760 sg.getEndRes()-sg.getStartRes()+1,
1761 viewport.alignment));
1764 viewport.setSelectionGroup(null);
1765 viewport.alignment.deleteGroup(sg);
1767 viewport.firePropertyChange("alignment", null,
1768 viewport.getAlignment().getSequences());
1770 if (viewport.getAlignment().getHeight() < 1)
1774 this.setClosed(true);
1776 catch (Exception ex)
1785 * @param e DOCUMENT ME!
1787 protected void deleteGroups_actionPerformed(ActionEvent e)
1789 viewport.alignment.deleteAllGroups();
1790 viewport.sequenceColours = null;
1791 viewport.setSelectionGroup(null);
1792 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
1793 alignPanel.paintAlignment(true);
1799 * @param e DOCUMENT ME!
1801 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
1803 SequenceGroup sg = new SequenceGroup();
1805 for (int i = 0; i < viewport.getAlignment().getSequences().size();
1808 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
1811 sg.setEndRes(viewport.alignment.getWidth() - 1);
1812 viewport.setSelectionGroup(sg);
1813 alignPanel.paintAlignment(true);
1814 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
1820 * @param e DOCUMENT ME!
1822 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
1824 if(viewport.cursorMode)
1826 alignPanel.seqPanel.keyboardNo1 = null;
1827 alignPanel.seqPanel.keyboardNo2 = null;
1829 viewport.setSelectionGroup(null);
1830 viewport.getColumnSelection().clear();
1831 viewport.setSelectionGroup(null);
1832 alignPanel.seqPanel.seqCanvas.highlightSearchResults(null);
1833 alignPanel.idPanel.idCanvas.searchResults = null;
1834 alignPanel.paintAlignment(true);
1835 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
1841 * @param e DOCUMENT ME!
1843 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
1845 SequenceGroup sg = viewport.getSelectionGroup();
1849 selectAllSequenceMenuItem_actionPerformed(null);
1854 for (int i = 0; i < viewport.getAlignment().getSequences().size();
1857 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
1860 alignPanel.paintAlignment(true);
1862 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
1865 public void invertColSel_actionPerformed(ActionEvent e)
1867 viewport.invertColumnSelection();
1868 alignPanel.paintAlignment(true);
1875 * @param e DOCUMENT ME!
1877 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
1879 trimAlignment(true);
1885 * @param e DOCUMENT ME!
1887 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
1889 trimAlignment(false);
1892 void trimAlignment(boolean trimLeft)
1894 ColumnSelection colSel = viewport.getColumnSelection();
1897 if (colSel.size() > 0)
1901 column = colSel.getMin();
1905 column = colSel.getMax();
1909 if(viewport.getSelectionGroup()!=null)
1911 seqs = viewport.getSelectionGroup().getSequencesAsArray(viewport.
1912 hiddenRepSequences);
1916 seqs = viewport.alignment.getSequencesArray();
1920 TrimRegionCommand trimRegion;
1923 trimRegion = new TrimRegionCommand("Remove Left",
1924 TrimRegionCommand.TRIM_LEFT,
1929 viewport.selectionGroup);
1930 viewport.setStartRes(0);
1934 trimRegion = new TrimRegionCommand("Remove Right",
1935 TrimRegionCommand.TRIM_RIGHT,
1940 viewport.selectionGroup);
1943 statusBar.setText("Removed "+trimRegion.getSize()+" columns.");
1946 addHistoryItem(trimRegion);
1948 Vector groups = viewport.alignment.getGroups();
1950 for (int i = 0; i < groups.size(); i++)
1952 SequenceGroup sg = (SequenceGroup) groups.get(i);
1954 if ( (trimLeft && !sg.adjustForRemoveLeft(column))
1955 || (!trimLeft && !sg.adjustForRemoveRight(column)))
1957 viewport.alignment.deleteGroup(sg);
1961 viewport.firePropertyChange("alignment", null,
1962 viewport.getAlignment().getSequences());
1969 * @param e DOCUMENT ME!
1971 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
1973 int start = 0, end = viewport.alignment.getWidth()-1;
1976 if (viewport.getSelectionGroup() != null)
1978 seqs = viewport.getSelectionGroup().getSequencesAsArray(viewport.
1979 hiddenRepSequences);
1980 start = viewport.getSelectionGroup().getStartRes();
1981 end = viewport.getSelectionGroup().getEndRes();
1985 seqs = viewport.alignment.getSequencesArray();
1989 RemoveGapColCommand removeGapCols =
1990 new RemoveGapColCommand("Remove Gapped Columns",
1993 viewport.alignment);
1995 addHistoryItem(removeGapCols);
1997 statusBar.setText("Removed "+removeGapCols.getSize()+" empty columns.");
1999 //This is to maintain viewport position on first residue
2001 SequenceI seq = viewport.alignment.getSequenceAt(0);
2002 int startRes = seq.findPosition(viewport.startRes);
2003 // ShiftList shifts;
2004 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2005 // edit.alColumnChanges=shifts.getInverse();
2006 // if (viewport.hasHiddenColumns)
2007 // viewport.getColumnSelection().compensateForEdits(shifts);
2008 viewport.setStartRes(seq.findIndex(startRes)-1);
2009 viewport.firePropertyChange("alignment", null,
2010 viewport.getAlignment().getSequences());
2017 * @param e DOCUMENT ME!
2019 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2021 int start = 0, end = viewport.alignment.getWidth()-1;
2024 if (viewport.getSelectionGroup() != null)
2026 seqs = viewport.getSelectionGroup().getSequencesAsArray(viewport.
2027 hiddenRepSequences);
2028 start = viewport.getSelectionGroup().getStartRes();
2029 end = viewport.getSelectionGroup().getEndRes();
2033 seqs = viewport.alignment.getSequencesArray();
2036 //This is to maintain viewport position on first residue
2038 SequenceI seq = viewport.alignment.getSequenceAt(0);
2039 int startRes = seq.findPosition(viewport.startRes);
2041 addHistoryItem(new RemoveGapsCommand("Remove Gaps",
2044 viewport.alignment));
2046 viewport.setStartRes(seq.findIndex(startRes)-1);
2048 viewport.firePropertyChange("alignment", null,
2049 viewport.getAlignment().getSequences());
2056 * @param e DOCUMENT ME!
2058 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2060 viewport.padGaps = padGapsMenuitem.isSelected();
2062 viewport.firePropertyChange("alignment",
2064 viewport.getAlignment().getSequences());
2070 * @param e DOCUMENT ME!
2072 public void findMenuItem_actionPerformed(ActionEvent e)
2077 public void newView_actionPerformed(ActionEvent e)
2079 AlignmentPanel newap =
2080 new Jalview2XML().copyAlignPanel(alignPanel, true);
2082 newap.av.gatherViewsHere = false;
2084 if (viewport.viewName == null)
2086 viewport.viewName = "Original";
2089 newap.av.historyList = viewport.historyList;
2090 newap.av.redoList = viewport.redoList;
2092 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2093 String newViewName = "View " +index;
2095 Vector comps = (Vector) PaintRefresher.components.get(viewport.
2096 getSequenceSetId());
2097 Vector existingNames = new Vector();
2098 for(int i=0; i<comps.size(); i++)
2100 if(comps.elementAt(i) instanceof AlignmentPanel)
2102 AlignmentPanel ap = (AlignmentPanel)comps.elementAt(i);
2103 if(!existingNames.contains(ap.av.viewName))
2105 existingNames.addElement(ap.av.viewName);
2110 while(existingNames.contains(newViewName))
2112 newViewName = "View "+ (++index);
2115 newap.av.viewName = newViewName;
2117 addAlignmentPanel(newap, false);
2119 if(alignPanels.size()==2)
2121 viewport.gatherViewsHere = true;
2123 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2126 public void expandViews_actionPerformed(ActionEvent e)
2128 Desktop.instance.explodeViews(this);
2131 public void gatherViews_actionPerformed(ActionEvent e)
2133 Desktop.instance.gatherViews(this);
2141 * @param e DOCUMENT ME!
2143 public void font_actionPerformed(ActionEvent e)
2145 new FontChooser(alignPanel);
2152 * @param e DOCUMENT ME!
2154 protected void seqLimit_actionPerformed(ActionEvent e)
2156 viewport.setShowJVSuffix(seqLimits.isSelected());
2158 alignPanel.idPanel.idCanvas.setPreferredSize(alignPanel.calculateIdWidth());
2159 alignPanel.paintAlignment(true);
2162 public void idRightAlign_actionPerformed(ActionEvent e)
2164 viewport.rightAlignIds = idRightAlign.isSelected();
2165 alignPanel.paintAlignment(true);
2173 * @param e DOCUMENT ME!
2175 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2177 viewport.setColourText(colourTextMenuItem.isSelected());
2178 alignPanel.paintAlignment(true);
2184 * @param e DOCUMENT ME!
2186 public void wrapMenuItem_actionPerformed(ActionEvent e)
2188 scaleAbove.setVisible(wrapMenuItem.isSelected());
2189 scaleLeft.setVisible(wrapMenuItem.isSelected());
2190 scaleRight.setVisible(wrapMenuItem.isSelected());
2191 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2192 alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2195 public void showAllSeqs_actionPerformed(ActionEvent e)
2197 viewport.showAllHiddenSeqs();
2200 public void showAllColumns_actionPerformed(ActionEvent e)
2202 viewport.showAllHiddenColumns();
2206 public void hideSelSequences_actionPerformed(ActionEvent e)
2208 viewport.hideAllSelectedSeqs();
2209 alignPanel.paintAlignment(true);
2212 public void hideSelColumns_actionPerformed(ActionEvent e)
2214 viewport.hideSelectedColumns();
2215 alignPanel.paintAlignment(true);
2218 public void hiddenMarkers_actionPerformed(ActionEvent e)
2220 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
2227 * @param e DOCUMENT ME!
2229 protected void scaleAbove_actionPerformed(ActionEvent e)
2231 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
2232 alignPanel.paintAlignment(true);
2238 * @param e DOCUMENT ME!
2240 protected void scaleLeft_actionPerformed(ActionEvent e)
2242 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
2243 alignPanel.paintAlignment(true);
2249 * @param e DOCUMENT ME!
2251 protected void scaleRight_actionPerformed(ActionEvent e)
2253 viewport.setScaleRightWrapped(scaleRight.isSelected());
2254 alignPanel.paintAlignment(true);
2260 * @param e DOCUMENT ME!
2262 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
2264 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
2265 alignPanel.paintAlignment(true);
2271 * @param e DOCUMENT ME!
2273 public void viewTextMenuItem_actionPerformed(ActionEvent e)
2275 viewport.setShowText(viewTextMenuItem.isSelected());
2276 alignPanel.paintAlignment(true);
2282 * @param e DOCUMENT ME!
2284 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
2286 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
2287 alignPanel.paintAlignment(true);
2291 public FeatureSettings featureSettings;
2292 public void featureSettings_actionPerformed(ActionEvent e)
2294 if(featureSettings !=null )
2296 featureSettings.close();
2297 featureSettings = null;
2299 featureSettings = new FeatureSettings(this);
2305 * @param evt DOCUMENT ME!
2307 public void showSeqFeatures_actionPerformed(ActionEvent evt)
2309 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
2310 alignPanel.paintAlignment(true);
2311 if (alignPanel.getOverviewPanel() != null)
2313 alignPanel.getOverviewPanel().updateOverviewImage();
2320 * @param e DOCUMENT ME!
2322 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
2324 viewport.setShowAnnotation(annotationPanelMenuItem.isSelected());
2325 alignPanel.setAnnotationVisible(annotationPanelMenuItem.isSelected());
2328 public void alignmentProperties()
2330 JEditorPane editPane = new JEditorPane("text/html","");
2331 editPane.setEditable(false);
2332 StringBuffer contents = new StringBuffer("<html>");
2335 int min=Integer.MAX_VALUE, max=0;
2336 for(int i=0; i<viewport.alignment.getHeight(); i++)
2338 int size = viewport.alignment.getSequenceAt(i).getEnd()
2339 -viewport.alignment.getSequenceAt(i).getStart();
2346 avg = avg/(float)viewport.alignment.getHeight();
2348 contents.append("<br>Sequences: "+ viewport.alignment.getHeight());
2349 contents.append("<br>Minimum Sequence Length: "+min);
2350 contents.append("<br>Maximum Sequence Length: "+max);
2351 contents.append("<br>Average Length: "+(int)avg);
2353 if (((Alignment)viewport.alignment).getProperties() != null)
2355 Hashtable props = ((Alignment)viewport.alignment).getProperties();
2356 Enumeration en = props.keys();
2357 contents.append("<br><br><table border=\"1\">");
2358 while(en.hasMoreElements())
2360 String key = en.nextElement().toString();
2361 StringBuffer val = new StringBuffer();
2362 String vals = props.get(key).toString();
2365 npos = vals.indexOf("\n",pos);
2368 val.append(vals.substring(pos));
2370 val.append(vals.substring(pos, npos));
2375 contents.append("<tr><td>"+key+"</td><td>"+val+"</td></tr>");
2377 contents.append("</table>");
2379 editPane.setText(contents.toString()+"</html>");
2380 JInternalFrame frame = new JInternalFrame();
2381 frame.getContentPane().add(new JScrollPane(editPane));
2383 Desktop.instance.addInternalFrame(frame,"Alignment Properties: "+getTitle(),500,400);
2390 * @param e DOCUMENT ME!
2392 public void overviewMenuItem_actionPerformed(ActionEvent e)
2394 if (alignPanel.overviewPanel != null)
2399 JInternalFrame frame = new JInternalFrame();
2400 OverviewPanel overview = new OverviewPanel(alignPanel);
2401 frame.setContentPane(overview);
2402 Desktop.addInternalFrame(frame, "Overview " + this.getTitle(),
2403 frame.getWidth(), frame.getHeight());
2405 frame.setLayer(JLayeredPane.PALETTE_LAYER);
2406 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
2408 public void internalFrameClosed(
2409 javax.swing.event.InternalFrameEvent evt)
2411 alignPanel.setOverviewPanel(null);
2416 alignPanel.setOverviewPanel(overview);
2419 public void textColour_actionPerformed(ActionEvent e)
2421 new TextColourChooser().chooseColour(alignPanel, null);
2427 * @param e DOCUMENT ME!
2429 protected void noColourmenuItem_actionPerformed(ActionEvent e)
2437 * @param e DOCUMENT ME!
2439 public void clustalColour_actionPerformed(ActionEvent e)
2441 changeColour(new ClustalxColourScheme(
2442 viewport.alignment.getSequences(), viewport.alignment.getWidth()));
2448 * @param e DOCUMENT ME!
2450 public void zappoColour_actionPerformed(ActionEvent e)
2452 changeColour(new ZappoColourScheme());
2458 * @param e DOCUMENT ME!
2460 public void taylorColour_actionPerformed(ActionEvent e)
2462 changeColour(new TaylorColourScheme());
2468 * @param e DOCUMENT ME!
2470 public void hydrophobicityColour_actionPerformed(ActionEvent e)
2472 changeColour(new HydrophobicColourScheme());
2478 * @param e DOCUMENT ME!
2480 public void helixColour_actionPerformed(ActionEvent e)
2482 changeColour(new HelixColourScheme());
2488 * @param e DOCUMENT ME!
2490 public void strandColour_actionPerformed(ActionEvent e)
2492 changeColour(new StrandColourScheme());
2498 * @param e DOCUMENT ME!
2500 public void turnColour_actionPerformed(ActionEvent e)
2502 changeColour(new TurnColourScheme());
2508 * @param e DOCUMENT ME!
2510 public void buriedColour_actionPerformed(ActionEvent e)
2512 changeColour(new BuriedColourScheme());
2518 * @param e DOCUMENT ME!
2520 public void nucleotideColour_actionPerformed(ActionEvent e)
2522 changeColour(new NucleotideColourScheme());
2525 public void annotationColour_actionPerformed(ActionEvent e)
2527 new AnnotationColourChooser(viewport, alignPanel);
2534 * @param e DOCUMENT ME!
2536 protected void applyToAllGroups_actionPerformed(ActionEvent e)
2538 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
2544 * @param cs DOCUMENT ME!
2546 public void changeColour(ColourSchemeI cs)
2552 if (viewport.getAbovePIDThreshold())
2554 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
2557 cs.setThreshold(threshold,
2558 viewport.getIgnoreGapsConsensus());
2560 viewport.setGlobalColourScheme(cs);
2564 cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
2567 if (viewport.getConservationSelected())
2570 Alignment al = (Alignment) viewport.alignment;
2571 Conservation c = new Conservation("All",
2572 ResidueProperties.propHash, 3,
2573 al.getSequences(), 0,
2577 c.verdict(false, viewport.ConsPercGaps);
2579 cs.setConservation(c);
2581 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel, cs,
2586 cs.setConservation(null);
2589 cs.setConsensus(viewport.hconsensus);
2592 viewport.setGlobalColourScheme(cs);
2594 if (viewport.getColourAppliesToAllGroups())
2596 Vector groups = viewport.alignment.getGroups();
2598 for (int i = 0; i < groups.size(); i++)
2600 SequenceGroup sg = (SequenceGroup) groups.elementAt(i);
2608 if (cs instanceof ClustalxColourScheme)
2610 sg.cs = new ClustalxColourScheme(
2611 sg.getSequences(viewport.hiddenRepSequences), sg.getWidth());
2613 else if (cs instanceof UserColourScheme)
2615 sg.cs = new UserColourScheme( ( (UserColourScheme) cs).getColours());
2621 sg.cs = (ColourSchemeI) cs.getClass().newInstance();
2623 catch (Exception ex)
2628 if (viewport.getAbovePIDThreshold()
2629 || cs instanceof PIDColourScheme
2630 || cs instanceof Blosum62ColourScheme)
2632 sg.cs.setThreshold(threshold,
2633 viewport.getIgnoreGapsConsensus());
2635 sg.cs.setConsensus(AAFrequency.calculate(
2636 sg.getSequences(viewport.hiddenRepSequences), sg.getStartRes(),
2641 sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
2645 if (viewport.getConservationSelected())
2647 Conservation c = new Conservation("Group",
2648 ResidueProperties.propHash, 3,
2649 sg.getSequences(viewport.
2650 hiddenRepSequences),
2654 c.verdict(false, viewport.ConsPercGaps);
2655 sg.cs.setConservation(c);
2659 sg.cs.setConservation(null);
2664 if (alignPanel.getOverviewPanel() != null)
2666 alignPanel.getOverviewPanel().updateOverviewImage();
2672 alignPanel.paintAlignment(true);
2678 * @param e DOCUMENT ME!
2680 protected void modifyPID_actionPerformed(ActionEvent e)
2682 if (viewport.getAbovePIDThreshold() && viewport.globalColourScheme!=null)
2684 SliderPanel.setPIDSliderSource(alignPanel,
2685 viewport.getGlobalColourScheme(),
2687 SliderPanel.showPIDSlider();
2694 * @param e DOCUMENT ME!
2696 protected void modifyConservation_actionPerformed(ActionEvent e)
2698 if (viewport.getConservationSelected() && viewport.globalColourScheme!=null)
2700 SliderPanel.setConservationSlider(alignPanel,
2701 viewport.globalColourScheme,
2703 SliderPanel.showConservationSlider();
2710 * @param e DOCUMENT ME!
2712 protected void conservationMenuItem_actionPerformed(ActionEvent e)
2714 viewport.setConservationSelected(conservationMenuItem.isSelected());
2716 viewport.setAbovePIDThreshold(false);
2717 abovePIDThreshold.setSelected(false);
2719 changeColour(viewport.getGlobalColourScheme());
2721 modifyConservation_actionPerformed(null);
2727 * @param e DOCUMENT ME!
2729 public void abovePIDThreshold_actionPerformed(ActionEvent e)
2731 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
2733 conservationMenuItem.setSelected(false);
2734 viewport.setConservationSelected(false);
2736 changeColour(viewport.getGlobalColourScheme());
2738 modifyPID_actionPerformed(null);
2744 * @param e DOCUMENT ME!
2746 public void userDefinedColour_actionPerformed(ActionEvent e)
2748 if (e.getActionCommand().equals("User Defined..."))
2750 new UserDefinedColours(alignPanel, null);
2754 UserColourScheme udc = (UserColourScheme) UserDefinedColours.
2755 getUserColourSchemes().get(e.getActionCommand());
2761 public void updateUserColourMenu()
2764 Component[] menuItems = colourMenu.getMenuComponents();
2765 int i, iSize = menuItems.length;
2766 for (i = 0; i < iSize; i++)
2768 if (menuItems[i].getName() != null &&
2769 menuItems[i].getName().equals("USER_DEFINED"))
2771 colourMenu.remove(menuItems[i]);
2775 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
2777 java.util.Enumeration userColours = jalview.gui.UserDefinedColours.
2778 getUserColourSchemes().keys();
2780 while (userColours.hasMoreElements())
2782 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
2784 nextElement().toString());
2785 radioItem.setName("USER_DEFINED");
2786 radioItem.addMouseListener(new MouseAdapter()
2788 public void mousePressed(MouseEvent evt)
2790 if(evt.isControlDown() || SwingUtilities.isRightMouseButton(evt))
2792 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
2794 int option = JOptionPane.showInternalConfirmDialog(jalview.gui.
2796 "Remove from default list?",
2797 "Remove user defined colour",
2798 JOptionPane.YES_NO_OPTION);
2799 if(option == JOptionPane.YES_OPTION)
2801 jalview.gui.UserDefinedColours.removeColourFromDefaults(
2802 radioItem.getText());
2803 colourMenu.remove(radioItem);
2807 radioItem.addActionListener(new ActionListener()
2809 public void actionPerformed(ActionEvent evt)
2811 userDefinedColour_actionPerformed(evt);
2818 radioItem.addActionListener(new ActionListener()
2820 public void actionPerformed(ActionEvent evt)
2822 userDefinedColour_actionPerformed(evt);
2826 colourMenu.insert(radioItem, 15);
2827 colours.add(radioItem);
2835 * @param e DOCUMENT ME!
2837 public void PIDColour_actionPerformed(ActionEvent e)
2839 changeColour(new PIDColourScheme());
2845 * @param e DOCUMENT ME!
2847 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
2849 changeColour(new Blosum62ColourScheme());
2855 * @param e DOCUMENT ME!
2857 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
2859 SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
2860 AlignmentSorter.sortByPID(viewport.getAlignment(),
2861 viewport.getAlignment().getSequenceAt(0));
2862 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
2863 viewport.alignment));
2864 alignPanel.paintAlignment(true);
2870 * @param e DOCUMENT ME!
2872 public void sortIDMenuItem_actionPerformed(ActionEvent e)
2874 SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
2875 AlignmentSorter.sortByID(viewport.getAlignment());
2876 addHistoryItem(new OrderCommand("ID Sort", oldOrder, viewport.alignment));
2877 alignPanel.paintAlignment(true);
2883 * @param e DOCUMENT ME!
2885 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
2887 SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
2888 AlignmentSorter.sortByGroup(viewport.getAlignment());
2889 addHistoryItem(new OrderCommand("Group Sort", oldOrder, viewport.alignment));
2891 alignPanel.paintAlignment(true);
2896 * @param e DOCUMENT ME!
2898 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
2900 new RedundancyPanel(alignPanel, this);
2907 * @param e DOCUMENT ME!
2909 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
2911 if ( (viewport.getSelectionGroup() == null) ||
2912 (viewport.getSelectionGroup().getSize() < 2))
2914 JOptionPane.showInternalMessageDialog(this,
2915 "You must select at least 2 sequences.",
2916 "Invalid Selection",
2917 JOptionPane.WARNING_MESSAGE);
2921 JInternalFrame frame = new JInternalFrame();
2922 frame.setContentPane(new PairwiseAlignPanel(viewport));
2923 Desktop.addInternalFrame(frame, "Pairwise Alignment", 600, 500);
2930 * @param e DOCUMENT ME!
2932 public void PCAMenuItem_actionPerformed(ActionEvent e)
2934 if ( ( (viewport.getSelectionGroup() != null) &&
2935 (viewport.getSelectionGroup().getSize() < 4) &&
2936 (viewport.getSelectionGroup().getSize() > 0)) ||
2937 (viewport.getAlignment().getHeight() < 4))
2939 JOptionPane.showInternalMessageDialog(this,
2940 "Principal component analysis must take\n" +
2941 "at least 4 input sequences.",
2942 "Sequence selection insufficient",
2943 JOptionPane.WARNING_MESSAGE);
2948 new PCAPanel(alignPanel);
2952 public void autoCalculate_actionPerformed(ActionEvent e)
2954 viewport.autoCalculateConsensus = autoCalculate.isSelected();
2955 if(viewport.autoCalculateConsensus)
2957 viewport.firePropertyChange("alignment",
2959 viewport.getAlignment().getSequences());
2967 * @param e DOCUMENT ME!
2969 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
2971 NewTreePanel("AV", "PID", "Average distance tree using PID");
2977 * @param e DOCUMENT ME!
2979 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
2981 NewTreePanel("NJ", "PID", "Neighbour joining tree using PID");
2987 * @param e DOCUMENT ME!
2989 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
2991 NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
2997 * @param e DOCUMENT ME!
2999 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3001 NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3007 * @param type DOCUMENT ME!
3008 * @param pwType DOCUMENT ME!
3009 * @param title DOCUMENT ME!
3011 void NewTreePanel(String type, String pwType, String title)
3015 if (viewport.getSelectionGroup() != null)
3017 if (viewport.getSelectionGroup().getSize() < 3)
3019 JOptionPane.showMessageDialog(Desktop.desktop,
3020 "You need to have more than two sequences selected to build a tree!",
3021 "Not enough sequences",
3022 JOptionPane.WARNING_MESSAGE);
3027 SequenceGroup sg = viewport.getSelectionGroup();
3029 /* Decide if the selection is a column region */
3030 while (s < sg.getSize())
3032 if ( ( (SequenceI) sg.getSequences(null).elementAt(s++)).getLength() <
3035 JOptionPane.showMessageDialog(Desktop.desktop,
3036 "The selected region to create a tree may\nonly contain residues or gaps.\n" +
3037 "Try using the Pad function in the edit menu,\n" +
3038 "or one of the multiple sequence alignment web services.",
3039 "Sequences in selection are not aligned",
3040 JOptionPane.WARNING_MESSAGE);
3046 title = title + " on region";
3047 tp = new TreePanel(alignPanel, type, pwType);
3051 //are the sequences aligned?
3052 if (!viewport.alignment.isAligned())
3054 JOptionPane.showMessageDialog(Desktop.desktop,
3055 "The sequences must be aligned before creating a tree.\n" +
3056 "Try using the Pad function in the edit menu,\n" +
3057 "or one of the multiple sequence alignment web services.",
3058 "Sequences not aligned",
3059 JOptionPane.WARNING_MESSAGE);
3064 if(viewport.alignment.getHeight()<2)
3069 tp = new TreePanel(alignPanel, type, pwType);
3074 if(viewport.viewName!=null)
3076 title+= viewport.viewName+" of ";
3079 title += this.title;
3081 Desktop.addInternalFrame(tp, title, 600, 500);
3087 * @param title DOCUMENT ME!
3088 * @param order DOCUMENT ME!
3090 public void addSortByOrderMenuItem(String title, final AlignmentOrder order)
3092 final JMenuItem item = new JMenuItem("by " + title);
3094 item.addActionListener(new java.awt.event.ActionListener()
3096 public void actionPerformed(ActionEvent e)
3098 SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
3100 // TODO: JBPNote - have to map order entries to curent SequenceI pointers
3101 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3103 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3104 viewport.alignment));
3106 alignPanel.paintAlignment(true);
3111 * Add a new sort by annotation score menu item
3112 * @param sort the menu to add the option to
3113 * @param scoreLabel the label used to retrieve scores for each sequence on the alignment
3115 public void addSortByAnnotScoreMenuItem(JMenu sort, final String scoreLabel)
3117 final JMenuItem item = new JMenuItem(scoreLabel);
3119 item.addActionListener(new java.awt.event.ActionListener()
3121 public void actionPerformed(ActionEvent e)
3123 SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
3124 AlignmentSorter.sortByAnnotationScore(scoreLabel, viewport.getAlignment());
3125 addHistoryItem(new OrderCommand("Sort by "+scoreLabel, oldOrder, viewport.alignment));
3126 alignPanel.paintAlignment(true);
3131 * last hash for alignment's annotation array - used to minimise cost of rebuild.
3133 protected int _annotationScoreVectorHash;
3135 * search the alignment and rebuild the sort by annotation score submenu
3136 * the last alignment annotation vector hash is stored to minimize
3137 * cost of rebuilding in subsequence calls.
3140 public void buildSortByAnnotationScoresMenu()
3142 if(viewport.alignment.getAlignmentAnnotation()==null)
3147 if (viewport.alignment.getAlignmentAnnotation().hashCode()!=_annotationScoreVectorHash)
3149 sortByAnnotScore.removeAll();
3150 // almost certainly a quicker way to do this - but we keep it simple
3151 Hashtable scoreSorts=new Hashtable();
3152 AlignmentAnnotation aann[];
3153 Enumeration sq = viewport.alignment.getSequences().elements();
3154 while (sq.hasMoreElements())
3156 aann = ((SequenceI) sq.nextElement()).getAnnotation();
3157 for (int i=0;aann!=null && i<aann.length; i++)
3159 if (aann[i].hasScore() && aann[i].sequenceRef!=null)
3161 scoreSorts.put(aann[i].label, aann[i].label);
3165 Enumeration labels = scoreSorts.keys();
3166 while (labels.hasMoreElements())
3168 addSortByAnnotScoreMenuItem(sortByAnnotScore, (String) labels.nextElement());
3170 sortByAnnotScore.setVisible(scoreSorts.size()>0);
3173 _annotationScoreVectorHash =
3174 viewport.alignment.getAlignmentAnnotation().hashCode();
3179 * Maintain the Order by->Displayed Tree menu.
3180 * Creates a new menu item for a TreePanel with an appropriate
3181 * <code>jalview.analysis.AlignmentSorter</code> call. Listeners are added
3182 * to remove the menu item when the treePanel is closed, and adjust
3183 * the tree leaf to sequence mapping when the alignment is modified.
3184 * @param treePanel Displayed tree window.
3185 * @param title SortBy menu item title.
3187 public void buildTreeMenu()
3189 sortByTreeMenu.removeAll();
3191 Vector comps = (Vector) PaintRefresher.components.get(viewport.
3192 getSequenceSetId());
3193 Vector treePanels = new Vector();
3194 int i, iSize = comps.size();
3195 for(i=0; i<iSize; i++)
3197 if(comps.elementAt(i) instanceof TreePanel)
3199 treePanels.add(comps.elementAt(i));
3203 iSize = treePanels.size();
3207 sortByTreeMenu.setVisible(false);
3211 sortByTreeMenu.setVisible(true);
3213 for(i=0; i<treePanels.size(); i++)
3215 TreePanel tp = (TreePanel)treePanels.elementAt(i);
3216 final JMenuItem item = new JMenuItem(tp.getTitle());
3217 final NJTree tree = ((TreePanel)treePanels.elementAt(i)).getTree();
3218 item.addActionListener(new java.awt.event.ActionListener()
3220 public void actionPerformed(ActionEvent e)
3222 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3223 AlignmentSorter.sortByTree(viewport.getAlignment(), tree);
3225 addHistoryItem(new OrderCommand("Tree Sort",
3227 viewport.alignment));
3229 alignPanel.paintAlignment(true);
3233 sortByTreeMenu.add(item);
3238 * Work out whether the whole set of sequences
3239 * or just the selected set will be submitted for multiple alignment.
3242 private jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3244 // Now, check we have enough sequences
3245 AlignmentView msa = null;
3247 if ( (viewport.getSelectionGroup() != null) &&
3248 (viewport.getSelectionGroup().getSize() > 1))
3250 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to some common interface!
3251 /*SequenceGroup seqs = viewport.getSelectionGroup();
3253 msa = new SequenceI[sz = seqs.getSize(false)];
3255 for (int i = 0; i < sz; i++)
3257 msa[i] = (SequenceI) seqs.getSequenceAt(i);
3259 msa = viewport.getAlignmentView(true);
3263 /*Vector seqs = viewport.getAlignment().getSequences();
3265 if (seqs.size() > 1)
3267 msa = new SequenceI[seqs.size()];
3269 for (int i = 0; i < seqs.size(); i++)
3271 msa[i] = (SequenceI) seqs.elementAt(i);
3274 msa = viewport.getAlignmentView(false);
3280 * Decides what is submitted to a secondary structure prediction service,
3281 * the currently selected sequence, or the currently selected alignment
3282 * (where the first sequence in the set is the one that the prediction
3285 AlignmentView gatherSeqOrMsaForSecStrPrediction()
3287 AlignmentView seqs = null;
3289 if ( (viewport.getSelectionGroup() != null) &&
3290 (viewport.getSelectionGroup().getSize() > 0))
3292 seqs = viewport.getAlignmentView(true);
3296 seqs = viewport.getAlignmentView(false);
3298 // limit sequences - JBPNote in future - could spawn multiple prediction jobs
3299 // TODO: viewport.alignment.isAligned is a global state - the local selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3300 if (!viewport.alignment.isAligned())
3302 seqs.setSequences(new SeqCigar[]
3303 {seqs.getSequences()[0]});
3310 * @param e DOCUMENT ME!
3312 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
3314 // Pick the tree file
3315 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
3318 chooser.setFileView(new JalviewFileView());
3319 chooser.setDialogTitle("Select a newick-like tree file");
3320 chooser.setToolTipText("Load a tree file");
3322 int value = chooser.showOpenDialog(null);
3324 if (value == JalviewFileChooser.APPROVE_OPTION)
3326 String choice = chooser.getSelectedFile().getPath();
3327 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
3328 jalview.io.NewickFile fin = null;
3331 fin = new jalview.io.NewickFile(choice,
3333 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
3335 catch (Exception ex)
3337 JOptionPane.showMessageDialog(Desktop.desktop,
3339 "Problem reading tree file",
3340 JOptionPane.WARNING_MESSAGE);
3341 ex.printStackTrace();
3343 if (fin!=null && fin.hasWarningMessage())
3345 JOptionPane.showMessageDialog(Desktop.desktop,
3346 fin.getWarningMessage(),
3347 "Possible problem with tree file",
3348 JOptionPane.WARNING_MESSAGE);
3354 public TreePanel ShowNewickTree(NewickFile nf, String title)
3356 return ShowNewickTree(nf,title,600,500,4,5);
3359 public TreePanel ShowNewickTree(NewickFile nf, String title,
3360 AlignmentView input)
3362 return ShowNewickTree(nf,title, input, 600,500,4,5);
3365 public TreePanel ShowNewickTree(NewickFile nf, String title, int w, int h,
3368 return ShowNewickTree(nf, title, null, w, h, x, y);
3371 * Add a treeviewer for the tree extracted from a newick file object to the current alignment view
3373 * @param nf the tree
3374 * @param title tree viewer title
3375 * @param input Associated alignment input data (or null)
3380 * @return TreePanel handle
3382 public TreePanel ShowNewickTree(NewickFile nf, String title,
3383 AlignmentView input, int w, int h, int x,
3386 TreePanel tp = null;
3392 if (nf.getTree() != null)
3394 tp = new TreePanel(alignPanel,
3403 tp.setLocation(x,y);
3407 Desktop.addInternalFrame(tp, title, w, h);
3410 catch (Exception ex)
3412 ex.printStackTrace();
3420 * Generates menu items and listener event actions for web service clients
3423 public void BuildWebServiceMenu()
3425 if ( (Discoverer.services != null)
3426 && (Discoverer.services.size() > 0))
3428 Vector msaws = (Vector) Discoverer.services.get("MsaWS");
3429 Vector secstrpr = (Vector) Discoverer.services.get("SecStrPred");
3430 Vector wsmenu = new Vector();
3431 final AlignFrame af = this;
3434 // Add any Multiple Sequence Alignment Services
3435 final JMenu msawsmenu = new JMenu("Alignment");
3436 for (int i = 0, j = msaws.size(); i < j; i++)
3438 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) msaws.
3440 final JMenuItem method = new JMenuItem(sh.getName());
3441 method.addActionListener(new ActionListener()
3443 public void actionPerformed(ActionEvent e)
3445 AlignmentView msa = gatherSequencesForAlignment();
3446 new jalview.ws.MsaWSClient(sh, title, msa,
3448 viewport.getAlignment().getDataset(),
3454 msawsmenu.add(method);
3455 // Deal with services that we know accept partial alignments.
3456 if (sh.getName().indexOf("lustal") > -1)
3458 // We know that ClustalWS can accept partial alignments for refinement.
3459 final JMenuItem methodR = new JMenuItem(sh.getName()+" Realign");
3460 methodR.addActionListener(new ActionListener()
3462 public void actionPerformed(ActionEvent e)
3464 AlignmentView msa = gatherSequencesForAlignment();
3465 new jalview.ws.MsaWSClient(sh, title, msa,
3467 viewport.getAlignment().getDataset(),
3473 msawsmenu.add(methodR);
3477 wsmenu.add(msawsmenu);
3479 if (secstrpr != null)
3481 // Add any secondary structure prediction services
3482 final JMenu secstrmenu = new JMenu("Secondary Structure Prediction");
3483 for (int i = 0, j = secstrpr.size(); i < j; i++)
3485 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle)
3487 final JMenuItem method = new JMenuItem(sh.getName());
3488 method.addActionListener(new ActionListener()
3490 public void actionPerformed(ActionEvent e)
3492 AlignmentView msa = gatherSeqOrMsaForSecStrPrediction();
3493 if (msa.getSequences().length == 1)
3495 // Single Sequence prediction
3496 new jalview.ws.JPredClient(sh, title, false, msa, af, true);
3500 if (msa.getSequences().length > 1)
3502 // Sequence profile based prediction
3503 new jalview.ws.JPredClient(sh,
3504 title, true, msa, af, true);
3509 secstrmenu.add(method);
3511 wsmenu.add(secstrmenu);
3513 resetWebServiceMenu();
3514 for (int i = 0, j = wsmenu.size(); i < j; i++)
3516 webService.add( (JMenu) wsmenu.get(i));
3521 resetWebServiceMenu();
3522 this.webService.add(this.webServiceNoServices);
3524 // TODO: add in rediscovery function
3525 // TODO: reduce code redundancy.
3526 // TODO: group services by location as well as function.
3531 * empty the web service menu and add any ad-hoc functions
3532 * not dynamically discovered.
3535 private void resetWebServiceMenu()
3537 webService.removeAll();
3538 // Temporary hack - DBRef Fetcher always top level ws entry.
3539 JMenuItem rfetch = new JMenuItem("Fetch DB References");
3540 rfetch.setToolTipText("Retrieve and parse uniprot records for the alignment or the currently selected sequences");
3541 webService.add(rfetch);
3542 rfetch.addActionListener(new ActionListener() {
3544 public void actionPerformed(ActionEvent e)
3546 new jalview.ws.DBRefFetcher(
3547 alignPanel.av.getSequenceSelection(),
3548 alignPanel.alignFrame).fetchDBRefs(false);
3554 /* public void vamsasStore_actionPerformed(ActionEvent e)
3556 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
3557 getProperty("LAST_DIRECTORY"));
3559 chooser.setFileView(new JalviewFileView());
3560 chooser.setDialogTitle("Export to Vamsas file");
3561 chooser.setToolTipText("Export");
3563 int value = chooser.showSaveDialog(this);
3565 if (value == JalviewFileChooser.APPROVE_OPTION)
3567 jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
3568 //vs.store(chooser.getSelectedFile().getAbsolutePath() );
3569 vs.storeJalview( chooser.getSelectedFile().getAbsolutePath(), this);
3573 * prototype of an automatically enabled/disabled analysis function
3576 protected void setShowProductsEnabled()
3578 SequenceI [] selection = viewport.getSequenceSelection();
3579 if (canShowProducts(selection, viewport.getSelectionGroup()!=null, viewport.getAlignment().getDataset()))
3581 showProducts.setEnabled(true);
3584 showProducts.setEnabled(false);
3588 * search selection for sequence xRef products and build the
3589 * show products menu.
3592 * @return true if showProducts menu should be enabled.
3594 public boolean canShowProducts(SequenceI[] selection, boolean isRegionSelection, Alignment dataset)
3596 boolean showp=false;
3598 showProducts.removeAll();
3599 final boolean dna = viewport.getAlignment().isNucleotide();
3600 final Alignment ds = dataset;
3601 String[] ptypes = CrossRef.findSequenceXrefTypes(dna, selection, dataset);
3602 //Object[] prods = CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(), selection, dataset, true);
3603 final SequenceI[] sel = selection;
3604 for (int t=0; ptypes!=null && t<ptypes.length; t++)
3607 final boolean isRegSel = isRegionSelection;
3608 final AlignFrame af = this;
3609 final String source = ptypes[t];
3610 JMenuItem xtype = new JMenuItem(ptypes[t]);
3611 xtype.addActionListener(new ActionListener() {
3613 public void actionPerformed(ActionEvent e)
3615 af.showProductsFor(sel, ds, isRegSel, dna, source);
3619 showProducts.add(xtype);
3621 showProducts.setVisible(showp);
3622 showProducts.setEnabled(showp);
3623 } catch (Exception e)
3625 jalview.bin.Cache.log.warn("canTranslate threw an exception - please report to help@jalview.org",e);
3630 protected void showProductsFor(SequenceI[] sel, Alignment ds, boolean isRegSel, boolean dna, String source)
3632 ds = this.getViewport().alignment.getDataset(); // update our local dataset reference
3633 Alignment prods = CrossRef.findXrefSequences(sel, dna, source, ds);
3636 SequenceI[] sprods = new SequenceI[prods.getHeight()];
3637 for (int s=0; s<sprods.length;s++)
3639 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
3640 if (ds.getSequences()==null || !ds.getSequences().contains(sprods[s].getDatasetSequence()))
3641 ds.addSequence(sprods[s].getDatasetSequence());
3643 Alignment al = new Alignment(sprods);
3644 AlignedCodonFrame[] cf = prods.getCodonFrames();
3645 for (int s=0; cf!=null && s<cf.length; s++)
3647 al.addCodonFrame(cf[s]);
3651 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
3652 String newtitle =""+((dna) ? "Proteins " : "Nucleotides ") + " for "+((isRegSel) ? "selected region of " : "")
3654 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
3657 System.err.println("No Sequences generated for xRef type "+source);
3662 public boolean canShowTranslationProducts(SequenceI[] selection, AlignmentI alignment)
3666 return (jalview.analysis.Dna.canTranslate(selection, viewport.getViewAsVisibleContigs(true)));
3667 } catch (Exception e)
3669 jalview.bin.Cache.log.warn("canTranslate threw an exception - please report to help@jalview.org",e);
3674 public void showProducts_actionPerformed(ActionEvent e)
3676 ///////////////////////////////
3677 // Collect Data to be translated/transferred
3679 SequenceI [] selection = viewport.getSequenceSelection();
3680 AlignmentI al = null;
3682 al = jalview.analysis.Dna.CdnaTranslate(selection, viewport.getViewAsVisibleContigs(true),
3683 viewport.getGapCharacter(), viewport.getAlignment().getDataset());
3684 } catch (Exception ex) {
3686 jalview.bin.Cache.log.debug("Exception during translation.",ex);
3690 JOptionPane.showMessageDialog(Desktop.desktop,
3691 "Please select at least three bases in at least one sequence in order to perform a cDNA translation.",
3692 "Translation Failed",
3693 JOptionPane.WARNING_MESSAGE);
3695 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
3696 Desktop.addInternalFrame(af, "Translation of "+this.getTitle(),
3702 public void showTranslation_actionPerformed(ActionEvent e)
3704 ///////////////////////////////
3705 // Collect Data to be translated/transferred
3707 SequenceI [] selection = viewport.getSequenceSelection();
3708 String [] seqstring = viewport.getViewAsString(true);
3709 AlignmentI al = null;
3711 al = jalview.analysis.Dna.CdnaTranslate(selection, seqstring, viewport.getViewAsVisibleContigs(true),
3712 viewport.getGapCharacter(), viewport.alignment.getAlignmentAnnotation(),
3713 viewport.alignment.getWidth(), viewport.getAlignment().getDataset());
3714 } catch (Exception ex) {
3716 jalview.bin.Cache.log.debug("Exception during translation.",ex);
3720 JOptionPane.showMessageDialog(Desktop.desktop,
3721 "Please select at least three bases in at least one sequence in order to perform a cDNA translation.",
3722 "Translation Failed",
3723 JOptionPane.WARNING_MESSAGE);
3725 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
3726 Desktop.addInternalFrame(af, "Translation of "+this.getTitle(),
3735 * @param String DOCUMENT ME!
3737 public boolean parseFeaturesFile(String file, String type)
3739 boolean featuresFile = false;
3742 featuresFile = new FeaturesFile(file,
3743 type).parse(viewport.alignment.getDataset(),
3744 alignPanel.seqPanel.seqCanvas.
3745 getFeatureRenderer().featureColours,
3750 ex.printStackTrace();
3755 viewport.showSequenceFeatures = true;
3756 showSeqFeatures.setSelected(true);
3757 alignPanel.paintAlignment(true);
3760 return featuresFile;
3763 public void dragEnter(DropTargetDragEvent evt)
3766 public void dragExit(DropTargetEvent evt)
3769 public void dragOver(DropTargetDragEvent evt)
3772 public void dropActionChanged(DropTargetDragEvent evt)
3775 public void drop(DropTargetDropEvent evt)
3777 Transferable t = evt.getTransferable();
3778 java.util.List files = null;
3782 DataFlavor uriListFlavor = new DataFlavor(
3783 "text/uri-list;class=java.lang.String");
3784 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
3786 //Works on Windows and MacOSX
3787 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
3788 files = (java.util.List) t.getTransferData(DataFlavor.
3789 javaFileListFlavor);
3791 else if (t.isDataFlavorSupported(uriListFlavor))
3793 // This is used by Unix drag system
3794 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
3795 String data = (String) t.getTransferData(uriListFlavor);
3796 files = new java.util.ArrayList(1);
3797 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
3800 st.hasMoreTokens(); )
3802 String s = st.nextToken();
3803 if (s.startsWith("#"))
3805 // the line is a comment (as per the RFC 2483)
3809 java.net.URI uri = new java.net.URI(s);
3810 java.io.File file = new java.io.File(uri);
3817 e.printStackTrace();
3824 for (int i = 0; i < files.size(); i++)
3826 loadJalviewDataFile(files.get(i).toString());
3829 catch (Exception ex)
3831 ex.printStackTrace();
3836 // This method will attempt to load a "dropped" file first by testing
3837 // whether its and Annotation file, then features file. If both are
3838 // false then the user may have dropped an alignment file onto this
3840 public void loadJalviewDataFile(String file)
3844 String protocol = "File";
3846 if (file.indexOf("http:") > -1 || file.indexOf("file:") > -1)
3851 boolean isAnnotation = new AnnotationFile().readAnnotationFile(viewport.
3852 alignment, file, protocol);
3856 boolean isGroupsFile = parseFeaturesFile(file,protocol);
3859 String format = new IdentifyFile().Identify(file, protocol);
3861 if(format.equalsIgnoreCase("JnetFile"))
3863 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
3865 new JnetAnnotationMaker().add_annotation(predictions,
3866 viewport.getAlignment(),
3868 alignPanel.adjustAnnotationHeight();
3869 alignPanel.paintAlignment(true);
3873 new FileLoader().LoadFile(viewport, file, protocol, format);
3880 alignPanel.adjustAnnotationHeight();
3881 buildSortByAnnotationScoresMenu();
3885 catch (Exception ex)
3887 ex.printStackTrace();
3891 public void tabSelectionChanged(int index)
3895 alignPanel = (AlignmentPanel) alignPanels.elementAt(index);
3896 viewport = alignPanel.av;
3897 setMenusFromViewport(viewport);
3901 public void tabbedPane_mousePressed(MouseEvent e)
3903 if(SwingUtilities.isRightMouseButton(e))
3905 String reply = JOptionPane.showInternalInputDialog(this,
3908 JOptionPane.QUESTION_MESSAGE);
3912 viewport.viewName = reply;
3913 tabbedPane.setTitleAt( tabbedPane.getSelectedIndex() ,reply);
3919 public AlignViewport getCurrentView()
3926 * Open the dialog for regex description parsing.
3928 protected void extractScores_actionPerformed(ActionEvent e)
3930 ParseProperties pp = new jalview.analysis.ParseProperties(viewport.alignment);
3931 if (pp.getScoresFromDescription("col", "score column ", "\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)")>0)
3933 buildSortByAnnotationScoresMenu();
3942 public PrintThread(AlignmentPanel ap)
3946 static PageFormat pf;
3949 PrinterJob printJob = PrinterJob.getPrinterJob();
3953 printJob.setPrintable(ap, pf);
3957 printJob.setPrintable(ap);
3960 if (printJob.printDialog())
3966 catch (Exception PrintException)
3968 PrintException.printStackTrace();